Completed
Push — master ( 147214...53e4d6 )
by Zaahid
09:05
created

MailMimeParser::copyToTmpFile()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 11
ccs 0
cts 0
cp 0
rs 9.4285
cc 3
eloc 8
nc 2
nop 2
crap 12
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;
8
9
/**
10
 * Parses a MIME message into a \ZBateson\MailMimeParser\Message object.
11
 *
12
 * To invoke, call parse on a MailMimeParser object.
13
 * 
14
 * $handle = fopen('path/to/file.txt');
15
 * $parser = new MailMimeParser();
16
 * $parser->parse($handle);
17
 * fclose($handle);
18
 * 
19
 * @author Zaahid Bateson
20
 */
21
class MailMimeParser
22
{
23
    /**
24
     * @var \ZBateson\MailMimeParser\SimpleDi dependency injection container
25
     */
26
    protected $di;
27
    
28
    /**
29
     * Sets up the parser.
30
     */
31 3
    public function __construct()
32
    {
33 3
        $this->di = SimpleDi::singleton();
34 3
    }
35
    
36
    /**
37
     * Parses the passed stream handle into a ZBateson\MailMimeParser\Message
38
     * object and returns it.
39
     * 
40
     * Internally, the message is first copied to a temp stream (with php://temp
41
     * which may keep it in memory or write it to disk) and its stream is used.
42
     * That way if the message is too large to hold in memory it can be written
43
     * to a temporary file if need be.
44
     * 
45
     * @param resource|string $handleOrString the resource handle to the input
46
     *        stream of the mime message, or a string containing a mime message
47
     * @return \ZBateson\MailMimeParser\Message
48
     */
49 2
    public function parse($handleOrString)
50
    {
51
        // $tempHandle is attached to $message, and closed in its destructor
52 2
        $tempHandle = fopen('php://temp', 'r+');
53 2
        if (is_string($handleOrString)) {
54 1
            fwrite($tempHandle, $handleOrString);
55 1
        } else {
56 1
            stream_copy_to_stream($handleOrString, $tempHandle);
57
        }
58 2
        rewind($tempHandle);
59 2
        $parser = $this->di->newMessageParser();
60 2
        $message = $parser->parse($tempHandle);
61 2
        return $message;
62
    }
63
}
64