Completed
Push — master ( f5d71d...bfd9cb )
by Sam
12:52
created

Transliterator::useStrTr()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 16
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 19
rs 9.4285
1
<?php
2
3
namespace SilverStripe\View\Parsers;
4
5
use SilverStripe\Core\Object;
6
7
/**
8
 * Support class for converting unicode strings into a suitable 7-bit ASCII equivalent.
9
 *
10
 * Usage:
11
 *
12
 * <code>
13
 * $tr = new Transliterator();
14
 * $ascii = $tr->toASCII($unicode);
15
 * </code>
16
 */
17
class Transliterator extends Object {
18
	/**
19
	 * @config
20
	 * @var boolean Allow the use of iconv() to perform transliteration.  Set to false to disable.
21
	 * Even if this variable is true, iconv() won't be used if it's not installed.
22
	 */
23
	private static $use_iconv = false;
24
25
	/**
26
	 * Convert the given utf8 string to a safe ASCII source
27
	 *
28
	 * @param string $source
29
	 * @return string
30
	 */
31
	public function toASCII($source) {
32
		if(function_exists('iconv') && $this->config()->use_iconv) {
33
			return $this->useIconv($source);
34
		} else {
35
			return $this->useStrTr($source);
36
		}
37
	}
38
39
	/**
40
	 * Transliteration using strtr() and a lookup table
41
	 *
42
	 * @param string $source
43
	 * @return string
44
	 */
45
	protected function useStrTr($source) {
46
		$table = array(
47
			'Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c',
48
			'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'Ae', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
49
			'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
50
			'Õ'=>'O', 'Ö'=>'Oe', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'Ue', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'ss',
51
			'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'ae', 'å'=>'a', 'æ'=>'ae', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
52
			'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
53
			'ô'=>'o', 'õ'=>'o', 'ö'=>'oe', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ü'=>'ue', 'ý'=>'y',
54
			'þ'=>'b', 'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r',
55
			'Ā'=>'A', 'ā'=>'a', 'Ē'=>'E', 'ē'=>'e', 'Ī'=>'I', 'ī'=>'i', 'Ō'=>'O', 'ō'=>'o', 'Ū'=>'U', 'ū'=>'u',
56
			'œ'=>'oe', 'ij'=>'ij', 'ą'=>'a','ę'=>'e', 'ė'=>'e', 'į'=>'i','ų'=>'u', 'Ą'=>'A',
57
			'Ę'=>'E', 'Ė'=>'E', 'Į'=>'I','Ų'=>'U',
58
			"ľ"=>"l", "Ľ"=>"L", "ť"=>"t", "Ť"=>"T", "ů"=>"u", "Ů"=>"U",
59
			'ł'=>'l', 'Ł'=>'L', 'ń'=>'n', 'Ń'=>'N', 'ś'=>'s', 'Ś'=>'S', 'ź'=>'z', 'Ź'=>'Z', 'ż'=>'z', 'Ż'=>'Z',
60
		);
61
62
		return strtr($source, $table);
63
	}
64
65
	/**
66
	 * Transliteration using iconv()
67
	 *
68
	 * @param string $source
69
	 * @return string
70
	 */
71
	protected function useIconv($source) {
72
		return iconv("utf-8", "us-ascii//IGNORE//TRANSLIT", $source);
73
	}
74
}
75