SimpleMailer::buildSubject()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Notifier\Channel\Email;
6
7
use ErrorException;
8
use Notifier\Exception\SendingMessageFailed;
9
10
final class SimpleMailer implements Mailer
11
{
12
    private const MESSAGE_LINE_CHARACTERS_LIMIT = 70;
13
14
    /** @var callable|null */
15
    private $handler;
16
17
    /** @var EmailMessage */
18
    private $message;
19
20 2
    public function __construct(callable $handler = null)
21
    {
22 2
        $this->handler = $handler;
23 2
    }
24
25 2
    public function send(EmailMessage $message): void
26
    {
27 2
        $this->message = $message;
28
29 2
        $status = call_user_func(
30 2
            $this->handler ?? 'mail',
31 2
            $this->buildTo(),
32 2
            $this->buildSubject(),
33 2
            $this->buildMessage(),
34 2
            $this->buildHeaders()
35
        );
36
37 2
        if (!$status) {
38 1
            $error = error_get_last();
39 1
            throw SendingMessageFailed::dueTo(new ErrorException($error['message'] ?? 'Email has not been accepted for delivery'));
40
        }
41 1
    }
42
43 2
    private function buildTo(): string
44
    {
45 2
        return implode(', ', $this->message->getTo());
46
    }
47
48 2
    private function buildSubject(): string
49
    {
50 2
        return $this->message->getSubject();
51
    }
52
53 2
    private function buildMessage(): string
54
    {
55 2
        return wordwrap($this->message->getBody(), self::MESSAGE_LINE_CHARACTERS_LIMIT);
56
    }
57
58 2
    private function buildHeaders(): string
59
    {
60
        $headers = array_map(function (string $name, $value) {
61 2
            if (is_array($value)) {
62 2
                $value = implode(', ', $value);
63
            }
64
65 2
            return "$name: $value";
66 2
        }, array_keys($this->message->getHeaders()), $this->message->getHeaders());
67
68 2
        return implode("\r\n", $headers);
69
    }
70
}
71