This repository has been archived by the owner on May 13, 2024. It is now read-only.
forked from lassodatasystems/LassoMailParserBundle
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ParseHelper.php
93 lines (84 loc) · 2.75 KB
/
ParseHelper.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
namespace Lasso\MailParserBundle;
use ArrayIterator;
use Exception;
use Laminas\Mail\Header\HeaderInterface;
use Laminas\Mail\Storage\Part;
abstract class ParseHelper {
/**
* @param Part $part
*
* @return bool
*/
protected function isEnvelopedEmail(Part $part)
{
if (!$this->hasHeader($part, 'Content-Type')) {
return false;
}
return $this->getContentType($part)->getType() == 'message/rfc822';
}
/**
* The confusing zend API makes a custom function for
* header checking necessary.
*
* @param Part $part
* @param string $header
*
* @return bool
*/
protected function hasHeader(Part $part, $header)
{
if ($part->getHeaders() === null) {
return false;
}
if (count($part->getHeaders()) < 1) {
return false;
}
return $part
->getHeaders()
->has($header);
}
/**
* Returns the content type of the given part. Since zends API
* allows for four different return values, we need to handle
* every type differently. Multiple content-type headers can't
* be accounted for, in those cases we simply take the first
* one and hope for the best. If it doesn't work, there's not
* much that could be done as content-type guessing is not an
* easily solved problem.
*
* The content-type header should always be broken up into
* a header interface, it just could happen that the zend
* framework returns an array or array iterator when multiple
* content-type headers are present. In that case, the first
* encountered header will be used.
*
* @param Part $part
*
* @return HeaderInterface
* @throws \Exception
*/
protected function getContentType(Part $part)
{
if (!$this->hasHeader($part, 'Content-Type')) {
throw new Exception('This email does not have a content type. Check for that with hasContentType()');
}
$zendContentType = $part
->getHeaders()
->get('Content-Type');
switch (true) {
case is_array($zendContentType):
return $zendContentType[0];
case $zendContentType instanceof HeaderInterface:
return $zendContentType;
case $zendContentType instanceof ArrayIterator:
return $zendContentType->current();
default:
throw new Exception('Unexpected return type ' .
gettype($zendContentType) .
', expected one of string, array, HeaderInterface or ArrayIterator' .
' from Part::getHeaders()::get("Content-Type"))'
);
}
}
}