Completed
Pull Request — master (#64)
by Frederik
01:41
created

GenericMessage::withHeader()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Genkgo\Mail;
5
6
use Genkgo\Mail\Header\HeaderLine;
7
use Genkgo\Mail\Header\MimeVersion;
8
use Genkgo\Mail\Stream\EmptyStream;
9
use Genkgo\Mail\Stream\MessageStream;
10
use Genkgo\Mail\Stream\StringStream;
11
12
final class GenericMessage implements MessageInterface
13
{
14
    /**
15
     * @var array<string, array<int, HeaderInterface>>
16
     */
17
    private $headers = [
18
        'return-path' => [],
19
        'received' => [],
20
        'dkim-signature' => [],
21
        'domainkey-signature' => [],
22
        'sender' => [],
23
        'message-id' => [],
24
        'date' => [],
25
        'subject' => [],
26
        'from' => [],
27
        'reply-to' => [],
28
        'to' => [],
29
        'cc' => [],
30
        'bcc' => [],
31
        'mime-version' => [],
32
        'content-type' => [],
33
        'content-transfer-encoding' => [],
34
    ];
35
36
    /**
37
     * @var StreamInterface
38
     */
39
    private $body;
40
    
41 123
    public function __construct()
42
    {
43 123
        $this->body = new EmptyStream();
44 123
        $this->headers['mime-version'] = [new MimeVersion()];
45 123
    }
46
47
    /**
48
     * @return iterable<iterable<HeaderInterface>>
0 ignored issues
show
Documentation introduced by
The doc-type iterable<iterable<HeaderInterface>> could not be parsed: Expected "|" or "end of type", but got "<" at position 8. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
49
     */
50 71
    public function getHeaders(): iterable
51
    {
52 71
        return $this->headers;
53
    }
54
55
    /**
56
     * @param string $name
57
     * @return bool
58
     */
59 31
    public function hasHeader(string $name): bool
60
    {
61 31
        $name = \strtolower($name);
62 31
        return isset($this->headers[$name]) && $this->headers[$name];
63
    }
64
65
    /**
66
     * @param string $name
67
     * @return HeaderInterface[]|iterable
68
     */
69 54
    public function getHeader(string $name): iterable
70
    {
71 54
        $name = \strtolower($name);
72
73 54
        if (!isset($this->headers[$name])) {
74 2
            return [];
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array(); (array) is incompatible with the return type declared by the interface Genkgo\Mail\MessageInterface::getHeader of type Genkgo\Mail\iterable|Genkgo\Mail\HeaderInterface[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
75
        }
76
77 54
        return $this->headers[$name];
78
    }
79
80
    /**
81
     * @param HeaderInterface $header
82
     * @return MessageInterface
83
     */
84 106
    public function withHeader(HeaderInterface $header): MessageInterface
85
    {
86 106
        $clone = clone $this;
87 106
        $clone->headers[\strtolower((string)$header->getName())] = [$header];
88 106
        return $clone;
89
    }
90
91
    /**
92
     * @param HeaderInterface $header
93
     * @return MessageInterface
94
     */
95 3
    public function withAddedHeader(HeaderInterface $header): MessageInterface
96
    {
97 3
        $clone = clone $this;
98 3
        $clone->headers[\strtolower((string)$header->getName())][] = $header;
99 3
        return $clone;
100
    }
101
102
    /**
103
     * @param string $name
104
     * @return MessageInterface
105
     */
106 5
    public function withoutHeader(string $name): MessageInterface
107
    {
108 5
        $clone = clone $this;
109 5
        unset($clone->headers[(string)\strtolower($name)]);
110 5
        return $clone;
111
    }
112
113
    /**
114
     * @param StreamInterface $body
115
     * @return MessageInterface
116
     */
117 84
    public function withBody(StreamInterface $body): MessageInterface
118
    {
119 84
        $clone = clone $this;
120 84
        $clone->body = $body;
121 84
        return $clone;
122
    }
123
124
    /**
125
     * @return StreamInterface
126
     */
127 73
    public function getBody(): StreamInterface
128
    {
129 73
        return $this->body;
130
    }
131
132
    /**
133
     * @return string
134
     */
135 56
    public function __toString(): string
136
    {
137 56
        return (string) (new MessageStream($this));
138
    }
139
140
    /**
141
     * @param string $messageString
142
     * @return MessageInterface
143
     */
144 44
    public static function fromString(string $messageString): MessageInterface
145
    {
146 44
        $message = new self();
147
148 44
        $lines = \preg_split('/\r\n/', $messageString);
149 44
        if ($lines === false) {
150
            throw new \UnexpectedValueException('Cannot parse from string, cannot split lines');
151
        }
152
153 44
        for ($n = 0, $length = \count($lines); $n < $length; $n++) {
154 44
            $line = $lines[$n];
155
156 44
            if ($line === '') {
157 43
                $message = $message->withBody(
158 43
                    new StringStream(
159 43
                        \implode(
160 43
                            "\r\n",
161 43
                            \array_slice($lines, $n + 1)
162
                        )
163
                    )
164
                );
165 43
                break;
166
            }
167
168 44
            while (isset($lines[$n + 1]) && $lines[$n + 1] !== '' && \trim($lines[$n + 1][0]) === '') {
169 2
                $line .= ' ' . \ltrim($lines[$n + 1]);
170 2
                $n++;
171
            }
172
173 44
            $message = $message->withHeader(HeaderLine::fromString($line)->getHeader());
174
        }
175
176 43
        return $message;
177
    }
178
}
179