選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

537 行
19KB

  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. '/eaus$/' => 'eau',
  96. '/^(.*us)$/' => '\\1',
  97. '/s$/i' => '',
  98. ];
  99. /**
  100. * @var array the special rules for converting a word between its plural form and singular form.
  101. * The keys are the special words in singular form, and the values are the corresponding plural form.
  102. */
  103. public static $specials = [
  104. 'atlas' => 'atlases',
  105. 'beef' => 'beefs',
  106. 'brother' => 'brothers',
  107. 'cafe' => 'cafes',
  108. 'child' => 'children',
  109. 'cookie' => 'cookies',
  110. 'corpus' => 'corpuses',
  111. 'cow' => 'cows',
  112. 'curve' => 'curves',
  113. 'foe' => 'foes',
  114. 'ganglion' => 'ganglions',
  115. 'genie' => 'genies',
  116. 'genus' => 'genera',
  117. 'graffito' => 'graffiti',
  118. 'hoof' => 'hoofs',
  119. 'loaf' => 'loaves',
  120. 'man' => 'men',
  121. 'money' => 'monies',
  122. 'mongoose' => 'mongooses',
  123. 'move' => 'moves',
  124. 'mythos' => 'mythoi',
  125. 'niche' => 'niches',
  126. 'numen' => 'numina',
  127. 'occiput' => 'occiputs',
  128. 'octopus' => 'octopuses',
  129. 'opus' => 'opuses',
  130. 'ox' => 'oxen',
  131. 'penis' => 'penises',
  132. 'sex' => 'sexes',
  133. 'soliloquy' => 'soliloquies',
  134. 'testis' => 'testes',
  135. 'trilby' => 'trilbys',
  136. 'turf' => 'turfs',
  137. 'wave' => 'waves',
  138. 'Amoyese' => 'Amoyese',
  139. 'bison' => 'bison',
  140. 'Borghese' => 'Borghese',
  141. 'bream' => 'bream',
  142. 'breeches' => 'breeches',
  143. 'britches' => 'britches',
  144. 'buffalo' => 'buffalo',
  145. 'cantus' => 'cantus',
  146. 'carp' => 'carp',
  147. 'chassis' => 'chassis',
  148. 'clippers' => 'clippers',
  149. 'cod' => 'cod',
  150. 'coitus' => 'coitus',
  151. 'Congoese' => 'Congoese',
  152. 'contretemps' => 'contretemps',
  153. 'corps' => 'corps',
  154. 'debris' => 'debris',
  155. 'diabetes' => 'diabetes',
  156. 'djinn' => 'djinn',
  157. 'eland' => 'eland',
  158. 'elk' => 'elk',
  159. 'equipment' => 'equipment',
  160. 'Faroese' => 'Faroese',
  161. 'flounder' => 'flounder',
  162. 'Foochowese' => 'Foochowese',
  163. 'gallows' => 'gallows',
  164. 'Genevese' => 'Genevese',
  165. 'Genoese' => 'Genoese',
  166. 'Gilbertese' => 'Gilbertese',
  167. 'graffiti' => 'graffiti',
  168. 'headquarters' => 'headquarters',
  169. 'herpes' => 'herpes',
  170. 'hijinks' => 'hijinks',
  171. 'Hottentotese' => 'Hottentotese',
  172. 'information' => 'information',
  173. 'innings' => 'innings',
  174. 'jackanapes' => 'jackanapes',
  175. 'Kiplingese' => 'Kiplingese',
  176. 'Kongoese' => 'Kongoese',
  177. 'Lucchese' => 'Lucchese',
  178. 'mackerel' => 'mackerel',
  179. 'Maltese' => 'Maltese',
  180. 'mews' => 'mews',
  181. 'moose' => 'moose',
  182. 'mumps' => 'mumps',
  183. 'Nankingese' => 'Nankingese',
  184. 'news' => 'news',
  185. 'nexus' => 'nexus',
  186. 'Niasese' => 'Niasese',
  187. 'Pekingese' => 'Pekingese',
  188. 'Piedmontese' => 'Piedmontese',
  189. 'pincers' => 'pincers',
  190. 'Pistoiese' => 'Pistoiese',
  191. 'pliers' => 'pliers',
  192. 'Portuguese' => 'Portuguese',
  193. 'proceedings' => 'proceedings',
  194. 'rabies' => 'rabies',
  195. 'rice' => 'rice',
  196. 'rhinoceros' => 'rhinoceros',
  197. 'salmon' => 'salmon',
  198. 'Sarawakese' => 'Sarawakese',
  199. 'scissors' => 'scissors',
  200. 'series' => 'series',
  201. 'Shavese' => 'Shavese',
  202. 'shears' => 'shears',
  203. 'siemens' => 'siemens',
  204. 'species' => 'species',
  205. 'swine' => 'swine',
  206. 'testes' => 'testes',
  207. 'trousers' => 'trousers',
  208. 'trout' => 'trout',
  209. 'tuna' => 'tuna',
  210. 'Vermontese' => 'Vermontese',
  211. 'Wenchowese' => 'Wenchowese',
  212. 'whiting' => 'whiting',
  213. 'wildebeest' => 'wildebeest',
  214. 'Yengeese' => 'Yengeese',
  215. ];
  216. /**
  217. * @var array fallback map for transliteration used by [[slug()]] when intl isn't available.
  218. */
  219. public static $transliteration = [
  220. 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'AE', 'Ç' => 'C',
  221. 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I',
  222. 'Ð' => 'D', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ő' => 'O',
  223. 'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ű' => 'U', 'Ý' => 'Y', 'Þ' => 'TH',
  224. 'ß' => 'ss',
  225. 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'ae', 'ç' => 'c',
  226. 'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i',
  227. 'ð' => 'd', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ő' => 'o',
  228. 'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u', 'ű' => 'u', 'ý' => 'y', 'þ' => 'th',
  229. 'ÿ' => 'y',
  230. ];
  231. /**
  232. * @var mixed Either a [[Transliterator]] or a string from which a [[Transliterator]]
  233. * can be built for transliteration used by [[slug()]] when intl is available.
  234. * @see http://php.net/manual/en/transliterator.transliterate.php
  235. */
  236. public static $transliterator = 'Any-Latin; NFKD';
  237. /**
  238. * Converts a word to its plural form.
  239. * Note that this is for English only!
  240. * For example, 'apple' will become 'apples', and 'child' will become 'children'.
  241. * @param string $word the word to be pluralized
  242. * @return string the pluralized word
  243. */
  244. public static function pluralize($word)
  245. {
  246. if (isset(static::$specials[$word])) {
  247. return static::$specials[$word];
  248. }
  249. foreach (static::$plurals as $rule => $replacement) {
  250. if (preg_match($rule, $word)) {
  251. return preg_replace($rule, $replacement, $word);
  252. }
  253. }
  254. return $word;
  255. }
  256. /**
  257. * Returns the singular of the $word
  258. * @param string $word the english word to singularize
  259. * @return string Singular noun.
  260. */
  261. public static function singularize($word)
  262. {
  263. $result = array_search($word, static::$specials, true);
  264. if ($result !== false) {
  265. return $result;
  266. }
  267. foreach (static::$singulars as $rule => $replacement) {
  268. if (preg_match($rule, $word)) {
  269. return preg_replace($rule, $replacement, $word);
  270. }
  271. }
  272. return $word;
  273. }
  274. /**
  275. * Converts an underscored or CamelCase word into a English
  276. * sentence.
  277. * @param string $words
  278. * @param boolean $ucAll whether to set all words to uppercase
  279. * @return string
  280. */
  281. public static function titleize($words, $ucAll = false)
  282. {
  283. $words = static::humanize(static::underscore($words), $ucAll);
  284. return $ucAll ? ucwords($words) : ucfirst($words);
  285. }
  286. /**
  287. * Returns given word as CamelCased
  288. * Converts a word like "send_email" to "SendEmail". It
  289. * will remove non alphanumeric character from the word, so
  290. * "who's online" will be converted to "WhoSOnline"
  291. * @see variablize()
  292. * @param string $word the word to CamelCase
  293. * @return string
  294. */
  295. public static function camelize($word)
  296. {
  297. return str_replace(' ', '', ucwords(preg_replace('/[^A-Za-z0-9]+/', ' ', $word)));
  298. }
  299. /**
  300. * Converts a CamelCase name into space-separated words.
  301. * For example, 'PostTag' will be converted to 'Post Tag'.
  302. * @param string $name the string to be converted
  303. * @param boolean $ucwords whether to capitalize the first letter in each word
  304. * @return string the resulting words
  305. */
  306. public static function camel2words($name, $ucwords = true)
  307. {
  308. $label = trim(strtolower(str_replace([
  309. '-',
  310. '_',
  311. '.'
  312. ], ' ', preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name))));
  313. return $ucwords ? ucwords($label) : $label;
  314. }
  315. /**
  316. * Converts a CamelCase name into an ID in lowercase.
  317. * Words in the ID may be concatenated using the specified character (defaults to '-').
  318. * For example, 'PostTag' will be converted to 'post-tag'.
  319. * @param string $name the string to be converted
  320. * @param string $separator the character used to concatenate the words in the ID
  321. * @param boolean|string $strict whether to insert a separator between two consecutive uppercase chars, defaults to false
  322. * @return string the resulting ID
  323. */
  324. public static function camel2id($name, $separator = '-', $strict = false)
  325. {
  326. $regex = $strict ? '/[A-Z]/' : '/(?<![A-Z])[A-Z]/';
  327. if ($separator === '_') {
  328. return trim(strtolower(preg_replace($regex, '_\0', $name)), '_');
  329. } else {
  330. return trim(strtolower(str_replace('_', $separator, preg_replace($regex, $separator . '\0', $name))), $separator);
  331. }
  332. }
  333. /**
  334. * Converts an ID into a CamelCase name.
  335. * Words in the ID separated by `$separator` (defaults to '-') will be concatenated into a CamelCase name.
  336. * For example, 'post-tag' is converted to 'PostTag'.
  337. * @param string $id the ID to be converted
  338. * @param string $separator the character used to separate the words in the ID
  339. * @return string the resulting CamelCase name
  340. */
  341. public static function id2camel($id, $separator = '-')
  342. {
  343. return str_replace(' ', '', ucwords(implode(' ', explode($separator, $id))));
  344. }
  345. /**
  346. * Converts any "CamelCased" into an "underscored_word".
  347. * @param string $words the word(s) to underscore
  348. * @return string
  349. */
  350. public static function underscore($words)
  351. {
  352. return strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $words));
  353. }
  354. /**
  355. * Returns a human-readable string from $word
  356. * @param string $word the string to humanize
  357. * @param boolean $ucAll whether to set all words to uppercase or not
  358. * @return string
  359. */
  360. public static function humanize($word, $ucAll = false)
  361. {
  362. $word = str_replace('_', ' ', preg_replace('/_id$/', '', $word));
  363. return $ucAll ? ucwords($word) : ucfirst($word);
  364. }
  365. /**
  366. * Same as camelize but first char is in lowercase.
  367. * Converts a word like "send_email" to "sendEmail". It
  368. * will remove non alphanumeric character from the word, so
  369. * "who's online" will be converted to "whoSOnline"
  370. * @param string $word to lowerCamelCase
  371. * @return string
  372. */
  373. public static function variablize($word)
  374. {
  375. $word = static::camelize($word);
  376. return strtolower($word[0]) . substr($word, 1);
  377. }
  378. /**
  379. * Converts a class name to its table name (pluralized)
  380. * naming conventions. For example, converts "Person" to "people"
  381. * @param string $className the class name for getting related table_name
  382. * @return string
  383. */
  384. public static function tableize($className)
  385. {
  386. return static::pluralize(static::underscore($className));
  387. }
  388. /**
  389. * Returns a string with all spaces converted to given replacement,
  390. * non word characters removed and the rest of characters transliterated.
  391. *
  392. * If intl extension isn't available uses fallback that converts latin characters only
  393. * and removes the rest. You may customize characters map via $transliteration property
  394. * of the helper.
  395. *
  396. * @param string $string An arbitrary string to convert
  397. * @param string $replacement The replacement to use for spaces
  398. * @param boolean $lowercase whether to return the string in lowercase or not. Defaults to `true`.
  399. * @return string The converted string.
  400. */
  401. public static function slug($string, $replacement = '-', $lowercase = true)
  402. {
  403. $string = static::transliterate($string);
  404. $string = preg_replace('/[^a-zA-Z0-9=\s—–-]+/u', '', $string);
  405. $string = preg_replace('/[=\s—–-]+/u', $replacement, $string);
  406. $string = trim($string, $replacement);
  407. return $lowercase ? strtolower($string) : $string;
  408. }
  409. /**
  410. * Returns transliterated version of a string.
  411. *
  412. * If intl extension isn't available uses fallback that converts latin characters only
  413. * and removes the rest. You may customize characters map via $transliteration property
  414. * of the helper.
  415. *
  416. * @param string $string input string
  417. * @return string
  418. */
  419. protected static function transliterate($string)
  420. {
  421. if (static::hasIntl()) {
  422. return transliterator_transliterate(static::$transliterator, $string);
  423. } else {
  424. return str_replace(array_keys(static::$transliteration), static::$transliteration, $string);
  425. }
  426. }
  427. /**
  428. * @return boolean if intl extension is loaded
  429. */
  430. protected static function hasIntl()
  431. {
  432. return extension_loaded('intl');
  433. }
  434. /**
  435. * Converts a table name to its class name. For example, converts "people" to "Person"
  436. * @param string $tableName
  437. * @return string
  438. */
  439. public static function classify($tableName)
  440. {
  441. return static::camelize(static::singularize($tableName));
  442. }
  443. /**
  444. * Converts number to its ordinal English form. For example, converts 13 to 13th, 2 to 2nd ...
  445. * @param integer $number the number to get its ordinal value
  446. * @return string
  447. */
  448. public static function ordinalize($number)
  449. {
  450. if (in_array(($number % 100), range(11, 13))) {
  451. return $number . 'th';
  452. }
  453. switch ($number % 10) {
  454. case 1:
  455. return $number . 'st';
  456. case 2:
  457. return $number . 'nd';
  458. case 3:
  459. return $number . 'rd';
  460. default:
  461. return $number . 'th';
  462. }
  463. }
  464. /**
  465. * Converts a list of words into a sentence.
  466. *
  467. * Special treatment is done for the last few words. For example,
  468. *
  469. * ```php
  470. * $words = ['Spain', 'France'];
  471. * echo Inflector::sentence($words);
  472. * // output: Spain and France
  473. *
  474. * $words = ['Spain', 'France', 'Italy'];
  475. * echo Inflector::sentence($words);
  476. * // output: Spain, France and Italy
  477. *
  478. * $words = ['Spain', 'France', 'Italy'];
  479. * echo Inflector::sentence($words, ' & ');
  480. * // output: Spain, France & Italy
  481. * ```
  482. *
  483. * @param array $words the words to be converted into an string
  484. * @param string $twoWordsConnector the string connecting words when there are only two
  485. * @param string $lastWordConnector the string connecting the last two words. If this is null, it will
  486. * take the value of `$twoWordsConnector`.
  487. * @param string $connector the string connecting words other than those connected by
  488. * $lastWordConnector and $twoWordsConnector
  489. * @return string the generated sentence
  490. * @since 2.0.1
  491. */
  492. public static function sentence(array $words, $twoWordsConnector = ' and ', $lastWordConnector = null, $connector = ', ')
  493. {
  494. if ($lastWordConnector === null) {
  495. $lastWordConnector = $twoWordsConnector;
  496. }
  497. switch (count($words)) {
  498. case 0:
  499. return '';
  500. case 1:
  501. return reset($words);
  502. case 2:
  503. return implode($twoWordsConnector, $words);
  504. default:
  505. return implode($connector, array_slice($words, 0, -1)) . $lastWordConnector . end($words);
  506. }
  507. }
  508. }