1: <?php
2:
3: namespace PHPixie\ORM\Configs;
4:
5: class Inflector
6: {
7: protected $pluralRules = array(
8: '/^(.*?[sxz])$/i' => '\\1es',
9: '/^(.*?[^aeioudgkprt]h)$/i' => '\\1es',
10: '/^(.*?[^aeiou])y$/i' => '\\1ies',
11: '/$/i' => 's',
12: );
13:
14: protected $singularRules = array(
15: '/^(.*?us)$/i' => '\\1',
16: '/^(.*?[sxz])es$/i' => '\\1',
17: '/^(.*?[^aeioudgkprt]h)es$/i' => '\\1',
18: '/^(.*?[^aeiou])ies$/i' => '\\1y',
19: '/^(.*?)s$/' => '\\1',
20: );
21:
22: protected $pluralCache = array();
23: protected $singularCache = array();
24:
25: public function plural($singular)
26: {
27: if(!isset($this->pluralCache[$singular])) {
28: $plural = $this->applySingleRule($singular, $this->pluralRules);
29: $this->cachePair($singular, $plural);
30: }
31:
32: return $this->pluralCache[$singular];
33: }
34:
35: public function singular($plural)
36: {
37: if(!isset($this->singularCache[$plural])) {
38: $singular = $this->applySingleRule($plural, $this->singularRules);
39: $this->cachePair($singular, $plural);
40: }
41: return $this->singularCache[$plural];
42: }
43:
44: protected function cachePair($singular, $plural)
45: {
46: $this->pluralCache[$singular] = $plural;
47: $this->singularCache[$plural] = $singular;
48: }
49:
50: protected function applySingleRule($word, $rules)
51: {
52: foreach ($rules as $pattern => $replacement) {
53: $word = preg_replace($pattern, $replacement, $word, -1, $count);
54: if ($count > 0)
55: break;
56: }
57:
58: return $word;
59: }
60: }
61: