Completed
Push — master ( 069b41...a6b5af )
by Naveen
01:17 queued 22s
created
src/wordlift/post/class-post-adapter.php 2 patches
Indentation   +364 added lines, -364 removed lines patch added patch discarded remove patch
@@ -20,369 +20,369 @@
 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
-
92
-		$post_status = $data['post_status'];
93
-		if ( 'auto-draft' === $post_status || 'inherit' === $post_status ) {
94
-			return $data;
95
-		}
96
-
97
-		$this->log->trace( "The following data has been received by `wp_insert_post_data`:\n"
98
-		                   . var_export( $data, true ) );
99
-
100
-
101
-		try {
102
-			$entities = $this->parse_content( wp_unslash( $data['post_content'] ) );
103
-
104
-			foreach ( $entities as $entity ) {
105
-
106
-				$entity_id = array_key_exists( 'id', $entity ) ? $entity['id'] : '';
107
-
108
-				if ( ! $this->entity_id_valid( $entity_id ) ) {
109
-					continue;
110
-				}
111
-
112
-				$entity_uris = $this->get_entity_uris( $entity );
113
-
114
-				if ( $this->get_first_matching_entity_by_uri( $entity_uris ) === null &&
115
-				     Post_Entities_Validator::is_local_entity_uri_exist( Wordlift_Entity_Uri_Service::get_instance(), $entity_uris ) ) {
116
-					// Skip the entity
117
-					continue;
118
-				}
119
-
120
-				// If 'entity auto publish' is false, we set the status to `draft` by default.
121
-				$post_status = apply_filters( 'wl_feature__enable__entity-auto-publish', true )
122
-					? $data['post_status'] : 'draft';
123
-				$this->create_or_update_entity( $entity, $post_status );
124
-
125
-			}
126
-
127
-		} catch ( \Exception $e ) {
128
-			$this->log->error( $e->getMessage() );
129
-		}
130
-
131
-
132
-		return $data;
133
-	}
134
-
135
-	/**
136
-	 * Parse the post content to find the `wordlift/classification` block and return the entities' data.
137
-	 *
138
-	 * @param string $post_content The post content.
139
-	 *
140
-	 * @return array An array of entities' structures.
141
-	 * @throws \Exception
142
-	 */
143
-	private function parse_content( $post_content ) {
144
-
145
-		$all_blocks = parse_blocks( $post_content );
146
-		$this->log->trace( "The following blocks have been parsed while in `wp_insert_post`:\n"
147
-		                   . var_export( $all_blocks, true ) );
148
-
149
-		$blocks = array_filter( $all_blocks, function ( $item ) {
150
-			return ! empty( $item['blockName'] ) && 'wordlift/classification' === $item['blockName'];
151
-		} );
152
-
153
-		// Bail out if the blocks' array is empty.
154
-		if ( empty( $blocks ) ) {
155
-			return array();
156
-		}
157
-
158
-		$block = current( $blocks );
159
-		$this->log->trace( "The following block has been found while in `wp_insert_post`:\n"
160
-		                   . var_export( $block, true ) );
161
-
162
-		// Bail out if the entities array is empty.
163
-		if ( empty( $block['attrs'] ) && empty( $block['attrs']['entities'] ) ) {
164
-			return array();
165
-		}
166
-
167
-		return $block['attrs']['entities'];
168
-	}
169
-
170
-	/**
171
-	 * Collect entity labels from the entity array.
172
-	 *
173
-	 * This function expects an array with the following keys:
174
-	 *
175
-	 * array(
176
-	 *   'label'       => ...,
177
-	 *   'synonyms'    => array( ... ),
178
-	 *   'annotations' => array(
179
-	 *     ...id...      => array( text => ... ),
180
-	 *   ),
181
-	 *   'occurrences' => array( ... ),
182
-	 * )
183
-	 *
184
-	 * and it is going to output an array with all the labels, keeping the `label` at first position:
185
-	 *
186
-	 * array(
187
-	 *   ...label...,
188
-	 *   ...synonyms...,
189
-	 *   ...texts...,
190
-	 * )
191
-	 *
192
-	 * This function is going to collect the label from the `label` property, from the `synonyms` property and from
193
-	 * `annotations` property. Since the `annotations` property contains all the annotations including those that
194
-	 * haven't been selected, this function is going to only get the `text` for the annotations property listed in
195
-	 * `occurrences`.
196
-	 *
197
-	 * @param array $entity {
198
-	 *  The entity data.
199
-	 *
200
-	 * @type string $label The entity label.
201
-	 * @type array $synonyms The entity synonyms.
202
-	 * @type array $occurrences The selected occurrences.
203
-	 * @type array $annotations The annotations.
204
-	 * }
205
-	 *
206
-	 * @return array An array of labels.
207
-	 */
208
-	public function get_labels( $entity ) {
209
-
210
-		$args = wp_parse_args( $entity, array(
211
-			'label'       => array(),
212
-			'synonyms'    => array(),
213
-			'annotations' => array(),
214
-			'occurrences' => array(),
215
-		) );
216
-
217
-		// We gather all the labels, occurrences texts and synonyms into one array.
218
-		$initial = array_merge(
219
-			(array) $args['label'],
220
-			(array) $args['synonyms']
221
-		);
222
-
223
-		$annotations = $args['annotations'];
224
-
225
-		return array_reduce( $args['occurrences'], function ( $carry, $item ) use ( $annotations ) {
226
-
227
-			// Bail out if occurrences->$item->text isn't set or its contents are already
228
-			// in `$carry`.
229
-			if ( ! isset( $annotations[ $item ]['text'] )
230
-			     || in_array( $annotations[ $item ]['text'], $carry ) ) {
231
-				return $carry;
232
-			}
233
-
234
-			// Push the label.
235
-			$carry[] = $annotations[ $item ]['text'];
236
-
237
-			return $carry;
238
-		}, $initial );
239
-	}
240
-
241
-	/**
242
-	 * Create or update the entity.
243
-	 *
244
-	 * An entity lookup is performed on the local vocabulary using the `id` and `sameAs` URIs. If an entity is found
245
-	 * the {@link Entity_Store} update function is called to update the `labels` and the `sameAs` values.
246
-	 *
247
-	 * If an entity is not found the {@link Entity_Store} create function is called to create a new entity.
248
-	 *
249
-	 * @param array $entity {
250
-	 * The entity parameters.
251
-	 *
252
-	 * @type string The entity item id URI.
253
-	 * @type string|array The entity sameAs URI(s).
254
-	 * @type string $description The entity description.
255
-	 * }
256
-	 *
257
-	 * @param       $string $post_status The post status, default 'draft'.
258
-	 *
259
-	 * @return int|\WP_Error
260
-	 * @throws \Exception
261
-	 */
262
-	private function create_or_update_entity( $entity, $post_status = 'draft' ) {
263
-
264
-		// Get only valid IDs.
265
-		$uris = $this->get_entity_uris( $entity );
266
-
267
-		$post = $this->get_first_matching_entity_by_uri( $uris );
268
-
269
-		$this->log->trace( 'Entity' . ( empty( $post ) ? ' not' : '' ) . " found with the following URIs:\n"
270
-		                   . var_export( $uris, true ) );
271
-
272
-		// Get the labels.
273
-		$labels = $this->get_labels( $entity );
274
-
275
-		if ( empty( $post ) ) {
276
-			$entity_description = array_key_exists( 'description', $entity ) ? $entity['description'] : '';
277
-			// Create the entity if it doesn't exist.
278
-			$post_id = Entity_Store::get_instance()->create( array(
279
-				'labels'      => $labels,
280
-				'description' => $entity_description,
281
-				'same_as'     => $uris,
282
-			), $post_status );
283
-
284
-			// Return the WP_Error if we got one.
285
-			if ( is_wp_error( $post_id ) ) {
286
-				return $post_id;
287
-			}
288
-
289
-			// Add the entity type.
290
-			if ( isset( $entity['mainType'] ) ) {
291
-				wp_set_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
292
-			}
293
-
294
-			if ( isset( $entity['properties'] ) && isset( $entity['properties']['latitude'] ) && isset( $entity['properties']['longitude'] ) ) {
295
-				add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LATITUDE, $entity['properties']['latitude'] );
296
-				add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LONGITUDE, $entity['properties']['longitude'] );
297
-			}
298
-		} else {
299
-			// Update the entity otherwise.
300
-			$post_id = Entity_Store::get_instance()->update( array(
301
-				'ID'      => $post->ID,
302
-				'labels'  => $labels,
303
-				'same_as' => $uris,
304
-			) );
305
-
306
-			// Add the entity type.
307
-			if ( isset( $entity['mainType'] ) ) {
308
-				wp_add_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
309
-			}
310
-
311
-			// see https://github.com/insideout10/wordlift-plugin/issues/1304
312
-			// Set the post status, we need to set that in order to support entities
313
-			// created using rest endpoint on block editor, so that they get published
314
-			// when the post is published.
315
-			// Once the entity is published dont update the post status.
316
-			if ( $post->post_status !== 'publish' ) {
317
-				wp_update_post( array(
318
-					'ID'          => $post->ID,
319
-					'post_status' => $post_status
320
-				) );
321
-			}
322
-		}
323
-
324
-		return $post_id;
325
-	}
326
-
327
-	/**
328
-	 * Get the first matching entity for the provided URI array.
329
-	 *
330
-	 * Entities IDs and sameAs are searched.
331
-	 *
332
-	 * @param array $uris An array of URIs.
333
-	 *
334
-	 * @return \WP_Post|null The entity WP_Post if found or null if not found.
335
-	 */
336
-	private function get_first_matching_entity_by_uri( $uris ) {
337
-
338
-		foreach ( $uris as $uri ) {
339
-
340
-			$content = Wordpress_Content_Service::get_instance()->get_by_entity_id_or_same_as( $uri );
341
-
342
-			if ( ! $content ) {
343
-				continue;
344
-			}
345
-
346
-			$existing_entity = $content->get_bag();
347
-
348
-			if ( is_a( $existing_entity, 'WP_Post' ) ) {
349
-				return $existing_entity;
350
-			}
351
-		}
352
-
353
-		return null;
354
-	}
355
-
356
-	/**
357
-	 * @param $entity
358
-	 *
359
-	 * @return array
360
-	 */
361
-	private function filter_valid_entity_ids( $entity ) {
362
-		$id = $entity['id'];
363
-
364
-		return array_filter( (array) $id, function ( $id ) {
365
-			return preg_match( '|^https?://|', $id );
366
-		} );
367
-	}
368
-
369
-	/**
370
-	 * @param array $entity
371
-	 *
372
-	 * @return array
373
-	 */
374
-	private function get_entity_uris( $entity ) {
375
-		$ids     = $this->filter_valid_entity_ids( $entity );
376
-		$same_as = array_key_exists( 'sameAs', $entity ) ? $entity['sameAs'] : array();
377
-
378
-		return array_merge(
379
-			(array) $ids,
380
-			(array) $same_as
381
-		);
382
-	}
383
-
384
-	private function entity_id_valid( $entity_id ) {
385
-		return preg_match( '#^https?://#i', $entity_id ) === 1;
386
-	}
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
+
92
+        $post_status = $data['post_status'];
93
+        if ( 'auto-draft' === $post_status || 'inherit' === $post_status ) {
94
+            return $data;
95
+        }
96
+
97
+        $this->log->trace( "The following data has been received by `wp_insert_post_data`:\n"
98
+                            . var_export( $data, true ) );
99
+
100
+
101
+        try {
102
+            $entities = $this->parse_content( wp_unslash( $data['post_content'] ) );
103
+
104
+            foreach ( $entities as $entity ) {
105
+
106
+                $entity_id = array_key_exists( 'id', $entity ) ? $entity['id'] : '';
107
+
108
+                if ( ! $this->entity_id_valid( $entity_id ) ) {
109
+                    continue;
110
+                }
111
+
112
+                $entity_uris = $this->get_entity_uris( $entity );
113
+
114
+                if ( $this->get_first_matching_entity_by_uri( $entity_uris ) === null &&
115
+                     Post_Entities_Validator::is_local_entity_uri_exist( Wordlift_Entity_Uri_Service::get_instance(), $entity_uris ) ) {
116
+                    // Skip the entity
117
+                    continue;
118
+                }
119
+
120
+                // If 'entity auto publish' is false, we set the status to `draft` by default.
121
+                $post_status = apply_filters( 'wl_feature__enable__entity-auto-publish', true )
122
+                    ? $data['post_status'] : 'draft';
123
+                $this->create_or_update_entity( $entity, $post_status );
124
+
125
+            }
126
+
127
+        } catch ( \Exception $e ) {
128
+            $this->log->error( $e->getMessage() );
129
+        }
130
+
131
+
132
+        return $data;
133
+    }
134
+
135
+    /**
136
+     * Parse the post content to find the `wordlift/classification` block and return the entities' data.
137
+     *
138
+     * @param string $post_content The post content.
139
+     *
140
+     * @return array An array of entities' structures.
141
+     * @throws \Exception
142
+     */
143
+    private function parse_content( $post_content ) {
144
+
145
+        $all_blocks = parse_blocks( $post_content );
146
+        $this->log->trace( "The following blocks have been parsed while in `wp_insert_post`:\n"
147
+                            . var_export( $all_blocks, true ) );
148
+
149
+        $blocks = array_filter( $all_blocks, function ( $item ) {
150
+            return ! empty( $item['blockName'] ) && 'wordlift/classification' === $item['blockName'];
151
+        } );
152
+
153
+        // Bail out if the blocks' array is empty.
154
+        if ( empty( $blocks ) ) {
155
+            return array();
156
+        }
157
+
158
+        $block = current( $blocks );
159
+        $this->log->trace( "The following block has been found while in `wp_insert_post`:\n"
160
+                            . var_export( $block, true ) );
161
+
162
+        // Bail out if the entities array is empty.
163
+        if ( empty( $block['attrs'] ) && empty( $block['attrs']['entities'] ) ) {
164
+            return array();
165
+        }
166
+
167
+        return $block['attrs']['entities'];
168
+    }
169
+
170
+    /**
171
+     * Collect entity labels from the entity array.
172
+     *
173
+     * This function expects an array with the following keys:
174
+     *
175
+     * array(
176
+     *   'label'       => ...,
177
+     *   'synonyms'    => array( ... ),
178
+     *   'annotations' => array(
179
+     *     ...id...      => array( text => ... ),
180
+     *   ),
181
+     *   'occurrences' => array( ... ),
182
+     * )
183
+     *
184
+     * and it is going to output an array with all the labels, keeping the `label` at first position:
185
+     *
186
+     * array(
187
+     *   ...label...,
188
+     *   ...synonyms...,
189
+     *   ...texts...,
190
+     * )
191
+     *
192
+     * This function is going to collect the label from the `label` property, from the `synonyms` property and from
193
+     * `annotations` property. Since the `annotations` property contains all the annotations including those that
194
+     * haven't been selected, this function is going to only get the `text` for the annotations property listed in
195
+     * `occurrences`.
196
+     *
197
+     * @param array $entity {
198
+     *  The entity data.
199
+     *
200
+     * @type string $label The entity label.
201
+     * @type array $synonyms The entity synonyms.
202
+     * @type array $occurrences The selected occurrences.
203
+     * @type array $annotations The annotations.
204
+     * }
205
+     *
206
+     * @return array An array of labels.
207
+     */
208
+    public function get_labels( $entity ) {
209
+
210
+        $args = wp_parse_args( $entity, array(
211
+            'label'       => array(),
212
+            'synonyms'    => array(),
213
+            'annotations' => array(),
214
+            'occurrences' => array(),
215
+        ) );
216
+
217
+        // We gather all the labels, occurrences texts and synonyms into one array.
218
+        $initial = array_merge(
219
+            (array) $args['label'],
220
+            (array) $args['synonyms']
221
+        );
222
+
223
+        $annotations = $args['annotations'];
224
+
225
+        return array_reduce( $args['occurrences'], function ( $carry, $item ) use ( $annotations ) {
226
+
227
+            // Bail out if occurrences->$item->text isn't set or its contents are already
228
+            // in `$carry`.
229
+            if ( ! isset( $annotations[ $item ]['text'] )
230
+                 || in_array( $annotations[ $item ]['text'], $carry ) ) {
231
+                return $carry;
232
+            }
233
+
234
+            // Push the label.
235
+            $carry[] = $annotations[ $item ]['text'];
236
+
237
+            return $carry;
238
+        }, $initial );
239
+    }
240
+
241
+    /**
242
+     * Create or update the entity.
243
+     *
244
+     * An entity lookup is performed on the local vocabulary using the `id` and `sameAs` URIs. If an entity is found
245
+     * the {@link Entity_Store} update function is called to update the `labels` and the `sameAs` values.
246
+     *
247
+     * If an entity is not found the {@link Entity_Store} create function is called to create a new entity.
248
+     *
249
+     * @param array $entity {
250
+     * The entity parameters.
251
+     *
252
+     * @type string The entity item id URI.
253
+     * @type string|array The entity sameAs URI(s).
254
+     * @type string $description The entity description.
255
+     * }
256
+     *
257
+     * @param       $string $post_status The post status, default 'draft'.
258
+     *
259
+     * @return int|\WP_Error
260
+     * @throws \Exception
261
+     */
262
+    private function create_or_update_entity( $entity, $post_status = 'draft' ) {
263
+
264
+        // Get only valid IDs.
265
+        $uris = $this->get_entity_uris( $entity );
266
+
267
+        $post = $this->get_first_matching_entity_by_uri( $uris );
268
+
269
+        $this->log->trace( 'Entity' . ( empty( $post ) ? ' not' : '' ) . " found with the following URIs:\n"
270
+                            . var_export( $uris, true ) );
271
+
272
+        // Get the labels.
273
+        $labels = $this->get_labels( $entity );
274
+
275
+        if ( empty( $post ) ) {
276
+            $entity_description = array_key_exists( 'description', $entity ) ? $entity['description'] : '';
277
+            // Create the entity if it doesn't exist.
278
+            $post_id = Entity_Store::get_instance()->create( array(
279
+                'labels'      => $labels,
280
+                'description' => $entity_description,
281
+                'same_as'     => $uris,
282
+            ), $post_status );
283
+
284
+            // Return the WP_Error if we got one.
285
+            if ( is_wp_error( $post_id ) ) {
286
+                return $post_id;
287
+            }
288
+
289
+            // Add the entity type.
290
+            if ( isset( $entity['mainType'] ) ) {
291
+                wp_set_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
292
+            }
293
+
294
+            if ( isset( $entity['properties'] ) && isset( $entity['properties']['latitude'] ) && isset( $entity['properties']['longitude'] ) ) {
295
+                add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LATITUDE, $entity['properties']['latitude'] );
296
+                add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LONGITUDE, $entity['properties']['longitude'] );
297
+            }
298
+        } else {
299
+            // Update the entity otherwise.
300
+            $post_id = Entity_Store::get_instance()->update( array(
301
+                'ID'      => $post->ID,
302
+                'labels'  => $labels,
303
+                'same_as' => $uris,
304
+            ) );
305
+
306
+            // Add the entity type.
307
+            if ( isset( $entity['mainType'] ) ) {
308
+                wp_add_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
309
+            }
310
+
311
+            // see https://github.com/insideout10/wordlift-plugin/issues/1304
312
+            // Set the post status, we need to set that in order to support entities
313
+            // created using rest endpoint on block editor, so that they get published
314
+            // when the post is published.
315
+            // Once the entity is published dont update the post status.
316
+            if ( $post->post_status !== 'publish' ) {
317
+                wp_update_post( array(
318
+                    'ID'          => $post->ID,
319
+                    'post_status' => $post_status
320
+                ) );
321
+            }
322
+        }
323
+
324
+        return $post_id;
325
+    }
326
+
327
+    /**
328
+     * Get the first matching entity for the provided URI array.
329
+     *
330
+     * Entities IDs and sameAs are searched.
331
+     *
332
+     * @param array $uris An array of URIs.
333
+     *
334
+     * @return \WP_Post|null The entity WP_Post if found or null if not found.
335
+     */
336
+    private function get_first_matching_entity_by_uri( $uris ) {
337
+
338
+        foreach ( $uris as $uri ) {
339
+
340
+            $content = Wordpress_Content_Service::get_instance()->get_by_entity_id_or_same_as( $uri );
341
+
342
+            if ( ! $content ) {
343
+                continue;
344
+            }
345
+
346
+            $existing_entity = $content->get_bag();
347
+
348
+            if ( is_a( $existing_entity, 'WP_Post' ) ) {
349
+                return $existing_entity;
350
+            }
351
+        }
352
+
353
+        return null;
354
+    }
355
+
356
+    /**
357
+     * @param $entity
358
+     *
359
+     * @return array
360
+     */
361
+    private function filter_valid_entity_ids( $entity ) {
362
+        $id = $entity['id'];
363
+
364
+        return array_filter( (array) $id, function ( $id ) {
365
+            return preg_match( '|^https?://|', $id );
366
+        } );
367
+    }
368
+
369
+    /**
370
+     * @param array $entity
371
+     *
372
+     * @return array
373
+     */
374
+    private function get_entity_uris( $entity ) {
375
+        $ids     = $this->filter_valid_entity_ids( $entity );
376
+        $same_as = array_key_exists( 'sameAs', $entity ) ? $entity['sameAs'] : array();
377
+
378
+        return array_merge(
379
+            (array) $ids,
380
+            (array) $same_as
381
+        );
382
+    }
383
+
384
+    private function entity_id_valid( $entity_id ) {
385
+        return preg_match( '#^https?://#i', $entity_id ) === 1;
386
+    }
387 387
 
388 388
 }
Please login to merge, or discard this patch.
Spacing   +77 added lines, -77 removed lines patch added patch discarded remove patch
@@ -31,14 +31,14 @@  discard block
 block discarded – undo
31 31
 	public function __construct() {
32 32
 
33 33
 		// Bail out if block editor's functions aren't available.
34
-		if ( ! function_exists( 'register_block_type' ) || ! function_exists( 'parse_blocks' ) ) {
34
+		if ( ! function_exists('register_block_type') || ! function_exists('parse_blocks')) {
35 35
 			return;
36 36
 		}
37 37
 
38
-		$this->log = \Wordlift_Log_Service::get_logger( get_class() );
38
+		$this->log = \Wordlift_Log_Service::get_logger(get_class());
39 39
 
40
-		add_action( 'init', array( $this, 'init' ) );
41
-		add_filter( 'wp_insert_post_data', array( $this, 'wp_insert_post_data' ), 10, 2 );
40
+		add_action('init', array($this, 'init'));
41
+		add_filter('wp_insert_post_data', array($this, 'wp_insert_post_data'), 10, 2);
42 42
 
43 43
 	}
44 44
 
@@ -48,12 +48,12 @@  discard block
 block discarded – undo
48 48
 	 */
49 49
 	public function init() {
50 50
 
51
-		register_block_type( 'wordlift/classification', array(
51
+		register_block_type('wordlift/classification', array(
52 52
 			'editor_script' => 'wl-block-editor',
53 53
 			'attributes'    => array(
54
-				'entities' => array( 'type' => 'array' ),
54
+				'entities' => array('type' => 'array'),
55 55
 			),
56
-		) );
56
+		));
57 57
 
58 58
 	}
59 59
 
@@ -87,45 +87,45 @@  discard block
 block discarded – undo
87 87
 	 *
88 88
 	 * @return array The data array.
89 89
 	 */
90
-	public function wp_insert_post_data( $data, $postarr ) {
90
+	public function wp_insert_post_data($data, $postarr) {
91 91
 
92 92
 		$post_status = $data['post_status'];
93
-		if ( 'auto-draft' === $post_status || 'inherit' === $post_status ) {
93
+		if ('auto-draft' === $post_status || 'inherit' === $post_status) {
94 94
 			return $data;
95 95
 		}
96 96
 
97
-		$this->log->trace( "The following data has been received by `wp_insert_post_data`:\n"
98
-		                   . var_export( $data, true ) );
97
+		$this->log->trace("The following data has been received by `wp_insert_post_data`:\n"
98
+		                   . var_export($data, true));
99 99
 
100 100
 
101 101
 		try {
102
-			$entities = $this->parse_content( wp_unslash( $data['post_content'] ) );
102
+			$entities = $this->parse_content(wp_unslash($data['post_content']));
103 103
 
104
-			foreach ( $entities as $entity ) {
104
+			foreach ($entities as $entity) {
105 105
 
106
-				$entity_id = array_key_exists( 'id', $entity ) ? $entity['id'] : '';
106
+				$entity_id = array_key_exists('id', $entity) ? $entity['id'] : '';
107 107
 
108
-				if ( ! $this->entity_id_valid( $entity_id ) ) {
108
+				if ( ! $this->entity_id_valid($entity_id)) {
109 109
 					continue;
110 110
 				}
111 111
 
112
-				$entity_uris = $this->get_entity_uris( $entity );
112
+				$entity_uris = $this->get_entity_uris($entity);
113 113
 
114
-				if ( $this->get_first_matching_entity_by_uri( $entity_uris ) === null &&
115
-				     Post_Entities_Validator::is_local_entity_uri_exist( Wordlift_Entity_Uri_Service::get_instance(), $entity_uris ) ) {
114
+				if ($this->get_first_matching_entity_by_uri($entity_uris) === null &&
115
+				     Post_Entities_Validator::is_local_entity_uri_exist(Wordlift_Entity_Uri_Service::get_instance(), $entity_uris)) {
116 116
 					// Skip the entity
117 117
 					continue;
118 118
 				}
119 119
 
120 120
 				// If 'entity auto publish' is false, we set the status to `draft` by default.
121
-				$post_status = apply_filters( 'wl_feature__enable__entity-auto-publish', true )
121
+				$post_status = apply_filters('wl_feature__enable__entity-auto-publish', true)
122 122
 					? $data['post_status'] : 'draft';
123
-				$this->create_or_update_entity( $entity, $post_status );
123
+				$this->create_or_update_entity($entity, $post_status);
124 124
 
125 125
 			}
126 126
 
127
-		} catch ( \Exception $e ) {
128
-			$this->log->error( $e->getMessage() );
127
+		} catch (\Exception $e) {
128
+			$this->log->error($e->getMessage());
129 129
 		}
130 130
 
131 131
 
@@ -140,27 +140,27 @@  discard block
 block discarded – undo
140 140
 	 * @return array An array of entities' structures.
141 141
 	 * @throws \Exception
142 142
 	 */
143
-	private function parse_content( $post_content ) {
143
+	private function parse_content($post_content) {
144 144
 
145
-		$all_blocks = parse_blocks( $post_content );
146
-		$this->log->trace( "The following blocks have been parsed while in `wp_insert_post`:\n"
147
-		                   . var_export( $all_blocks, true ) );
145
+		$all_blocks = parse_blocks($post_content);
146
+		$this->log->trace("The following blocks have been parsed while in `wp_insert_post`:\n"
147
+		                   . var_export($all_blocks, true));
148 148
 
149
-		$blocks = array_filter( $all_blocks, function ( $item ) {
150
-			return ! empty( $item['blockName'] ) && 'wordlift/classification' === $item['blockName'];
149
+		$blocks = array_filter($all_blocks, function($item) {
150
+			return ! empty($item['blockName']) && 'wordlift/classification' === $item['blockName'];
151 151
 		} );
152 152
 
153 153
 		// Bail out if the blocks' array is empty.
154
-		if ( empty( $blocks ) ) {
154
+		if (empty($blocks)) {
155 155
 			return array();
156 156
 		}
157 157
 
158
-		$block = current( $blocks );
159
-		$this->log->trace( "The following block has been found while in `wp_insert_post`:\n"
160
-		                   . var_export( $block, true ) );
158
+		$block = current($blocks);
159
+		$this->log->trace("The following block has been found while in `wp_insert_post`:\n"
160
+		                   . var_export($block, true));
161 161
 
162 162
 		// Bail out if the entities array is empty.
163
-		if ( empty( $block['attrs'] ) && empty( $block['attrs']['entities'] ) ) {
163
+		if (empty($block['attrs']) && empty($block['attrs']['entities'])) {
164 164
 			return array();
165 165
 		}
166 166
 
@@ -205,14 +205,14 @@  discard block
 block discarded – undo
205 205
 	 *
206 206
 	 * @return array An array of labels.
207 207
 	 */
208
-	public function get_labels( $entity ) {
208
+	public function get_labels($entity) {
209 209
 
210
-		$args = wp_parse_args( $entity, array(
210
+		$args = wp_parse_args($entity, array(
211 211
 			'label'       => array(),
212 212
 			'synonyms'    => array(),
213 213
 			'annotations' => array(),
214 214
 			'occurrences' => array(),
215
-		) );
215
+		));
216 216
 
217 217
 		// We gather all the labels, occurrences texts and synonyms into one array.
218 218
 		$initial = array_merge(
@@ -222,20 +222,20 @@  discard block
 block discarded – undo
222 222
 
223 223
 		$annotations = $args['annotations'];
224 224
 
225
-		return array_reduce( $args['occurrences'], function ( $carry, $item ) use ( $annotations ) {
225
+		return array_reduce($args['occurrences'], function($carry, $item) use ($annotations) {
226 226
 
227 227
 			// Bail out if occurrences->$item->text isn't set or its contents are already
228 228
 			// in `$carry`.
229
-			if ( ! isset( $annotations[ $item ]['text'] )
230
-			     || in_array( $annotations[ $item ]['text'], $carry ) ) {
229
+			if ( ! isset($annotations[$item]['text'])
230
+			     || in_array($annotations[$item]['text'], $carry)) {
231 231
 				return $carry;
232 232
 			}
233 233
 
234 234
 			// Push the label.
235
-			$carry[] = $annotations[ $item ]['text'];
235
+			$carry[] = $annotations[$item]['text'];
236 236
 
237 237
 			return $carry;
238
-		}, $initial );
238
+		}, $initial);
239 239
 	}
240 240
 
241 241
 	/**
@@ -259,53 +259,53 @@  discard block
 block discarded – undo
259 259
 	 * @return int|\WP_Error
260 260
 	 * @throws \Exception
261 261
 	 */
262
-	private function create_or_update_entity( $entity, $post_status = 'draft' ) {
262
+	private function create_or_update_entity($entity, $post_status = 'draft') {
263 263
 
264 264
 		// Get only valid IDs.
265
-		$uris = $this->get_entity_uris( $entity );
265
+		$uris = $this->get_entity_uris($entity);
266 266
 
267
-		$post = $this->get_first_matching_entity_by_uri( $uris );
267
+		$post = $this->get_first_matching_entity_by_uri($uris);
268 268
 
269
-		$this->log->trace( 'Entity' . ( empty( $post ) ? ' not' : '' ) . " found with the following URIs:\n"
270
-		                   . var_export( $uris, true ) );
269
+		$this->log->trace('Entity'.(empty($post) ? ' not' : '')." found with the following URIs:\n"
270
+		                   . var_export($uris, true));
271 271
 
272 272
 		// Get the labels.
273
-		$labels = $this->get_labels( $entity );
273
+		$labels = $this->get_labels($entity);
274 274
 
275
-		if ( empty( $post ) ) {
276
-			$entity_description = array_key_exists( 'description', $entity ) ? $entity['description'] : '';
275
+		if (empty($post)) {
276
+			$entity_description = array_key_exists('description', $entity) ? $entity['description'] : '';
277 277
 			// Create the entity if it doesn't exist.
278
-			$post_id = Entity_Store::get_instance()->create( array(
278
+			$post_id = Entity_Store::get_instance()->create(array(
279 279
 				'labels'      => $labels,
280 280
 				'description' => $entity_description,
281 281
 				'same_as'     => $uris,
282
-			), $post_status );
282
+			), $post_status);
283 283
 
284 284
 			// Return the WP_Error if we got one.
285
-			if ( is_wp_error( $post_id ) ) {
285
+			if (is_wp_error($post_id)) {
286 286
 				return $post_id;
287 287
 			}
288 288
 
289 289
 			// Add the entity type.
290
-			if ( isset( $entity['mainType'] ) ) {
291
-				wp_set_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
290
+			if (isset($entity['mainType'])) {
291
+				wp_set_object_terms($post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME);
292 292
 			}
293 293
 
294
-			if ( isset( $entity['properties'] ) && isset( $entity['properties']['latitude'] ) && isset( $entity['properties']['longitude'] ) ) {
295
-				add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LATITUDE, $entity['properties']['latitude'] );
296
-				add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LONGITUDE, $entity['properties']['longitude'] );
294
+			if (isset($entity['properties']) && isset($entity['properties']['latitude']) && isset($entity['properties']['longitude'])) {
295
+				add_post_meta($post_id, \Wordlift_Schema_Service::FIELD_GEO_LATITUDE, $entity['properties']['latitude']);
296
+				add_post_meta($post_id, \Wordlift_Schema_Service::FIELD_GEO_LONGITUDE, $entity['properties']['longitude']);
297 297
 			}
298 298
 		} else {
299 299
 			// Update the entity otherwise.
300
-			$post_id = Entity_Store::get_instance()->update( array(
300
+			$post_id = Entity_Store::get_instance()->update(array(
301 301
 				'ID'      => $post->ID,
302 302
 				'labels'  => $labels,
303 303
 				'same_as' => $uris,
304
-			) );
304
+			));
305 305
 
306 306
 			// Add the entity type.
307
-			if ( isset( $entity['mainType'] ) ) {
308
-				wp_add_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
307
+			if (isset($entity['mainType'])) {
308
+				wp_add_object_terms($post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME);
309 309
 			}
310 310
 
311 311
 			// see https://github.com/insideout10/wordlift-plugin/issues/1304
@@ -313,11 +313,11 @@  discard block
 block discarded – undo
313 313
 			// created using rest endpoint on block editor, so that they get published
314 314
 			// when the post is published.
315 315
 			// Once the entity is published dont update the post status.
316
-			if ( $post->post_status !== 'publish' ) {
317
-				wp_update_post( array(
316
+			if ($post->post_status !== 'publish') {
317
+				wp_update_post(array(
318 318
 					'ID'          => $post->ID,
319 319
 					'post_status' => $post_status
320
-				) );
320
+				));
321 321
 			}
322 322
 		}
323 323
 
@@ -333,19 +333,19 @@  discard block
 block discarded – undo
333 333
 	 *
334 334
 	 * @return \WP_Post|null The entity WP_Post if found or null if not found.
335 335
 	 */
336
-	private function get_first_matching_entity_by_uri( $uris ) {
336
+	private function get_first_matching_entity_by_uri($uris) {
337 337
 
338
-		foreach ( $uris as $uri ) {
338
+		foreach ($uris as $uri) {
339 339
 
340
-			$content = Wordpress_Content_Service::get_instance()->get_by_entity_id_or_same_as( $uri );
340
+			$content = Wordpress_Content_Service::get_instance()->get_by_entity_id_or_same_as($uri);
341 341
 
342
-			if ( ! $content ) {
342
+			if ( ! $content) {
343 343
 				continue;
344 344
 			}
345 345
 
346 346
 			$existing_entity = $content->get_bag();
347 347
 
348
-			if ( is_a( $existing_entity, 'WP_Post' ) ) {
348
+			if (is_a($existing_entity, 'WP_Post')) {
349 349
 				return $existing_entity;
350 350
 			}
351 351
 		}
@@ -358,11 +358,11 @@  discard block
 block discarded – undo
358 358
 	 *
359 359
 	 * @return array
360 360
 	 */
361
-	private function filter_valid_entity_ids( $entity ) {
361
+	private function filter_valid_entity_ids($entity) {
362 362
 		$id = $entity['id'];
363 363
 
364
-		return array_filter( (array) $id, function ( $id ) {
365
-			return preg_match( '|^https?://|', $id );
364
+		return array_filter((array) $id, function($id) {
365
+			return preg_match('|^https?://|', $id);
366 366
 		} );
367 367
 	}
368 368
 
@@ -371,9 +371,9 @@  discard block
 block discarded – undo
371 371
 	 *
372 372
 	 * @return array
373 373
 	 */
374
-	private function get_entity_uris( $entity ) {
375
-		$ids     = $this->filter_valid_entity_ids( $entity );
376
-		$same_as = array_key_exists( 'sameAs', $entity ) ? $entity['sameAs'] : array();
374
+	private function get_entity_uris($entity) {
375
+		$ids     = $this->filter_valid_entity_ids($entity);
376
+		$same_as = array_key_exists('sameAs', $entity) ? $entity['sameAs'] : array();
377 377
 
378 378
 		return array_merge(
379 379
 			(array) $ids,
@@ -381,8 +381,8 @@  discard block
 block discarded – undo
381 381
 		);
382 382
 	}
383 383
 
384
-	private function entity_id_valid( $entity_id ) {
385
-		return preg_match( '#^https?://#i', $entity_id ) === 1;
384
+	private function entity_id_valid($entity_id) {
385
+		return preg_match('#^https?://#i', $entity_id) === 1;
386 386
 	}
387 387
 
388 388
 }
Please login to merge, or discard this patch.
src/wordlift/vocabulary/class-analysis-service.php 2 patches
Indentation   +142 added lines, -142 removed lines patch added patch discarded remove patch
@@ -13,184 +13,184 @@
 block discarded – undo
13 13
  */
14 14
 class Analysis_Service {
15 15
 
16
-	/**
17
-	 * @var Default_Api_Service
18
-	 */
19
-	private $api_service;
20
-	/**
21
-	 * @var Cache
22
-	 */
23
-	private $cache_service;
24
-	/**
25
-	 * @var \Wordlift_Log_Service
26
-	 */
27
-	private $log;
16
+    /**
17
+     * @var Default_Api_Service
18
+     */
19
+    private $api_service;
20
+    /**
21
+     * @var Cache
22
+     */
23
+    private $cache_service;
24
+    /**
25
+     * @var \Wordlift_Log_Service
26
+     */
27
+    private $log;
28 28
 
29 29
 
30
-	/**
31
-	 * Tag_Rest_Endpoint constructor.
32
-	 *
33
-	 * @param Default_Api_Service $api_service
34
-	 * @param Cache $cache_service
35
-	 */
36
-	public function __construct( $api_service, $cache_service ) {
30
+    /**
31
+     * Tag_Rest_Endpoint constructor.
32
+     *
33
+     * @param Default_Api_Service $api_service
34
+     * @param Cache $cache_service
35
+     */
36
+    public function __construct( $api_service, $cache_service ) {
37 37
 
38
-		$this->api_service = $api_service;
38
+        $this->api_service = $api_service;
39 39
 
40
-		$this->cache_service = $cache_service;
40
+        $this->cache_service = $cache_service;
41 41
 
42
-		$this->log = \Wordlift_Log_Service::get_logger( get_class() );
42
+        $this->log = \Wordlift_Log_Service::get_logger( get_class() );
43 43
 
44
-	}
44
+    }
45 45
 
46 46
 
47
-	/**
48
-	 * Check if entities are in cache, if not return the results from
49
-	 * cache service.
50
-	 *
51
-	 * @param $tag \WP_Term
52
-	 */
53
-	public function get_entities( $tag ) {
47
+    /**
48
+     * Check if entities are in cache, if not return the results from
49
+     * cache service.
50
+     *
51
+     * @param $tag \WP_Term
52
+     */
53
+    public function get_entities( $tag ) {
54 54
 
55
-		$cache_key    = $tag->term_id;
56
-		$cache_result = $this->cache_service->get( $cache_key );
57
-		if ( $cache_result !== false ) {
58
-			return $cache_result;
59
-		}
55
+        $cache_key    = $tag->term_id;
56
+        $cache_result = $this->cache_service->get( $cache_key );
57
+        if ( $cache_result !== false ) {
58
+            return $cache_result;
59
+        }
60 60
 
61
-		// send the request.
62
-		$tag_name = $tag->name;
61
+        // send the request.
62
+        $tag_name = $tag->name;
63 63
 
64
-		$entities = $this->get_entities_by_search_query( $tag_name );
64
+        $entities = $this->get_entities_by_search_query( $tag_name );
65 65
 
66
-		if ( ! $entities ) {
67
-			return false;
68
-		}
69
-
70
-		$this->cache_service->put( $cache_key, $entities );
71
-
72
-		return $entities;
73
-
74
-	}
75
-
76
-
77
-	/**
78
-	 * @param $entity_url string
79
-	 * Formats the entity url from https://foo.com/some/path to
80
-	 * https/foo.com/some/path
81
-	 *
82
-	 * @return bool|string
83
-	 */
84
-	public static function format_entity_url( $entity_url ) {
85
-		$result = parse_url( $entity_url );
86
-		if ( ! $result ) {
87
-			return false;
88
-		}
89
-		if ( ! array_key_exists( 'scheme', $result )
90
-		     || ! array_key_exists( 'host', $result )
91
-		     || ! array_key_exists( 'path', $result ) ) {
92
-			return false;
93
-		}
66
+        if ( ! $entities ) {
67
+            return false;
68
+        }
69
+
70
+        $this->cache_service->put( $cache_key, $entities );
71
+
72
+        return $entities;
73
+
74
+    }
75
+
76
+
77
+    /**
78
+     * @param $entity_url string
79
+     * Formats the entity url from https://foo.com/some/path to
80
+     * https/foo.com/some/path
81
+     *
82
+     * @return bool|string
83
+     */
84
+    public static function format_entity_url( $entity_url ) {
85
+        $result = parse_url( $entity_url );
86
+        if ( ! $result ) {
87
+            return false;
88
+        }
89
+        if ( ! array_key_exists( 'scheme', $result )
90
+             || ! array_key_exists( 'host', $result )
91
+             || ! array_key_exists( 'path', $result ) ) {
92
+            return false;
93
+        }
94 94
 
95
-		return $result['scheme'] . "/" . $result['host'] . $result['path'];
96
-	}
95
+        return $result['scheme'] . "/" . $result['host'] . $result['path'];
96
+    }
97 97
 
98
-	private function get_meta( $entity_url ) {
98
+    private function get_meta( $entity_url ) {
99 99
 
100 100
 
101
-		$cache_results = $this->cache_service->get( $entity_url );
101
+        $cache_results = $this->cache_service->get( $entity_url );
102 102
 
103
-		if ( $cache_results !== false ) {
104
-			return $cache_results;
105
-		}
103
+        if ( $cache_results !== false ) {
104
+            return $cache_results;
105
+        }
106 106
 
107
-		$formatted_url = self::format_entity_url( $entity_url );
107
+        $formatted_url = self::format_entity_url( $entity_url );
108 108
 
109
-		if ( ! $formatted_url ) {
110
-			return array();
111
-		}
109
+        if ( ! $formatted_url ) {
110
+            return array();
111
+        }
112 112
 
113
-		$meta_url = 'https://api.wordlift.io/id/' . $formatted_url;
113
+        $meta_url = 'https://api.wordlift.io/id/' . $formatted_url;
114 114
 
115
-		$response = wp_remote_get( $meta_url );
115
+        $response = wp_remote_get( $meta_url );
116 116
 
117
-		if ( is_wp_error( $response )
118
-		     || ! isset( $response['response']['code'] )
119
-		     || 2 !== (int) $response['response']['code'] / 100 ) {
120
-			return false;
121
-		}
117
+        if ( is_wp_error( $response )
118
+             || ! isset( $response['response']['code'] )
119
+             || 2 !== (int) $response['response']['code'] / 100 ) {
120
+            return false;
121
+        }
122 122
 
123
-		$this->log->debug( "Requesting entity data for url :" . $meta_url );
124
-		$this->log->debug( "Got entity meta data as : " );
125
-		$this->log->debug( var_export( $response, true ) );
126
-		if ( ! is_wp_error( $response ) ) {
127
-			$meta = json_decode( wp_remote_retrieve_body( $response ), true );
128
-			$this->log->debug( "Saved entity data to meta :" );
129
-			$this->log->debug( var_export( $meta, true ) );
130
-			$this->cache_service->put( $entity_url, $meta );
123
+        $this->log->debug( "Requesting entity data for url :" . $meta_url );
124
+        $this->log->debug( "Got entity meta data as : " );
125
+        $this->log->debug( var_export( $response, true ) );
126
+        if ( ! is_wp_error( $response ) ) {
127
+            $meta = json_decode( wp_remote_retrieve_body( $response ), true );
128
+            $this->log->debug( "Saved entity data to meta :" );
129
+            $this->log->debug( var_export( $meta, true ) );
130
+            $this->cache_service->put( $entity_url, $meta );
131 131
 
132
-			return $meta;
133
-		}
132
+            return $meta;
133
+        }
134 134
 
135 135
 
136
-		return array();
136
+        return array();
137 137
 
138
-	}
138
+    }
139 139
 
140
-	private function get_meta_for_entities( $entities ) {
140
+    private function get_meta_for_entities( $entities ) {
141 141
 
142
-		$filtered_entities = array();
143
-		foreach ( $entities as $entity ) {
144
-			$entity['meta'] = array();
145
-			$meta           = $this->get_meta( $entity['entityId'] );
146
-			if ( $meta ) {
147
-				$meta                = Default_Entity_List::compact_jsonld( $meta );
148
-				$entity['meta']      = $meta;
149
-				$filtered_entities[] = $entity;
150
-			}
151
-		}
152
-		$this->log->debug( "Returning filtered entities as" );
153
-		$this->log->debug( var_export( $filtered_entities, true ) );
142
+        $filtered_entities = array();
143
+        foreach ( $entities as $entity ) {
144
+            $entity['meta'] = array();
145
+            $meta           = $this->get_meta( $entity['entityId'] );
146
+            if ( $meta ) {
147
+                $meta                = Default_Entity_List::compact_jsonld( $meta );
148
+                $entity['meta']      = $meta;
149
+                $filtered_entities[] = $entity;
150
+            }
151
+        }
152
+        $this->log->debug( "Returning filtered entities as" );
153
+        $this->log->debug( var_export( $filtered_entities, true ) );
154 154
 
155
-		return $filtered_entities;
155
+        return $filtered_entities;
156 156
 
157
-	}
157
+    }
158 158
 
159
-	/**
160
-	 * @param $tag_name
161
-	 *
162
-	 * @return array
163
-	 */
164
-	public function get_entities_by_search_query( $tag_name ) {
165
-		$response = $this->api_service->request(
166
-			'POST',
167
-			"/analysis/single",
168
-			array( 'Content-Type' => 'application/json' ),
169
-			wp_json_encode( array(
170
-				"content"         => $tag_name,
171
-				"contentType"     => "text/plain",
172
-				"version"         => "1.0.0",
173
-				"contentLanguage" => "en",
174
-				"scope"           => "all",
175
-			) )
176
-		);
177
-
178
-
179
-		if ( ! $response->is_success() ) {
180
-			return false;
181
-		}
182
-
183
-		$response = json_decode( $response->get_body(), true );
159
+    /**
160
+     * @param $tag_name
161
+     *
162
+     * @return array
163
+     */
164
+    public function get_entities_by_search_query( $tag_name ) {
165
+        $response = $this->api_service->request(
166
+            'POST',
167
+            "/analysis/single",
168
+            array( 'Content-Type' => 'application/json' ),
169
+            wp_json_encode( array(
170
+                "content"         => $tag_name,
171
+                "contentType"     => "text/plain",
172
+                "version"         => "1.0.0",
173
+                "contentLanguage" => "en",
174
+                "scope"           => "all",
175
+            ) )
176
+        );
177
+
178
+
179
+        if ( ! $response->is_success() ) {
180
+            return false;
181
+        }
182
+
183
+        $response = json_decode( $response->get_body(), true );
184 184
 
185
-		if ( ! array_key_exists( 'entities', $response ) ) {
186
-			return false;
187
-		}
185
+        if ( ! array_key_exists( 'entities', $response ) ) {
186
+            return false;
187
+        }
188 188
 
189 189
 
190
-		$entities = $this->get_meta_for_entities( $response['entities'] );
190
+        $entities = $this->get_meta_for_entities( $response['entities'] );
191 191
 
192
-		return $entities;
193
-	}
192
+        return $entities;
193
+    }
194 194
 
195 195
 
196 196
 }
Please login to merge, or discard this patch.
Spacing   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -33,13 +33,13 @@  discard block
 block discarded – undo
33 33
 	 * @param Default_Api_Service $api_service
34 34
 	 * @param Cache $cache_service
35 35
 	 */
36
-	public function __construct( $api_service, $cache_service ) {
36
+	public function __construct($api_service, $cache_service) {
37 37
 
38 38
 		$this->api_service = $api_service;
39 39
 
40 40
 		$this->cache_service = $cache_service;
41 41
 
42
-		$this->log = \Wordlift_Log_Service::get_logger( get_class() );
42
+		$this->log = \Wordlift_Log_Service::get_logger(get_class());
43 43
 
44 44
 	}
45 45
 
@@ -50,24 +50,24 @@  discard block
 block discarded – undo
50 50
 	 *
51 51
 	 * @param $tag \WP_Term
52 52
 	 */
53
-	public function get_entities( $tag ) {
53
+	public function get_entities($tag) {
54 54
 
55 55
 		$cache_key    = $tag->term_id;
56
-		$cache_result = $this->cache_service->get( $cache_key );
57
-		if ( $cache_result !== false ) {
56
+		$cache_result = $this->cache_service->get($cache_key);
57
+		if ($cache_result !== false) {
58 58
 			return $cache_result;
59 59
 		}
60 60
 
61 61
 		// send the request.
62 62
 		$tag_name = $tag->name;
63 63
 
64
-		$entities = $this->get_entities_by_search_query( $tag_name );
64
+		$entities = $this->get_entities_by_search_query($tag_name);
65 65
 
66
-		if ( ! $entities ) {
66
+		if ( ! $entities) {
67 67
 			return false;
68 68
 		}
69 69
 
70
-		$this->cache_service->put( $cache_key, $entities );
70
+		$this->cache_service->put($cache_key, $entities);
71 71
 
72 72
 		return $entities;
73 73
 
@@ -81,53 +81,53 @@  discard block
 block discarded – undo
81 81
 	 *
82 82
 	 * @return bool|string
83 83
 	 */
84
-	public static function format_entity_url( $entity_url ) {
85
-		$result = parse_url( $entity_url );
86
-		if ( ! $result ) {
84
+	public static function format_entity_url($entity_url) {
85
+		$result = parse_url($entity_url);
86
+		if ( ! $result) {
87 87
 			return false;
88 88
 		}
89
-		if ( ! array_key_exists( 'scheme', $result )
90
-		     || ! array_key_exists( 'host', $result )
91
-		     || ! array_key_exists( 'path', $result ) ) {
89
+		if ( ! array_key_exists('scheme', $result)
90
+		     || ! array_key_exists('host', $result)
91
+		     || ! array_key_exists('path', $result)) {
92 92
 			return false;
93 93
 		}
94 94
 
95
-		return $result['scheme'] . "/" . $result['host'] . $result['path'];
95
+		return $result['scheme']."/".$result['host'].$result['path'];
96 96
 	}
97 97
 
98
-	private function get_meta( $entity_url ) {
98
+	private function get_meta($entity_url) {
99 99
 
100 100
 
101
-		$cache_results = $this->cache_service->get( $entity_url );
101
+		$cache_results = $this->cache_service->get($entity_url);
102 102
 
103
-		if ( $cache_results !== false ) {
103
+		if ($cache_results !== false) {
104 104
 			return $cache_results;
105 105
 		}
106 106
 
107
-		$formatted_url = self::format_entity_url( $entity_url );
107
+		$formatted_url = self::format_entity_url($entity_url);
108 108
 
109
-		if ( ! $formatted_url ) {
109
+		if ( ! $formatted_url) {
110 110
 			return array();
111 111
 		}
112 112
 
113
-		$meta_url = 'https://api.wordlift.io/id/' . $formatted_url;
113
+		$meta_url = 'https://api.wordlift.io/id/'.$formatted_url;
114 114
 
115
-		$response = wp_remote_get( $meta_url );
115
+		$response = wp_remote_get($meta_url);
116 116
 
117
-		if ( is_wp_error( $response )
118
-		     || ! isset( $response['response']['code'] )
119
-		     || 2 !== (int) $response['response']['code'] / 100 ) {
117
+		if (is_wp_error($response)
118
+		     || ! isset($response['response']['code'])
119
+		     || 2 !== (int) $response['response']['code'] / 100) {
120 120
 			return false;
121 121
 		}
122 122
 
123
-		$this->log->debug( "Requesting entity data for url :" . $meta_url );
124
-		$this->log->debug( "Got entity meta data as : " );
125
-		$this->log->debug( var_export( $response, true ) );
126
-		if ( ! is_wp_error( $response ) ) {
127
-			$meta = json_decode( wp_remote_retrieve_body( $response ), true );
128
-			$this->log->debug( "Saved entity data to meta :" );
129
-			$this->log->debug( var_export( $meta, true ) );
130
-			$this->cache_service->put( $entity_url, $meta );
123
+		$this->log->debug("Requesting entity data for url :".$meta_url);
124
+		$this->log->debug("Got entity meta data as : ");
125
+		$this->log->debug(var_export($response, true));
126
+		if ( ! is_wp_error($response)) {
127
+			$meta = json_decode(wp_remote_retrieve_body($response), true);
128
+			$this->log->debug("Saved entity data to meta :");
129
+			$this->log->debug(var_export($meta, true));
130
+			$this->cache_service->put($entity_url, $meta);
131 131
 
132 132
 			return $meta;
133 133
 		}
@@ -137,20 +137,20 @@  discard block
 block discarded – undo
137 137
 
138 138
 	}
139 139
 
140
-	private function get_meta_for_entities( $entities ) {
140
+	private function get_meta_for_entities($entities) {
141 141
 
142 142
 		$filtered_entities = array();
143
-		foreach ( $entities as $entity ) {
143
+		foreach ($entities as $entity) {
144 144
 			$entity['meta'] = array();
145
-			$meta           = $this->get_meta( $entity['entityId'] );
146
-			if ( $meta ) {
147
-				$meta                = Default_Entity_List::compact_jsonld( $meta );
145
+			$meta           = $this->get_meta($entity['entityId']);
146
+			if ($meta) {
147
+				$meta                = Default_Entity_List::compact_jsonld($meta);
148 148
 				$entity['meta']      = $meta;
149 149
 				$filtered_entities[] = $entity;
150 150
 			}
151 151
 		}
152
-		$this->log->debug( "Returning filtered entities as" );
153
-		$this->log->debug( var_export( $filtered_entities, true ) );
152
+		$this->log->debug("Returning filtered entities as");
153
+		$this->log->debug(var_export($filtered_entities, true));
154 154
 
155 155
 		return $filtered_entities;
156 156
 
@@ -161,33 +161,33 @@  discard block
 block discarded – undo
161 161
 	 *
162 162
 	 * @return array
163 163
 	 */
164
-	public function get_entities_by_search_query( $tag_name ) {
164
+	public function get_entities_by_search_query($tag_name) {
165 165
 		$response = $this->api_service->request(
166 166
 			'POST',
167 167
 			"/analysis/single",
168
-			array( 'Content-Type' => 'application/json' ),
169
-			wp_json_encode( array(
168
+			array('Content-Type' => 'application/json'),
169
+			wp_json_encode(array(
170 170
 				"content"         => $tag_name,
171 171
 				"contentType"     => "text/plain",
172 172
 				"version"         => "1.0.0",
173 173
 				"contentLanguage" => "en",
174 174
 				"scope"           => "all",
175
-			) )
175
+			))
176 176
 		);
177 177
 
178 178
 
179
-		if ( ! $response->is_success() ) {
179
+		if ( ! $response->is_success()) {
180 180
 			return false;
181 181
 		}
182 182
 
183
-		$response = json_decode( $response->get_body(), true );
183
+		$response = json_decode($response->get_body(), true);
184 184
 
185
-		if ( ! array_key_exists( 'entities', $response ) ) {
185
+		if ( ! array_key_exists('entities', $response)) {
186 186
 			return false;
187 187
 		}
188 188
 
189 189
 
190
-		$entities = $this->get_meta_for_entities( $response['entities'] );
190
+		$entities = $this->get_meta_for_entities($response['entities']);
191 191
 
192 192
 		return $entities;
193 193
 	}
Please login to merge, or discard this patch.
src/admin/class-wordlift-admin-settings-page.php 2 patches
Indentation   +388 added lines, -388 removed lines patch added patch discarded remove patch
@@ -18,393 +18,393 @@
 block discarded – undo
18 18
  */
19 19
 class Wordlift_Admin_Settings_Page extends Wordlift_Admin_Page {
20 20
 
21
-	/**
22
-	 * A {@link Wordlift_Entity_Service} instance.
23
-	 *
24
-	 * @since  3.11.0
25
-	 * @access private
26
-	 * @var \Wordlift_Entity_Service $entity_service A {@link Wordlift_Entity_Service} instance.
27
-	 */
28
-	private $entity_service;
29
-
30
-	/**
31
-	 * A {@link Wordlift_Admin_Input_Element} element renderer.
32
-	 *
33
-	 * @since  3.11.0
34
-	 * @access private
35
-	 * @var \Wordlift_Admin_Input_Element $input_element An {@link Wordlift_Admin_Input_Element} element renderer.
36
-	 */
37
-	private $input_element;
38
-
39
-	/**
40
-	 * A {@link Wordlift_Admin_Radio_Input_Element} element renderer.
41
-	 *
42
-	 * @since  3.13.0
43
-	 * @access protected
44
-	 * @var \Wordlift_Admin_Radio_Input_Element $radio_input_element A {@link Wordlift_Admin_Radio_Input_Element} element renderer.
45
-	 */
46
-	private $radio_input_element;
47
-
48
-	/**
49
-	 * A {@link Wordlift_Admin_Language_Select_Element} element renderer.
50
-	 *
51
-	 * @since  3.11.0
52
-	 * @access private
53
-	 * @var \Wordlift_Admin_Language_Select_Element $language_select_element A {@link Wordlift_Admin_Language_Select_Element} element renderer.
54
-	 */
55
-	private $language_select_element;
56
-
57
-	/**
58
-	 * A {@link Wordlift_Admin_Country_Select_Element} element renderer.
59
-	 *
60
-	 * @since  3.18.0
61
-	 * @access private
62
-	 * @var \Wordlift_Admin_Country_Select_Element $country_select_element A {@link Wordlift_Admin_Country_Select_Element} element renderer.
63
-	 */
64
-	private $country_select_element;
65
-
66
-	/**
67
-	 * A {@link Wordlift_Admin_Publisher_Element} element renderer.
68
-	 *
69
-	 * @since  3.11.0
70
-	 * @access private
71
-	 * @var \Wordlift_Admin_Publisher_Element $publisher_element A {@link Wordlift_Admin_Publisher_Element} element renderer.
72
-	 */
73
-	private $publisher_element;
74
-
75
-	/**
76
-	 * Create a {@link Wordlift_Admin_Settings_Page} instance.
77
-	 *
78
-	 * @param \Wordlift_Entity_Service $entity_service A {@link Wordlift_Entity_Service} instance.
79
-	 * @param \Wordlift_Admin_Input_Element $input_element A {@link Wordlift_Admin_Input_Element} element renderer.
80
-	 * @param \Wordlift_Admin_Language_Select_Element $language_select_element A {@link Wordlift_Admin_Language_Select_Element} element renderer.
81
-	 * @param \Wordlift_Admin_Country_Select_Element $country_select_element A {@link Wordlift_Admin_Country_Select_Element} element renderer.
82
-	 * @param \Wordlift_Admin_Publisher_Element $publisher_element A {@link Wordlift_Admin_Publisher_Element} element renderer.
83
-	 * @param \Wordlift_Admin_Radio_Input_Element $radio_input_element A {@link Wordlift_Admin_Radio_Input_Element} element renderer.
84
-	 *
85
-	 * @since 3.11.0
86
-	 *
87
-	 */
88
-	public function __construct( $entity_service, $input_element, $language_select_element, $country_select_element, $publisher_element, $radio_input_element ) {
89
-
90
-		$this->entity_service = $entity_service;
91
-
92
-		// Set a reference to the UI elements.
93
-		$this->input_element           = $input_element;
94
-		$this->radio_input_element     = $radio_input_element;
95
-		$this->language_select_element = $language_select_element;
96
-		$this->country_select_element  = $country_select_element;
97
-		$this->publisher_element       = $publisher_element;
98
-
99
-	}
100
-
101
-	private static $instance;
102
-
103
-	/**
104
-	 * Get the singleton instance of the Notice service.
105
-	 *
106
-	 * @return \Wordlift_Admin_Settings_Page The singleton instance of the settings page service.
107
-	 * @since 3.14.0
108
-	 */
109
-	public static function get_instance() {
110
-
111
-		if ( ! isset( self::$instance ) ) {
112
-			$publisher_element = new Wordlift_Admin_Publisher_Element(
113
-				Wordlift_Publisher_Service::get_instance(),
114
-				new Wordlift_Admin_Tabs_Element(),
115
-				new Wordlift_Admin_Select2_Element() );
116
-
117
-			self::$instance = new self(
118
-				Wordlift_Entity_Service::get_instance(),
119
-				new Wordlift_Admin_Input_Element(),
120
-				new Wordlift_Admin_Language_Select_Element(),
121
-				new Wordlift_Admin_Country_Select_Element(),
122
-				$publisher_element,
123
-				new Wordlift_Admin_Radio_Input_Element() );
124
-		}
125
-
126
-		return self::$instance;
127
-	}
128
-
129
-	/**
130
-	 * @inheritdoc
131
-	 */
132
-	function get_parent_slug() {
133
-
134
-		return 'wl_admin_menu';
135
-	}
136
-
137
-	/**
138
-	 * @inheritdoc
139
-	 */
140
-	function get_capability() {
141
-
142
-		return 'manage_options';
143
-	}
144
-
145
-	/**
146
-	 * @inheritdoc
147
-	 */
148
-	function get_page_title() {
149
-
150
-		return 'WordLift Settings';
151
-	}
152
-
153
-	/**
154
-	 * @inheritdoc
155
-	 */
156
-	function get_menu_title() {
157
-
158
-		return 'Settings';
159
-	}
160
-
161
-	/**
162
-	 * @inheritdoc
163
-	 */
164
-	function get_menu_slug() {
165
-
166
-		return 'wl_configuration_admin_menu';
167
-	}
168
-
169
-	/**
170
-	 * @inheritdoc
171
-	 */
172
-	function get_partial_name() {
173
-
174
-		return 'wordlift-admin-settings-page.php';
175
-	}
176
-
177
-	/**
178
-	 * @inheritdoc
179
-	 */
180
-	public function enqueue_scripts() {
181
-
182
-		// Enqueue the media scripts to be used for the publisher's logo selection.
183
-		wp_enqueue_media();
184
-
185
-		// JavaScript required for the settings page.
186
-		// @todo: try to move to the `wordlift-admin.bundle.js`.
187
-		wp_enqueue_script( 'wordlift-admin-settings-page', plugin_dir_url( dirname( __FILE__ ) ) . 'admin/js/1/settings.js', array( 'wp-util' ) );
188
-		wp_enqueue_style( 'wordlift-admin-settings-page', plugin_dir_url( dirname( __FILE__ ) ) . 'admin/js/1/settings.css' );
189
-
190
-	}
191
-
192
-	/**
193
-	 * Configure all the configuration parameters.
194
-	 *
195
-	 * Called by the *admin_init* hook.
196
-	 *
197
-	 * @since 3.11.0
198
-	 */
199
-	function admin_init() {
200
-		// Register WordLift's general settings, providing our own sanitize callback
201
-		// which will also check whether the user filled the WL Publisher form.
202
-		register_setting(
203
-			'wl_general_settings',
204
-			'wl_general_settings',
205
-			array( $this, 'sanitize_callback' )
206
-		);
207
-
208
-		// Add the general settings section.
209
-		add_settings_section(
210
-			'wl_general_settings_section', // ID used to identify this section and with which to register options.
211
-			'',                            // Section header.
212
-			'',                            // Callback used to render the description of the section.
213
-			'wl_general_settings'          // Page on which to add this section of options.
214
-		);
215
-
216
-		$key_args = array(
217
-			'id'          => 'wl-key',
218
-			'name'        => 'wl_general_settings[' . Wordlift_Configuration_Service::KEY . ']',
219
-			'value'       => Wordlift_Configuration_Service::get_instance()->get_key(),
220
-			'description' => __( 'Insert the <a href="https://www.wordlift.io/blogger">WordLift Key</a> you received via email.', 'wordlift' )
221
-			                 . ' [' . get_option( 'home' ) . ']',
222
-		);
223
-
224
-		// Before we were used to validate the key beforehand, but this means
225
-		// an http call whenever a page is opened in the admin area. Therefore
226
-		// we now leave the input `untouched`, leaving to the client to update
227
-		// the `css_class`.
228
-		//
229
-		// See https://github.com/insideout10/wordlift-plugin/issues/669.
230
-		$key_args['css_class'] = 'untouched';
231
-
232
-		// Add the `key` field.
233
-		add_settings_field(
234
-			'wl-key',                                       // Element id used to identify the field throughout the theme.
235
-			__( 'WordLift Key', 'wordlift' ),               // The label to the left of the option interface element.
236
-			// The name of the function responsible for rendering the option interface.
237
-			array( $this->input_element, 'render' ),
238
-			'wl_general_settings',                          // The page on which this option will be displayed.
239
-			'wl_general_settings_section',                  // The name of the section to which this field belongs.
240
-			$key_args                                       // The array of arguments to pass to the callback. In this case, just a description.
241
-		);
242
-
243
-		// Entity Base Path input.
244
-		$entity_base_path_args = array(
245
-			// The array of arguments to pass to the callback. In this case, just a description.
246
-			'id'          => 'wl-entity-base-path',
247
-			'name'        => 'wl_general_settings[' . Wordlift_Configuration_Service::ENTITY_BASE_PATH_KEY . ']',
248
-			'value'       => Wordlift_Configuration_Service::get_instance()->get_entity_base_path(),
249
-			/* translators: Placeholders: %s - a link to FAQ's page. */
250
-			'description' => sprintf( __( 'All new pages created with WordLift, will be stored inside your internal vocabulary. You can customize the url pattern of these pages in the field above. Check our <a href="%s">FAQs</a> if you need more info.', 'wordlift' ), 'https://wordlift.io/wordlift-user-faqs/#10-why-and-how-should-i-customize-the-url-of-the-entity-pages-created-in-my-vocabulary' ),
251
-		);
252
-
253
-		// The following call is very heavy on large web sites and is always run
254
-		// also when not needed:
255
-		// $entity_base_path_args['readonly'] = 0 < $this->entity_service->count();
256
-		//
257
-		// It is now replaced by a filter to add the `readonly` flag to the
258
-		// input element when this is actually rendered.
259
-		add_filter( 'wl_admin_input_element_params', array(
260
-			$this,
261
-			'entity_path_input_element_params',
262
-		) );
263
-
264
-		// Add the `wl_entity_base_path` field.
265
-		add_settings_field(
266
-			'wl-entity-base-path',                                // ID used to identify the field throughout the theme
267
-			__( 'Entity Base Path', 'wordlift' ),                 // The label to the left of the option interface element
268
-			// The name of the function responsible for rendering the option interface
269
-			array( $this->input_element, 'render', ),
270
-			'wl_general_settings',                                // The page on which this option will be displayed
271
-			'wl_general_settings_section',                        // The name of the section to which this field belongs
272
-			$entity_base_path_args
273
-		);
274
-
275
-
276
-		$language_name = Wordlift_Languages::get_language_name(
277
-			Wordlift_Configuration_Service::get_instance()->get_language_code()
278
-		);
279
-
280
-		// Add the `language_name` field.
281
-		add_settings_field(
282
-			'wl-site-language',
283
-			__( 'Site Language', 'wordlift' ),
284
-			function () use ( $language_name ) {
285
-				echo sprintf( '<p><label>%s</label></p>', esc_html( $language_name ) );
286
-				echo sprintf( __( '<br/><p>WordLift uses the site language, You can change the language from <a href="%s">settings.</a></p>', 'wordlift' ),
287
-					admin_url( 'options-general.php#WPLANG' )
288
-				);
289
-			},
290
-			'wl_general_settings',
291
-			'wl_general_settings_section'
292
-		);
293
-
294
-		// Add the `country_code` field.
295
-		add_settings_field(
296
-			'wl-country-code',
297
-			_x( 'Country', 'wordlift' ),
298
-			array( $this->country_select_element, 'render' ),
299
-			'wl_general_settings',
300
-			'wl_general_settings_section',
301
-			array(
302
-				'id'          => 'wl-country-code',
303
-				'name'        => 'wl_general_settings[' . Wordlift_Configuration_Service::COUNTRY_CODE . ']',
304
-				'value'       => Wordlift_Configuration_Service::get_instance()->get_country_code(),
305
-				'description' => __( 'Please select a country.', 'wordlift' ),
306
-				'notice'      => __( 'The selected language is not supported in this country.</br>Please choose another country or language.', 'wordlift' ),
307
-			)
308
-		);
309
-
310
-		// Add the `publisher` field.
311
-		add_settings_field(
312
-			'wl-publisher-id',
313
-			__( 'Publisher', 'wordlift' ),
314
-			array( $this->publisher_element, 'render' ),
315
-			'wl_general_settings',
316
-			'wl_general_settings_section',
317
-			array(
318
-				'id'   => 'wl-publisher-id',
319
-				'name' => 'wl_general_settings[' . Wordlift_Configuration_Service::PUBLISHER_ID . ']',
320
-			)
321
-		);
322
-
323
-		// Add the `link by default` field.
324
-		add_settings_field(
325
-			'wl-link-by-default',
326
-			__( 'Link by Default', 'wordlift' ),
327
-			array( $this->radio_input_element, 'render' ),
328
-			'wl_general_settings',
329
-			'wl_general_settings_section',
330
-			array(
331
-				'id'          => 'wl-link-by-default',
332
-				'name'        => 'wl_general_settings[' . Wordlift_Configuration_Service::LINK_BY_DEFAULT . ']',
333
-				'value'       => Wordlift_Configuration_Service::get_instance()->is_link_by_default() ? 'yes' : 'no',
334
-				'description' => __( 'Whether to link entities by default or not. This setting applies to all the entities.', 'wordlift' ),
335
-			)
336
-		);
337
-
338
-		// Add the `diagnostic data` field.
339
-		add_settings_field(
340
-			'wl-send-diagnostic',
341
-			__( 'Send Diagnostic Data', 'wordlift' ),
342
-			array( $this->radio_input_element, 'render' ),
343
-			'wl_general_settings',
344
-			'wl_general_settings_section',
345
-			array(
346
-				'id'          => 'wl-send-diagnostic',
347
-				'name'        => 'wl_general_settings[' . Wordlift_Configuration_Service::SEND_DIAGNOSTIC . ']',
348
-				'value'       => 'yes' === Wordlift_Configuration_Service::get_instance()->get_diagnostic_preferences() ? 'yes' : 'no',
349
-				'description' => __( 'Whether to send diagnostic data or not.', 'wordlift' ),
350
-			)
351
-		);
352
-
353
-	}
354
-
355
-	/**
356
-	 * Filter the {@link Wordlift_Admin_Input_Element} in order to add the
357
-	 * `readonly` flag to the `wl-entity-base-path` input.
358
-	 *
359
-	 * @param array $args An array of {@link Wordlift_Admin_Input_Element} parameters.
360
-	 *
361
-	 * @return array The updated array.
362
-	 * @since 3.17.0
363
-	 *
364
-	 */
365
-	public function entity_path_input_element_params( $args ) {
366
-
367
-		// Bail out if it's not the `wl-entity-base-path`).
368
-		if ( 'wl-entity-base-path' !== $args['id'] ) {
369
-			return $args;
370
-		}
371
-
372
-		// Set the readonly flag according to the entities count.
373
-		$args['readonly'] = 0 < $this->entity_service->count();
374
-
375
-		// Return the updated args.
376
-		return $args;
377
-	}
378
-
379
-	/**
380
-	 * Sanitize the configuration settings to be stored.
381
-	 *
382
-	 * If a new entity is being created for the publisher, create it and set The
383
-	 * publisher setting.
384
-	 *
385
-	 * @param array $input The configuration settings array.
386
-	 *
387
-	 * @return array The sanitized input array.
388
-	 * @since 3.11.0
389
-	 *
390
-	 */
391
-	function sanitize_callback( $input ) {
392
-
393
-		// Check whether a publisher name has been set.
394
-		if ( isset( $_POST['wl_publisher'] ) && ! empty( $_POST['wl_publisher']['name'] ) ) { // WPCS: CSRF, input var, sanitization ok.
395
-			$name         = isset( $_POST['wl_publisher']['name'] ) ? (string) $_POST['wl_publisher']['name'] : '';
396
-			$type         = isset( $_POST['wl_publisher']['type'] ) ? (string) $_POST['wl_publisher']['type'] : '';
397
-			$thumbnail_id = isset( $_POST['wl_publisher']['thumbnail_id'] ) ? $_POST['wl_publisher']['thumbnail_id'] : null; // WPCS: CSRF, input var, sanitization ok.
398
-
399
-			// Set the type URI, either http://schema.org/Person or http://schema.org/Organization.
400
-			$type_uri = sprintf( 'http://schema.org/%s', 'organization' === $type ? 'Organization' : 'Person' );
401
-
402
-			// Create an entity for the publisher and assign it to the input
403
-			// parameter which WordPress automatically saves into the settings.
404
-			$input['publisher_id'] = $this->entity_service->create( $name, $type_uri, $thumbnail_id, 'publish' );
405
-		}
406
-
407
-		return $input;
408
-	}
21
+    /**
22
+     * A {@link Wordlift_Entity_Service} instance.
23
+     *
24
+     * @since  3.11.0
25
+     * @access private
26
+     * @var \Wordlift_Entity_Service $entity_service A {@link Wordlift_Entity_Service} instance.
27
+     */
28
+    private $entity_service;
29
+
30
+    /**
31
+     * A {@link Wordlift_Admin_Input_Element} element renderer.
32
+     *
33
+     * @since  3.11.0
34
+     * @access private
35
+     * @var \Wordlift_Admin_Input_Element $input_element An {@link Wordlift_Admin_Input_Element} element renderer.
36
+     */
37
+    private $input_element;
38
+
39
+    /**
40
+     * A {@link Wordlift_Admin_Radio_Input_Element} element renderer.
41
+     *
42
+     * @since  3.13.0
43
+     * @access protected
44
+     * @var \Wordlift_Admin_Radio_Input_Element $radio_input_element A {@link Wordlift_Admin_Radio_Input_Element} element renderer.
45
+     */
46
+    private $radio_input_element;
47
+
48
+    /**
49
+     * A {@link Wordlift_Admin_Language_Select_Element} element renderer.
50
+     *
51
+     * @since  3.11.0
52
+     * @access private
53
+     * @var \Wordlift_Admin_Language_Select_Element $language_select_element A {@link Wordlift_Admin_Language_Select_Element} element renderer.
54
+     */
55
+    private $language_select_element;
56
+
57
+    /**
58
+     * A {@link Wordlift_Admin_Country_Select_Element} element renderer.
59
+     *
60
+     * @since  3.18.0
61
+     * @access private
62
+     * @var \Wordlift_Admin_Country_Select_Element $country_select_element A {@link Wordlift_Admin_Country_Select_Element} element renderer.
63
+     */
64
+    private $country_select_element;
65
+
66
+    /**
67
+     * A {@link Wordlift_Admin_Publisher_Element} element renderer.
68
+     *
69
+     * @since  3.11.0
70
+     * @access private
71
+     * @var \Wordlift_Admin_Publisher_Element $publisher_element A {@link Wordlift_Admin_Publisher_Element} element renderer.
72
+     */
73
+    private $publisher_element;
74
+
75
+    /**
76
+     * Create a {@link Wordlift_Admin_Settings_Page} instance.
77
+     *
78
+     * @param \Wordlift_Entity_Service $entity_service A {@link Wordlift_Entity_Service} instance.
79
+     * @param \Wordlift_Admin_Input_Element $input_element A {@link Wordlift_Admin_Input_Element} element renderer.
80
+     * @param \Wordlift_Admin_Language_Select_Element $language_select_element A {@link Wordlift_Admin_Language_Select_Element} element renderer.
81
+     * @param \Wordlift_Admin_Country_Select_Element $country_select_element A {@link Wordlift_Admin_Country_Select_Element} element renderer.
82
+     * @param \Wordlift_Admin_Publisher_Element $publisher_element A {@link Wordlift_Admin_Publisher_Element} element renderer.
83
+     * @param \Wordlift_Admin_Radio_Input_Element $radio_input_element A {@link Wordlift_Admin_Radio_Input_Element} element renderer.
84
+     *
85
+     * @since 3.11.0
86
+     *
87
+     */
88
+    public function __construct( $entity_service, $input_element, $language_select_element, $country_select_element, $publisher_element, $radio_input_element ) {
89
+
90
+        $this->entity_service = $entity_service;
91
+
92
+        // Set a reference to the UI elements.
93
+        $this->input_element           = $input_element;
94
+        $this->radio_input_element     = $radio_input_element;
95
+        $this->language_select_element = $language_select_element;
96
+        $this->country_select_element  = $country_select_element;
97
+        $this->publisher_element       = $publisher_element;
98
+
99
+    }
100
+
101
+    private static $instance;
102
+
103
+    /**
104
+     * Get the singleton instance of the Notice service.
105
+     *
106
+     * @return \Wordlift_Admin_Settings_Page The singleton instance of the settings page service.
107
+     * @since 3.14.0
108
+     */
109
+    public static function get_instance() {
110
+
111
+        if ( ! isset( self::$instance ) ) {
112
+            $publisher_element = new Wordlift_Admin_Publisher_Element(
113
+                Wordlift_Publisher_Service::get_instance(),
114
+                new Wordlift_Admin_Tabs_Element(),
115
+                new Wordlift_Admin_Select2_Element() );
116
+
117
+            self::$instance = new self(
118
+                Wordlift_Entity_Service::get_instance(),
119
+                new Wordlift_Admin_Input_Element(),
120
+                new Wordlift_Admin_Language_Select_Element(),
121
+                new Wordlift_Admin_Country_Select_Element(),
122
+                $publisher_element,
123
+                new Wordlift_Admin_Radio_Input_Element() );
124
+        }
125
+
126
+        return self::$instance;
127
+    }
128
+
129
+    /**
130
+     * @inheritdoc
131
+     */
132
+    function get_parent_slug() {
133
+
134
+        return 'wl_admin_menu';
135
+    }
136
+
137
+    /**
138
+     * @inheritdoc
139
+     */
140
+    function get_capability() {
141
+
142
+        return 'manage_options';
143
+    }
144
+
145
+    /**
146
+     * @inheritdoc
147
+     */
148
+    function get_page_title() {
149
+
150
+        return 'WordLift Settings';
151
+    }
152
+
153
+    /**
154
+     * @inheritdoc
155
+     */
156
+    function get_menu_title() {
157
+
158
+        return 'Settings';
159
+    }
160
+
161
+    /**
162
+     * @inheritdoc
163
+     */
164
+    function get_menu_slug() {
165
+
166
+        return 'wl_configuration_admin_menu';
167
+    }
168
+
169
+    /**
170
+     * @inheritdoc
171
+     */
172
+    function get_partial_name() {
173
+
174
+        return 'wordlift-admin-settings-page.php';
175
+    }
176
+
177
+    /**
178
+     * @inheritdoc
179
+     */
180
+    public function enqueue_scripts() {
181
+
182
+        // Enqueue the media scripts to be used for the publisher's logo selection.
183
+        wp_enqueue_media();
184
+
185
+        // JavaScript required for the settings page.
186
+        // @todo: try to move to the `wordlift-admin.bundle.js`.
187
+        wp_enqueue_script( 'wordlift-admin-settings-page', plugin_dir_url( dirname( __FILE__ ) ) . 'admin/js/1/settings.js', array( 'wp-util' ) );
188
+        wp_enqueue_style( 'wordlift-admin-settings-page', plugin_dir_url( dirname( __FILE__ ) ) . 'admin/js/1/settings.css' );
189
+
190
+    }
191
+
192
+    /**
193
+     * Configure all the configuration parameters.
194
+     *
195
+     * Called by the *admin_init* hook.
196
+     *
197
+     * @since 3.11.0
198
+     */
199
+    function admin_init() {
200
+        // Register WordLift's general settings, providing our own sanitize callback
201
+        // which will also check whether the user filled the WL Publisher form.
202
+        register_setting(
203
+            'wl_general_settings',
204
+            'wl_general_settings',
205
+            array( $this, 'sanitize_callback' )
206
+        );
207
+
208
+        // Add the general settings section.
209
+        add_settings_section(
210
+            'wl_general_settings_section', // ID used to identify this section and with which to register options.
211
+            '',                            // Section header.
212
+            '',                            // Callback used to render the description of the section.
213
+            'wl_general_settings'          // Page on which to add this section of options.
214
+        );
215
+
216
+        $key_args = array(
217
+            'id'          => 'wl-key',
218
+            'name'        => 'wl_general_settings[' . Wordlift_Configuration_Service::KEY . ']',
219
+            'value'       => Wordlift_Configuration_Service::get_instance()->get_key(),
220
+            'description' => __( 'Insert the <a href="https://www.wordlift.io/blogger">WordLift Key</a> you received via email.', 'wordlift' )
221
+                                . ' [' . get_option( 'home' ) . ']',
222
+        );
223
+
224
+        // Before we were used to validate the key beforehand, but this means
225
+        // an http call whenever a page is opened in the admin area. Therefore
226
+        // we now leave the input `untouched`, leaving to the client to update
227
+        // the `css_class`.
228
+        //
229
+        // See https://github.com/insideout10/wordlift-plugin/issues/669.
230
+        $key_args['css_class'] = 'untouched';
231
+
232
+        // Add the `key` field.
233
+        add_settings_field(
234
+            'wl-key',                                       // Element id used to identify the field throughout the theme.
235
+            __( 'WordLift Key', 'wordlift' ),               // The label to the left of the option interface element.
236
+            // The name of the function responsible for rendering the option interface.
237
+            array( $this->input_element, 'render' ),
238
+            'wl_general_settings',                          // The page on which this option will be displayed.
239
+            'wl_general_settings_section',                  // The name of the section to which this field belongs.
240
+            $key_args                                       // The array of arguments to pass to the callback. In this case, just a description.
241
+        );
242
+
243
+        // Entity Base Path input.
244
+        $entity_base_path_args = array(
245
+            // The array of arguments to pass to the callback. In this case, just a description.
246
+            'id'          => 'wl-entity-base-path',
247
+            'name'        => 'wl_general_settings[' . Wordlift_Configuration_Service::ENTITY_BASE_PATH_KEY . ']',
248
+            'value'       => Wordlift_Configuration_Service::get_instance()->get_entity_base_path(),
249
+            /* translators: Placeholders: %s - a link to FAQ's page. */
250
+            'description' => sprintf( __( 'All new pages created with WordLift, will be stored inside your internal vocabulary. You can customize the url pattern of these pages in the field above. Check our <a href="%s">FAQs</a> if you need more info.', 'wordlift' ), 'https://wordlift.io/wordlift-user-faqs/#10-why-and-how-should-i-customize-the-url-of-the-entity-pages-created-in-my-vocabulary' ),
251
+        );
252
+
253
+        // The following call is very heavy on large web sites and is always run
254
+        // also when not needed:
255
+        // $entity_base_path_args['readonly'] = 0 < $this->entity_service->count();
256
+        //
257
+        // It is now replaced by a filter to add the `readonly` flag to the
258
+        // input element when this is actually rendered.
259
+        add_filter( 'wl_admin_input_element_params', array(
260
+            $this,
261
+            'entity_path_input_element_params',
262
+        ) );
263
+
264
+        // Add the `wl_entity_base_path` field.
265
+        add_settings_field(
266
+            'wl-entity-base-path',                                // ID used to identify the field throughout the theme
267
+            __( 'Entity Base Path', 'wordlift' ),                 // The label to the left of the option interface element
268
+            // The name of the function responsible for rendering the option interface
269
+            array( $this->input_element, 'render', ),
270
+            'wl_general_settings',                                // The page on which this option will be displayed
271
+            'wl_general_settings_section',                        // The name of the section to which this field belongs
272
+            $entity_base_path_args
273
+        );
274
+
275
+
276
+        $language_name = Wordlift_Languages::get_language_name(
277
+            Wordlift_Configuration_Service::get_instance()->get_language_code()
278
+        );
279
+
280
+        // Add the `language_name` field.
281
+        add_settings_field(
282
+            'wl-site-language',
283
+            __( 'Site Language', 'wordlift' ),
284
+            function () use ( $language_name ) {
285
+                echo sprintf( '<p><label>%s</label></p>', esc_html( $language_name ) );
286
+                echo sprintf( __( '<br/><p>WordLift uses the site language, You can change the language from <a href="%s">settings.</a></p>', 'wordlift' ),
287
+                    admin_url( 'options-general.php#WPLANG' )
288
+                );
289
+            },
290
+            'wl_general_settings',
291
+            'wl_general_settings_section'
292
+        );
293
+
294
+        // Add the `country_code` field.
295
+        add_settings_field(
296
+            'wl-country-code',
297
+            _x( 'Country', 'wordlift' ),
298
+            array( $this->country_select_element, 'render' ),
299
+            'wl_general_settings',
300
+            'wl_general_settings_section',
301
+            array(
302
+                'id'          => 'wl-country-code',
303
+                'name'        => 'wl_general_settings[' . Wordlift_Configuration_Service::COUNTRY_CODE . ']',
304
+                'value'       => Wordlift_Configuration_Service::get_instance()->get_country_code(),
305
+                'description' => __( 'Please select a country.', 'wordlift' ),
306
+                'notice'      => __( 'The selected language is not supported in this country.</br>Please choose another country or language.', 'wordlift' ),
307
+            )
308
+        );
309
+
310
+        // Add the `publisher` field.
311
+        add_settings_field(
312
+            'wl-publisher-id',
313
+            __( 'Publisher', 'wordlift' ),
314
+            array( $this->publisher_element, 'render' ),
315
+            'wl_general_settings',
316
+            'wl_general_settings_section',
317
+            array(
318
+                'id'   => 'wl-publisher-id',
319
+                'name' => 'wl_general_settings[' . Wordlift_Configuration_Service::PUBLISHER_ID . ']',
320
+            )
321
+        );
322
+
323
+        // Add the `link by default` field.
324
+        add_settings_field(
325
+            'wl-link-by-default',
326
+            __( 'Link by Default', 'wordlift' ),
327
+            array( $this->radio_input_element, 'render' ),
328
+            'wl_general_settings',
329
+            'wl_general_settings_section',
330
+            array(
331
+                'id'          => 'wl-link-by-default',
332
+                'name'        => 'wl_general_settings[' . Wordlift_Configuration_Service::LINK_BY_DEFAULT . ']',
333
+                'value'       => Wordlift_Configuration_Service::get_instance()->is_link_by_default() ? 'yes' : 'no',
334
+                'description' => __( 'Whether to link entities by default or not. This setting applies to all the entities.', 'wordlift' ),
335
+            )
336
+        );
337
+
338
+        // Add the `diagnostic data` field.
339
+        add_settings_field(
340
+            'wl-send-diagnostic',
341
+            __( 'Send Diagnostic Data', 'wordlift' ),
342
+            array( $this->radio_input_element, 'render' ),
343
+            'wl_general_settings',
344
+            'wl_general_settings_section',
345
+            array(
346
+                'id'          => 'wl-send-diagnostic',
347
+                'name'        => 'wl_general_settings[' . Wordlift_Configuration_Service::SEND_DIAGNOSTIC . ']',
348
+                'value'       => 'yes' === Wordlift_Configuration_Service::get_instance()->get_diagnostic_preferences() ? 'yes' : 'no',
349
+                'description' => __( 'Whether to send diagnostic data or not.', 'wordlift' ),
350
+            )
351
+        );
352
+
353
+    }
354
+
355
+    /**
356
+     * Filter the {@link Wordlift_Admin_Input_Element} in order to add the
357
+     * `readonly` flag to the `wl-entity-base-path` input.
358
+     *
359
+     * @param array $args An array of {@link Wordlift_Admin_Input_Element} parameters.
360
+     *
361
+     * @return array The updated array.
362
+     * @since 3.17.0
363
+     *
364
+     */
365
+    public function entity_path_input_element_params( $args ) {
366
+
367
+        // Bail out if it's not the `wl-entity-base-path`).
368
+        if ( 'wl-entity-base-path' !== $args['id'] ) {
369
+            return $args;
370
+        }
371
+
372
+        // Set the readonly flag according to the entities count.
373
+        $args['readonly'] = 0 < $this->entity_service->count();
374
+
375
+        // Return the updated args.
376
+        return $args;
377
+    }
378
+
379
+    /**
380
+     * Sanitize the configuration settings to be stored.
381
+     *
382
+     * If a new entity is being created for the publisher, create it and set The
383
+     * publisher setting.
384
+     *
385
+     * @param array $input The configuration settings array.
386
+     *
387
+     * @return array The sanitized input array.
388
+     * @since 3.11.0
389
+     *
390
+     */
391
+    function sanitize_callback( $input ) {
392
+
393
+        // Check whether a publisher name has been set.
394
+        if ( isset( $_POST['wl_publisher'] ) && ! empty( $_POST['wl_publisher']['name'] ) ) { // WPCS: CSRF, input var, sanitization ok.
395
+            $name         = isset( $_POST['wl_publisher']['name'] ) ? (string) $_POST['wl_publisher']['name'] : '';
396
+            $type         = isset( $_POST['wl_publisher']['type'] ) ? (string) $_POST['wl_publisher']['type'] : '';
397
+            $thumbnail_id = isset( $_POST['wl_publisher']['thumbnail_id'] ) ? $_POST['wl_publisher']['thumbnail_id'] : null; // WPCS: CSRF, input var, sanitization ok.
398
+
399
+            // Set the type URI, either http://schema.org/Person or http://schema.org/Organization.
400
+            $type_uri = sprintf( 'http://schema.org/%s', 'organization' === $type ? 'Organization' : 'Person' );
401
+
402
+            // Create an entity for the publisher and assign it to the input
403
+            // parameter which WordPress automatically saves into the settings.
404
+            $input['publisher_id'] = $this->entity_service->create( $name, $type_uri, $thumbnail_id, 'publish' );
405
+        }
406
+
407
+        return $input;
408
+    }
409 409
 
410 410
 }
Please login to merge, or discard this patch.
Spacing   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
 	 * @since 3.11.0
86 86
 	 *
87 87
 	 */
88
-	public function __construct( $entity_service, $input_element, $language_select_element, $country_select_element, $publisher_element, $radio_input_element ) {
88
+	public function __construct($entity_service, $input_element, $language_select_element, $country_select_element, $publisher_element, $radio_input_element) {
89 89
 
90 90
 		$this->entity_service = $entity_service;
91 91
 
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
 	 */
109 109
 	public static function get_instance() {
110 110
 
111
-		if ( ! isset( self::$instance ) ) {
111
+		if ( ! isset(self::$instance)) {
112 112
 			$publisher_element = new Wordlift_Admin_Publisher_Element(
113 113
 				Wordlift_Publisher_Service::get_instance(),
114 114
 				new Wordlift_Admin_Tabs_Element(),
@@ -184,8 +184,8 @@  discard block
 block discarded – undo
184 184
 
185 185
 		// JavaScript required for the settings page.
186 186
 		// @todo: try to move to the `wordlift-admin.bundle.js`.
187
-		wp_enqueue_script( 'wordlift-admin-settings-page', plugin_dir_url( dirname( __FILE__ ) ) . 'admin/js/1/settings.js', array( 'wp-util' ) );
188
-		wp_enqueue_style( 'wordlift-admin-settings-page', plugin_dir_url( dirname( __FILE__ ) ) . 'admin/js/1/settings.css' );
187
+		wp_enqueue_script('wordlift-admin-settings-page', plugin_dir_url(dirname(__FILE__)).'admin/js/1/settings.js', array('wp-util'));
188
+		wp_enqueue_style('wordlift-admin-settings-page', plugin_dir_url(dirname(__FILE__)).'admin/js/1/settings.css');
189 189
 
190 190
 	}
191 191
 
@@ -202,23 +202,23 @@  discard block
 block discarded – undo
202 202
 		register_setting(
203 203
 			'wl_general_settings',
204 204
 			'wl_general_settings',
205
-			array( $this, 'sanitize_callback' )
205
+			array($this, 'sanitize_callback')
206 206
 		);
207 207
 
208 208
 		// Add the general settings section.
209 209
 		add_settings_section(
210 210
 			'wl_general_settings_section', // ID used to identify this section and with which to register options.
211
-			'',                            // Section header.
212
-			'',                            // Callback used to render the description of the section.
211
+			'', // Section header.
212
+			'', // Callback used to render the description of the section.
213 213
 			'wl_general_settings'          // Page on which to add this section of options.
214 214
 		);
215 215
 
216 216
 		$key_args = array(
217 217
 			'id'          => 'wl-key',
218
-			'name'        => 'wl_general_settings[' . Wordlift_Configuration_Service::KEY . ']',
218
+			'name'        => 'wl_general_settings['.Wordlift_Configuration_Service::KEY.']',
219 219
 			'value'       => Wordlift_Configuration_Service::get_instance()->get_key(),
220
-			'description' => __( 'Insert the <a href="https://www.wordlift.io/blogger">WordLift Key</a> you received via email.', 'wordlift' )
221
-			                 . ' [' . get_option( 'home' ) . ']',
220
+			'description' => __('Insert the <a href="https://www.wordlift.io/blogger">WordLift Key</a> you received via email.', 'wordlift')
221
+			                 . ' ['.get_option('home').']',
222 222
 		);
223 223
 
224 224
 		// Before we were used to validate the key beforehand, but this means
@@ -231,12 +231,12 @@  discard block
 block discarded – undo
231 231
 
232 232
 		// Add the `key` field.
233 233
 		add_settings_field(
234
-			'wl-key',                                       // Element id used to identify the field throughout the theme.
235
-			__( 'WordLift Key', 'wordlift' ),               // The label to the left of the option interface element.
234
+			'wl-key', // Element id used to identify the field throughout the theme.
235
+			__('WordLift Key', 'wordlift'), // The label to the left of the option interface element.
236 236
 			// The name of the function responsible for rendering the option interface.
237
-			array( $this->input_element, 'render' ),
238
-			'wl_general_settings',                          // The page on which this option will be displayed.
239
-			'wl_general_settings_section',                  // The name of the section to which this field belongs.
237
+			array($this->input_element, 'render'),
238
+			'wl_general_settings', // The page on which this option will be displayed.
239
+			'wl_general_settings_section', // The name of the section to which this field belongs.
240 240
 			$key_args                                       // The array of arguments to pass to the callback. In this case, just a description.
241 241
 		);
242 242
 
@@ -244,10 +244,10 @@  discard block
 block discarded – undo
244 244
 		$entity_base_path_args = array(
245 245
 			// The array of arguments to pass to the callback. In this case, just a description.
246 246
 			'id'          => 'wl-entity-base-path',
247
-			'name'        => 'wl_general_settings[' . Wordlift_Configuration_Service::ENTITY_BASE_PATH_KEY . ']',
247
+			'name'        => 'wl_general_settings['.Wordlift_Configuration_Service::ENTITY_BASE_PATH_KEY.']',
248 248
 			'value'       => Wordlift_Configuration_Service::get_instance()->get_entity_base_path(),
249 249
 			/* translators: Placeholders: %s - a link to FAQ's page. */
250
-			'description' => sprintf( __( 'All new pages created with WordLift, will be stored inside your internal vocabulary. You can customize the url pattern of these pages in the field above. Check our <a href="%s">FAQs</a> if you need more info.', 'wordlift' ), 'https://wordlift.io/wordlift-user-faqs/#10-why-and-how-should-i-customize-the-url-of-the-entity-pages-created-in-my-vocabulary' ),
250
+			'description' => sprintf(__('All new pages created with WordLift, will be stored inside your internal vocabulary. You can customize the url pattern of these pages in the field above. Check our <a href="%s">FAQs</a> if you need more info.', 'wordlift'), 'https://wordlift.io/wordlift-user-faqs/#10-why-and-how-should-i-customize-the-url-of-the-entity-pages-created-in-my-vocabulary'),
251 251
 		);
252 252
 
253 253
 		// The following call is very heavy on large web sites and is always run
@@ -256,19 +256,19 @@  discard block
 block discarded – undo
256 256
 		//
257 257
 		// It is now replaced by a filter to add the `readonly` flag to the
258 258
 		// input element when this is actually rendered.
259
-		add_filter( 'wl_admin_input_element_params', array(
259
+		add_filter('wl_admin_input_element_params', array(
260 260
 			$this,
261 261
 			'entity_path_input_element_params',
262
-		) );
262
+		));
263 263
 
264 264
 		// Add the `wl_entity_base_path` field.
265 265
 		add_settings_field(
266
-			'wl-entity-base-path',                                // ID used to identify the field throughout the theme
267
-			__( 'Entity Base Path', 'wordlift' ),                 // The label to the left of the option interface element
266
+			'wl-entity-base-path', // ID used to identify the field throughout the theme
267
+			__('Entity Base Path', 'wordlift'), // The label to the left of the option interface element
268 268
 			// The name of the function responsible for rendering the option interface
269
-			array( $this->input_element, 'render', ),
270
-			'wl_general_settings',                                // The page on which this option will be displayed
271
-			'wl_general_settings_section',                        // The name of the section to which this field belongs
269
+			array($this->input_element, 'render',),
270
+			'wl_general_settings', // The page on which this option will be displayed
271
+			'wl_general_settings_section', // The name of the section to which this field belongs
272 272
 			$entity_base_path_args
273 273
 		);
274 274
 
@@ -280,11 +280,11 @@  discard block
 block discarded – undo
280 280
 		// Add the `language_name` field.
281 281
 		add_settings_field(
282 282
 			'wl-site-language',
283
-			__( 'Site Language', 'wordlift' ),
284
-			function () use ( $language_name ) {
285
-				echo sprintf( '<p><label>%s</label></p>', esc_html( $language_name ) );
286
-				echo sprintf( __( '<br/><p>WordLift uses the site language, You can change the language from <a href="%s">settings.</a></p>', 'wordlift' ),
287
-					admin_url( 'options-general.php#WPLANG' )
283
+			__('Site Language', 'wordlift'),
284
+			function() use ($language_name) {
285
+				echo sprintf('<p><label>%s</label></p>', esc_html($language_name));
286
+				echo sprintf(__('<br/><p>WordLift uses the site language, You can change the language from <a href="%s">settings.</a></p>', 'wordlift'),
287
+					admin_url('options-general.php#WPLANG')
288 288
 				);
289 289
 			},
290 290
 			'wl_general_settings',
@@ -294,59 +294,59 @@  discard block
 block discarded – undo
294 294
 		// Add the `country_code` field.
295 295
 		add_settings_field(
296 296
 			'wl-country-code',
297
-			_x( 'Country', 'wordlift' ),
298
-			array( $this->country_select_element, 'render' ),
297
+			_x('Country', 'wordlift'),
298
+			array($this->country_select_element, 'render'),
299 299
 			'wl_general_settings',
300 300
 			'wl_general_settings_section',
301 301
 			array(
302 302
 				'id'          => 'wl-country-code',
303
-				'name'        => 'wl_general_settings[' . Wordlift_Configuration_Service::COUNTRY_CODE . ']',
303
+				'name'        => 'wl_general_settings['.Wordlift_Configuration_Service::COUNTRY_CODE.']',
304 304
 				'value'       => Wordlift_Configuration_Service::get_instance()->get_country_code(),
305
-				'description' => __( 'Please select a country.', 'wordlift' ),
306
-				'notice'      => __( 'The selected language is not supported in this country.</br>Please choose another country or language.', 'wordlift' ),
305
+				'description' => __('Please select a country.', 'wordlift'),
306
+				'notice'      => __('The selected language is not supported in this country.</br>Please choose another country or language.', 'wordlift'),
307 307
 			)
308 308
 		);
309 309
 
310 310
 		// Add the `publisher` field.
311 311
 		add_settings_field(
312 312
 			'wl-publisher-id',
313
-			__( 'Publisher', 'wordlift' ),
314
-			array( $this->publisher_element, 'render' ),
313
+			__('Publisher', 'wordlift'),
314
+			array($this->publisher_element, 'render'),
315 315
 			'wl_general_settings',
316 316
 			'wl_general_settings_section',
317 317
 			array(
318 318
 				'id'   => 'wl-publisher-id',
319
-				'name' => 'wl_general_settings[' . Wordlift_Configuration_Service::PUBLISHER_ID . ']',
319
+				'name' => 'wl_general_settings['.Wordlift_Configuration_Service::PUBLISHER_ID.']',
320 320
 			)
321 321
 		);
322 322
 
323 323
 		// Add the `link by default` field.
324 324
 		add_settings_field(
325 325
 			'wl-link-by-default',
326
-			__( 'Link by Default', 'wordlift' ),
327
-			array( $this->radio_input_element, 'render' ),
326
+			__('Link by Default', 'wordlift'),
327
+			array($this->radio_input_element, 'render'),
328 328
 			'wl_general_settings',
329 329
 			'wl_general_settings_section',
330 330
 			array(
331 331
 				'id'          => 'wl-link-by-default',
332
-				'name'        => 'wl_general_settings[' . Wordlift_Configuration_Service::LINK_BY_DEFAULT . ']',
332
+				'name'        => 'wl_general_settings['.Wordlift_Configuration_Service::LINK_BY_DEFAULT.']',
333 333
 				'value'       => Wordlift_Configuration_Service::get_instance()->is_link_by_default() ? 'yes' : 'no',
334
-				'description' => __( 'Whether to link entities by default or not. This setting applies to all the entities.', 'wordlift' ),
334
+				'description' => __('Whether to link entities by default or not. This setting applies to all the entities.', 'wordlift'),
335 335
 			)
336 336
 		);
337 337
 
338 338
 		// Add the `diagnostic data` field.
339 339
 		add_settings_field(
340 340
 			'wl-send-diagnostic',
341
-			__( 'Send Diagnostic Data', 'wordlift' ),
342
-			array( $this->radio_input_element, 'render' ),
341
+			__('Send Diagnostic Data', 'wordlift'),
342
+			array($this->radio_input_element, 'render'),
343 343
 			'wl_general_settings',
344 344
 			'wl_general_settings_section',
345 345
 			array(
346 346
 				'id'          => 'wl-send-diagnostic',
347
-				'name'        => 'wl_general_settings[' . Wordlift_Configuration_Service::SEND_DIAGNOSTIC . ']',
347
+				'name'        => 'wl_general_settings['.Wordlift_Configuration_Service::SEND_DIAGNOSTIC.']',
348 348
 				'value'       => 'yes' === Wordlift_Configuration_Service::get_instance()->get_diagnostic_preferences() ? 'yes' : 'no',
349
-				'description' => __( 'Whether to send diagnostic data or not.', 'wordlift' ),
349
+				'description' => __('Whether to send diagnostic data or not.', 'wordlift'),
350 350
 			)
351 351
 		);
352 352
 
@@ -362,10 +362,10 @@  discard block
 block discarded – undo
362 362
 	 * @since 3.17.0
363 363
 	 *
364 364
 	 */
365
-	public function entity_path_input_element_params( $args ) {
365
+	public function entity_path_input_element_params($args) {
366 366
 
367 367
 		// Bail out if it's not the `wl-entity-base-path`).
368
-		if ( 'wl-entity-base-path' !== $args['id'] ) {
368
+		if ('wl-entity-base-path' !== $args['id']) {
369 369
 			return $args;
370 370
 		}
371 371
 
@@ -388,20 +388,20 @@  discard block
 block discarded – undo
388 388
 	 * @since 3.11.0
389 389
 	 *
390 390
 	 */
391
-	function sanitize_callback( $input ) {
391
+	function sanitize_callback($input) {
392 392
 
393 393
 		// Check whether a publisher name has been set.
394
-		if ( isset( $_POST['wl_publisher'] ) && ! empty( $_POST['wl_publisher']['name'] ) ) { // WPCS: CSRF, input var, sanitization ok.
395
-			$name         = isset( $_POST['wl_publisher']['name'] ) ? (string) $_POST['wl_publisher']['name'] : '';
396
-			$type         = isset( $_POST['wl_publisher']['type'] ) ? (string) $_POST['wl_publisher']['type'] : '';
397
-			$thumbnail_id = isset( $_POST['wl_publisher']['thumbnail_id'] ) ? $_POST['wl_publisher']['thumbnail_id'] : null; // WPCS: CSRF, input var, sanitization ok.
394
+		if (isset($_POST['wl_publisher']) && ! empty($_POST['wl_publisher']['name'])) { // WPCS: CSRF, input var, sanitization ok.
395
+			$name         = isset($_POST['wl_publisher']['name']) ? (string) $_POST['wl_publisher']['name'] : '';
396
+			$type         = isset($_POST['wl_publisher']['type']) ? (string) $_POST['wl_publisher']['type'] : '';
397
+			$thumbnail_id = isset($_POST['wl_publisher']['thumbnail_id']) ? $_POST['wl_publisher']['thumbnail_id'] : null; // WPCS: CSRF, input var, sanitization ok.
398 398
 
399 399
 			// Set the type URI, either http://schema.org/Person or http://schema.org/Organization.
400
-			$type_uri = sprintf( 'http://schema.org/%s', 'organization' === $type ? 'Organization' : 'Person' );
400
+			$type_uri = sprintf('http://schema.org/%s', 'organization' === $type ? 'Organization' : 'Person');
401 401
 
402 402
 			// Create an entity for the publisher and assign it to the input
403 403
 			// parameter which WordPress automatically saves into the settings.
404
-			$input['publisher_id'] = $this->entity_service->create( $name, $type_uri, $thumbnail_id, 'publish' );
404
+			$input['publisher_id'] = $this->entity_service->create($name, $type_uri, $thumbnail_id, 'publish');
405 405
 		}
406 406
 
407 407
 		return $input;
Please login to merge, or discard this patch.