Passed
Push — 2.x ( 92ec38...c080f0 )
by Terry
02:07
created

Sendgrid::sandbox()   B

Complexity

Conditions 8
Paths 5

Size

Total Lines 30
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 17
c 1
b 0
f 0
nc 5
nop 2
dl 0
loc 30
rs 8.4444
1
<?php
2
/*
3
 * This file is part of the Shieldon package.
4
 *
5
 * (c) Terry L. <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
declare(strict_types=1);
12
13
namespace Shieldon\Firewall\Panel\Sandbox;
14
15
use Shieldon\Messenger as Messenger;
16
17
/**
18
 * The sandbox for Sendgrid.
19
 */
20
class Sendgrid
21
{
22
    /**
23
     * Invoker.
24
     *
25
     * @param array $args
26
     *
27
     * @return bool
28
     */
29
    public function __invoke(array $args): bool
30
    {
31
        return $this->sandbox($args[0], $args[1]);
32
    }
33
34
    /**
35
     * Test Sendgrid.
36
     *
37
     * @param array $getParams The GET params passed from tryMessenger method.
38
     * @param array $message   The message title and body.
39
     *
40
     * @return bool
41
     */
42
    private function sandbox($getParams, $message)
43
    {
44
        $apiKey = $getParams['apiKey'] ?? '';
45
        $sender = $getParams['sender'] ?? '';
46
        $recipients = $getParams['recipients'] ?? '';
47
48
        if (!empty($sender) && !empty($recipients) && !empty($apiKey)) {
49
            $recipients = str_replace("\r", '|', $recipients);
50
            $recipients = str_replace("\n", '|', $recipients);
51
            $recipients = explode('|', $recipients);
52
53
            $messenger = new Messenger\Sendgrid($apiKey);
54
55
            foreach($recipients as $recipient) {
56
                if (filter_var($recipient, FILTER_VALIDATE_EMAIL)) {
57
                    $messenger->addRecipient($recipient);
58
                }
59
            }
60
61
            if (filter_var($sender, FILTER_VALIDATE_EMAIL)) {
62
                $messenger->addSender($sender);
63
            }
64
65
            $messenger->setSubject($message['title']);
66
67
            if ($messenger->send($message['body'])) {
68
                return true;
69
            }
70
        }
71
        return false;
72
    }
73
}