FilterPlugin   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 89.29%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 3
dl 0
loc 79
ccs 25
cts 28
cp 0.8929
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A filterEmailArray() 0 10 3
A filterEmail() 0 11 3
A beforeSendPerformed() 0 18 2
A sendPerformed() 0 4 1
1
<?php
2
3
namespace Openbuildings\Swiftmailer;
4
5
use Openbuildings\Swiftmailer\Filters\FilterInterface;
6
use Swift_Events_SendEvent;
7
use Swift_Events_SendListener;
8
9
/**
10
 * @author     Ivan Kerin <[email protected]>
11
 * @copyright  (c) 2015 Clippings Ltd.
12
 * @license    http://spdx.org/licenses/BSD-3-Clause
13
 */
14
class FilterPlugin implements Swift_Events_SendListener
15
{
16
    /**
17
     * @var FilterInterface[]
18
     */
19
    private $filters;
20
21
    public function __construct(array $filters = [])
22
    {
23
        $this->filters = $filters;
24
    }
25
26
    /**
27
     * @param string $email
28
     *
29
     * @return bool
30
     */
31 11
    public function filterEmail($email)
32
    {
33 11
        foreach ($this->filters as $filter) {
34 11
            $shouldKeepEmail = $filter->checkEmail($email);
35 11
            if (!$shouldKeepEmail) {
36 7
                return true;
37
            }
38
        }
39
40 8
        return false;
41
    }
42
43
    /**
44
     * @param array $emails
45
     *
46
     * @return array
47
     */
48 11
    public function filterEmailArray(array $emails)
49
    {
50 11
        foreach ($emails as $email => $name) {
51 11
            if ($this->filterEmail($email)) {
52 7
                unset($emails[$email]);
53
            }
54
        }
55
56 11
        return $emails;
57
    }
58
59
    /**
60
     * Apply whitelist and blacklist to "to", "cc" and "bcc".
61
     *
62
     * @param Swift_Events_SendEvent $event
63
     */
64 4
    public function beforeSendPerformed(Swift_Events_SendEvent $event)
65
    {
66 4
        $message = $event->getMessage();
67
68 4
        $to = $this->filterEmailArray((array) $message->getTo());
69 4
        $cc = $this->filterEmailArray((array) $message->getCc());
70 4
        $bcc = $this->filterEmailArray((array) $message->getBcc());
71
72 4
        $message->setTo($to);
73 4
        $message->setCc($cc);
74 4
        $message->setBcc($bcc);
75
76 4
        $all = $to + $cc + $bcc;
77
78 4
        if (empty($all)) {
79 1
            $event->cancelBubble();
80
        }
81 4
    }
82
83
    /**
84
     * Do nothing.
85
     *
86
     * @param Swift_Events_SendEvent $event
87
     */
88 3
    public function sendPerformed(Swift_Events_SendEvent $event)
89
    {
90
        // Do Nothing
91 3
    }
92
}
93