Imap   A
last analyzed

Complexity

Total Complexity 21

Size/Duplication

Total Lines 108
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 21
c 0
b 0
f 0
lcom 1
cbo 0
dl 0
loc 108
ccs 0
cts 63
cp 0
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A closeConnections() 0 4 1
A setConnection() 0 12 3
B getMessages() 0 28 4
B query() 0 22 6
A detectProcessFunction() 0 13 2
B getMessageBody() 0 16 5
1
<?php
2
/**
3
 * @author Sergii Bondarenko, <[email protected]>
4
 */
5
namespace Drupal\TqExtension\Utils;
6
7
trait Imap
8
{
9
    /**
10
     * @var resource[]
11
     */
12
    private $connections = [];
13
14
    public function closeConnections()
15
    {
16
        array_map('imap_close', $this->connections);
17
    }
18
19
    public function setConnection($email, $imap, $username, $password)
20
    {
21
        if (empty($this->connections[$email])) {
22
            $connection = imap_open('{' . $imap . '}INBOX', $username, $password);
23
24
            if (false === $connection) {
25
                throw new \RuntimeException('IMAP connection cannot be open. Maybe some parameters are incorrect.');
26
            }
27
28
            $this->connections[$email] = $connection;
29
        }
30
    }
31
32
    public function getMessages($email)
33
    {
34
        $messages = [];
35
36
        foreach ($this->query(['to' => $email, 'on' => date('d F Y'), 'unseen' => false]) as $messageId) {
37
            $structure = imap_fetchstructure($this->connections[$email], $messageId);
38
            $encoding = isset($structure->parts) ? reset($structure->parts) : $structure;
39
            $message = imap_fetch_overview($this->connections[$email], $messageId);
40
            $message = reset($message);
41
42
            $processFunction = $this->detectProcessFunction($encoding->encoding);
43
            $message->subject = $processFunction($message->subject);
44
            $message->body = $this->getMessageBody($email, $messageId, $processFunction, reset($structure->parameters));
45
46
            foreach (['from', 'to'] as $direction) {
47
                $address = imap_rfc822_parse_adrlist(imap_utf8($message->$direction), '');
48
                $address = reset($address);
49
50
                $message->$direction = "$address->mailbox@$address->host";
51
            }
52
53
            $messages[] = (array) $message;
54
55
            imap_delete($this->connections[$email], $messageId);
56
        }
57
58
        return $messages;
59
    }
60
61
    private function query(array $arguments)
62
    {
63
        if (empty($arguments['to'])) {
64
            throw new \Exception('The "to" argument is required!');
65
        }
66
67
        $query = [];
68
69
        foreach ($arguments as $name => $value) {
70
            $name = strtoupper($name);
71
72
            if (false === $value) {
73
                $query[] = $name;
74
            } elseif (!empty($value)) {
75
                $query[] = sprintf('%s "%s"', $name, $value);
76
            }
77
        }
78
79
        $result = imap_search($this->connections[$arguments['to']], implode(' ', $query));
80
81
        return is_array($result) ? $result : [];
82
    }
83
84
    private function detectProcessFunction($encoding)
85
    {
86
        $process = [
87
            1 => 'imap_utf8',
88
            2 => 'imap_binary',
89
            3 => 'imap_base64',
90
            4 => 'imap_qprint',
91
        ];
92
93
        return isset($process[$encoding]) ? $process[$encoding] : function ($string) {
94
            return $string;
95
        };
96
    }
97
98
    private function getMessageBody($email, $messageId, callable $process, $parameter)
99
    {
100
        foreach ([1, 2] as $option) {
101
            $data = $process(imap_fetchbody($this->connections[$email], $messageId, $option));
102
103
            if (!empty($data)) {
104
                if ('charset' === strtolower($parameter->attribute) && 'utf-8' !== strtolower($parameter->value)) {
105
                    $data = iconv($parameter->value, 'utf-8', $data);
106
                }
107
108
                return quoted_printable_decode($data);
109
            }
110
        }
111
112
        return '';
113
    }
114
}
115