Headers::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 12
Bugs 4 Features 1
Metric Value
c 12
b 4
f 1
dl 0
loc 9
rs 9.6666
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
3
namespace Ddeboer\Imap\Message;
4
5
use Ddeboer\Imap\Parameters;
6
7
/**
8
 * Collection of message headers
9
 */
10
class Headers extends Parameters
11
{
12
    /**
13
     * Constructor
14
     *
15
     * @param \stdClass $headers
16
     */
17
    public function __construct(\stdClass $headers)
18
    {
19
        // Store all headers as lowercase
20
        $headers = array_change_key_case((array) $headers);
21
22
        foreach ($headers as $key => $value) {
23
            $this->parameters[$key] = $this->parseHeader($key, $value);
24
        }
25
    }
26
27
    /**
28
     * Get header
29
     * 
30
     * @param string $key
31
     *
32
     * @return string
33
     */
34
    public function get($key)
35
    {
36
        return parent::get(strtolower($key));
37
    }
38
    
39
    private function parseHeader($key, $value)
40
    {
41
        switch ($key) {
42
            case 'msgno':
43
                return (int)$value;
44
            case 'answered':
45
                // no break
46
            case 'deleted':
47
                // no break
48
            case 'draft':
49
                // no break
50
            case 'unseen':
51
                return (bool)trim($value);
52
            case 'date':
53
                $value = $this->decode($value);
54
                $value = preg_replace('/([^\(]*)\(.*\)/', '$1', $value);
55
56
                return new \DateTime($value);
57
            case 'from':
58
                return $this->decodeEmailAddress(current($value));
59
            case 'to':
60
                // no break
61
            case 'cc':
62
                $emails = [];
63
                foreach ($value as $address) {
64
                    $emails[] = $this->decodeEmailAddress($address);
65
                }
66
            
67
                return $emails;
68
            case 'subject':
69
                return $this->decode($value);
70
            default:
71
                return $value;
72
        }
73
    }
74
75
    private function decodeEmailAddress($value)
76
    {
77
        return new EmailAddress(
78
            $value->mailbox,
79
            isset($value->host) ? $value->host : null,
80
            isset($value->personal) ? $this->decode($value->personal) : null
81
        );
82
    }
83
}
84