Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
365 lars 1
<?php
2
namespace stringEncode;
3
 
4
class Encode {
5
 
6
	/**
7
	 * The encoding that the string is currently in.
8
	 *
9
	 * @var string
10
	 */
11
	protected $from;
12
 
13
	/**
14
	 * The encoding that we would like the string to be in.
15
	 *
16
	 * @var string
17
	 */
18
	protected $to;
19
 
20
	/**
21
	 * Sets the default charsets for thie package.
22
	 */
23
	public function __construct()
24
	{
25
		// default from encoding
26
		$this->from = 'CP1252';
27
 
28
		// default to encoding
29
		$this->to = 'UTF-8';
30
	}
31
 
32
	/**
33
	 * Sets the charset that we will be converting to.
34
	 *
35
	 * @param string $charset
36
	 * @chainable
37
	 */
38
	public function to($charset)
39
	{
40
		$this->to = strtoupper($charset);
41
		return $this;
42
	}
43
 
44
	/**
45
	 * Sets the charset that we will be converting from.
46
	 *
47
	 * @param string $charset
48
	 * @chainable
49
	 */
50
	public function from($charset)
51
	{
52
		$this->from = strtoupper($charset);
53
	}
54
 
55
	/**
56
	 * Returns the to and from charset that we will be using.
57
	 *
58
	 * @return array
59
	 */
60
	public function charset()
61
	{
62
		return [
63
			'from' => $this->from,
64
			'to'   => $this->to,
65
		];
66
	}
67
 
68
	/**
69
	 * Attempts to detect the encoding of the given string from the encodingList.
70
	 *
71
	 * @param string $str
72
	 * @param array $encodingList
73
	 * @return bool
74
	 */
75
	public function detect($str, $encodingList = ['UTF-8', 'CP1252'])
76
	{
77
		$charset = mb_detect_encoding($str, $encodingList);
78
		if ($charset === false)
79
		{
80
			// could not detect charset
81
			return false;
82
		}
83
 
84
		$this->from = $charset;
85
		return true;
86
	}
87
 
88
	/**
89
	 * Attempts to convert the string to the proper charset.
90
	 *
91
	 * @return string
92
	 */
93
	public  function convert($str)
94
	{
95
		if ($this->from != $this->to)
96
		{
97
			$str = iconv($this->from, $this->to, $str);
98
		}
99
 
100
		if ($str === false)
101
		{
102
			// the convertion was a failure
103
			throw new Exception('The convertion from "'.$this->from.'" to "'.$this->to.'" was a failure.');
104
		}
105
 
106
		// deal with BOM issue for utf-8 text
107
		if ($this->to == 'UTF-8')
108
		{
109
			if (substr($str, 0, 3) == "\xef\xbb\xbf")
110
			{
111
				$str = substr($str, 3);
112
			}
113
			if (substr($str, -3, 3) == "\xef\xbb\xbf")
114
			{
115
				$str = substr($str, 0, -3);
116
			}
117
		}
118
 
119
		return $str;
120
	}
121
}