Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

BaseInflector.php 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\helpers;
  8. use Yii;
  9. /**
  10. * BaseInflector provides concrete implementation for [[Inflector]].
  11. *
  12. * Do not use BaseInflector. Use [[Inflector]] instead.
  13. *
  14. * @author Antonio Ramirez <amigo.cobos@gmail.com>
  15. * @author Alexander Makarov <sam@rmcreative.ru>
  16. * @since 2.0
  17. */
  18. class BaseInflector
  19. {
  20. /**
  21. * @var array the rules for converting a word into its plural form.
  22. * The keys are the regular expressions and the values are the corresponding replacements.
  23. */
  24. public static $plurals = [
  25. '/([nrlm]ese|deer|fish|sheep|measles|ois|pox|media)$/i' => '\1',
  26. '/^(sea[- ]bass)$/i' => '\1',
  27. '/(m)ove$/i' => '\1oves',
  28. '/(f)oot$/i' => '\1eet',
  29. '/(h)uman$/i' => '\1umans',
  30. '/(s)tatus$/i' => '\1tatuses',
  31. '/(s)taff$/i' => '\1taff',
  32. '/(t)ooth$/i' => '\1eeth',
  33. '/(quiz)$/i' => '\1zes',
  34. '/^(ox)$/i' => '\1\2en',
  35. '/([m|l])ouse$/i' => '\1ice',
  36. '/(matr|vert|ind)(ix|ex)$/i' => '\1ices',
  37. '/(x|ch|ss|sh)$/i' => '\1es',
  38. '/([^aeiouy]|qu)y$/i' => '\1ies',
  39. '/(hive)$/i' => '\1s',
  40. '/(?:([^f])fe|([lr])f)$/i' => '\1\2ves',
  41. '/sis$/i' => 'ses',
  42. '/([ti])um$/i' => '\1a',
  43. '/(p)erson$/i' => '\1eople',
  44. '/(m)an$/i' => '\1en',
  45. '/(c)hild$/i' => '\1hildren',
  46. '/(buffal|tomat|potat|ech|her|vet)o$/i' => '\1oes',
  47. '/(alumn|bacill|cact|foc|fung|nucle|radi|stimul|syllab|termin|vir)us$/i' => '\1i',
  48. '/us$/i' => 'uses',
  49. '/(alias)$/i' => '\1es',
  50. '/(ax|cris|test)is$/i' => '\1es',
  51. '/s$/' => 's',
  52. '/^$/' => '',
  53. '/$/' => 's',
  54. ];
  55. /**
  56. * @var array the rules for converting a word into its singular form.
  57. * The keys are the regular expressions and the values are the corresponding replacements.
  58. */
  59. public static $singulars = [
  60. '/([nrlm]ese|deer|fish|sheep|measles|ois|pox|media|ss)$/i' => '\1',
  61. '/^(sea[- ]bass)$/i' => '\1',
  62. '/(s)tatuses$/i' => '\1tatus',
  63. '/(f)eet$/i' => '\1oot',
  64. '/(t)eeth$/i' => '\1ooth',
  65. '/^(.*)(menu)s$/i' => '\1\2',
  66. '/(quiz)zes$/i' => '\\1',
  67. '/(matr)ices$/i' => '\1ix',
  68. '/(vert|ind)ices$/i' => '\1ex',
  69. '/^(ox)en/i' => '\1',
  70. '/(alias)(es)*$/i' => '\1',
  71. '/(alumn|bacill|cact|foc|fung|nucle|radi|stimul|syllab|termin|viri?)i$/i' => '\1us',
  72. '/([ftw]ax)es/i' => '\1',
  73. '/(cris|ax|test)es$/i' => '\1is',
  74. '/(shoe|slave)s$/i' => '\1',
  75. '/(o)es$/i' => '\1',
  76. '/ouses$/' => 'ouse',
  77. '/([^a])uses$/' => '\1us',
  78. '/([m|l])ice$/i' => '\1ouse',
  79. '/(x|ch|ss|sh)es$/i' => '\1',
  80. '/(m)ovies$/i' => '\1\2ovie',
  81. '/(s)eries$/i' => '\1\2eries',
  82. '/([^aeiouy]|qu)ies$/i' => '\1y',
  83. '/([lr])ves$/i' => '\1f',
  84. '/(tive)s$/i' => '\1',
  85. '/(hive)s$/i' => '\1',
  86. '/(drive)s$/i' => '\1',
  87. '/([^fo])ves$/i' => '\1fe',
  88. '/(^analy)ses$/i' => '\1sis',
  89. '/(analy|diagno|^ba|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '\1\2sis',
  90. '/([ti])a$/i' => '\1um',
  91. '/(p)eople$/i' => '\1\2erson',
  92. '/(m)en$/i' => '\1an',
  93. '/(c)hildren$/i' => '\1\2hild',
  94. '/(n)ews$/i' => '\1\2ews',
  95. '/(n)etherlands$/i' => '\1\2etherlands',
  96. '/eaus$/' => 'eau',
  97. '/^(.*us)$/' => '\\1',
  98. '/s$/i' => '',
  99. ];
  100. /**
  101. * @var array the special rules for converting a word between its plural form and singular form.
  102. * The keys are the special words in singular form, and the values are the corresponding plural form.
  103. */
  104. public static $specials = [
  105. 'atlas' => 'atlases',
  106. 'beef' => 'beefs',
  107. 'brother' => 'brothers',
  108. 'cafe' => 'cafes',
  109. 'child' => 'children',
  110. 'cookie' => 'cookies',
  111. 'corpus' => 'corpuses',
  112. 'cow' => 'cows',
  113. 'curve' => 'curves',
  114. 'foe' => 'foes',
  115. 'ganglion' => 'ganglions',
  116. 'genie' => 'genies',
  117. 'genus' => 'genera',
  118. 'graffito' => 'graffiti',
  119. 'hoof' => 'hoofs',
  120. 'loaf' => 'loaves',
  121. 'man' => 'men',
  122. 'money' => 'monies',
  123. 'mongoose' => 'mongooses',
  124. 'move' => 'moves',
  125. 'mythos' => 'mythoi',
  126. 'niche' => 'niches',
  127. 'numen' => 'numina',
  128. 'occiput' => 'occiputs',
  129. 'octopus' => 'octopuses',
  130. 'opus' => 'opuses',
  131. 'ox' => 'oxen',
  132. 'penis' => 'penises',
  133. 'sex' => 'sexes',
  134. 'soliloquy' => 'soliloquies',
  135. 'testis' => 'testes',
  136. 'trilby' => 'trilbys',
  137. 'turf' => 'turfs',
  138. 'wave' => 'waves',
  139. 'Amoyese' => 'Amoyese',
  140. 'bison' => 'bison',
  141. 'Borghese' => 'Borghese',
  142. 'bream' => 'bream',
  143. 'breeches' => 'breeches',
  144. 'britches' => 'britches',
  145. 'buffalo' => 'buffalo',
  146. 'cantus' => 'cantus',
  147. 'carp' => 'carp',
  148. 'chassis' => 'chassis',
  149. 'clippers' => 'clippers',
  150. 'cod' => 'cod',
  151. 'coitus' => 'coitus',
  152. 'Congoese' => 'Congoese',
  153. 'contretemps' => 'contretemps',
  154. 'corps' => 'corps',
  155. 'debris' => 'debris',
  156. 'diabetes' => 'diabetes',
  157. 'djinn' => 'djinn',
  158. 'eland' => 'eland',
  159. 'elk' => 'elk',
  160. 'equipment' => 'equipment',
  161. 'Faroese' => 'Faroese',
  162. 'flounder' => 'flounder',
  163. 'Foochowese' => 'Foochowese',
  164. 'gallows' => 'gallows',
  165. 'Genevese' => 'Genevese',
  166. 'Genoese' => 'Genoese',
  167. 'Gilbertese' => 'Gilbertese',
  168. 'graffiti' => 'graffiti',
  169. 'headquarters' => 'headquarters',
  170. 'herpes' => 'herpes',
  171. 'hijinks' => 'hijinks',
  172. 'Hottentotese' => 'Hottentotese',
  173. 'information' => 'information',
  174. 'innings' => 'innings',
  175. 'jackanapes' => 'jackanapes',
  176. 'Kiplingese' => 'Kiplingese',
  177. 'Kongoese' => 'Kongoese',
  178. 'Lucchese' => 'Lucchese',
  179. 'mackerel' => 'mackerel',
  180. 'Maltese' => 'Maltese',
  181. 'mews' => 'mews',
  182. 'moose' => 'moose',
  183. 'mumps' => 'mumps',
  184. 'Nankingese' => 'Nankingese',
  185. 'news' => 'news',
  186. 'nexus' => 'nexus',
  187. 'Niasese' => 'Niasese',
  188. 'Pekingese' => 'Pekingese',
  189. 'Piedmontese' => 'Piedmontese',
  190. 'pincers' => 'pincers',
  191. 'Pistoiese' => 'Pistoiese',
  192. 'pliers' => 'pliers',
  193. 'Portuguese' => 'Portuguese',
  194. 'proceedings' => 'proceedings',
  195. 'rabies' => 'rabies',
  196. 'rice' => 'rice',
  197. 'rhinoceros' => 'rhinoceros',
  198. 'salmon' => 'salmon',
  199. 'Sarawakese' => 'Sarawakese',
  200. 'scissors' => 'scissors',
  201. 'series' => 'series',
  202. 'Shavese' => 'Shavese',
  203. 'shears' => 'shears',
  204. 'siemens' => 'siemens',
  205. 'species' => 'species',
  206. 'swine' => 'swine',
  207. 'testes' => 'testes',
  208. 'trousers' => 'trousers',
  209. 'trout' => 'trout',
  210. 'tuna' => 'tuna',
  211. 'Vermontese' => 'Vermontese',
  212. 'Wenchowese' => 'Wenchowese',
  213. 'whiting' => 'whiting',
  214. 'wildebeest' => 'wildebeest',
  215. 'Yengeese' => 'Yengeese',
  216. ];
  217. /**
  218. * @var array fallback map for transliteration used by [[transliterate()]] when intl isn't available.
  219. */
  220. public static $transliteration = [
  221. 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'AE', 'Ç' => 'C',
  222. 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I',
  223. 'Ð' => 'D', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ő' => 'O',
  224. 'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ű' => 'U', 'Ý' => 'Y', 'Þ' => 'TH',
  225. 'ß' => 'ss',
  226. 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'ae', 'ç' => 'c',
  227. 'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i',
  228. 'ð' => 'd', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ő' => 'o',
  229. 'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u', 'ű' => 'u', 'ý' => 'y', 'þ' => 'th',
  230. 'ÿ' => 'y',
  231. ];
  232. /**
  233. * Shortcut for `Any-Latin; NFKD` transliteration rule. The rule is strict, letters will be transliterated with
  234. * the closest sound-representation chars. The result may contain any UTF-8 chars. For example:
  235. * `获取到 どちら Українська: ґ,є, Српска: ђ, њ, џ! ¿Español?` will be transliterated to
  236. * `huò qǔ dào dochira Ukraí̈nsʹka: g̀,ê, Srpska: đ, n̂, d̂! ¿Español?`
  237. *
  238. * Used in [[transliterate()]].
  239. * For detailed information see [unicode normalization forms](http://unicode.org/reports/tr15/#Normalization_Forms_Table)
  240. * @see http://unicode.org/reports/tr15/#Normalization_Forms_Table
  241. * @see transliterate()
  242. * @since 2.0.7
  243. */
  244. const TRANSLITERATE_STRICT = 'Any-Latin; NFKD';
  245. /**
  246. * Shortcut for `Any-Latin; Latin-ASCII` transliteration rule. The rule is medium, letters will be
  247. * transliterated to characters of Latin-1 (ISO 8859-1) ASCII table. For example:
  248. * `获取到 どちら Українська: ґ,є, Српска: ђ, њ, џ! ¿Español?` will be transliterated to
  249. * `huo qu dao dochira Ukrainsʹka: g,e, Srpska: d, n, d! ¿Espanol?`
  250. *
  251. * Used in [[transliterate()]].
  252. * For detailed information see [unicode normalization forms](http://unicode.org/reports/tr15/#Normalization_Forms_Table)
  253. * @see http://unicode.org/reports/tr15/#Normalization_Forms_Table
  254. * @see transliterate()
  255. * @since 2.0.7
  256. */
  257. const TRANSLITERATE_MEDIUM = 'Any-Latin; Latin-ASCII';
  258. /**
  259. * Shortcut for `Any-Latin; Latin-ASCII; [\u0080-\uffff] remove` transliteration rule. The rule is loose,
  260. * letters will be transliterated with the characters of Basic Latin Unicode Block.
  261. * For example:
  262. * `获取到 どちら Українська: ґ,є, Српска: ђ, њ, џ! ¿Español?` will be transliterated to
  263. * `huo qu dao dochira Ukrainska: g,e, Srpska: d, n, d! Espanol?`
  264. *
  265. * Used in [[transliterate()]].
  266. * For detailed information see [unicode normalization forms](http://unicode.org/reports/tr15/#Normalization_Forms_Table)
  267. * @see http://unicode.org/reports/tr15/#Normalization_Forms_Table
  268. * @see transliterate()
  269. * @since 2.0.7
  270. */
  271. const TRANSLITERATE_LOOSE = 'Any-Latin; Latin-ASCII; [\u0080-\uffff] remove';
  272. /**
  273. * @var mixed Either a [[\Transliterator]], or a string from which a [[\Transliterator]] can be built
  274. * for transliteration. Used by [[transliterate()]] when intl is available. Defaults to [[TRANSLITERATE_LOOSE]]
  275. * @see http://php.net/manual/en/transliterator.transliterate.php
  276. */
  277. public static $transliterator = self::TRANSLITERATE_LOOSE;
  278. /**
  279. * Converts a word to its plural form.
  280. * Note that this is for English only!
  281. * For example, 'apple' will become 'apples', and 'child' will become 'children'.
  282. * @param string $word the word to be pluralized
  283. * @return string the pluralized word
  284. */
  285. public static function pluralize($word)
  286. {
  287. if (isset(static::$specials[$word])) {
  288. return static::$specials[$word];
  289. }
  290. foreach (static::$plurals as $rule => $replacement) {
  291. if (preg_match($rule, $word)) {
  292. return preg_replace($rule, $replacement, $word);
  293. }
  294. }
  295. return $word;
  296. }
  297. /**
  298. * Returns the singular of the $word
  299. * @param string $word the english word to singularize
  300. * @return string Singular noun.
  301. */
  302. public static function singularize($word)
  303. {
  304. $result = array_search($word, static::$specials, true);
  305. if ($result !== false) {
  306. return $result;
  307. }
  308. foreach (static::$singulars as $rule => $replacement) {
  309. if (preg_match($rule, $word)) {
  310. return preg_replace($rule, $replacement, $word);
  311. }
  312. }
  313. return $word;
  314. }
  315. /**
  316. * Converts an underscored or CamelCase word into a English
  317. * sentence.
  318. * @param string $words
  319. * @param boolean $ucAll whether to set all words to uppercase
  320. * @return string
  321. */
  322. public static function titleize($words, $ucAll = false)
  323. {
  324. $words = static::humanize(static::underscore($words), $ucAll);
  325. return $ucAll ? ucwords($words) : ucfirst($words);
  326. }
  327. /**
  328. * Returns given word as CamelCased
  329. * Converts a word like "send_email" to "SendEmail". It
  330. * will remove non alphanumeric character from the word, so
  331. * "who's online" will be converted to "WhoSOnline"
  332. * @see variablize()
  333. * @param string $word the word to CamelCase
  334. * @return string
  335. */
  336. public static function camelize($word)
  337. {
  338. return str_replace(' ', '', ucwords(preg_replace('/[^A-Za-z0-9]+/', ' ', $word)));
  339. }
  340. /**
  341. * Converts a CamelCase name into space-separated words.
  342. * For example, 'PostTag' will be converted to 'Post Tag'.
  343. * @param string $name the string to be converted
  344. * @param boolean $ucwords whether to capitalize the first letter in each word
  345. * @return string the resulting words
  346. */
  347. public static function camel2words($name, $ucwords = true)
  348. {
  349. $label = trim(strtolower(str_replace([
  350. '-',
  351. '_',
  352. '.',
  353. ], ' ', preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name))));
  354. return $ucwords ? ucwords($label) : $label;
  355. }
  356. /**
  357. * Converts a CamelCase name into an ID in lowercase.
  358. * Words in the ID may be concatenated using the specified character (defaults to '-').
  359. * For example, 'PostTag' will be converted to 'post-tag'.
  360. * @param string $name the string to be converted
  361. * @param string $separator the character used to concatenate the words in the ID
  362. * @param boolean|string $strict whether to insert a separator between two consecutive uppercase chars, defaults to false
  363. * @return string the resulting ID
  364. */
  365. public static function camel2id($name, $separator = '-', $strict = false)
  366. {
  367. $regex = $strict ? '/[A-Z]/' : '/(?<![A-Z])[A-Z]/';
  368. if ($separator === '_') {
  369. return trim(strtolower(preg_replace($regex, '_\0', $name)), '_');
  370. } else {
  371. return trim(strtolower(str_replace('_', $separator, preg_replace($regex, $separator . '\0', $name))), $separator);
  372. }
  373. }
  374. /**
  375. * Converts an ID into a CamelCase name.
  376. * Words in the ID separated by `$separator` (defaults to '-') will be concatenated into a CamelCase name.
  377. * For example, 'post-tag' is converted to 'PostTag'.
  378. * @param string $id the ID to be converted
  379. * @param string $separator the character used to separate the words in the ID
  380. * @return string the resulting CamelCase name
  381. */
  382. public static function id2camel($id, $separator = '-')
  383. {
  384. return str_replace(' ', '', ucwords(implode(' ', explode($separator, $id))));
  385. }
  386. /**
  387. * Converts any "CamelCased" into an "underscored_word".
  388. * @param string $words the word(s) to underscore
  389. * @return string
  390. */
  391. public static function underscore($words)
  392. {
  393. return strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $words));
  394. }
  395. /**
  396. * Returns a human-readable string from $word
  397. * @param string $word the string to humanize
  398. * @param boolean $ucAll whether to set all words to uppercase or not
  399. * @return string
  400. */
  401. public static function humanize($word, $ucAll = false)
  402. {
  403. $word = str_replace('_', ' ', preg_replace('/_id$/', '', $word));
  404. return $ucAll ? ucwords($word) : ucfirst($word);
  405. }
  406. /**
  407. * Same as camelize but first char is in lowercase.
  408. * Converts a word like "send_email" to "sendEmail". It
  409. * will remove non alphanumeric character from the word, so
  410. * "who's online" will be converted to "whoSOnline"
  411. * @param string $word to lowerCamelCase
  412. * @return string
  413. */
  414. public static function variablize($word)
  415. {
  416. $word = static::camelize($word);
  417. return strtolower($word[0]) . substr($word, 1);
  418. }
  419. /**
  420. * Converts a class name to its table name (pluralized)
  421. * naming conventions. For example, converts "Person" to "people"
  422. * @param string $className the class name for getting related table_name
  423. * @return string
  424. */
  425. public static function tableize($className)
  426. {
  427. return static::pluralize(static::underscore($className));
  428. }
  429. /**
  430. * Returns a string with all spaces converted to given replacement,
  431. * non word characters removed and the rest of characters transliterated.
  432. *
  433. * If intl extension isn't available uses fallback that converts latin characters only
  434. * and removes the rest. You may customize characters map via $transliteration property
  435. * of the helper.
  436. *
  437. * @param string $string An arbitrary string to convert
  438. * @param string $replacement The replacement to use for spaces
  439. * @param boolean $lowercase whether to return the string in lowercase or not. Defaults to `true`.
  440. * @return string The converted string.
  441. */
  442. public static function slug($string, $replacement = '-', $lowercase = true)
  443. {
  444. $string = static::transliterate($string);
  445. $string = preg_replace('/[^a-zA-Z0-9=\s—–-]+/u', '', $string);
  446. $string = preg_replace('/[=\s—–-]+/u', $replacement, $string);
  447. $string = trim($string, $replacement);
  448. return $lowercase ? strtolower($string) : $string;
  449. }
  450. /**
  451. * Returns transliterated version of a string.
  452. *
  453. * If intl extension isn't available uses fallback that converts latin characters only
  454. * and removes the rest. You may customize characters map via $transliteration property
  455. * of the helper.
  456. *
  457. * @param string $string input string
  458. * @param string|\Transliterator $transliterator either a [[Transliterator]] or a string
  459. * from which a [[Transliterator]] can be built.
  460. * @return string
  461. * @since 2.0.7 this method is public.
  462. */
  463. public static function transliterate($string, $transliterator = null)
  464. {
  465. if (static::hasIntl()) {
  466. if ($transliterator === null) {
  467. $transliterator = static::$transliterator;
  468. }
  469. return transliterator_transliterate($transliterator, $string);
  470. } else {
  471. return strtr($string, static::$transliteration);
  472. }
  473. }
  474. /**
  475. * @return boolean if intl extension is loaded
  476. */
  477. protected static function hasIntl()
  478. {
  479. return extension_loaded('intl');
  480. }
  481. /**
  482. * Converts a table name to its class name. For example, converts "people" to "Person"
  483. * @param string $tableName
  484. * @return string
  485. */
  486. public static function classify($tableName)
  487. {
  488. return static::camelize(static::singularize($tableName));
  489. }
  490. /**
  491. * Converts number to its ordinal English form. For example, converts 13 to 13th, 2 to 2nd ...
  492. * @param integer $number the number to get its ordinal value
  493. * @return string
  494. */
  495. public static function ordinalize($number)
  496. {
  497. if (in_array($number % 100, range(11, 13))) {
  498. return $number . 'th';
  499. }
  500. switch ($number % 10) {
  501. case 1:
  502. return $number . 'st';
  503. case 2:
  504. return $number . 'nd';
  505. case 3:
  506. return $number . 'rd';
  507. default:
  508. return $number . 'th';
  509. }
  510. }
  511. /**
  512. * Converts a list of words into a sentence.
  513. *
  514. * Special treatment is done for the last few words. For example,
  515. *
  516. * ```php
  517. * $words = ['Spain', 'France'];
  518. * echo Inflector::sentence($words);
  519. * // output: Spain and France
  520. *
  521. * $words = ['Spain', 'France', 'Italy'];
  522. * echo Inflector::sentence($words);
  523. * // output: Spain, France and Italy
  524. *
  525. * $words = ['Spain', 'France', 'Italy'];
  526. * echo Inflector::sentence($words, ' & ');
  527. * // output: Spain, France & Italy
  528. * ```
  529. *
  530. * @param array $words the words to be converted into an string
  531. * @param string $twoWordsConnector the string connecting words when there are only two
  532. * @param string $lastWordConnector the string connecting the last two words. If this is null, it will
  533. * take the value of `$twoWordsConnector`.
  534. * @param string $connector the string connecting words other than those connected by
  535. * $lastWordConnector and $twoWordsConnector
  536. * @return string the generated sentence
  537. * @since 2.0.1
  538. */
  539. public static function sentence(array $words, $twoWordsConnector = ' and ', $lastWordConnector = null, $connector = ', ')
  540. {
  541. if ($lastWordConnector === null) {
  542. $lastWordConnector = $twoWordsConnector;
  543. }
  544. switch (count($words)) {
  545. case 0:
  546. return '';
  547. case 1:
  548. return reset($words);
  549. case 2:
  550. return implode($twoWordsConnector, $words);
  551. default:
  552. return implode($connector, array_slice($words, 0, -1)) . $lastWordConnector . end($words);
  553. }
  554. }
  555. }