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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
<?php
/*
* This file is part of the ICanBoogie package.
*
* (c) Olivier Laviale <olivier.laviale@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ICanBoogie;
/**
* The Inflector transforms words from singular to plural, class names to table names, modularized
* class names to ones without, and class names to foreign keys. Inflections can be localized, the
* default english inflections for pluralization, singularization, and uncountable words are
* kept in `lib/inflections/en.php`.
*
* @property-read Inflections $inflections Inflections used by the inflector.
*/
class Inflector
{
/**
* Default inflector locale.
*
* Alias to {@link INFLECTOR_DEFAULT_LOCALE}.
*/
const DEFAULT_LOCALE = INFLECTOR_DEFAULT_LOCALE;
/**
* {@link camelize()} option to downcase the first letter.
*/
const DOWNCASE_FIRST_LETTER = true;
/**
* {@link camelize()} option to keep the first letter as is.
*/
const UPCASE_FIRST_LETTER = false;
/**
* @var Inflector[]
*/
static private $inflectors = array();
/**
* Returns an inflector for the specified locale.
*
* Note: Inflectors are shared for the same locale. If you need to alter an inflector you
* MUST clone it first.
*
* @param string $locale
*
* @return \ICanBoogie\Inflector
*/
static public function get($locale = self::DEFAULT_LOCALE)
{
if (isset(self::$inflectors[$locale]))
{
return self::$inflectors[$locale];
}
return self::$inflectors[$locale] = new static(Inflections::get($locale));
}
/**
* Inflections used by the inflector.
*
* @var Inflections
*/
protected $inflections;
/**
* Initializes the {@link $inflections} property.
*
* @param Inflections $inflections
*/
protected function __construct(Inflections $inflections = null)
{
$this->inflections = $inflections ?: new Inflections;
}
/**
* Returns the {@link $inflections} property.
*
* @param string $property
*
* @throws PropertyNotDefined in attempt to read an inaccessible property. If the {@link PropertyNotDefined}
* class is not available a {@link \InvalidArgumentException} is thrown instead.
*/
public function __get($property)
{
if ($property === 'inflections')
{
return $this->$property;
}
if (class_exists('ICanBoogie\PropertyNotDefined'))
{
throw new PropertyNotDefined(array($property, $this));
}
else
{
throw new \InvalidArgumentException("Property not defined: $property");
}
}
/**
* Clone inflections.
*/
public function __clone()
{
$this->inflections = clone $this->inflections;
}
/**
* Applies inflection rules for {@link singularize} and {@link pluralize}.
*
* <pre>
* $this->apply_inflections('post', $this->plurals); // "posts"
* $this->apply_inflections('posts', $this->singulars); // "post"
* </pre>
*
* @param string $word
* @param array $rules
*
* @return string
*/
private function apply_inflections($word, array $rules)
{
$rc = (string) $word;
if (!$rc)
{
return $rc;
}
if (preg_match('/\b[[:word:]]+\Z/u', downcase($rc), $matches))
{
if (isset($this->inflections->uncountables[$matches[0]]))
{
return $rc;
}
}
foreach ($rules as $rule => $replacement)
{
$rc = preg_replace($rule, $replacement, $rc, -1, $count);
if ($count) break;
}
return $rc;
}
/**
* Returns the plural form of the word in the string.
*
* <pre>
* $this->pluralize('post'); // "posts"
* $this->pluralize('children'); // "child"
* $this->pluralize('sheep'); // "sheep"
* $this->pluralize('words'); // "words"
* $this->pluralize('CamelChild'); // "CamelChild"
* </pre>
*
* @param string $word
*
* @return string
*/
public function pluralize($word)
{
return $this->apply_inflections($word, $this->inflections->plurals);
}
/**
* The reverse of {@link pluralize}, returns the singular form of a word in a string.
*
* <pre>
* $this->singularize('posts'); // "post"
* $this->singularize('childred'); // "child"
* $this->singularize('sheep'); // "sheep"
* $this->singularize('word'); // "word"
* $this->singularize('CamelChildren'); // "CamelChild"
* </pre>
*
* @param string $word
*
* @return string
*/
public function singularize($word)
{
return $this->apply_inflections($word, $this->inflections->singulars);
}
/**
* By default, {@link camelize} converts strings to UpperCamelCase.
*
* {@link camelize} will also convert "/" to "\" which is useful for converting paths to
* namespaces.
*
* <pre>
* $this->camelize('active_model'); // 'ActiveModel'
* $this->camelize('active_model', true); // 'activeModel'
* $this->camelize('active_model/errors'); // 'ActiveModel\Errors'
* $this->camelize('active_model/errors', true); // 'activeModel\Errors'
* </pre>
*
* As a rule of thumb you can think of {@link camelize} as the inverse of {@link underscore},
* though there are cases where that does not hold:
*
* <pre>
* $this->camelize($this->underscore('SSLError')); // "SslError"
* </pre>
*
* @param string $term
* @param bool $downcase_first_letter One of {@link UPCASE_FIRST_LETTER},
* {@link DOWNCASE_FIRST_LETTER}.
*
* @return string
*/
public function camelize($term, $downcase_first_letter = self::UPCASE_FIRST_LETTER)
{
$string = (string) $term;
$acronyms = $this->inflections->acronyms;
if ($downcase_first_letter)
{
$string = preg_replace_callback('/^(?:' . trim($this->inflections->acronym_regex, '/') . '(?=\b|[[:upper:]_])|\w)/u', function($matches) {
return downcase($matches[0]);
}, $string, 1);
}
else
{
$string = preg_replace_callback('/^[[:lower:]\d]*/u', function($matches) use($acronyms) {
$m = $matches[0];
return !empty($acronyms[$m]) ? $acronyms[$m] : capitalize($m, true);
}, $string, 1);
}
$string = preg_replace_callback('/(?:_|-|(\/))([[:alnum:]]*)/u', function($matches) use($acronyms) {
list(, $m1, $m2) = $matches;
return $m1 . (isset($acronyms[$m2]) ? $acronyms[$m2] : capitalize($m2, true));
}, $string);
$string = str_replace('/', '\\', $string);
return $string;
}
/**
* Makes an underscored, lowercase form from the expression in the string.
*
* Changes "\" to "/" to convert namespaces to paths.
*
* <pre>
* $this->underscore('ActiveModel'); // 'active_model'
* $this->underscore('ActiveModel\Errors'); // 'active_model/errors'
* </pre>
*
* As a rule of thumb you can think of {@link underscore} as the inverse of {@link camelize()},
* though there are cases where that does not hold:
*
* <pre>
* $this->camelize($this->underscore('SSLError')); // "SslError"
* </pre>
*
* @param string $camel_cased_word
*
* @return string
*/
public function underscore($camel_cased_word)
{
$word = (string) $camel_cased_word;
$word = str_replace('\\', '/', $word);
$word = preg_replace_callback('/(?:([[:alpha:]\d])|^)(' . trim($this->inflections->acronym_regex, '/') . ')(?=\b|[^[:lower:]])/u', function($matches) {
list(, $m1, $m2) = $matches;
return $m1 . ($m1 ? '_' : '') . downcase($m2);
}, $word);
$word = preg_replace('/([[:upper:]\d]+)([[:upper:]][[:lower:]])/u', '\1_\2', $word);
$word = preg_replace('/([[:lower:]\d])([[:upper:]])/u','\1_\2', $word);
$word = strtr($word, "-", "_");
$word = downcase($word);
return $word;
}
/**
* Capitalizes the first word and turns underscores into spaces and strips a trailing "_id",
* if any. Like {@link titleize()}, this is meant for creating pretty output.
*
* <pre>
* $this->humanize('employee_salary'); // "Employee salary"
* $this->humanize('author_id'); // "Author"
* </pre>
*
* @param string $lower_case_and_underscored_word
*
* @return string
*/
public function humanize($lower_case_and_underscored_word)
{
$result = (string) $lower_case_and_underscored_word;
foreach ($this->inflections->humans as $rule => $replacement)
{
$result = preg_replace($rule, $replacement, $result, 1, $count);
if ($count) break;
}
$acronyms = $this->inflections->acronyms;
$result = preg_replace('/_id$/', "", $result);
$result = strtr($result, '_', ' ');
$result = preg_replace_callback('/([[:alnum:]]+)/u', function($matches) use($acronyms) {
list($m) = $matches;
return !empty($acronyms[$m]) ? $acronyms[$m] : downcase($m);
}, $result);
$result = preg_replace_callback('/^[[:lower:]]/u', function($matches) {
return upcase($matches[0]);
}, $result);
return $result;
}
/**
* Capitalizes all the words and replaces some characters in the string to create a nicer
* looking title. {@link titleize()} is meant for creating pretty output. It is not used in
* the Rails internals.
*
* <pre>
* $this->titleize('man from the boondocks'); // "Man From The Boondocks"
* $this->titleize('x-men: the last stand'); // "X Men: The Last Stand"
* $this->titleize('TheManWithoutAPast'); // "The Man Without A Past"
* $this->titleize('raiders_of_the_lost_ark'); // "Raiders Of The Lost Ark"
* </pre>
*
* @param string $str
*
* @return string
*/
public function titleize($str)
{
$str = $this->underscore($str);
$str = $this->humanize($str);
$str = preg_replace_callback('/\b(?<![\'’`])[[:lower:]]/u', function($matches) {
return upcase($matches[0]);
}, $str);
return $str;
}
/**
* Replaces underscores with dashes in the string.
*
* <pre>
* $this->dasherize('puni_puni'); // "puni-puni"
* </pre>
*
* @param string $underscored_word
*
* @return string
*/
public function dasherize($underscored_word)
{
return strtr($underscored_word, '_', '-');
}
/**
* Makes an hyphenated, lowercase form from the expression in the string.
*
* This is a combination of {@link underscore} and {@link dasherize}.
*
* @param string $str
*
* @return string
*/
public function hyphenate($str)
{
return $this->dasherize($this->underscore($str));
}
/**
* Returns the suffix that should be added to a number to denote the position in an ordered
* sequence such as 1st, 2nd, 3rd, 4th.
*
* <pre>
* $this->ordinal(1); // "st"
* $this->ordinal(2); // "nd"
* $this->ordinal(1002); // "nd"
* $this->ordinal(1003); // "rd"
* $this->ordinal(-11); // "th"
* $this->ordinal(-1021); // "st"
* </pre>
*
* @param int $number
*
* @return string
*/
public function ordinal($number)
{
$abs_number = abs($number);
if (($abs_number % 100) > 10 && ($abs_number % 100) < 14)
{
return 'th';
}
switch ($abs_number % 10)
{
case 1; return "st";
case 2; return "nd";
case 3; return "rd";
default: return "th";
}
}
/**
* Turns a number into an ordinal string used to denote the position in an ordered sequence
* such as 1st, 2nd, 3rd, 4th.
*
* <pre>
* $this->ordinalize(1); // "1st"
* $this->ordinalize(2); // "2nd"
* $this->ordinalize(1002); // "1002nd"
* $this->ordinalize(1003); // "1003rd"
* $this->ordinalize(-11); // "-11th"
* $this->ordinalize(-1021); // "-1021st"
* </pre>
*
* @param int $number
*
* @return string
*/
public function ordinalize($number)
{
return $number . $this->ordinal($number);
}
}