Completed
Push — develop ( 2b9d63...78c426 )
by
unknown
03:31
created

Wordlift_Entity_Service::is_used()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 42
Code Lines 20

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 42
rs 8.5806
cc 4
eloc 20
nc 4
nop 1
1
<?php
2
3
/**
4
 * Provide entity-related services.
5
 *
6
 * @since 3.1.0
7
 */
8
class Wordlift_Entity_Service {
9
10
	/**
11
	 * The Log service.
12
	 *
13
	 * @since 3.2.0
14
	 * @access private
15
	 * @var \Wordlift_Log_Service $log_service The Log service.
16
	 */
17
	private $log_service;
18
19
	/**
20
	 * The UI service.
21
	 *
22
	 * @since 3.2.0
23
	 * @access private
24
	 * @var \Wordlift_UI_Service $ui_service The UI service.
25
	 */
26
	private $ui_service;
27
28
	/**
29
	 * The Schema service.
30
	 *
31
	 * @since 3.3.0
32
	 * @access private
33
	 * @var \Wordlift_Schema_Service $schema_service The Schema service.
34
	 */
35
	private $schema_service;
36
37
	/**
38
	 * The Notice service.
39
	 *
40
	 * @since 3.3.0
41
	 * @access private
42
	 * @var \Wordlift_Notice_Service $notice_service The Notice service.
43
	 */
44
	private $notice_service;
45
46
	/**
47
	 * The entity post type name.
48
	 *
49
	 * @since 3.1.0
50
	 */
51
	const TYPE_NAME = 'entity';
52
53
	/**
54
	 * Entity rating max.
55
	 *
56
	 * @since 3.3.0
57
	 */
58
	const RATING_MAX = 7;
59
	
60
	/**
61
	 * Entity rating score meta key.
62
	 *
63
	 * @since 3.3.0
64
	 */
65
	const RATING_RAW_SCORE_META_KEY = '_wl_entity_rating_raw_score';
66
	
67
	/**
68
	 * Entity rating warnings meta key.
69
	 *
70
	 * @since 3.3.0
71
	 */
72
	const RATING_WARNINGS_META_KEY = '_wl_entity_rating_warnings';
73
74
	/**
75
	 * Entity warning has related post identifier.
76
	 *
77
	 * @since 3.3.0
78
	 */
79
	const RATING_WARNING_HAS_RELATED_POSTS = 'There are no related posts for the current entity.';
80
81
	/**
82
	 * Entity warning has content post identifier.
83
	 *
84
	 * @since 3.3.0
85
	 */
86
	const RATING_WARNING_HAS_CONTENT_POST = 'This entity has not description.';
87
88
	/**
89
	 * Entity warning has related entities identifier.
90
	 *
91
	 * @since 3.3.0
92
	 */
93
	const RATING_WARNING_HAS_RELATED_ENTITIES = 'There are no related entities for the current entity.';
94
95
	/**
96
	 * Entity warning is published identifier.
97
	 *
98
	 * @since 3.3.0
99
	 */
100
	const RATING_WARNING_IS_PUBLISHED = 'This entity is not published. It will not appear within analysis results.';
101
102
	/**
103
	 * Entity warning has thumbnail identifier.
104
	 *
105
	 * @since 3.3.0
106
	 */
107
	const RATING_WARNING_HAS_THUMBNAIL = 'This entity has no featured image yet.';
108
109
	/**
110
	 * Entity warning has same as identifier.
111
	 *
112
	 * @since 3.3.0
113
	 */
114
	const RATING_WARNING_HAS_SAME_AS = 'There are no sameAs configured for this entity.';
115
116
	/**
117
	 * Entity warning has completed metadata identifier.
118
	 *
119
	 * @since 3.3.0
120
	 */
121
	const RATING_WARNING_HAS_COMPLETED_METADATA = 'Schema.org metadata for this entity are not completed.';
122
123
	/**
124
	 * The alternative label meta key.
125
	 *
126
	 * @since 3.2.0
127
	 */
128
	const ALTERNATIVE_LABEL_META_KEY = '_wl_alt_label';
129
130
	/**
131
	 * The alternative label input template.
132
	 *
133
	 * @since 3.2.0
134
	 */
135
	// TODO: this should be moved to a class that deals with HTML code.
136
	const ALTERNATIVE_LABEL_INPUT_TEMPLATE = '<div class="wl-alternative-label">
137
                <label class="screen-reader-text" id="wl-alternative-label-prompt-text" for="wl-alternative-label">Enter alternative label here</label>
138
                <input name="wl_alternative_label[]" size="30" value="%s" id="wl-alternative-label" type="text">
139
                <button class="button wl-delete-button">%s</button>
140
                </div>';
141
142
	/**
143
	 * A singleton instance of the Entity service.
144
	 *
145
	 * @since 3.2.0
146
	 * @access private
147
	 * @var \Wordlift_Entity_Service $instance A singleton instance of the Entity service.
148
	 */
149
	private static $instance;
150
151
	/**
152
	 * Create a Wordlift_Entity_Service instance.
153
	 *
154
	 * @since 3.2.0
155
	 *
156
	 * @param \Wordlift_UI_Service $ui_service The UI service.
157
	 */
158
	public function __construct( $ui_service, $schema_service, $notice_service ) {
159
160
		$this->log_service = Wordlift_Log_Service::get_logger( 'Wordlift_Entity_Service' );
161
162
		// Set the UI service.
163
		$this->ui_service = $ui_service;
164
165
		// Set the Schema service.
166
		$this->schema_service = $schema_service;
167
168
		// Set the Schema service.
169
		$this->notice_service = $notice_service;
170
171
		// Set the singleton instance.
172
		self::$instance = $this;
173
174
	}
175
176
	/**
177
	 * Get the singleton instance of the Entity service.
178
	 *
179
	 * @since 3.2.0
180
	 * @return \Wordlift_Entity_Service The singleton instance of the Entity service.
181
	 */
182
	public static function get_instance() {
183
184
		return self::$instance;
185
	}
186
187
	/**
188
	 * Get rating max 
189
	 *
190
	 * @since 3.3.0
191
	 *
192
	 * @return int Max rating according to performed checks.
193
	 */
194
	public static function get_rating_max() {
195
		return self::RATING_MAX;
196
	}
197
198
	/**
199
	 * Get the entities related to the last 50 posts published on this blog (we're keeping a long function name due to
200
	 * its specific function).
201
	 *
202
	 * @since 3.1.0
203
	 *
204
	 * @return array An array of post IDs.
205
	 */
206
	public function get_all_related_to_last_50_published_posts() {
207
208
		// Global timeline. Get entities from the latest posts.
209
		$latest_posts_ids = get_posts( array(
210
			'numberposts' => 50,
211
			'fields'      => 'ids', //only get post IDs
212
			'post_type'   => 'post',
213
			'post_status' => 'publish'
214
		) );
215
216
		if ( empty( $latest_posts_ids ) ) {
217
			// There are no posts.
218
			return array();
219
		}
220
221
		// Collect entities related to latest posts
222
		$entity_ids = array();
223
		foreach ( $latest_posts_ids as $id ) {
224
			$entity_ids = array_merge( $entity_ids, wl_core_get_related_entity_ids( $id, array(
225
				'status' => 'publish'
226
			) ) );
227
		}
228
229
		return $entity_ids;
230
	}
231
232
	/**
233
	 * Determines whether a post is an entity or not.
234
	 *
235
	 * @since 3.1.0
236
	 *
237
	 * @param int $post_id A post id.
238
	 *
239
	 * @return bool Return true if the post is an entity otherwise false.
240
	 */
241
	public function is_entity( $post_id ) {
242
243
		return ( self::TYPE_NAME === get_post_type( $post_id ) );
244
	}
245
246
	/**
247
	 * Build an entity uri for a given title
248
	 * The uri is composed using a given post_type and a title
249
	 * If already exists an entity e2 with a given uri a numeric suffix is added
250
	 * If a schema type is given entities with same label and same type are overridden 
251
	 *
252
	 * @since 3.5.0
253
	 *
254
	 * @param string $title A post title.
255
	 * @param string $post_type A post type. Default value is 'entity'
256
	 * @param string $schema_type A schema org type. 
257
	 * @param integer $increment_digit A digit used to call recursively the same function.
258
	 *
259
	 * @return string Returns an uri.
260
	 */
261
	public function build_uri( $title, $post_type, $schema_type = NULL, $increment_digit = 0 ) {
262
		
263
		// Get the entity slug suffix digit
264
		$suffix_digit = $increment_digit + 1;
265
		// Get a sanitized uri for a given title
266
		$entity_slug = ( 0 == $increment_digit ) ? 
267
			wl_sanitize_uri_path( $title ) :
268
			wl_sanitize_uri_path( $title . '_'. $suffix_digit );
269
270
		// Compose a candidated uri
271
		$new_entity_uri = sprintf( '%s/%s/%s', 
272
			wl_configuration_get_redlink_dataset_uri(), 
273
			$post_type, 
274
			$entity_slug 
275
		); 
276
		
277
		$this->log_service->trace( "Going to check if uri is used [ new_entity_uri :: $new_entity_uri ] [ increment_digit :: $increment_digit ]" );
278
		
279
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
280
    	// Check if the candidated uri already is used
281
    	// TODO Get post ids instead of count()
282
		$stmt = $wpdb->prepare( 
283
    		"SELECT post_id FROM $wpdb->postmeta WHERE meta_key = %s AND meta_value = %s LIMIT 1", 
284
    		WL_ENTITY_URL_META_NAME,
285
    		$new_entity_uri
286
    	);
287
288
    	// Perform the query
289
		$post_id = $wpdb->get_var( $stmt ); 		
290
			
291
		// If the post does not exist, then the new uri is returned 	
0 ignored issues
show
Coding Style introduced by
There is some trailing whitespace on this line which should be avoided as per coding-style.
Loading history...
292
		if ( ! is_numeric( $post_id ) ) {
293
			$this->log_service->trace( "Going to return uri [ new_entity_uri :: $new_entity_uri ]" );
294
			return $new_entity_uri;
295
		}
296
		// If schema_type is equal to schema org type of post x, then the new uri is returned 
297
		$schema_post_type = wl_entity_type_taxonomy_get_type( $post_id );
298
			
299
		if ( $schema_type === $schema_post_type[ 'css_class' ] ) {
300
			$this->log_service->trace( "An entity with the same title and type already exists! Return uri [ new_entity_uri :: $new_entity_uri ]" );
301
			return $new_entity_uri;
302
		}
303
304
		// Otherwise the same function is called recorsively
305
		return $this->build_uri( $title, $post_type, $schema_type, ++$increment_digit );
306
	}
307
308
	public function is_used( $post_id ) {
309
310
		if ( FALSE === $this->is_entity( $post_id ) ) {
311
			return null;
312
		}
313
		// Retrieve the post
314
		$entity = get_post( $post_id ); 
315
316
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
317
    	// Retrieve Wordlift relation instances table name
318
    	$table_name = wl_core_get_relation_instances_table_name();
319
320
		// Check is it's referenced / related to another post / entity
321
    	$stmt = $wpdb->prepare( 
322
    		"SELECT COUNT(*) FROM $table_name WHERE  object_id = %d", 
323
    		$entity->ID
324
    	);
325
		
326
		// Perform the query
327
		$relation_instances = (int) $wpdb->get_var( $stmt ); 
328
		// If there is at least one relation instance for the current entity, then it's used
329
		if ( 0 < $relation_instances ) {		
330
			return TRUE;
331
		}
332
333
    	// Check if the entity uri is used as meta_value
334
		$stmt = $wpdb->prepare( 
335
    		"SELECT COUNT(*) FROM $wpdb->postmeta WHERE post_id != %d AND meta_value = %s", 
336
    		$entity->ID,
337
    		wl_get_entity_uri( $entity->ID )
338
    	);
339
    	// Perform the query
340
		$meta_instances = (int) $wpdb->get_var( $stmt ); 
341
		
342
		// If there is at least one meta that refers the current entity uri, then current entity is used
343
		if ( 0 < $meta_instances ) {
344
			return TRUE;
345
		}
346
347
		// If we are here, it means the current entity is not used at the moment
348
		return FALSE;
349
	}
350
351
	/**
352
	 * Determines whether a given uri is an internal uri or not.
353
	 *
354
	 * @since 3.3.2
355
	 *
356
	 * @param int $uri An uri.
357
	 *
358
	 * @return true if the uri internal to the current dataset otherwise false.
359
	 */
360
	public function is_internal_uri( $uri ) {
361
362
		return ( 0 === strrpos( $uri, wl_configuration_get_redlink_dataset_uri() ) );
363
	}
364
365
	/**
366
	 * Find entity posts by the entity URI. Entity as searched by their entity URI or same as.
367
	 *
368
	 * @since 3.2.0
369
	 *
370
	 * @param string $uri The entity URI.
371
	 *
372
	 * @return WP_Post|null A WP_Post instance or null if not found.
373
	 */
374
	public function get_entity_post_by_uri( $uri ) {
375
376
		$query_args = array(
377
			'posts_per_page'	=> 1,
378
			'post_status'		=> 'any',
379
			'post_type'			=> self::TYPE_NAME,
380
			'meta_query'		=> array(
381
				array(
382
					'key'     => WL_ENTITY_URL_META_NAME,
383
					'value'   => $uri,
384
					'compare' => '='
385
				)
386
			)
387
		);
388
389
		// Only if the current uri is not an internal uri 
390
		// entity search is performed also looking at sameAs values
391
		// This solve issues like https://github.com/insideout10/wordlift-plugin/issues/237
392
		if ( !$this->is_internal_uri( $uri ) ) {
393
		
394
			$query_args[ 'meta_query' ][ 'relation' ] = 'OR';
395
			$query_args[ 'meta_query' ][] = array(
396
				'key'     => Wordlift_Schema_Service::FIELD_SAME_AS,
397
				'value'   => $uri,
398
				'compare' => '='
399
			);
400
		} 
401
402
		$query = new WP_Query( $query_args );
403
404
		// Get the matching entity posts.
405
		$posts = $query->get_posts();
406
407
		// Return null if no post is found.
408
		if ( 0 === count( $posts ) ) {
409
			return null;
410
		}
411
412
		// Return the found post.
413
		return $posts[0];
414
	}
415
416
	/**
417
	 * Fires once a post has been saved.
418
	 *
419
	 * @since 3.2.0
420
	 *
421
	 * @param int $post_id Post ID.
422
	 * @param WP_Post $post Post object.
423
	 * @param bool $update Whether this is an existing post being updated or not.
424
	 */
425
	public function save_post( $post_id, $post, $update ) {
0 ignored issues
show
Unused Code introduced by
The parameter $post is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $update is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Coding Style introduced by
save_post uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
426
427
		// If it's not an entity, return.
428
		if ( ! $this->is_entity( $post_id ) ) {
429
			return;
430
		}
431
432
		// Get the alt labels from the request (or empty array).
433
		$alt_labels = isset( $_REQUEST['wl_alternative_label'] ) ? $_REQUEST['wl_alternative_label'] : array();
434
435
		// Set the alternative labels.
436
		$this->set_alternative_labels( $post_id, $alt_labels );
437
438
	}
439
440
	/**
441
	 * Set the alternative labels.
442
	 *
443
	 * @since 3.2.0
444
	 *
445
	 * @param int $post_id The post id.
446
	 * @param array $alt_labels An array of labels.
447
	 */
448
	public function set_alternative_labels( $post_id, $alt_labels ) {
449
		
450
		// Force $alt_labels to be an array
451
		if( !is_array( $alt_labels ) ) {
452
			$alt_labels = array( $alt_labels );
453
		}
454
455
		$this->log_service->debug( "Setting alternative labels [ post id :: $post_id ][ alt labels :: " . implode( ',', $alt_labels ) . " ]" );
456
457
		// Delete all the existing alternate labels.
458
		delete_post_meta( $post_id, self::ALTERNATIVE_LABEL_META_KEY );
459
		
460
		// Set the alternative labels.
461
		foreach ( $alt_labels as $alt_label ) {
462
			if ( ! empty( $alt_label ) ) {
463
				add_post_meta( $post_id, self::ALTERNATIVE_LABEL_META_KEY, $alt_label );
464
			}
465
		}
466
467
	}
468
469
	/**
470
	 * Retrieve the alternate labels.
471
	 *
472
	 * @since 3.2.0
473
	 *
474
	 * @param int $post_id Post id.
475
	 *
476
	 * @return mixed An array  of alternative labels.
477
	 */
478
	public function get_alternative_labels( $post_id ) {
479
480
		return get_post_meta( $post_id, self::ALTERNATIVE_LABEL_META_KEY );
481
	}
482
483
	/**
484
	 * Fires before the permalink field in the edit form (this event is available in WP from 4.1.0).
485
	 *
486
	 * @since 3.2.0
487
	 *
488
	 * @param WP_Post $post Post object.
489
	 */
490
	public function edit_form_before_permalink( $post ) {
491
492
		// If it's not an entity, return.
493
		if ( ! $this->is_entity( $post->ID ) ) {
494
			return;
495
		}
496
497
		// Print the input template.
498
		$this->ui_service->print_template( 'wl-tmpl-alternative-label-input', $this->get_alternative_label_input() );
499
500
		// Print all the currently set alternative labels.
501
		foreach ( $this->get_alternative_labels( $post->ID ) as $alt_label ) {
502
503
			echo $this->get_alternative_label_input( $alt_label );
504
505
		};
506
507
		// Print the button.
508
		$this->ui_service->print_button( 'wl-add-alternative-labels-button', __( 'Add more titles', 'wordlift' ) );
509
510
	}
511
512
	/**
513
	 * Add admin notices for the current entity depending on the current rating.
514
	 *
515
	 * @since 3.3.0
516
	 *
517
	 * @param WP_Post $post Post object.
0 ignored issues
show
Bug introduced by
There is no parameter named $post. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
518
	 */
519
	public function in_admin_header() {
520
521
		// Return safely if get_current_screen() is not defined (yet)
522
		if ( FALSE === function_exists( 'get_current_screen' ) ) {
523
			return;
524
		}
525
		
526
		$screen = get_current_screen();
527
		// If there is any valid screen nothing to do
528
		if ( NULL === $screen ) {
529
			return $clauses;
0 ignored issues
show
Bug introduced by
The variable $clauses does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
530
		}
531
532
		// If you're not in the entity post edit page, return.
533
		if ( self::TYPE_NAME !== $screen->id ) {
534
			return;
535
		}
536
		// Retrieve the current global post
537
		global $post;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
538
		// If it's not an entity, return.
539
		if ( ! $this->is_entity( $post->ID ) ) {
540
			return;
541
		}
542
		// Retrieve an updated rating for the current entity
543
		$rating = $this->get_rating_for( $post->ID, true );
544
		// If there is at least 1 warning
545
		if ( isset( $rating[ 'warnings' ] ) && 0 < count( $rating[ 'warnings' ] ) ) {
546
			// TODO - Pass Wordlift_Notice_Service trough the service constructor 
547
			$this->notice_service->add_suggestion( $rating[ 'warnings' ] );
548
		}
549
		
550
	}
551
	
552
	/**
553
	 * Set rating for a given entity
554
	 *
555
	 * @since 3.3.0
556
	 *
557
	 * @param int $post_id The entity post id.
558
	 *
559
	 * @return int An array representing the rating obj.
560
	 */
561
	public function set_rating_for( $post_id ) {
562
563
		// Calculate rating for the given post
564
		$rating = $this->calculate_rating_for( $post_id );
565
		// Store the rating on db as post meta
566
		// Please notice that RATING_RAW_SCORE_META_KEY 
567
		// is saved on a different meta to allow score sorting
568
		// Both meta are managed as unique
569
		// https://codex.wordpress.org/Function_Reference/update_post_meta
570
		update_post_meta( $post_id, self::RATING_RAW_SCORE_META_KEY, $rating[ 'raw_score' ] );
571
		update_post_meta( $post_id, self::RATING_WARNINGS_META_KEY, $rating[ 'warnings' ] );
572
		
573
		$this->log_service->trace( sprintf( "Rating set for [ post_id :: $post_id ] [ rating :: %s ]", $rating[ 'raw_score' ]  ) );
574
		
575
		// Finally returns the rating 
576
		return $rating;
577
	}
578
	/**
579
	 * Get or calculate rating for a given entity
580
	 *
581
	 * @since 3.3.0
582
	 *
583
	 * @param int $post_id The entity post id.
584
	 * @param $force_reload $warnings_needed If true, detailed warnings collection is provided with the rating obj.
0 ignored issues
show
Documentation introduced by
The doc-type $force_reload could not be parsed: Unknown type name "$force_reload" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
Bug introduced by
There is no parameter named $warnings_needed. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
585
	 *
586
	 * @return int An array representing the rating obj.
587
	 */
588
	public function get_rating_for( $post_id, $force_reload = false ) {
589
		
590
		// If forced reload is required or rating is missing ..
591
		if ( $force_reload ) {
592
			$this->log_service->trace( "Force rating reload [ post_id :: $post_id ]" );
593
			return $this->set_rating_for( $post_id );
594
		}
595
		
596
		$current_raw_score = get_post_meta( $post_id, self::RATING_RAW_SCORE_META_KEY, true );  
597
			
598
		if ( ! is_numeric( $current_raw_score ) ) {
599
			$this->log_service->trace( "Rating missing for [ post_id :: $post_id ] [ current_raw_score :: $current_raw_score ]" );
600
			return $this->set_rating_for( $post_id );
601
		}
602
		$current_warnings = get_post_meta( $post_id, self::RATING_WARNINGS_META_KEY, true );  
603
		
604
		// Finally return score and warnings
605
		return array( 
606
			'raw_score'				=> $current_raw_score,
607
			'traffic_light_score'	=> $this->convert_raw_score_to_traffic_light( $current_raw_score ),
608
			'percentage_score'		=> $this->convert_raw_score_to_percentage( $current_raw_score ),
609
			'warnings'				=> $current_warnings, 
610
		);
611
612
	}
613
	/**
614
	 * Calculate rating for a given entity
615
	 * Rating depends from following criteria
616
	 *
617
	 * 1. Is the current entity related to at least 1 post?
618
	 * 2. Is the current entity content post not empty?
619
	 * 3. Is the current entity related to at least 1 entity?
620
	 * 4. Is the entity published? 
621
	 * 5. There is a a thumbnail associated to the entity?
622
	 * 6. Has the entity a sameas defined?
623
	 * 7. Are all schema.org required metadata compiled?
624
	 *
625
	 * Each positive check means +1 in terms of rating score
626
	 *
627
	 * @since 3.3.0
628
	 *
629
	 * @param int $post_id The entity post id.
630
	 *
631
	 * @return int An array representing the rating obj.
632
	 */
633
	public function calculate_rating_for( $post_id ) {
634
		
635
		// If it's not an entity, return.
636
		if ( ! $this->is_entity( $post_id ) ) {
637
			return;
638
		}
639
		// Retrieve the post object
640
		$post = get_post( $post_id );
641
		// Rating value
642
		$score = 0;
643
		// Store warning messages
644
		$warnings = array();
645
646
		// Is the current entity related to at least 1 post?
647
		( 0 < count( wl_core_get_related_post_ids( $post->ID ) ) ) ?
648
			$score++ : 
649
			array_push( $warnings, __( self::RATING_WARNING_HAS_RELATED_POSTS, 'wordlift' ) );
650
		
651
		// Is the post content not empty?
652
		( ! empty( $post->post_content ) ) ?
653
			$score++ :
654
			array_push( $warnings, __( self::RATING_WARNING_HAS_CONTENT_POST, 'wordlift' ) );
655
		
656
		// Is the current entity related to at least 1 entity?
657
		// Was the current entity already disambiguated?
658
		( 0 < count( wl_core_get_related_entity_ids( $post->ID ) ) ) ?
659
			$score++ :
660
			array_push( $warnings, __( self::RATING_WARNING_HAS_RELATED_ENTITIES, 'wordlift' ) );
661
		
662
		// Is the entity published?
663
		( 'publish' === get_post_status( $post->ID ) ) ?
664
			$score++ :
665
			array_push( $warnings, __( self::RATING_WARNING_IS_PUBLISHED, 'wordlift' ) );
666
		
667
		// Has a thumbnail?
668
		( has_post_thumbnail( $post->ID ) ) ?
669
			$score++ :
670
			array_push( $warnings, __( self::RATING_WARNING_HAS_THUMBNAIL, 'wordlift' ) );
671
		
672
		// Get all post meta keys for the current post		
673
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
674
		$query = $wpdb->prepare( 
675
			"SELECT DISTINCT(meta_key) FROM $wpdb->postmeta  WHERE post_id = %d", $post->ID 
676
		);
677
		
678
		// Check intersection between available meta keys 
679
		// and expected ones arrays to detect missing values
680
		$available_meta_keys = $wpdb->get_col( $query );
681
682
		// If each expected key is contained in available keys array ...
683
		( in_array( Wordlift_Schema_Service::FIELD_SAME_AS, $available_meta_keys ) ) ?
684
			$score++ :
685
			array_push( $warnings, __( self::RATING_WARNING_HAS_SAME_AS, 'wordlift' ) );
686
		
687
		$schema = wl_entity_type_taxonomy_get_type( $post_id );
688
689
		$expected_meta_keys = ( null === $schema[ 'custom_fields' ] ) ? 
690
			array() : 
691
			array_keys( $schema[ 'custom_fields' ] );
692
693
		$intersection = array_intersect( $expected_meta_keys, $available_meta_keys );
694
		// If each expected key is contained in available keys array ...
695
		( count( $intersection ) === count( $expected_meta_keys ) ) ?
696
			$score++ :
697
			array_push( $warnings, __( self::RATING_WARNING_HAS_COMPLETED_METADATA, 'wordlift' ) );
698
		
699
		// Finally return score and warnings
700
		return array( 
701
			'raw_score'				=> $score,
702
			'traffic_light_score'	=> $this->convert_raw_score_to_traffic_light( $score ),
703
			'percentage_score'		=> $this->convert_raw_score_to_percentage( $score ),
704
			'warnings'				=> $warnings, 
705
		);
706
707
	}
708
709
	/**
710
	 * Get as rating as input and convert in a traffic-light rating
711
	 *
712
	 * @since 3.3.0
713
	 *
714
	 * @param int $score The rating score for a given entity.
715
	 *
716
	 * @return string The input HTML code.
717
	 */
718
	private function convert_raw_score_to_traffic_light( $score ) {
719
		// RATING_MAX : $score = 3 : x 
720
		// See http://php.net/manual/en/function.round.php
721
		$rating = round( ( $score * 3 ) / self::get_rating_max(), 0, PHP_ROUND_HALF_UP );
722
		// If rating is 0, return 1, otherwise return rating
723
		return ( 0 == $rating ) ? 1 : $rating; 
724
725
	}
726
727
	/**
728
	 * Get as rating as input and convert in a traffic-light rating
729
	 *
730
	 * @since 3.3.0
731
	 *
732
	 * @param int $score The rating score for a given entity.
733
	 *
734
	 * @return string The input HTML code.
735
	 */
736
	public function convert_raw_score_to_percentage( $score ) {
737
		// RATING_MAX : $score = 100 : x 
738
		return round( ( $score * 100) / self::get_rating_max(), 0, PHP_ROUND_HALF_UP );
739
	}
740
741
	/**
742
	 * Get the alternative label input HTML code.
743
	 *
744
	 * @since 3.2.0
745
	 *
746
	 * @param string $value The input value.
747
	 *
748
	 * @return string The input HTML code.
749
	 */
750
	private function get_alternative_label_input( $value = '' ) {
751
752
		return sprintf( self::ALTERNATIVE_LABEL_INPUT_TEMPLATE, esc_attr( $value ), __( 'Delete', 'wordlift' ) );
753
	}
754
}
755