1 | <?php |
||
2 | |||
3 | namespace Mamaduka\BpNotifications; |
||
4 | |||
5 | use InvalidArgumentException; |
||
6 | |||
7 | /** |
||
8 | * Messages service. |
||
9 | */ |
||
10 | class MessagesService implements Service { |
||
11 | |||
12 | /** |
||
13 | * Register the current Registerable. |
||
14 | * |
||
15 | * @return void |
||
16 | */ |
||
17 | public function register() { |
||
18 | 1 | add_filter( 'bp_activity_notification_callback', function ( $callback ) { |
|
0 ignored issues
–
show
|
|||
19 | return [ $this, 'callback' ]; |
||
20 | 1 | } ); |
|
21 | 1 | } |
|
22 | |||
23 | /** |
||
24 | * Filter Activity notifications description. |
||
25 | * |
||
26 | * @return mixed |
||
27 | */ |
||
28 | 3 | public function callback( $action, $activity_id, $user_id, $total, $format = 'string', $id ) { |
|
29 | $data = [ |
||
30 | 3 | 'id' => $id, |
|
31 | 3 | 'action' => $action, |
|
32 | 3 | 'activity_id' => $activity_id, |
|
33 | 3 | 'user_id' => $user_id, |
|
34 | 3 | 'total' => $total, |
|
35 | 3 | 'format' => $format, |
|
36 | ]; |
||
37 | |||
38 | 3 | $messages = $this->getMessages(); |
|
39 | |||
40 | 3 | $message = $this->instantiateMessage( $data, $messages ); |
|
41 | |||
42 | 2 | if ( $format === 'string' ) { |
|
43 | 1 | return $message->toHtml(); |
|
44 | } |
||
45 | |||
46 | 1 | return $message->toArray(); |
|
47 | } |
||
48 | |||
49 | /** |
||
50 | * Instantiate message. |
||
51 | * |
||
52 | * @param array $data |
||
53 | * @param array $messages |
||
54 | * |
||
55 | * @return Messages\Message |
||
56 | * @throws InvalidArgumentException |
||
57 | */ |
||
58 | protected function instantiateMessage( array $data, array $messages ) { |
||
59 | $action = $data['action']; |
||
60 | |||
61 | if ( ! array_key_exists( $action, $messages ) ) { |
||
62 | throw new InvalidArgumentException( sprintf( |
||
63 | 'Message class for %s action does not exist', |
||
64 | $action |
||
65 | ) ); |
||
66 | } |
||
67 | |||
68 | $message = new $messages[ $action ]( $data ); |
||
69 | |||
70 | if ( ! $message instanceof Messages\Message ) { |
||
71 | throw new InvalidArgumentException( sprintf( |
||
72 | 'The message "%s" is not recognized and cannot be rendered', |
||
73 | is_object( $message ) ? get_class( $message ) : (string) $message |
||
74 | ) ); |
||
75 | } |
||
76 | |||
77 | return $message; |
||
78 | } |
||
79 | |||
80 | /** |
||
81 | * Get list of notification messages. |
||
82 | * |
||
83 | * @return array |
||
84 | */ |
||
85 | protected function getMessages() { |
||
86 | return [ |
||
87 | 'new_at_mention' => Messages\AtMentionMessage::class, |
||
88 | 'update_reply' => Messages\UpdateReplyMessage::class, |
||
89 | 'comment_reply' => Messages\CommentReplyMessage::class, |
||
90 | ]; |
||
91 | } |
||
92 | } |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.