Passed
Push — master ( 25783a...cd4854 )
by Paul
05:21
created

CreateReview::createWebhookNotification()   A

Complexity

Conditions 5
Paths 16

Size

Total Lines 25
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 19
nc 16
nop 1
dl 0
loc 25
ccs 0
cts 19
cp 0
crap 30
rs 9.3222
c 0
b 0
f 0
1
<?php
2
3
namespace GeminiLabs\SiteReviews\Handlers;
4
5
use Exception;
6
use GeminiLabs\SiteReviews\Commands\CreateReview as Command;
7
use GeminiLabs\SiteReviews\Database;
8
use GeminiLabs\SiteReviews\Database\OptionManager;
9
use GeminiLabs\SiteReviews\Database\ReviewManager;
10
use GeminiLabs\SiteReviews\Modules\Email;
11
use GeminiLabs\SiteReviews\Modules\Session;
12
use ReflectionException;
13
use WP_Error;
14
15
class CreateReview
16
{
17
	/**
18
	 * @var Command
19
	 */
20
	protected $command;
21
22
	/**
23
	 * @return void|string
24
	 */
25 1
	public function handle( Command $command )
26
	{
27 1
		$this->command = $command;
28 1
		$postId = glsr( ReviewManager::class )->create( $command );
29 1
		if( $postId < 1 ) {
30
			glsr( Session::class )->set( $command->form_id.'errors', [] );
31
			glsr( Session::class )->set( $command->form_id.'message', __( 'Your review could not be submitted and the error has been logged. Please notify the site admin.', 'site-reviews' ));
32
			return;
33
		}
34 1
		$this->sendNotification( $postId );
35 1
		do_action( 'site-reviews/local/review/submitted', $postId, $command );
36 1
		glsr( Session::class )->set( $command->form_id.'message', __( 'Your review has been submitted!', 'site-reviews' ));
37 1
		if( $command->ajax_request )return;
38
		wp_safe_redirect( $command->referrer );
39
		exit;
40
	}
41
42
	/**
43
	 * @return Email
44
	 */
45
	protected function createEmailNotification( array $args = [] )
46
	{
47
		$email = [
48
			'to' => $args['recipient'],
49
			'subject' => $args['notification_title'],
50
			'template' => 'email-notification',
51
			'template-tags' => [
52
				'review_author' => $this->command->author,
53
				'review_content' => $this->command->content,
54
				'review_email' => $this->command->email,
55
				'review_ip' => $this->command->ip_address,
56
				'review_link' => sprintf( '<a href="%1$s">%1$s</a>', $args['notification_link'] ),
57
				'review_rating' => $this->command->rating,
58
				'review_title' => $this->command->title,
59
			],
60
		];
61
		return glsr( Email::class )->compose( $email );
62
	}
63
64
	/**
65
	 * @return string
66
	 */
67
	protected function createWebhookNotification( array $args )
68
	{
69
		$fields = [];
70
		$fields[] = ['title' => str_repeat( ':star:', $this->command->rating )];
71
		if( $this->command->title ) {
72
			$fields[] = ['title' => $this->command->title];
73
		}
74
		if( $this->command->content ) {
75
			$fields[] = ['value' => $this->command->content];
76
		}
77
		if( $this->command->email ) {
78
			$this->command->email = ' <'.$this->command->email.'>';
79
		}
80
		if( $this->command->author ) {
81
			$fields[] = ['value' => trim( $this->command->author.$this->command->email.' - '.$this->command->ip_address )];
82
		}
83
		$fields[] = ['value' => sprintf( '<%s|%s>', $args['notification_link'], __( 'View Review', 'site-reviews' ))];
84
		return json_encode([
85
			'icon_url' => glsr()->url( 'assets/img/icon.png' ),
86
			'username' => glsr()->name,
87
			'attachments' => [[
88
				'pretext' => $args['notification_title'],
89
				'color' => '#665068',
90
				'fallback' => $this->createEmailNotification( $args )->read( 'plaintext' ),
91
				'fields' => $fields,
92
			]],
93
		]);
94
	}
95
96
	/**
97
	 * @param int $post_id
98
	 * @return void
99
	 */
100 1
	protected function sendNotification( $postId )
101
	{
102 1
		$notificationType = glsr( OptionManager::class )->get( 'settings.general.notification' );
103 1
		if( !in_array( $notificationType, ['default','custom','webhook'] ))return;
104
		$assignedToTitle = get_the_title( (int)$this->command->assigned_to );
105
		$notificationSubject = _nx(
106
			'New %s-star review',
107
			'New %s-star review of: %s',
108
			intval( empty( $assignedToTitle )),
109
			'The text is different depending on whether or not the review has been assigned to a post.',
110
			'site-reviews'
111
		);
112
		$notificationTitle = sprintf( '[%s] %s',
113
			wp_specialchars_decode( (string)get_option( 'blogname' ), ENT_QUOTES ),
114
			sprintf( $notificationSubject, $this->command->rating, $assignedToTitle )
115
		);
116
		$args = [
117
			'notification_link' => esc_url( admin_url( sprintf( 'post.php?post=%s&action=edit', $postId ))),
118
			'notification_title' => $notificationTitle,
119
			'notification_type' => $notificationType,
120
		];
121
		$notificationMethod = $args['notification_type'] == 'webhook'
122
			? 'sendWebhookNotification'
123
			: 'sendEmailNotification';
124
		$this->$notificationMethod( $args );
125
	}
126
127
	/**
128
	 * @return void
129
	 */
130
	protected function sendEmailNotification( array $args )
131
	{
132
		$args['recipient'] = $args['notification_type'] !== 'default'
133
			? glsr( OptionManager::class )->get( 'settings.general.notification_email' )
134
			: get_option( 'admin_email' );
135
		if( empty( $args['recipient'] )) {
136
			glsr_log()->error( 'Email notification was not sent: missing email, subject, or message.' );
137
		}
138
		else {
139
			$email = $this->createEmailNotification( $args );
140
			if( $email->send() === false ) {
141
				glsr_log()->error( 'Email notification was not sent: wp_mail() failed.' )->debug( $email );
142
			}
143
		}
144
	}
145
146
	/**
147
	 * @return void
148
	 */
149
	protected function sendWebhookNotification( array $args )
150
	{
151
		if( !( $endpoint = glsr( OptionManager::class )->get( 'settings.general.webhook_url' )))return;
152
		$notification = $this->createWebhookNotification( $args );
153
		$result = wp_remote_post( $endpoint, [
154
			'blocking' => false,
155
			'body' => apply_filters( 'site-reviews/webhook/notification', $notification, $this->command ),
156
			'headers' => ['Content-Type' => 'application/json'],
157
			'httpversion' => '1.0',
158
			'method' => 'POST',
159
			'redirection' => 5,
160
			'sslverify' => false,
161
			'timeout' => 45,
162
		]);
163
		if( is_wp_error( $result )) {
164
			glsr_log()->error( $result->get_error_message() );
165
		}
166
	}
167
}
168