Completed
Push — develop ( 6bede6...f6e111 )
by
unknown
26s
created

Top_Entities::save_top_entities()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 38
rs 9.312
c 0
b 0
f 0
1
<?php
2
3
namespace Wordlift\Admin;
4
/**
5
 * @since 3.27.7
6
 * @author Naveen Muthusamy <[email protected]>
7
 */
8
class Top_Entities {
9
10
	const CRON_ACTION = 'wl_admin_dashboard_top_entities';
11
12
	/**
13
	 * Option key where the top entities data is stored.
14
	 */
15
	const OPTION_KEY = 'wl_admin_dashboard_top_entities_option';
16
17
18
	public function __construct() {
19
		add_action( self::CRON_ACTION, array( $this, 'save_top_entities' ) );
20
	}
21
22
23
	public function save_top_entities() {
24
25
		global $wpdb;
26
27
		$query = <<<EOF
28
SELECT p.ID
29
     , p.post_title
30
     , coalesce(sum(case when obj_t.slug is null then 1 end), 0)     entities
31
     , coalesce(sum(case when obj_t.slug is not null then 1 end), 0) posts
32
     , count(entity.subject_id) AS                                   total
33
FROM {$wpdb->prefix}wl_relation_instances entity
34
       INNER JOIN {$wpdb->prefix}posts p
35
                  ON p.ID = entity.object_id
36
       INNER JOIN {$wpdb->prefix}term_relationships tr
37
                  ON tr.object_id = entity.object_id
38
       INNER JOIN {$wpdb->prefix}term_taxonomy tt
39
                  ON tt.term_id = tr.term_taxonomy_id
40
                    AND tt.taxonomy = 'wl_entity_type'
41
       INNER JOIN {$wpdb->prefix}terms t
42
                  ON t.term_id = tt.term_id
43
                    AND 'article' != t.slug
44
       INNER JOIN {$wpdb->prefix}term_relationships obj_tr
45
                  ON obj_tr.object_id = entity.subject_id
46
       INNER JOIN {$wpdb->prefix}term_taxonomy obj_tt
47
                  ON obj_tt.term_id = obj_tr.term_taxonomy_id
48
                    AND obj_tt.taxonomy = 'wl_entity_type'
49
       LEFT OUTER JOIN {$wpdb->prefix}terms obj_t
50
                       ON obj_t.term_id = obj_tt.term_id
51
                         AND 'article' = obj_t.slug
52
GROUP BY p.ID, p.post_title
53
ORDER BY total DESC
54
LIMIT 20;
55
EOF;
56
57
		$results = $wpdb->get_results( $query );
58
59
		update_option( self::OPTION_KEY, $results );
60
	}
61
62
63
	public static function activate() {
64
		if ( ! wp_next_scheduled( self::CRON_ACTION ) ) {
65
			wp_schedule_event( time(), 'hourly', self::CRON_ACTION );
66
		}
67
	}
68
69
	public static function deactivate() {
70
		$timestamp = wp_next_scheduled( self::CRON_ACTION );
71
		wp_unschedule_event( $timestamp, self::CRON_ACTION );
72
	}
73
74
}