Completed
Push — master ( 4041bf...487db1 )
by Zaahid
07:54
created

CharsetStreamFilter::filter()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 2
eloc 6
nc 2
nop 4
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\Stream;
8
9
use php_user_filter;
10
11
/**
12
 * Implements a filter converting the stream's character encoding while reading
13
 * from it, so the charset of strings returned by read operations are guaranteed
14
 * to be encoded to UTF-8.
15
 * 
16
 * The underlying charset is set on the filtername used when creating the
17
 * stream with stream_filter_append - it is assumed the charset is after a '.'
18
 * character in the name.
19
 *
20
 * @author Zaahid Bateson
21
 */
22
class CharsetStreamFilter extends php_user_filter
23
{
24
    /**
25
     * Name used when registering with stream_filter_register.
26
     */
27
    const STREAM_FILTER_NAME = 'mailmimeparser-encode.*';
28
    
29
    /**
30
     * @var string the character set the stream is using
31
     */
32
    protected $charset = 'iso-8859-1';
33
    
34
    /**
35
     * Filter implementation converts encoding before returning PSFS_PASS_ON.
36
     * 
37
     * @param resource $in
38
     * @param resource $out
39
     * @param int $consumed
40
     * @param bool $closing
41
     * @return int
42
     */
43
    public function filter($in, $out, &$consumed, $closing)
44
    {
45
        while ($bucket = stream_bucket_make_writeable($in)) {
46
            $bucket->data = mb_convert_encoding($bucket->data, 'UTF-8', $this->charset);
47
            $consumed += $bucket->datalen;
48
            stream_bucket_append($out, $bucket);
49
        }
50
        return PSFS_PASS_ON;
51
    }
52
    
53
    /**
54
     * Overridden to extract the charset from the filtername.  An example of a
55
     * filter name sent to stream_filter_append with a charset would be:
56
     * 
57
     * stream_filter_append(resource, 'mailmimeparser-encode.utf-8');
58
     */
59
    public function onCreate()
60
    {
61
        $charset = substr($this->filtername, strrpos($this->filtername, '.') + 1);
62
        if (!empty($charset)) {
63
            $this->charset = $charset;
64
        }
65
    }
66
}
67