Passed
Push — master ( 042452...c272a3 )
by Paul
05:20
created

CreateReview::normalize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 14
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 11
nc 1
nop 1
crap 2
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\Modules\Email;
10
use GeminiLabs\SiteReviews\Modules\Session;
11
use ReflectionException;
12
use WP_Error;
13
14
class CreateReview
15
{
16
	/**
17
	 * @var Command
18
	 */
19
	protected $command;
20
21
	/**
22
	 * @return void|string
23
	 */
24
	public function handle( Command $command )
25
	{
26
		$this->command = $command;
27
		$postId = glsr( Database::class )->createReview( $command );
28
		if( !$postId ) {
29
			glsr( Session::class )->set( $command->form_id.'errors', [] );
30
			return __( 'Your review could not be submitted, please notify the site admin.', 'site-reviews' );
31
		}
32
		$this->sendNotification( $postId, $command );
0 ignored issues
show
Unused Code introduced by
The call to GeminiLabs\SiteReviews\H...iew::sendNotification() has too many arguments starting with $command. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

32
		$this->/** @scrutinizer ignore-call */ 
33
         sendNotification( $postId, $command );

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
33
		do_action( 'site-reviews/local/review/submitted', $postId, $command );
34
		$message = __( 'Your review has been submitted!', 'site-reviews' );
35
		if( $command->ajax_request ) {
36
			glsr( Session::class )->clear();
37
			return $message;
38
		}
39
		glsr( Session::class )->set( $command->form_id.'message', $message );
40
		wp_safe_redirect( $command->referrer );
41
		exit;
42
	}
43
44
	/**
45
	 * @return Email
46
	 */
47
	protected function createEmailNotification( array $args = [] )
48
	{
49
		$email = [
50
			'to' => $args['recipient'],
51
			'subject' => $args['notification_title'],
52
			'template' => 'review-notification',
53
			'template-tags' => [
54
				'review_author' => $this->command->author,
55
				'review_content' => $this->command->content,
56
				'review_email' => $this->command->email,
57
				'review_ip' => $this->command->ip_address,
58
				'review_link' => sprintf( '<a href="%1$s">%1$s</a>', $args['notification_link'] ),
59
				'review_rating' => $this->command->rating,
60
				'review_title' => $this->command->title,
61
			],
62
		];
63
		return glsr( Email::class )->compose( $email );
64
	}
65
66
	/**
67
	 * @return string
68
	 */
69
	protected function createWebhookNotification( array $args )
70
	{
71
		$fields = [];
72
		$fields[] = ['title' => str_repeat( ':star:', $this->command->rating )];
73
		if( $this->command->title ) {
74
			$fields[] = ['title' => $this->command->title];
75
		}
76
		if( $this->command->content ) {
77
			$fields[] = ['value' => $this->command->content];
78
		}
79
		if( $this->command->email ) {
80
			$this->command->email = ' <'.$this->command->email.'>';
81
		}
82
		if( $this->command->author ) {
83
			$fields[] = ['value' => trim( $this->command->author.$this->command->email.' - '.$this->command->ip_address )];
84
		}
85
		$fields[] = ['value' => sprintf( '<%s|%s>', $args['notification_link'], __( 'View Review', 'site-reviews' ))];
86
		return json_encode([
87
			'icon_url' => glsr()->url( 'assets/img/icon.png' ),
88
			'username' => glsr()->name,
89
			'attachments' => [[
90
				'pretext' => $args['notification_title'],
91
				'color' => '#665068',
92
				'fallback' => $this->createEmailNotification( $args )->read( 'plaintext' ),
93
				'fields' => $fields,
94
			]],
95
		]);
96
	}
97
98
	/**
99
	 * @param int $post_id
100
	 * @return void
101
	 */
102
	protected function sendNotification( $postId )
103
	{
104
		$notificationType = glsr( OptionManager::class )->get( 'settings.general.notification' );
105
		if( !in_array( $notificationType, ['default','custom','webhook'] ))return;
106
		$assignedToTitle = get_the_title( (int)$this->command->assigned_to );
107
		$notificationSubject = _nx(
108
			'New %s-star review',
109
			'New %s-star review of: %s',
110
			intval( empty( $assignedToTitle )),
111
			'The text is different depending on whether or not the review has been assigned to a post.',
112
			'site-reviews'
113
		);
114
		$notificationTitle = sprintf( '[%s] %s',
115
			wp_specialchars_decode( (string)get_option( 'blogname' ), ENT_QUOTES ),
116
			sprintf( $notificationSubject, $this->command->rating, $assignedToTitle )
117
		);
118
		$args = [
119
			'notification_link' => esc_url( admin_url( sprintf( 'post.php?post=%s&action=edit', $postId ))),
120
			'notification_title' => $notificationTitle,
121
			'notification_type' => $notificationType,
122
		];
123
		$notificationMethod = $args['notification_type'] == 'webhook'
124
			? 'sendWebhookNotification'
125
			: 'sendEmailNotification';
126
		$this->$notificationMethod( $args );
127
	}
128
129
	/**
130
	 * @return void
131
	 */
132
	protected function sendEmailNotification( array $args )
133
	{
134
		$args['recipient'] = $args['notification_type'] !== 'default'
135
			? glsr( OptionManager::class )->get( 'settings.general.notification_email' )
136
			: get_option( 'admin_email' );
137
		$result = !empty( $args['recipient'] )
138
			? $this->createEmailNotification( $args )->send()
139
			: false;
140
		if( !is_bool( $result )) {
141
			glsr_log()->error( __( 'Email notification was not sent: missing email, subject, or message.', 'site-reviews' ));
142
		}
143
		if( $result === false ) {
144
			glsr_log()->error( __( 'Email notification was not sent: wp_mail() failed.', 'site-reviews' ));
145
		}
146
	}
147
148
	/**
149
	 * @return void
150
	 */
151
	protected function sendWebhookNotification( array $args )
152
	{
153
		if( !( $endpoint = glsr( OptionManager::class )->get( 'settings.general.webhook_url' )))return;
154
		$notification = $this->createWebhookNotification( $args );
155
		$result = wp_remote_post( $endpoint, [
156
			'blocking' => false,
157
			'body' => apply_filters( 'site-reviews/webhook/notification', $notification, $this->command ),
158
			'headers' => ['Content-Type' => 'application/json'],
159
			'httpversion' => '1.0',
160
			'method' => 'POST',
161
			'redirection' => 5,
162
			'sslverify' => false,
163
			'timeout' => 45,
164
		]);
165
		if( is_wp_error( $result )) {
166
			glsr_log()->error( $result->get_error_message() );
167
		}
168
	}
169
}
170