Inflector.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Inflector;
  11. /**
  12. * Converts words between singular and plural forms.
  13. *
  14. * @author Bernhard Schussek <bschussek@gmail.com>
  15. */
  16. final class Inflector
  17. {
  18. /**
  19. * Map English plural to singular suffixes.
  20. *
  21. * @see http://english-zone.com/spelling/plurals.html
  22. */
  23. private static $pluralMap = [
  24. // First entry: plural suffix, reversed
  25. // Second entry: length of plural suffix
  26. // Third entry: Whether the suffix may succeed a vocal
  27. // Fourth entry: Whether the suffix may succeed a consonant
  28. // Fifth entry: singular suffix, normal
  29. // bacteria (bacterium), criteria (criterion), phenomena (phenomenon)
  30. ['a', 1, true, true, ['on', 'um']],
  31. // nebulae (nebula)
  32. ['ea', 2, true, true, 'a'],
  33. // services (service)
  34. ['secivres', 8, true, true, 'service'],
  35. // mice (mouse), lice (louse)
  36. ['eci', 3, false, true, 'ouse'],
  37. // geese (goose)
  38. ['esee', 4, false, true, 'oose'],
  39. // fungi (fungus), alumni (alumnus), syllabi (syllabus), radii (radius)
  40. ['i', 1, true, true, 'us'],
  41. // men (man), women (woman)
  42. ['nem', 3, true, true, 'man'],
  43. // children (child)
  44. ['nerdlihc', 8, true, true, 'child'],
  45. // oxen (ox)
  46. ['nexo', 4, false, false, 'ox'],
  47. // indices (index), appendices (appendix), prices (price)
  48. ['seci', 4, false, true, ['ex', 'ix', 'ice']],
  49. // selfies (selfie)
  50. ['seifles', 7, true, true, 'selfie'],
  51. // movies (movie)
  52. ['seivom', 6, true, true, 'movie'],
  53. // feet (foot)
  54. ['teef', 4, true, true, 'foot'],
  55. // geese (goose)
  56. ['eseeg', 5, true, true, 'goose'],
  57. // teeth (tooth)
  58. ['hteet', 5, true, true, 'tooth'],
  59. // news (news)
  60. ['swen', 4, true, true, 'news'],
  61. // series (series)
  62. ['seires', 6, true, true, 'series'],
  63. // babies (baby)
  64. ['sei', 3, false, true, 'y'],
  65. // accesses (access), addresses (address), kisses (kiss)
  66. ['sess', 4, true, false, 'ss'],
  67. // analyses (analysis), ellipses (ellipsis), fungi (fungus),
  68. // neuroses (neurosis), theses (thesis), emphases (emphasis),
  69. // oases (oasis), crises (crisis), houses (house), bases (base),
  70. // atlases (atlas)
  71. ['ses', 3, true, true, ['s', 'se', 'sis']],
  72. // objectives (objective), alternative (alternatives)
  73. ['sevit', 5, true, true, 'tive'],
  74. // drives (drive)
  75. ['sevird', 6, false, true, 'drive'],
  76. // lives (life), wives (wife)
  77. ['sevi', 4, false, true, 'ife'],
  78. // moves (move)
  79. ['sevom', 5, true, true, 'move'],
  80. // hooves (hoof), dwarves (dwarf), elves (elf), leaves (leaf), caves (cave), staves (staff)
  81. ['sev', 3, true, true, ['f', 've', 'ff']],
  82. // axes (axis), axes (ax), axes (axe)
  83. ['sexa', 4, false, false, ['ax', 'axe', 'axis']],
  84. // indexes (index), matrixes (matrix)
  85. ['sex', 3, true, false, 'x'],
  86. // quizzes (quiz)
  87. ['sezz', 4, true, false, 'z'],
  88. // bureaus (bureau)
  89. ['suae', 4, false, true, 'eau'],
  90. // fees (fee), trees (tree), employees (employee)
  91. ['see', 3, true, true, 'ee'],
  92. // roses (rose), garages (garage), cassettes (cassette),
  93. // waltzes (waltz), heroes (hero), bushes (bush), arches (arch),
  94. // shoes (shoe)
  95. ['se', 2, true, true, ['', 'e']],
  96. // tags (tag)
  97. ['s', 1, true, true, ''],
  98. // chateaux (chateau)
  99. ['xuae', 4, false, true, 'eau'],
  100. // people (person)
  101. ['elpoep', 6, true, true, 'person'],
  102. ];
  103. /**
  104. * Map English singular to plural suffixes.
  105. *
  106. * @see http://english-zone.com/spelling/plurals.html
  107. */
  108. private static $singularMap = [
  109. // First entry: singular suffix, reversed
  110. // Second entry: length of singular suffix
  111. // Third entry: Whether the suffix may succeed a vocal
  112. // Fourth entry: Whether the suffix may succeed a consonant
  113. // Fifth entry: plural suffix, normal
  114. // criterion (criteria)
  115. ['airetirc', 8, false, false, 'criterion'],
  116. // nebulae (nebula)
  117. ['aluben', 6, false, false, 'nebulae'],
  118. // children (child)
  119. ['dlihc', 5, true, true, 'children'],
  120. // prices (price)
  121. ['eci', 3, false, true, 'ices'],
  122. // services (service)
  123. ['ecivres', 7, true, true, 'services'],
  124. // lives (life), wives (wife)
  125. ['efi', 3, false, true, 'ives'],
  126. // selfies (selfie)
  127. ['eifles', 6, true, true, 'selfies'],
  128. // movies (movie)
  129. ['eivom', 5, true, true, 'movies'],
  130. // lice (louse)
  131. ['esuol', 5, false, true, 'lice'],
  132. // mice (mouse)
  133. ['esuom', 5, false, true, 'mice'],
  134. // geese (goose)
  135. ['esoo', 4, false, true, 'eese'],
  136. // houses (house), bases (base)
  137. ['es', 2, true, true, 'ses'],
  138. // geese (goose)
  139. ['esoog', 5, true, true, 'geese'],
  140. // caves (cave)
  141. ['ev', 2, true, true, 'ves'],
  142. // drives (drive)
  143. ['evird', 5, false, true, 'drives'],
  144. // objectives (objective), alternative (alternatives)
  145. ['evit', 4, true, true, 'tives'],
  146. // moves (move)
  147. ['evom', 4, true, true, 'moves'],
  148. // staves (staff)
  149. ['ffats', 5, true, true, 'staves'],
  150. // hooves (hoof), dwarves (dwarf), elves (elf), leaves (leaf)
  151. ['ff', 2, true, true, 'ffs'],
  152. // hooves (hoof), dwarves (dwarf), elves (elf), leaves (leaf)
  153. ['f', 1, true, true, ['fs', 'ves']],
  154. // arches (arch)
  155. ['hc', 2, true, true, 'ches'],
  156. // bushes (bush)
  157. ['hs', 2, true, true, 'shes'],
  158. // teeth (tooth)
  159. ['htoot', 5, true, true, 'teeth'],
  160. // bacteria (bacterium), criteria (criterion), phenomena (phenomenon)
  161. ['mu', 2, true, true, 'a'],
  162. // men (man), women (woman)
  163. ['nam', 3, true, true, 'men'],
  164. // people (person)
  165. ['nosrep', 6, true, true, ['persons', 'people']],
  166. // bacteria (bacterium), criteria (criterion), phenomena (phenomenon)
  167. ['noi', 3, true, true, 'ions'],
  168. // seasons (season), treasons (treason), poisons (poison), lessons (lesson)
  169. ['nos', 3, true, true, 'sons'],
  170. // bacteria (bacterium), criteria (criterion), phenomena (phenomenon)
  171. ['no', 2, true, true, 'a'],
  172. // echoes (echo)
  173. ['ohce', 4, true, true, 'echoes'],
  174. // heroes (hero)
  175. ['oreh', 4, true, true, 'heroes'],
  176. // atlases (atlas)
  177. ['salta', 5, true, true, 'atlases'],
  178. // irises (iris)
  179. ['siri', 4, true, true, 'irises'],
  180. // analyses (analysis), ellipses (ellipsis), neuroses (neurosis)
  181. // theses (thesis), emphases (emphasis), oases (oasis),
  182. // crises (crisis)
  183. ['sis', 3, true, true, 'ses'],
  184. // accesses (access), addresses (address), kisses (kiss)
  185. ['ss', 2, true, false, 'sses'],
  186. // syllabi (syllabus)
  187. ['suballys', 8, true, true, 'syllabi'],
  188. // buses (bus)
  189. ['sub', 3, true, true, 'buses'],
  190. // circuses (circus)
  191. ['suc', 3, true, true, 'cuses'],
  192. // fungi (fungus), alumni (alumnus), syllabi (syllabus), radii (radius)
  193. ['su', 2, true, true, 'i'],
  194. // news (news)
  195. ['swen', 4, true, true, 'news'],
  196. // feet (foot)
  197. ['toof', 4, true, true, 'feet'],
  198. // chateaux (chateau), bureaus (bureau)
  199. ['uae', 3, false, true, ['eaus', 'eaux']],
  200. // oxen (ox)
  201. ['xo', 2, false, false, 'oxen'],
  202. // hoaxes (hoax)
  203. ['xaoh', 4, true, false, 'hoaxes'],
  204. // indices (index)
  205. ['xedni', 5, false, true, ['indicies', 'indexes']],
  206. // boxes (box)
  207. ['xo', 2, false, true, 'oxes'],
  208. // indexes (index), matrixes (matrix)
  209. ['x', 1, true, false, ['cies', 'xes']],
  210. // appendices (appendix)
  211. ['xi', 2, false, true, 'ices'],
  212. // babies (baby)
  213. ['y', 1, false, true, 'ies'],
  214. // quizzes (quiz)
  215. ['ziuq', 4, true, false, 'quizzes'],
  216. // waltzes (waltz)
  217. ['z', 1, true, true, 'zes'],
  218. ];
  219. /**
  220. * A list of words which should not be inflected, reversed.
  221. */
  222. private static $uninflected = [
  223. 'atad',
  224. 'reed',
  225. 'kcabdeef',
  226. 'hsif',
  227. 'ofni',
  228. 'esoom',
  229. 'seires',
  230. 'peehs',
  231. 'seiceps',
  232. ];
  233. /**
  234. * This class should not be instantiated.
  235. */
  236. private function __construct()
  237. {
  238. }
  239. /**
  240. * Returns the singular form of a word.
  241. *
  242. * If the method can't determine the form with certainty, an array of the
  243. * possible singulars is returned.
  244. *
  245. * @param string $plural A word in plural form
  246. *
  247. * @return string|array The singular form or an array of possible singular forms
  248. */
  249. public static function singularize(string $plural)
  250. {
  251. $pluralRev = strrev($plural);
  252. $lowerPluralRev = strtolower($pluralRev);
  253. $pluralLength = \strlen($lowerPluralRev);
  254. // Check if the word is one which is not inflected, return early if so
  255. if (\in_array($lowerPluralRev, self::$uninflected, true)) {
  256. return $plural;
  257. }
  258. // The outer loop iterates over the entries of the plural table
  259. // The inner loop $j iterates over the characters of the plural suffix
  260. // in the plural table to compare them with the characters of the actual
  261. // given plural suffix
  262. foreach (self::$pluralMap as $map) {
  263. $suffix = $map[0];
  264. $suffixLength = $map[1];
  265. $j = 0;
  266. // Compare characters in the plural table and of the suffix of the
  267. // given plural one by one
  268. while ($suffix[$j] === $lowerPluralRev[$j]) {
  269. // Let $j point to the next character
  270. ++$j;
  271. // Successfully compared the last character
  272. // Add an entry with the singular suffix to the singular array
  273. if ($j === $suffixLength) {
  274. // Is there any character preceding the suffix in the plural string?
  275. if ($j < $pluralLength) {
  276. $nextIsVocal = false !== strpos('aeiou', $lowerPluralRev[$j]);
  277. if (!$map[2] && $nextIsVocal) {
  278. // suffix may not succeed a vocal but next char is one
  279. break;
  280. }
  281. if (!$map[3] && !$nextIsVocal) {
  282. // suffix may not succeed a consonant but next char is one
  283. break;
  284. }
  285. }
  286. $newBase = substr($plural, 0, $pluralLength - $suffixLength);
  287. $newSuffix = $map[4];
  288. // Check whether the first character in the plural suffix
  289. // is uppercased. If yes, uppercase the first character in
  290. // the singular suffix too
  291. $firstUpper = ctype_upper($pluralRev[$j - 1]);
  292. if (\is_array($newSuffix)) {
  293. $singulars = [];
  294. foreach ($newSuffix as $newSuffixEntry) {
  295. $singulars[] = $newBase.($firstUpper ? ucfirst($newSuffixEntry) : $newSuffixEntry);
  296. }
  297. return $singulars;
  298. }
  299. return $newBase.($firstUpper ? ucfirst($newSuffix) : $newSuffix);
  300. }
  301. // Suffix is longer than word
  302. if ($j === $pluralLength) {
  303. break;
  304. }
  305. }
  306. }
  307. // Assume that plural and singular is identical
  308. return $plural;
  309. }
  310. /**
  311. * Returns the plural form of a word.
  312. *
  313. * If the method can't determine the form with certainty, an array of the
  314. * possible plurals is returned.
  315. *
  316. * @param string $singular A word in singular form
  317. *
  318. * @return string|array The plural form or an array of possible plural forms
  319. */
  320. public static function pluralize(string $singular)
  321. {
  322. $singularRev = strrev($singular);
  323. $lowerSingularRev = strtolower($singularRev);
  324. $singularLength = \strlen($lowerSingularRev);
  325. // Check if the word is one which is not inflected, return early if so
  326. if (\in_array($lowerSingularRev, self::$uninflected, true)) {
  327. return $singular;
  328. }
  329. // The outer loop iterates over the entries of the singular table
  330. // The inner loop $j iterates over the characters of the singular suffix
  331. // in the singular table to compare them with the characters of the actual
  332. // given singular suffix
  333. foreach (self::$singularMap as $map) {
  334. $suffix = $map[0];
  335. $suffixLength = $map[1];
  336. $j = 0;
  337. // Compare characters in the singular table and of the suffix of the
  338. // given plural one by one
  339. while ($suffix[$j] === $lowerSingularRev[$j]) {
  340. // Let $j point to the next character
  341. ++$j;
  342. // Successfully compared the last character
  343. // Add an entry with the plural suffix to the plural array
  344. if ($j === $suffixLength) {
  345. // Is there any character preceding the suffix in the plural string?
  346. if ($j < $singularLength) {
  347. $nextIsVocal = false !== strpos('aeiou', $lowerSingularRev[$j]);
  348. if (!$map[2] && $nextIsVocal) {
  349. // suffix may not succeed a vocal but next char is one
  350. break;
  351. }
  352. if (!$map[3] && !$nextIsVocal) {
  353. // suffix may not succeed a consonant but next char is one
  354. break;
  355. }
  356. }
  357. $newBase = substr($singular, 0, $singularLength - $suffixLength);
  358. $newSuffix = $map[4];
  359. // Check whether the first character in the singular suffix
  360. // is uppercased. If yes, uppercase the first character in
  361. // the singular suffix too
  362. $firstUpper = ctype_upper($singularRev[$j - 1]);
  363. if (\is_array($newSuffix)) {
  364. $plurals = [];
  365. foreach ($newSuffix as $newSuffixEntry) {
  366. $plurals[] = $newBase.($firstUpper ? ucfirst($newSuffixEntry) : $newSuffixEntry);
  367. }
  368. return $plurals;
  369. }
  370. return $newBase.($firstUpper ? ucfirst($newSuffix) : $newSuffix);
  371. }
  372. // Suffix is longer than word
  373. if ($j === $singularLength) {
  374. break;
  375. }
  376. }
  377. }
  378. // Assume that plural is singular with a trailing `s`
  379. return $singular.'s';
  380. }
  381. }