Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
0.00% |
0 / 29 |
|
0.00% |
0 / 4 |
CRAP | |
0.00% |
0 / 1 |
EventService | |
0.00% |
0 / 29 |
|
0.00% |
0 / 4 |
182 | |
0.00% |
0 / 1 |
send | |
0.00% |
0 / 15 |
|
0.00% |
0 / 1 |
12 | |||
validate_category | |
0.00% |
0 / 5 |
|
0.00% |
0 / 1 |
12 | |||
validate_action | |
0.00% |
0 / 4 |
|
0.00% |
0 / 1 |
6 | |||
validate | |
0.00% |
0 / 5 |
|
0.00% |
0 / 1 |
30 |
1 | <?php |
2 | |
3 | namespace NewfoldLabs\WP\Module\Performance\Services; |
4 | |
5 | use NewfoldLabs\WP\Module\Performance\Data\Events; |
6 | |
7 | /** |
8 | * Class for handling Hiive events. |
9 | */ |
10 | class EventService { |
11 | |
12 | /** |
13 | * Sends a Hiive Event to the data module API. |
14 | * |
15 | * @param array $event The event to send. |
16 | * @return WP_REST_Response|WP_Error |
17 | */ |
18 | public static function send( $event ) { |
19 | $event = self::validate( $event ); |
20 | if ( ! $event ) { |
21 | return new \WP_Error( |
22 | 'nfd_module_performance_error', |
23 | __( 'Bad event structure/value.', 'wp-module-performance' ) |
24 | ); |
25 | } |
26 | |
27 | $event_data_request = new \WP_REST_Request( |
28 | \WP_REST_Server::CREATABLE, |
29 | NFD_MODULE_DATA_EVENTS_API |
30 | ); |
31 | $event_data_request->set_body_params( $event ); |
32 | |
33 | $response = rest_do_request( $event_data_request ); |
34 | if ( $response->is_error() ) { |
35 | return $response->as_error(); |
36 | } |
37 | |
38 | return $response; |
39 | } |
40 | |
41 | /** |
42 | * Validates the category of an event. |
43 | * |
44 | * @param string $category The category of an event. |
45 | * @return boolean |
46 | */ |
47 | public static function validate_category( $category ) { |
48 | $default_categories = Events::get_category(); |
49 | foreach ( $default_categories as $event_category ) { |
50 | if ( $event_category === $category ) { |
51 | return true; |
52 | } |
53 | } |
54 | return false; |
55 | } |
56 | |
57 | /** |
58 | * Validates the action performed in an event. |
59 | * |
60 | * @param string $action The action performed in an event. |
61 | * @return boolean |
62 | */ |
63 | public static function validate_action( $action ) { |
64 | $valid_actions = Events::get_valid_actions(); |
65 | if ( ! isset( $valid_actions[ $action ] ) ) { |
66 | return false; |
67 | } |
68 | |
69 | return true; |
70 | } |
71 | |
72 | /** |
73 | * Sanitizes and validates the action and category parameters of an event. |
74 | * |
75 | * @param array $event The event to sanitize and validate. |
76 | * @return array|boolean |
77 | */ |
78 | public static function validate( $event ) { |
79 | if ( ! isset( $event['action'] ) || ! self::validate_action( $event['action'] ) ) { |
80 | return false; |
81 | } |
82 | |
83 | if ( ! isset( $event['category'] ) || ! self::validate_category( $event['category'] ) ) { |
84 | return false; |
85 | } |
86 | |
87 | return $event; |
88 | } |
89 | } |