-
Notifications
You must be signed in to change notification settings - Fork 0
/
Translator.php
95 lines (84 loc) · 2.27 KB
/
Translator.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
namespace Kolyunya\StringProcessor\Translit;
use Kolyunya\StringProcessor\BaseProcessor;
use Kolyunya\StringProcessor\Translit\Dictionary\DictionaryInterface;
use Kolyunya\StringProcessor\Translit\TranslatorInterface;
/**
* Translator.
* @author Kolyunya
*/
class Translator extends BaseProcessor implements TranslatorInterface
{
/**
* Forward translation direction.
*/
const DIRECTION_FORWARD = 0x00;
/**
* Reversed translation direction.
*/
const DIRECTION_REVERSED = 0x01;
/**
* Translation dictionary.
* @var DictionaryInterface
*/
private $dictionary;
/**
* Translation direction.
* @var integer
*/
private $direction;
/**
* Constructs a translator using dictionary and direction
* @param DictionaryInterface $dictionary Translation dictionary.
* @param integer $direction Translation direction.
*/
public function __construct(
DictionaryInterface $dictionary = null,
$direction = self::DIRECTION_FORWARD
) {
$this->setDictionary($dictionary);
$this->setDirection($direction);
}
/**
* @inheritdoc
*/
public function setDictionary(DictionaryInterface $dictionary)
{
$this->dictionary = $dictionary;
}
/**
* @inheritdoc
*/
public function setDirection($direction)
{
$this->direction = $direction;
}
/**
* @inheritdoc
*/
protected function selfProcession($string)
{
$string = $this->substituteCharacters($string);
return $string;
}
/**
* Substitutes characters in a string.
* @param string $string String to substitute characters in.
* @return string String with substituted characters.
*/
private function substituteCharacters($string)
{
$substitutions = $this->dictionary->getSubstitutions();
foreach ($substitutions as $from => $to) {
if ($this->direction === self::DIRECTION_FORWARD) {
$pattern = "/$from/u";
$replacement = $to;
} else {
$pattern = "/$to/u";
$replacement = $from;
}
$string = preg_replace($pattern, $replacement, $string);
}
return $string;
}
}