-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathTranscoder.php
72 lines (59 loc) · 1.79 KB
/
Transcoder.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
<?php
namespace Ddeboer\Transcoder;
use Ddeboer\Transcoder\Exception\ExtensionMissingException;
use Ddeboer\Transcoder\Exception\UnsupportedEncodingException;
class Transcoder implements TranscoderInterface
{
private static $chain;
/**
* @var TranscoderInterface[]
*/
private $transcoders = [];
public function __construct(array $transcoders)
{
$this->transcoders = $transcoders;
}
/**
* {@inheritdoc}
*/
public function transcode($string, $from = null, $to = null)
{
foreach ($this->transcoders as $transcoder) {
try {
return $transcoder->transcode($string, $from, $to);
} catch (UnsupportedEncodingException $e) {
// Ignore as long as the fallback transcoder is all right
}
}
throw $e;
}
/**
* Create a transcoder
*
* @param string $defaultEncoding
*
* @return TranscoderInterface
*
* @throws ExtensionMissingException
*/
public static function create($defaultEncoding = 'UTF-8')
{
if (isset(self::$chain[$defaultEncoding])) {
return self::$chain[$defaultEncoding];
}
$transcoders = [];
try {
$transcoders[] = new MbTranscoder($defaultEncoding);
} catch (ExtensionMissingException $mb) {
// Ignore missing mbstring extension; fall back to iconv
}
try {
$transcoders[] = new IconvTranscoder($defaultEncoding);
} catch (ExtensionMissingException $iconv) {
// Neither mbstring nor iconv
throw $iconv;
}
self::$chain[$defaultEncoding] = new self($transcoders);
return self::$chain[$defaultEncoding];
}
}