Passed
Push — 194-hotfix/wp-ses-incompatibil... ( a813c4 )
by Maria Daniel Deepak
08:37 queued 03:13
created

EmailLogger::log_email()   B

Complexity

Conditions 8
Paths 72

Size

Total Lines 50
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 8.2964

Importance

Changes 0
Metric Value
cc 8
eloc 21
nc 72
nop 1
dl 0
loc 50
ccs 20
cts 24
cp 0.8333
crap 8.2964
rs 8.4444
c 0
b 0
f 0
1
<?php namespace EmailLog\Core;
2
3
/**
4
 * Log's emails sent through `wp_mail`.
5
 *
6
 * @package EmailLog\Core
7
 * @since   2.0
8
 */
9
class EmailLogger implements Loadie {
10
11
	/**
12
	 * Load the logger.
13
	 */
14
	public function load() {
15
		add_filter( 'wp_mail', array( $this, 'log_email' ) );
16
	}
17
18
	/**
19
	 * Logs email to database.
20
	 *
21
	 * @param array $mail_info Information about email.
22
	 *
23
	 * @return array Information about email.
24
	 */
25 1
	public function log_email( $mail_info ) {
26 1
		$email_log = email_log();
27
		/**
28
		 * Hook to modify wp_mail contents before Email Log plugin logs.
29
		 *
30
		 * @since Genesis
31
		 *
32
		 * @param array $mail_info {
33
		 *     @type string $to
34
		 *     @type string $subject
35
		 *     @type string $message
36
		 *     @type string $headers
37
		 *     @type string $attachment
38
		 * }
39
		 */
40 1
		$mail_info = apply_filters( 'el_wp_mail_log', $mail_info );
41
42
		// Sometimes the array passed to the `wp_mail` filter may not contain all the required keys.
43
		// See https://wordpress.org/support/topic/illegal-string-offset-attachments/
44 1
		$mail_info = wp_parse_args( $mail_info, array(
45 1
			'to'          => '',
46 1
			'subject'     => '',
47 1
			'headers'     => '',
48 1
		) );
49
50
		$data = array(
51 1
			'attachments' => ( ! empty( $mail_info['attachments'] ) && is_array( $mail_info['attachments'] ) && count( $mail_info['attachments'] ) > 0 ) ? 'true' : 'false',
52 1
			'to_email'    => is_array( $mail_info['to'] ) ? implode( ',', $mail_info['to'] ) : $mail_info['to'],
53 1
			'subject'     => $mail_info['subject'],
54 1
			'headers'     => is_array( $mail_info['headers'] ) ? implode( "\n", $mail_info['headers'] ) : $mail_info['headers'],
55 1
			'sent_date'   => current_time( 'mysql' ),
56 1
		);
57
58 1
		$message = '';
59
60 1
		if ( isset( $mail_info['message'] ) ) {
61
			$message = $mail_info['message'];
62
		} else {
63
			// wpmandrill plugin is changing "message" key to "html". See https://github.com/sudar/email-log/issues/20
64
			// Ideally this should be fixed in wpmandrill, but I am including this hack here till it is fixed by them.
65 1
			if ( isset( $mail_info['html'] ) ) {
66
				$message = $mail_info['html'];
67
			}
68
		}
69
70 1
		$data['message'] = $message;
71
72 1
		$email_log->table_manager->insert_log( $data );
73
74 1
		return $mail_info;
75
	}
76
}
77