Passed
Pull Request — master (#129)
by
unknown
03:20
created

DatePart   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 92.31%

Importance

Changes 7
Bugs 1 Features 0
Metric Value
eloc 14
c 7
b 1
f 0
dl 0
loc 49
ccs 12
cts 13
cp 0.9231
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getDateTime() 0 3 1
A __construct() 0 22 6
1
<?php
2
/**
3
 * This file is part of the ZBateson\MailMimeParser project.
4
 *
5
 * @license http://opensource.org/licenses/bsd-license.php BSD
6
 */
7
namespace ZBateson\MailMimeParser\Header\Part;
8
9
use ZBateson\MbWrapper\MbWrapper;
10
use DateTime;
11
use Exception;
12
13
/**
14
 * Parses a header into a DateTime object.
15
 *
16
 * @author Zaahid Bateson
17
 */
18
class DatePart extends LiteralPart
19
{
20
    /**
21
     * @var DateTime the parsed date, or null if the date could not be parsed
22
     */
23
    protected $date;
24
25
    /**
26
     * Tries parsing the passed token as an RFC 2822 date, and failing that into
27
     * an RFC 822 date, and failing that, tries to parse it by calling
28
     * ``` new DateTime($value) ```.
29
     *
30
     * @param MbWrapper $charsetConverter
31
     * @param string $token
32
     */
33 2
    public function __construct(MbWrapper $charsetConverter, $token)
34
    {
35 2
        $dateToken = trim($token);
36
        // parent::__construct converts character encoding -- may cause problems sometimes.
37 2
        parent::__construct($charsetConverter, $dateToken);
38
39
        // Missing "+" in timezone definition. eg: Thu, 13 Mar 2014 15:02:47 0000 (not RFC compliant)
40
        // Won't result in an Exception, but in a valid DateTime in year `0000` - therefore we need to check this first:
41 2
        if (preg_match('# [0-9]{4}$#', $dateToken)) {
42 1
            $dateToken = preg_replace('# ([0-9]{4})$#', ' +$1', $dateToken);
43
        }
44
45
        try {
46 2
            $this->date = new DateTime($dateToken);
47 2
        } catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
48
        }
49
50
        // @see https://bugs.php.net/bug.php?id=42486
51 2
        if (!isset($this->date) && preg_match('#UT$#', $dateToken)) {
52
            try {
53 1
                $this->date = new DateTime($dateToken . 'C');
54
            } catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
55
            }
56
        }
57 2
    }
58
59
    /**
60
     * Returns a DateTime object or false if it can't be parsed.
61
     *
62
     * @return DateTime
63
     */
64 2
    public function getDateTime()
65
    {
66 2
        return $this->date;
67
    }
68
}
69