MessageSelector.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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\Translation;
  11. /**
  12. * MessageSelector.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. *
  16. * @api
  17. */
  18. class MessageSelector
  19. {
  20. /**
  21. * Given a message with different plural translations separated by a
  22. * pipe (|), this method returns the correct portion of the message based
  23. * on the given number, locale and the pluralization rules in the message
  24. * itself.
  25. *
  26. * The message supports two different types of pluralization rules:
  27. *
  28. * interval: {0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples
  29. * indexed: There is one apple|There is %count% apples
  30. *
  31. * The indexed solution can also contain labels (e.g. one: There is one apple).
  32. * This is purely for making the translations more clear - it does not
  33. * affect the functionality.
  34. *
  35. * The two methods can also be mixed:
  36. * {0} There is no apples|one: There is one apple|more: There is %count% apples
  37. *
  38. * @throws InvalidArgumentException
  39. * @param string $message The message being translated
  40. * @param integer $number The number of items represented for the message
  41. * @param string $locale The locale to use for choosing
  42. * @return string
  43. *
  44. * @api
  45. */
  46. public function choose($message, $number, $locale)
  47. {
  48. $parts = explode('|', $message);
  49. $explicitRules = array();
  50. $standardRules = array();
  51. foreach ($parts as $part) {
  52. $part = trim($part);
  53. if (preg_match('/^(?P<interval>'.Interval::getIntervalRegexp().')\s+(?P<message>.+?)$/x', $part, $matches)) {
  54. $explicitRules[$matches['interval']] = $matches['message'];
  55. } elseif (preg_match('/^\w+\: +(.+)$/', $part, $matches)) {
  56. $standardRules[] = $matches[1];
  57. } else {
  58. $standardRules[] = $part;
  59. }
  60. }
  61. // try to match an explicit rule, then fallback to the standard ones
  62. foreach ($explicitRules as $interval => $m) {
  63. if (Interval::test($number, $interval)) {
  64. return $m;
  65. }
  66. }
  67. $position = PluralizationRules::get($number, $locale);
  68. if (!isset($standardRules[$position])) {
  69. throw new \InvalidArgumentException('Unable to choose a translation.');
  70. }
  71. return $standardRules[$position];
  72. }
  73. }