Completed
Push — master ( 4e57eb...947d26 )
by J.D.
02:55
created

WordPoints_Hook_Firer_Reverse::do_event()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 39
Code Lines 19

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 39
rs 6.7272
cc 7
eloc 19
nc 6
nop 2
1
<?php
2
3
/**
4
 * Reverse hook firer class.
5
 *
6
 * @package wordpoints-hooks-api
7
 * @since   1.0.0
8
 */
9
10
/**
11
 * Fires a reverse action for a hook event.
12
 *
13
 * @since 1.0.0
14
 */
15
class WordPoints_Hook_Firer_Reverse extends WordPoints_Hook_Firer {
16
17
	/**
18
	 * @since 1.0.0
19
	 */
20
	public function do_event( $event_slug, WordPoints_Hook_Event_Args $event_args ) {
21
22
		$hooks = wordpoints_hooks();
23
24
		foreach ( $this->get_hits( $event_slug, $event_args ) as $hit ) {
25
26
			$reactor = $hooks->reactors->get( $hit->reactor );
27
28
			if ( ! $reactor instanceof WordPoints_Hook_Reactor ) {
29
				continue;
30
			}
31
32
			$reactions = $reactor->get_reaction_group( $hit->reaction_type );
33
34
			if (
35
				! $reactions
36
				|| wp_json_encode( $reactions->get_context_id() ) !== $hit->reaction_context_id
37
			) {
38
				continue;
39
			}
40
41
			$reaction = $reactions->get_reaction( $hit->reaction_id );
42
43
			if ( ! $reaction ) {
44
				continue;
45
			}
46
47
			$fire = new WordPoints_Hook_Fire( $this, $event_args, $reaction, $hit );
48
49
			$fire->hit();
50
51
			$reactor->reverse_hit( $fire );
52
53
			/** @var WordPoints_Hook_Extension $extension */
54
			foreach ( $hooks->extensions->get_all() as $extension ) {
55
				$extension->after_reverse( $fire );
56
			}
57
		}
58
	}
59
60
	/**
61
	 * Retrieves a list of all hits matching this event that have not been reversed.
62
	 *
63
	 * @since 1.0.0
64
	 *
65
	 * @param string                     $event_slug The slug of the event.
66
	 * @param WordPoints_Hook_Event_Args $event_args The args for the event.
67
	 *
68
	 * @return object[] The data for each hit from the hit logs database table.
69
	 */
70
	protected function get_hits( $event_slug, WordPoints_Hook_Event_Args $event_args ) {
71
72
		global $wpdb;
73
74
		$hits = $wpdb->get_results(
75
			$wpdb->prepare(
76
				"
77
					SELECT *
78
					FROM `{$wpdb->wordpoints_hook_hits}`
79
					WHERE `firer` = 'fire'
80
					AND `primary_arg_guid` = %s
81
					AND `event` = %s
82
					AND `superseded_by` IS NULL
83
				"
84
				, wordpoints_hooks_get_event_primary_arg_guid_json( $event_args )
85
				, $event_slug
86
			)
87
		);
88
89
		if ( ! is_array( $hits ) ) {
90
			return array();
91
		}
92
93
		return $hits;
94
	}
95
}
96
97
// EOF
98