Formatter.php 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740
  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\i18n;
  8. use Closure;
  9. use DateInterval;
  10. use DateTime;
  11. use DateTimeInterface;
  12. use DateTimeZone;
  13. use IntlDateFormatter;
  14. use NumberFormatter;
  15. use Yii;
  16. use yii\base\Component;
  17. use yii\base\InvalidArgumentException;
  18. use yii\base\InvalidConfigException;
  19. use yii\helpers\FormatConverter;
  20. use yii\helpers\Html;
  21. use yii\helpers\HtmlPurifier;
  22. /**
  23. * Formatter provides a set of commonly used data formatting methods.
  24. *
  25. * The formatting methods provided by Formatter are all named in the form of `asXyz()`.
  26. * The behavior of some of them may be configured via the properties of Formatter. For example,
  27. * by configuring [[dateFormat]], one may control how [[asDate()]] formats the value into a date string.
  28. *
  29. * Formatter is configured as an application component in [[\yii\base\Application]] by default.
  30. * You can access that instance via `Yii::$app->formatter`.
  31. *
  32. * The Formatter class is designed to format values according to a [[locale]]. For this feature to work
  33. * the [PHP intl extension](http://php.net/manual/en/book.intl.php) has to be installed.
  34. * Most of the methods however work also if the PHP intl extension is not installed by providing
  35. * a fallback implementation. Without intl month and day names are in English only.
  36. * Note that even if the intl extension is installed, formatting date and time values for years >=2038 or <=1901
  37. * on 32bit systems will fall back to the PHP implementation because intl uses a 32bit UNIX timestamp internally.
  38. * On a 64bit system the intl formatter is used in all cases if installed.
  39. *
  40. * @author Qiang Xue <qiang.xue@gmail.com>
  41. * @author Enrica Ruedin <e.ruedin@guggach.com>
  42. * @author Carsten Brandt <mail@cebe.cc>
  43. * @since 2.0
  44. */
  45. class Formatter extends Component
  46. {
  47. /**
  48. * @since 2.0.13
  49. */
  50. const UNIT_SYSTEM_METRIC = 'metric';
  51. /**
  52. * @since 2.0.13
  53. */
  54. const UNIT_SYSTEM_IMPERIAL = 'imperial';
  55. /**
  56. * @since 2.0.13
  57. */
  58. const FORMAT_WIDTH_LONG = 'long';
  59. /**
  60. * @since 2.0.13
  61. */
  62. const FORMAT_WIDTH_SHORT = 'short';
  63. /**
  64. * @since 2.0.13
  65. */
  66. const UNIT_LENGTH = 'length';
  67. /**
  68. * @since 2.0.13
  69. */
  70. const UNIT_WEIGHT = 'mass';
  71. /**
  72. * @var string the text to be displayed when formatting a `null` value.
  73. * Defaults to `'<span class="not-set">(not set)</span>'`, where `(not set)`
  74. * will be translated according to [[locale]].
  75. */
  76. public $nullDisplay;
  77. /**
  78. * @var array the text to be displayed when formatting a boolean value. The first element corresponds
  79. * to the text displayed for `false`, the second element for `true`.
  80. * Defaults to `['No', 'Yes']`, where `Yes` and `No`
  81. * will be translated according to [[locale]].
  82. */
  83. public $booleanFormat;
  84. /**
  85. * @var string the locale ID that is used to localize the date and number formatting.
  86. * For number and date formatting this is only effective when the
  87. * [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed.
  88. * If not set, [[\yii\base\Application::language]] will be used.
  89. */
  90. public $locale;
  91. /**
  92. * @var string the time zone to use for formatting time and date values.
  93. *
  94. * This can be any value that may be passed to [date_default_timezone_set()](http://www.php.net/manual/en/function.date-default-timezone-set.php)
  95. * e.g. `UTC`, `Europe/Berlin` or `America/Chicago`.
  96. * Refer to the [php manual](http://www.php.net/manual/en/timezones.php) for available time zones.
  97. * If this property is not set, [[\yii\base\Application::timeZone]] will be used.
  98. *
  99. * Note that the default time zone for input data is assumed to be UTC by default if no time zone is included in the input date value.
  100. * If you store your data in a different time zone in the database, you have to adjust [[defaultTimeZone]] accordingly.
  101. */
  102. public $timeZone;
  103. /**
  104. * @var string the time zone that is assumed for input values if they do not include a time zone explicitly.
  105. *
  106. * The value must be a valid time zone identifier, e.g. `UTC`, `Europe/Berlin` or `America/Chicago`.
  107. * Please refer to the [php manual](http://www.php.net/manual/en/timezones.php) for available time zones.
  108. *
  109. * It defaults to `UTC` so you only have to adjust this value if you store datetime values in another time zone in your database.
  110. *
  111. * Note that a UNIX timestamp is always in UTC by its definition. That means that specifying a default time zone different from
  112. * UTC has no effect on date values given as UNIX timestamp.
  113. *
  114. * @since 2.0.1
  115. */
  116. public $defaultTimeZone = 'UTC';
  117. /**
  118. * @var string the default format string to be used to format a [[asDate()|date]].
  119. * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
  120. *
  121. * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax).
  122. * Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the
  123. * PHP [date()](http://php.net/manual/en/function.date.php)-function.
  124. *
  125. * For example:
  126. *
  127. * ```php
  128. * 'MM/dd/yyyy' // date in ICU format
  129. * 'php:m/d/Y' // the same date in PHP format
  130. * ```
  131. */
  132. public $dateFormat = 'medium';
  133. /**
  134. * @var string the default format string to be used to format a [[asTime()|time]].
  135. * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
  136. *
  137. * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax).
  138. * Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the
  139. * PHP [date()](http://php.net/manual/en/function.date.php)-function.
  140. *
  141. * For example:
  142. *
  143. * ```php
  144. * 'HH:mm:ss' // time in ICU format
  145. * 'php:H:i:s' // the same time in PHP format
  146. * ```
  147. */
  148. public $timeFormat = 'medium';
  149. /**
  150. * @var string the default format string to be used to format a [[asDatetime()|date and time]].
  151. * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
  152. *
  153. * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax).
  154. *
  155. * Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the
  156. * PHP [date()](http://php.net/manual/en/function.date.php)-function.
  157. *
  158. * For example:
  159. *
  160. * ```php
  161. * 'MM/dd/yyyy HH:mm:ss' // date and time in ICU format
  162. * 'php:m/d/Y H:i:s' // the same date and time in PHP format
  163. * ```
  164. */
  165. public $datetimeFormat = 'medium';
  166. /**
  167. * @var \IntlCalendar|int|null the calendar to be used for date formatting. The value of this property will be directly
  168. * passed to the [constructor of the `IntlDateFormatter` class](http://php.net/manual/en/intldateformatter.create.php).
  169. *
  170. * Defaults to `null`, which means the Gregorian calendar will be used. You may also explicitly pass the constant
  171. * `\IntlDateFormatter::GREGORIAN` for Gregorian calendar.
  172. *
  173. * To use an alternative calendar like for example the [Jalali calendar](https://en.wikipedia.org/wiki/Jalali_calendar),
  174. * set this property to `\IntlDateFormatter::TRADITIONAL`.
  175. * The calendar must then be specified in the [[locale]], for example for the persian calendar the configuration for the formatter would be:
  176. *
  177. * ```php
  178. * 'formatter' => [
  179. * 'locale' => 'fa_IR@calendar=persian',
  180. * 'calendar' => \IntlDateFormatter::TRADITIONAL,
  181. * ],
  182. * ```
  183. *
  184. * Available calendar names can be found in the [ICU manual](http://userguide.icu-project.org/datetime/calendar).
  185. *
  186. * Since PHP 5.5 you may also use an instance of the [[\IntlCalendar]] class.
  187. * Check the [PHP manual](http://php.net/manual/en/intldateformatter.create.php) for more details.
  188. *
  189. * If the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available, setting this property will have no effect.
  190. *
  191. * @see http://php.net/manual/en/intldateformatter.create.php
  192. * @see http://php.net/manual/en/class.intldateformatter.php#intl.intldateformatter-constants.calendartypes
  193. * @see http://php.net/manual/en/class.intlcalendar.php
  194. * @since 2.0.7
  195. */
  196. public $calendar;
  197. /**
  198. * @var string the character displayed as the decimal point when formatting a number.
  199. * If not set, the decimal separator corresponding to [[locale]] will be used.
  200. * If [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available, the default value is '.'.
  201. */
  202. public $decimalSeparator;
  203. /**
  204. * @var string the character displayed as the thousands separator (also called grouping separator) character when formatting a number.
  205. * If not set, the thousand separator corresponding to [[locale]] will be used.
  206. * If [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available, the default value is ','.
  207. */
  208. public $thousandSeparator;
  209. /**
  210. * @var array a list of name value pairs that are passed to the
  211. * intl [NumberFormatter::setAttribute()](http://php.net/manual/en/numberformatter.setattribute.php) method of all
  212. * the number formatter objects created by [[createNumberFormatter()]].
  213. * This property takes only effect if the [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed.
  214. *
  215. * Please refer to the [PHP manual](http://php.net/manual/en/class.numberformatter.php#intl.numberformatter-constants.unumberformatattribute)
  216. * for the possible options.
  217. *
  218. * For example to adjust the maximum and minimum value of fraction digits you can configure this property like the following:
  219. *
  220. * ```php
  221. * [
  222. * NumberFormatter::MIN_FRACTION_DIGITS => 0,
  223. * NumberFormatter::MAX_FRACTION_DIGITS => 2,
  224. * ]
  225. * ```
  226. */
  227. public $numberFormatterOptions = [];
  228. /**
  229. * @var array a list of name value pairs that are passed to the
  230. * intl [NumberFormatter::setTextAttribute()](http://php.net/manual/en/numberformatter.settextattribute.php) method of all
  231. * the number formatter objects created by [[createNumberFormatter()]].
  232. * This property takes only effect if the [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed.
  233. *
  234. * Please refer to the [PHP manual](http://php.net/manual/en/class.numberformatter.php#intl.numberformatter-constants.unumberformattextattribute)
  235. * for the possible options.
  236. *
  237. * For example to change the minus sign for negative numbers you can configure this property like the following:
  238. *
  239. * ```php
  240. * [
  241. * NumberFormatter::NEGATIVE_PREFIX => 'MINUS',
  242. * ]
  243. * ```
  244. */
  245. public $numberFormatterTextOptions = [];
  246. /**
  247. * @var array a list of name value pairs that are passed to the
  248. * intl [NumberFormatter::setSymbol()](http://php.net/manual/en/numberformatter.setsymbol.php) method of all
  249. * the number formatter objects created by [[createNumberFormatter()]].
  250. * This property takes only effect if the [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed.
  251. *
  252. * Please refer to the [PHP manual](http://php.net/manual/en/class.numberformatter.php#intl.numberformatter-constants.unumberformatsymbol)
  253. * for the possible options.
  254. *
  255. * For example to choose a custom currency symbol, e.g. [U+20BD](http://unicode-table.com/en/20BD/) instead of `руб.` for Russian Ruble:
  256. *
  257. * ```php
  258. * [
  259. * NumberFormatter::CURRENCY_SYMBOL => '₽',
  260. * ]
  261. * ```
  262. *
  263. * @since 2.0.4
  264. */
  265. public $numberFormatterSymbols = [];
  266. /**
  267. * @var string the 3-letter ISO 4217 currency code indicating the default currency to use for [[asCurrency]].
  268. * If not set, the currency code corresponding to [[locale]] will be used.
  269. * Note that in this case the [[locale]] has to be specified with a country code, e.g. `en-US` otherwise it
  270. * is not possible to determine the default currency.
  271. */
  272. public $currencyCode;
  273. /**
  274. * @var int the base at which a kilobyte is calculated (1000 or 1024 bytes per kilobyte), used by [[asSize]] and [[asShortSize]].
  275. * Defaults to 1024.
  276. */
  277. public $sizeFormatBase = 1024;
  278. /**
  279. * @var string default system of measure units. Defaults to [[UNIT_SYSTEM_METRIC]].
  280. * Possible values:
  281. * - [[UNIT_SYSTEM_METRIC]]
  282. * - [[UNIT_SYSTEM_IMPERIAL]]
  283. *
  284. * @see asLength
  285. * @see asWeight
  286. * @since 2.0.13
  287. */
  288. public $systemOfUnits = self::UNIT_SYSTEM_METRIC;
  289. /**
  290. * @var array configuration of weight and length measurement units.
  291. * This array contains the most usable measurement units, but you can change it
  292. * in case you have some special requirements.
  293. *
  294. * For example, you can add smaller measure unit:
  295. *
  296. * ```php
  297. * $this->measureUnits[self::UNIT_LENGTH][self::UNIT_SYSTEM_METRIC] = [
  298. * 'nanometer' => 0.000001
  299. * ]
  300. * ```
  301. * @see asLength
  302. * @see asWeight
  303. * @since 2.0.13
  304. */
  305. public $measureUnits = [
  306. self::UNIT_LENGTH => [
  307. self::UNIT_SYSTEM_IMPERIAL => [
  308. 'inch' => 1,
  309. 'foot' => 12,
  310. 'yard' => 36,
  311. 'chain' => 792,
  312. 'furlong' => 7920,
  313. 'mile' => 63360,
  314. ],
  315. self::UNIT_SYSTEM_METRIC => [
  316. 'millimeter' => 1,
  317. 'centimeter' => 10,
  318. 'meter' => 1000,
  319. 'kilometer' => 1000000,
  320. ],
  321. ],
  322. self::UNIT_WEIGHT => [
  323. self::UNIT_SYSTEM_IMPERIAL => [
  324. 'grain' => 1,
  325. 'drachm' => 27.34375,
  326. 'ounce' => 437.5,
  327. 'pound' => 7000,
  328. 'stone' => 98000,
  329. 'quarter' => 196000,
  330. 'hundredweight' => 784000,
  331. 'ton' => 15680000,
  332. ],
  333. self::UNIT_SYSTEM_METRIC => [
  334. 'gram' => 1,
  335. 'kilogram' => 1000,
  336. 'ton' => 1000000,
  337. ],
  338. ],
  339. ];
  340. /**
  341. * @var array The base units that are used as multipliers for smallest possible unit from [[measureUnits]].
  342. * @since 2.0.13
  343. */
  344. public $baseUnits = [
  345. self::UNIT_LENGTH => [
  346. self::UNIT_SYSTEM_IMPERIAL => 12, // 1 feet = 12 inches
  347. self::UNIT_SYSTEM_METRIC => 1000, // 1 meter = 1000 millimeters
  348. ],
  349. self::UNIT_WEIGHT => [
  350. self::UNIT_SYSTEM_IMPERIAL => 7000, // 1 pound = 7000 grains
  351. self::UNIT_SYSTEM_METRIC => 1000, // 1 kilogram = 1000 grams
  352. ],
  353. ];
  354. /**
  355. * @var bool whether the [PHP intl extension](http://php.net/manual/en/book.intl.php) is loaded.
  356. */
  357. private $_intlLoaded = false;
  358. /**
  359. * @var \ResourceBundle cached ResourceBundle object used to read unit translations
  360. */
  361. private $_resourceBundle;
  362. /**
  363. * @var array cached unit translation patterns
  364. */
  365. private $_unitMessages = [];
  366. /**
  367. * {@inheritdoc}
  368. */
  369. public function init()
  370. {
  371. if ($this->timeZone === null) {
  372. $this->timeZone = Yii::$app->timeZone;
  373. }
  374. if ($this->locale === null) {
  375. $this->locale = Yii::$app->language;
  376. }
  377. if ($this->booleanFormat === null) {
  378. $this->booleanFormat = [Yii::t('yii', 'No', [], $this->locale), Yii::t('yii', 'Yes', [], $this->locale)];
  379. }
  380. if ($this->nullDisplay === null) {
  381. $this->nullDisplay = '<span class="not-set">' . Yii::t('yii', '(not set)', [], $this->locale) . '</span>';
  382. }
  383. $this->_intlLoaded = extension_loaded('intl');
  384. if (!$this->_intlLoaded) {
  385. if ($this->decimalSeparator === null) {
  386. $this->decimalSeparator = '.';
  387. }
  388. if ($this->thousandSeparator === null) {
  389. $this->thousandSeparator = ',';
  390. }
  391. }
  392. }
  393. /**
  394. * Formats the value based on the given format type.
  395. * This method will call one of the "as" methods available in this class to do the formatting.
  396. * For type "xyz", the method "asXyz" will be used. For example, if the format is "html",
  397. * then [[asHtml()]] will be used. Format names are case insensitive.
  398. * @param mixed $value the value to be formatted.
  399. * @param string|array|Closure $format the format of the value, e.g., "html", "text" or an anonymous function
  400. * returning the formatted value.
  401. *
  402. * To specify additional parameters of the formatting method, you may use an array.
  403. * The first element of the array specifies the format name, while the rest of the elements will be used as the
  404. * parameters to the formatting method. For example, a format of `['date', 'Y-m-d']` will cause the invocation
  405. * of `asDate($value, 'Y-m-d')`.
  406. *
  407. * The anonymous function signature should be: `function($value, $formatter)`,
  408. * where `$value` is the value that should be formatted and `$formatter` is an instance of the Formatter class,
  409. * which can be used to call other formatting functions.
  410. * The possibility to use an anonymous function is available since version 2.0.13.
  411. * @return string the formatting result.
  412. * @throws InvalidArgumentException if the format type is not supported by this class.
  413. */
  414. public function format($value, $format)
  415. {
  416. if ($format instanceof Closure) {
  417. return call_user_func($format, $value, $this);
  418. } elseif (is_array($format)) {
  419. if (!isset($format[0])) {
  420. throw new InvalidArgumentException('The $format array must contain at least one element.');
  421. }
  422. $f = $format[0];
  423. $format[0] = $value;
  424. $params = $format;
  425. $format = $f;
  426. } else {
  427. $params = [$value];
  428. }
  429. $method = 'as' . $format;
  430. if ($this->hasMethod($method)) {
  431. return call_user_func_array([$this, $method], $params);
  432. }
  433. throw new InvalidArgumentException("Unknown format type: $format");
  434. }
  435. // simple formats
  436. /**
  437. * Formats the value as is without any formatting.
  438. * This method simply returns back the parameter without any format.
  439. * The only exception is a `null` value which will be formatted using [[nullDisplay]].
  440. * @param mixed $value the value to be formatted.
  441. * @return string the formatted result.
  442. */
  443. public function asRaw($value)
  444. {
  445. if ($value === null) {
  446. return $this->nullDisplay;
  447. }
  448. return $value;
  449. }
  450. /**
  451. * Formats the value as an HTML-encoded plain text.
  452. * @param string $value the value to be formatted.
  453. * @return string the formatted result.
  454. */
  455. public function asText($value)
  456. {
  457. if ($value === null) {
  458. return $this->nullDisplay;
  459. }
  460. return Html::encode($value);
  461. }
  462. /**
  463. * Formats the value as an HTML-encoded plain text with newlines converted into breaks.
  464. * @param string $value the value to be formatted.
  465. * @return string the formatted result.
  466. */
  467. public function asNtext($value)
  468. {
  469. if ($value === null) {
  470. return $this->nullDisplay;
  471. }
  472. return nl2br(Html::encode($value));
  473. }
  474. /**
  475. * Formats the value as HTML-encoded text paragraphs.
  476. * Each text paragraph is enclosed within a `<p>` tag.
  477. * One or multiple consecutive empty lines divide two paragraphs.
  478. * @param string $value the value to be formatted.
  479. * @return string the formatted result.
  480. */
  481. public function asParagraphs($value)
  482. {
  483. if ($value === null) {
  484. return $this->nullDisplay;
  485. }
  486. return str_replace('<p></p>', '', '<p>' . preg_replace('/\R{2,}/u', "</p>\n<p>", Html::encode($value)) . '</p>');
  487. }
  488. /**
  489. * Formats the value as HTML text.
  490. * The value will be purified using [[HtmlPurifier]] to avoid XSS attacks.
  491. * Use [[asRaw()]] if you do not want any purification of the value.
  492. * @param string $value the value to be formatted.
  493. * @param array|null $config the configuration for the HTMLPurifier class.
  494. * @return string the formatted result.
  495. */
  496. public function asHtml($value, $config = null)
  497. {
  498. if ($value === null) {
  499. return $this->nullDisplay;
  500. }
  501. return HtmlPurifier::process($value, $config);
  502. }
  503. /**
  504. * Formats the value as a mailto link.
  505. * @param string $value the value to be formatted.
  506. * @param array $options the tag options in terms of name-value pairs. See [[Html::mailto()]].
  507. * @return string the formatted result.
  508. */
  509. public function asEmail($value, $options = [])
  510. {
  511. if ($value === null) {
  512. return $this->nullDisplay;
  513. }
  514. return Html::mailto(Html::encode($value), $value, $options);
  515. }
  516. /**
  517. * Formats the value as an image tag.
  518. * @param mixed $value the value to be formatted.
  519. * @param array $options the tag options in terms of name-value pairs. See [[Html::img()]].
  520. * @return string the formatted result.
  521. */
  522. public function asImage($value, $options = [])
  523. {
  524. if ($value === null) {
  525. return $this->nullDisplay;
  526. }
  527. return Html::img($value, $options);
  528. }
  529. /**
  530. * Formats the value as a hyperlink.
  531. * @param mixed $value the value to be formatted.
  532. * @param array $options the tag options in terms of name-value pairs. See [[Html::a()]].
  533. * @return string the formatted result.
  534. */
  535. public function asUrl($value, $options = [])
  536. {
  537. if ($value === null) {
  538. return $this->nullDisplay;
  539. }
  540. $url = $value;
  541. if (strpos($url, '://') === false) {
  542. $url = 'http://' . $url;
  543. }
  544. return Html::a(Html::encode($value), $url, $options);
  545. }
  546. /**
  547. * Formats the value as a boolean.
  548. * @param mixed $value the value to be formatted.
  549. * @return string the formatted result.
  550. * @see booleanFormat
  551. */
  552. public function asBoolean($value)
  553. {
  554. if ($value === null) {
  555. return $this->nullDisplay;
  556. }
  557. return $value ? $this->booleanFormat[1] : $this->booleanFormat[0];
  558. }
  559. // date and time formats
  560. /**
  561. * Formats the value as a date.
  562. * @param int|string|DateTime $value the value to be formatted. The following
  563. * types of value are supported:
  564. *
  565. * - an integer representing a UNIX timestamp. A UNIX timestamp is always in UTC by its definition.
  566. * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
  567. * The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
  568. * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object. You may set the time zone
  569. * for the DateTime object to specify the source time zone.
  570. *
  571. * The formatter will convert date values according to [[timeZone]] before formatting it.
  572. * If no timezone conversion should be performed, you need to set [[defaultTimeZone]] and [[timeZone]] to the same value.
  573. * Also no conversion will be performed on values that have no time information, e.g. `"2017-06-05"`.
  574. *
  575. * @param string $format the format used to convert the value into a date string.
  576. * If null, [[dateFormat]] will be used.
  577. *
  578. * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
  579. * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
  580. *
  581. * Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the
  582. * PHP [date()](http://php.net/manual/en/function.date.php)-function.
  583. *
  584. * @return string the formatted result.
  585. * @throws InvalidArgumentException if the input value can not be evaluated as a date value.
  586. * @throws InvalidConfigException if the date format is invalid.
  587. * @see dateFormat
  588. */
  589. public function asDate($value, $format = null)
  590. {
  591. if ($format === null) {
  592. $format = $this->dateFormat;
  593. }
  594. return $this->formatDateTimeValue($value, $format, 'date');
  595. }
  596. /**
  597. * Formats the value as a time.
  598. * @param int|string|DateTime $value the value to be formatted. The following
  599. * types of value are supported:
  600. *
  601. * - an integer representing a UNIX timestamp. A UNIX timestamp is always in UTC by its definition.
  602. * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
  603. * The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
  604. * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object. You may set the time zone
  605. * for the DateTime object to specify the source time zone.
  606. *
  607. * The formatter will convert date values according to [[timeZone]] before formatting it.
  608. * If no timezone conversion should be performed, you need to set [[defaultTimeZone]] and [[timeZone]] to the same value.
  609. *
  610. * @param string $format the format used to convert the value into a date string.
  611. * If null, [[timeFormat]] will be used.
  612. *
  613. * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
  614. * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
  615. *
  616. * Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the
  617. * PHP [date()](http://php.net/manual/en/function.date.php)-function.
  618. *
  619. * @return string the formatted result.
  620. * @throws InvalidArgumentException if the input value can not be evaluated as a date value.
  621. * @throws InvalidConfigException if the date format is invalid.
  622. * @see timeFormat
  623. */
  624. public function asTime($value, $format = null)
  625. {
  626. if ($format === null) {
  627. $format = $this->timeFormat;
  628. }
  629. return $this->formatDateTimeValue($value, $format, 'time');
  630. }
  631. /**
  632. * Formats the value as a datetime.
  633. * @param int|string|DateTime $value the value to be formatted. The following
  634. * types of value are supported:
  635. *
  636. * - an integer representing a UNIX timestamp. A UNIX timestamp is always in UTC by its definition.
  637. * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
  638. * The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
  639. * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object. You may set the time zone
  640. * for the DateTime object to specify the source time zone.
  641. *
  642. * The formatter will convert date values according to [[timeZone]] before formatting it.
  643. * If no timezone conversion should be performed, you need to set [[defaultTimeZone]] and [[timeZone]] to the same value.
  644. *
  645. * @param string $format the format used to convert the value into a date string.
  646. * If null, [[datetimeFormat]] will be used.
  647. *
  648. * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
  649. * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
  650. *
  651. * Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the
  652. * PHP [date()](http://php.net/manual/en/function.date.php)-function.
  653. *
  654. * @return string the formatted result.
  655. * @throws InvalidArgumentException if the input value can not be evaluated as a date value.
  656. * @throws InvalidConfigException if the date format is invalid.
  657. * @see datetimeFormat
  658. */
  659. public function asDatetime($value, $format = null)
  660. {
  661. if ($format === null) {
  662. $format = $this->datetimeFormat;
  663. }
  664. return $this->formatDateTimeValue($value, $format, 'datetime');
  665. }
  666. /**
  667. * @var array map of short format names to IntlDateFormatter constant values.
  668. */
  669. private $_dateFormats = [
  670. 'short' => 3, // IntlDateFormatter::SHORT,
  671. 'medium' => 2, // IntlDateFormatter::MEDIUM,
  672. 'long' => 1, // IntlDateFormatter::LONG,
  673. 'full' => 0, // IntlDateFormatter::FULL,
  674. ];
  675. /**
  676. * @param int|string|DateTime $value the value to be formatted. The following
  677. * types of value are supported:
  678. *
  679. * - an integer representing a UNIX timestamp
  680. * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
  681. * The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
  682. * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
  683. *
  684. * @param string $format the format used to convert the value into a date string.
  685. * @param string $type 'date', 'time', or 'datetime'.
  686. * @throws InvalidConfigException if the date format is invalid.
  687. * @return string the formatted result.
  688. */
  689. private function formatDateTimeValue($value, $format, $type)
  690. {
  691. $timeZone = $this->timeZone;
  692. // avoid time zone conversion for date-only and time-only values
  693. if ($type === 'date' || $type === 'time') {
  694. list($timestamp, $hasTimeInfo, $hasDateInfo) = $this->normalizeDatetimeValue($value, true);
  695. if ($type === 'date' && !$hasTimeInfo || $type === 'time' && !$hasDateInfo) {
  696. $timeZone = $this->defaultTimeZone;
  697. }
  698. } else {
  699. $timestamp = $this->normalizeDatetimeValue($value);
  700. }
  701. if ($timestamp === null) {
  702. return $this->nullDisplay;
  703. }
  704. // intl does not work with dates >=2038 or <=1901 on 32bit machines, fall back to PHP
  705. $year = $timestamp->format('Y');
  706. if ($this->_intlLoaded && !(PHP_INT_SIZE === 4 && ($year <= 1901 || $year >= 2038))) {
  707. if (strncmp($format, 'php:', 4) === 0) {
  708. $format = FormatConverter::convertDatePhpToIcu(substr($format, 4));
  709. }
  710. if (isset($this->_dateFormats[$format])) {
  711. if ($type === 'date') {
  712. $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], IntlDateFormatter::NONE, $timeZone, $this->calendar);
  713. } elseif ($type === 'time') {
  714. $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, $this->_dateFormats[$format], $timeZone, $this->calendar);
  715. } else {
  716. $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], $this->_dateFormats[$format], $timeZone, $this->calendar);
  717. }
  718. } else {
  719. $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $timeZone, $this->calendar, $format);
  720. }
  721. if ($formatter === null) {
  722. throw new InvalidConfigException(intl_get_error_message());
  723. }
  724. // make IntlDateFormatter work with DateTimeImmutable
  725. if ($timestamp instanceof \DateTimeImmutable) {
  726. $timestamp = new DateTime($timestamp->format(DateTime::ISO8601), $timestamp->getTimezone());
  727. }
  728. return $formatter->format($timestamp);
  729. }
  730. if (strncmp($format, 'php:', 4) === 0) {
  731. $format = substr($format, 4);
  732. } else {
  733. $format = FormatConverter::convertDateIcuToPhp($format, $type, $this->locale);
  734. }
  735. if ($timeZone != null) {
  736. if ($timestamp instanceof \DateTimeImmutable) {
  737. $timestamp = $timestamp->setTimezone(new DateTimeZone($timeZone));
  738. } else {
  739. $timestamp->setTimezone(new DateTimeZone($timeZone));
  740. }
  741. }
  742. return $timestamp->format($format);
  743. }
  744. /**
  745. * Normalizes the given datetime value as a DateTime object that can be taken by various date/time formatting methods.
  746. *
  747. * @param int|string|DateTime $value the datetime value to be normalized. The following
  748. * types of value are supported:
  749. *
  750. * - an integer representing a UNIX timestamp
  751. * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
  752. * The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
  753. * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
  754. *
  755. * @param bool $checkDateTimeInfo whether to also check if the date/time value has some time and date information attached.
  756. * Defaults to `false`. If `true`, the method will then return an array with the first element being the normalized
  757. * timestamp, the second a boolean indicating whether the timestamp has time information and third a boolean indicating
  758. * whether the timestamp has date information.
  759. * This parameter is available since version 2.0.1.
  760. * @return DateTime|array the normalized datetime value.
  761. * Since version 2.0.1 this may also return an array if `$checkDateTimeInfo` is true.
  762. * The first element of the array is the normalized timestamp and the second is a boolean indicating whether
  763. * the timestamp has time information or it is just a date value.
  764. * Since version 2.0.12 the array has third boolean element indicating whether the timestamp has date information
  765. * or it is just a time value.
  766. * @throws InvalidArgumentException if the input value can not be evaluated as a date value.
  767. */
  768. protected function normalizeDatetimeValue($value, $checkDateTimeInfo = false)
  769. {
  770. // checking for DateTime and DateTimeInterface is not redundant, DateTimeInterface is only in PHP>5.5
  771. if ($value === null || $value instanceof DateTime || $value instanceof DateTimeInterface) {
  772. // skip any processing
  773. return $checkDateTimeInfo ? [$value, true, true] : $value;
  774. }
  775. if (empty($value)) {
  776. $value = 0;
  777. }
  778. try {
  779. if (is_numeric($value)) { // process as unix timestamp, which is always in UTC
  780. $timestamp = new DateTime('@' . (int) $value, new DateTimeZone('UTC'));
  781. return $checkDateTimeInfo ? [$timestamp, true, true] : $timestamp;
  782. } elseif (($timestamp = DateTime::createFromFormat('Y-m-d|', $value, new DateTimeZone($this->defaultTimeZone))) !== false) { // try Y-m-d format (support invalid dates like 2012-13-01)
  783. return $checkDateTimeInfo ? [$timestamp, false, true] : $timestamp;
  784. } elseif (($timestamp = DateTime::createFromFormat('Y-m-d H:i:s', $value, new DateTimeZone($this->defaultTimeZone))) !== false) { // try Y-m-d H:i:s format (support invalid dates like 2012-13-01 12:63:12)
  785. return $checkDateTimeInfo ? [$timestamp, true, true] : $timestamp;
  786. }
  787. // finally try to create a DateTime object with the value
  788. if ($checkDateTimeInfo) {
  789. $timestamp = new DateTime($value, new DateTimeZone($this->defaultTimeZone));
  790. $info = date_parse($value);
  791. return [
  792. $timestamp,
  793. !($info['hour'] === false && $info['minute'] === false && $info['second'] === false),
  794. !($info['year'] === false && $info['month'] === false && $info['day'] === false),
  795. ];
  796. }
  797. return new DateTime($value, new DateTimeZone($this->defaultTimeZone));
  798. } catch (\Exception $e) {
  799. throw new InvalidArgumentException("'$value' is not a valid date time value: " . $e->getMessage()
  800. . "\n" . print_r(DateTime::getLastErrors(), true), $e->getCode(), $e);
  801. }
  802. }
  803. /**
  804. * Formats a date, time or datetime in a float number as UNIX timestamp (seconds since 01-01-1970).
  805. * @param int|string|DateTime $value the value to be formatted. The following
  806. * types of value are supported:
  807. *
  808. * - an integer representing a UNIX timestamp
  809. * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
  810. * The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
  811. * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
  812. *
  813. * @return string the formatted result.
  814. */
  815. public function asTimestamp($value)
  816. {
  817. if ($value === null) {
  818. return $this->nullDisplay;
  819. }
  820. $timestamp = $this->normalizeDatetimeValue($value);
  821. return number_format($timestamp->format('U'), 0, '.', '');
  822. }
  823. /**
  824. * Formats the value as the time interval between a date and now in human readable form.
  825. *
  826. * This method can be used in three different ways:
  827. *
  828. * 1. Using a timestamp that is relative to `now`.
  829. * 2. Using a timestamp that is relative to the `$referenceTime`.
  830. * 3. Using a `DateInterval` object.
  831. *
  832. * @param int|string|DateTime|DateInterval $value the value to be formatted. The following
  833. * types of value are supported:
  834. *
  835. * - an integer representing a UNIX timestamp
  836. * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
  837. * The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
  838. * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
  839. * - a PHP DateInterval object (a positive time interval will refer to the past, a negative one to the future)
  840. *
  841. * @param int|string|DateTime $referenceTime if specified the value is used as a reference time instead of `now`
  842. * when `$value` is not a `DateInterval` object.
  843. * @return string the formatted result.
  844. * @throws InvalidArgumentException if the input value can not be evaluated as a date value.
  845. */
  846. public function asRelativeTime($value, $referenceTime = null)
  847. {
  848. if ($value === null) {
  849. return $this->nullDisplay;
  850. }
  851. if ($value instanceof DateInterval) {
  852. $interval = $value;
  853. } else {
  854. $timestamp = $this->normalizeDatetimeValue($value);
  855. if ($timestamp === false) {
  856. // $value is not a valid date/time value, so we try
  857. // to create a DateInterval with it
  858. try {
  859. $interval = new DateInterval($value);
  860. } catch (\Exception $e) {
  861. // invalid date/time and invalid interval
  862. return $this->nullDisplay;
  863. }
  864. } else {
  865. $timeZone = new DateTimeZone($this->timeZone);
  866. if ($referenceTime === null) {
  867. $dateNow = new DateTime('now', $timeZone);
  868. } else {
  869. $dateNow = $this->normalizeDatetimeValue($referenceTime);
  870. $dateNow->setTimezone($timeZone);
  871. }
  872. $dateThen = $timestamp->setTimezone($timeZone);
  873. $interval = $dateThen->diff($dateNow);
  874. }
  875. }
  876. if ($interval->invert) {
  877. if ($interval->y >= 1) {
  878. return Yii::t('yii', 'in {delta, plural, =1{a year} other{# years}}', ['delta' => $interval->y], $this->locale);
  879. }
  880. if ($interval->m >= 1) {
  881. return Yii::t('yii', 'in {delta, plural, =1{a month} other{# months}}', ['delta' => $interval->m], $this->locale);
  882. }
  883. if ($interval->d >= 1) {
  884. return Yii::t('yii', 'in {delta, plural, =1{a day} other{# days}}', ['delta' => $interval->d], $this->locale);
  885. }
  886. if ($interval->h >= 1) {
  887. return Yii::t('yii', 'in {delta, plural, =1{an hour} other{# hours}}', ['delta' => $interval->h], $this->locale);
  888. }
  889. if ($interval->i >= 1) {
  890. return Yii::t('yii', 'in {delta, plural, =1{a minute} other{# minutes}}', ['delta' => $interval->i], $this->locale);
  891. }
  892. if ($interval->s == 0) {
  893. return Yii::t('yii', 'just now', [], $this->locale);
  894. }
  895. return Yii::t('yii', 'in {delta, plural, =1{a second} other{# seconds}}', ['delta' => $interval->s], $this->locale);
  896. }
  897. if ($interval->y >= 1) {
  898. return Yii::t('yii', '{delta, plural, =1{a year} other{# years}} ago', ['delta' => $interval->y], $this->locale);
  899. }
  900. if ($interval->m >= 1) {
  901. return Yii::t('yii', '{delta, plural, =1{a month} other{# months}} ago', ['delta' => $interval->m], $this->locale);
  902. }
  903. if ($interval->d >= 1) {
  904. return Yii::t('yii', '{delta, plural, =1{a day} other{# days}} ago', ['delta' => $interval->d], $this->locale);
  905. }
  906. if ($interval->h >= 1) {
  907. return Yii::t('yii', '{delta, plural, =1{an hour} other{# hours}} ago', ['delta' => $interval->h], $this->locale);
  908. }
  909. if ($interval->i >= 1) {
  910. return Yii::t('yii', '{delta, plural, =1{a minute} other{# minutes}} ago', ['delta' => $interval->i], $this->locale);
  911. }
  912. if ($interval->s == 0) {
  913. return Yii::t('yii', 'just now', [], $this->locale);
  914. }
  915. return Yii::t('yii', '{delta, plural, =1{a second} other{# seconds}} ago', ['delta' => $interval->s], $this->locale);
  916. }
  917. /**
  918. * Represents the value as duration in human readable format.
  919. *
  920. * @param DateInterval|string|int $value the value to be formatted. Acceptable formats:
  921. * - [DateInterval object](http://php.net/manual/ru/class.dateinterval.php)
  922. * - integer - number of seconds. For example: value `131` represents `2 minutes, 11 seconds`
  923. * - ISO8601 duration format. For example, all of these values represent `1 day, 2 hours, 30 minutes` duration:
  924. * `2015-01-01T13:00:00Z/2015-01-02T13:30:00Z` - between two datetime values
  925. * `2015-01-01T13:00:00Z/P1D2H30M` - time interval after datetime value
  926. * `P1D2H30M/2015-01-02T13:30:00Z` - time interval before datetime value
  927. * `P1D2H30M` - simply a date interval
  928. * `P-1D2H30M` - a negative date interval (`-1 day, 2 hours, 30 minutes`)
  929. *
  930. * @param string $implodeString will be used to concatenate duration parts. Defaults to `, `.
  931. * @param string $negativeSign will be prefixed to the formatted duration, when it is negative. Defaults to `-`.
  932. * @return string the formatted duration.
  933. * @since 2.0.7
  934. */
  935. public function asDuration($value, $implodeString = ', ', $negativeSign = '-')
  936. {
  937. if ($value === null) {
  938. return $this->nullDisplay;
  939. }
  940. if ($value instanceof DateInterval) {
  941. $isNegative = $value->invert;
  942. $interval = $value;
  943. } elseif (is_numeric($value)) {
  944. $isNegative = $value < 0;
  945. $zeroDateTime = (new DateTime())->setTimestamp(0);
  946. $valueDateTime = (new DateTime())->setTimestamp(abs($value));
  947. $interval = $valueDateTime->diff($zeroDateTime);
  948. } elseif (strncmp($value, 'P-', 2) === 0) {
  949. $interval = new DateInterval('P' . substr($value, 2));
  950. $isNegative = true;
  951. } else {
  952. $interval = new DateInterval($value);
  953. $isNegative = $interval->invert;
  954. }
  955. $parts = [];
  956. if ($interval->y > 0) {
  957. $parts[] = Yii::t('yii', '{delta, plural, =1{1 year} other{# years}}', ['delta' => $interval->y], $this->locale);
  958. }
  959. if ($interval->m > 0) {
  960. $parts[] = Yii::t('yii', '{delta, plural, =1{1 month} other{# months}}', ['delta' => $interval->m], $this->locale);
  961. }
  962. if ($interval->d > 0) {
  963. $parts[] = Yii::t('yii', '{delta, plural, =1{1 day} other{# days}}', ['delta' => $interval->d], $this->locale);
  964. }
  965. if ($interval->h > 0) {
  966. $parts[] = Yii::t('yii', '{delta, plural, =1{1 hour} other{# hours}}', ['delta' => $interval->h], $this->locale);
  967. }
  968. if ($interval->i > 0) {
  969. $parts[] = Yii::t('yii', '{delta, plural, =1{1 minute} other{# minutes}}', ['delta' => $interval->i], $this->locale);
  970. }
  971. if ($interval->s > 0) {
  972. $parts[] = Yii::t('yii', '{delta, plural, =1{1 second} other{# seconds}}', ['delta' => $interval->s], $this->locale);
  973. }
  974. if ($interval->s === 0 && empty($parts)) {
  975. $parts[] = Yii::t('yii', '{delta, plural, =1{1 second} other{# seconds}}', ['delta' => $interval->s], $this->locale);
  976. $isNegative = false;
  977. }
  978. return empty($parts) ? $this->nullDisplay : (($isNegative ? $negativeSign : '') . implode($implodeString, $parts));
  979. }
  980. // number formats
  981. /**
  982. * Formats the value as an integer number by removing any decimal digits without rounding.
  983. *
  984. * @param mixed $value the value to be formatted.
  985. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
  986. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
  987. * @return string the formatted result.
  988. * @throws InvalidArgumentException if the input value is not numeric or the formatting failed.
  989. */
  990. public function asInteger($value, $options = [], $textOptions = [])
  991. {
  992. if ($value === null) {
  993. return $this->nullDisplay;
  994. }
  995. $value = $this->normalizeNumericValue($value);
  996. if ($this->_intlLoaded) {
  997. $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, null, $options, $textOptions);
  998. $f->setAttribute(NumberFormatter::FRACTION_DIGITS, 0);
  999. if (($result = $f->format($value, NumberFormatter::TYPE_INT64)) === false) {
  1000. throw new InvalidArgumentException('Formatting integer value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
  1001. }
  1002. return $result;
  1003. }
  1004. return number_format((int) $value, 0, $this->decimalSeparator, $this->thousandSeparator);
  1005. }
  1006. /**
  1007. * Formats the value as a decimal number.
  1008. *
  1009. * Property [[decimalSeparator]] will be used to represent the decimal point. The
  1010. * value is rounded automatically to the defined decimal digits.
  1011. *
  1012. * @param mixed $value the value to be formatted.
  1013. * @param int $decimals the number of digits after the decimal point.
  1014. * If not given, the number of digits depends in the input value and is determined based on
  1015. * `NumberFormatter::MIN_FRACTION_DIGITS` and `NumberFormatter::MAX_FRACTION_DIGITS`, which can be configured
  1016. * using [[$numberFormatterOptions]].
  1017. * If the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available, the default value is `2`.
  1018. * If you want consistent behavior between environments where intl is available and not, you should explicitly
  1019. * specify a value here.
  1020. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
  1021. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
  1022. * @return string the formatted result.
  1023. * @throws InvalidArgumentException if the input value is not numeric or the formatting failed.
  1024. * @see decimalSeparator
  1025. * @see thousandSeparator
  1026. */
  1027. public function asDecimal($value, $decimals = null, $options = [], $textOptions = [])
  1028. {
  1029. if ($value === null) {
  1030. return $this->nullDisplay;
  1031. }
  1032. $value = $this->normalizeNumericValue($value);
  1033. if ($this->_intlLoaded) {
  1034. $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, $decimals, $options, $textOptions);
  1035. if (($result = $f->format($value)) === false) {
  1036. throw new InvalidArgumentException('Formatting decimal value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
  1037. }
  1038. return $result;
  1039. }
  1040. if ($decimals === null) {
  1041. $decimals = 2;
  1042. }
  1043. return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator);
  1044. }
  1045. /**
  1046. * Formats the value as a percent number with "%" sign.
  1047. *
  1048. * @param mixed $value the value to be formatted. It must be a factor e.g. `0.75` will result in `75%`.
  1049. * @param int $decimals the number of digits after the decimal point.
  1050. * If not given, the number of digits depends in the input value and is determined based on
  1051. * `NumberFormatter::MIN_FRACTION_DIGITS` and `NumberFormatter::MAX_FRACTION_DIGITS`, which can be configured
  1052. * using [[$numberFormatterOptions]].
  1053. * If the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available, the default value is `0`.
  1054. * If you want consistent behavior between environments where intl is available and not, you should explicitly
  1055. * specify a value here.
  1056. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
  1057. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
  1058. * @return string the formatted result.
  1059. * @throws InvalidArgumentException if the input value is not numeric or the formatting failed.
  1060. */
  1061. public function asPercent($value, $decimals = null, $options = [], $textOptions = [])
  1062. {
  1063. if ($value === null) {
  1064. return $this->nullDisplay;
  1065. }
  1066. $value = $this->normalizeNumericValue($value);
  1067. if ($this->_intlLoaded) {
  1068. $f = $this->createNumberFormatter(NumberFormatter::PERCENT, $decimals, $options, $textOptions);
  1069. if (($result = $f->format($value)) === false) {
  1070. throw new InvalidArgumentException('Formatting percent value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
  1071. }
  1072. return $result;
  1073. }
  1074. if ($decimals === null) {
  1075. $decimals = 0;
  1076. }
  1077. $value *= 100;
  1078. return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator) . '%';
  1079. }
  1080. /**
  1081. * Formats the value as a scientific number.
  1082. *
  1083. * @param mixed $value the value to be formatted.
  1084. * @param int $decimals the number of digits after the decimal point.
  1085. * If not given, the number of digits depends in the input value and is determined based on
  1086. * `NumberFormatter::MIN_FRACTION_DIGITS` and `NumberFormatter::MAX_FRACTION_DIGITS`, which can be configured
  1087. * using [[$numberFormatterOptions]].
  1088. * If the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available, the default value depends on your PHP configuration.
  1089. * If you want consistent behavior between environments where intl is available and not, you should explicitly
  1090. * specify a value here.
  1091. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
  1092. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
  1093. * @return string the formatted result.
  1094. * @throws InvalidArgumentException if the input value is not numeric or the formatting failed.
  1095. */
  1096. public function asScientific($value, $decimals = null, $options = [], $textOptions = [])
  1097. {
  1098. if ($value === null) {
  1099. return $this->nullDisplay;
  1100. }
  1101. $value = $this->normalizeNumericValue($value);
  1102. if ($this->_intlLoaded) {
  1103. $f = $this->createNumberFormatter(NumberFormatter::SCIENTIFIC, $decimals, $options, $textOptions);
  1104. if (($result = $f->format($value)) === false) {
  1105. throw new InvalidArgumentException('Formatting scientific number value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
  1106. }
  1107. return $result;
  1108. }
  1109. if ($decimals !== null) {
  1110. return sprintf("%.{$decimals}E", $value);
  1111. }
  1112. return sprintf('%.E', $value);
  1113. }
  1114. /**
  1115. * Formats the value as a currency number.
  1116. *
  1117. * This function does not require the [PHP intl extension](http://php.net/manual/en/book.intl.php) to be installed
  1118. * to work, but it is highly recommended to install it to get good formatting results.
  1119. *
  1120. * @param mixed $value the value to be formatted.
  1121. * @param string $currency the 3-letter ISO 4217 currency code indicating the currency to use.
  1122. * If null, [[currencyCode]] will be used.
  1123. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
  1124. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
  1125. * @return string the formatted result.
  1126. * @throws InvalidArgumentException if the input value is not numeric or the formatting failed.
  1127. * @throws InvalidConfigException if no currency is given and [[currencyCode]] is not defined.
  1128. */
  1129. public function asCurrency($value, $currency = null, $options = [], $textOptions = [])
  1130. {
  1131. if ($value === null) {
  1132. return $this->nullDisplay;
  1133. }
  1134. $value = $this->normalizeNumericValue($value);
  1135. if ($this->_intlLoaded) {
  1136. $currency = $currency ?: $this->currencyCode;
  1137. // currency code must be set before fraction digits
  1138. // http://php.net/manual/en/numberformatter.formatcurrency.php#114376
  1139. if ($currency && !isset($textOptions[NumberFormatter::CURRENCY_CODE])) {
  1140. $textOptions[NumberFormatter::CURRENCY_CODE] = $currency;
  1141. }
  1142. $formatter = $this->createNumberFormatter(NumberFormatter::CURRENCY, null, $options, $textOptions);
  1143. if ($currency === null) {
  1144. $result = $formatter->format($value);
  1145. } else {
  1146. $result = $formatter->formatCurrency($value, $currency);
  1147. }
  1148. if ($result === false) {
  1149. throw new InvalidArgumentException('Formatting currency value failed: ' . $formatter->getErrorCode() . ' ' . $formatter->getErrorMessage());
  1150. }
  1151. return $result;
  1152. }
  1153. if ($currency === null) {
  1154. if ($this->currencyCode === null) {
  1155. throw new InvalidConfigException('The default currency code for the formatter is not defined and the php intl extension is not installed which could take the default currency from the locale.');
  1156. }
  1157. $currency = $this->currencyCode;
  1158. }
  1159. return $currency . ' ' . $this->asDecimal($value, 2, $options, $textOptions);
  1160. }
  1161. /**
  1162. * Formats the value as a number spellout.
  1163. *
  1164. * This function requires the [PHP intl extension](http://php.net/manual/en/book.intl.php) to be installed.
  1165. *
  1166. * @param mixed $value the value to be formatted
  1167. * @return string the formatted result.
  1168. * @throws InvalidArgumentException if the input value is not numeric or the formatting failed.
  1169. * @throws InvalidConfigException when the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available.
  1170. */
  1171. public function asSpellout($value)
  1172. {
  1173. if ($value === null) {
  1174. return $this->nullDisplay;
  1175. }
  1176. $value = $this->normalizeNumericValue($value);
  1177. if ($this->_intlLoaded) {
  1178. $f = $this->createNumberFormatter(NumberFormatter::SPELLOUT);
  1179. if (($result = $f->format($value)) === false) {
  1180. throw new InvalidArgumentException('Formatting number as spellout failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
  1181. }
  1182. return $result;
  1183. }
  1184. throw new InvalidConfigException('Format as Spellout is only supported when PHP intl extension is installed.');
  1185. }
  1186. /**
  1187. * Formats the value as a ordinal value of a number.
  1188. *
  1189. * This function requires the [PHP intl extension](http://php.net/manual/en/book.intl.php) to be installed.
  1190. *
  1191. * @param mixed $value the value to be formatted
  1192. * @return string the formatted result.
  1193. * @throws InvalidArgumentException if the input value is not numeric or the formatting failed.
  1194. * @throws InvalidConfigException when the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available.
  1195. */
  1196. public function asOrdinal($value)
  1197. {
  1198. if ($value === null) {
  1199. return $this->nullDisplay;
  1200. }
  1201. $value = $this->normalizeNumericValue($value);
  1202. if ($this->_intlLoaded) {
  1203. $f = $this->createNumberFormatter(NumberFormatter::ORDINAL);
  1204. if (($result = $f->format($value)) === false) {
  1205. throw new InvalidArgumentException('Formatting number as ordinal failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
  1206. }
  1207. return $result;
  1208. }
  1209. throw new InvalidConfigException('Format as Ordinal is only supported when PHP intl extension is installed.');
  1210. }
  1211. /**
  1212. * Formats the value in bytes as a size in human readable form for example `12 KB`.
  1213. *
  1214. * This is the short form of [[asSize]].
  1215. *
  1216. * If [[sizeFormatBase]] is 1024, [binary prefixes](http://en.wikipedia.org/wiki/Binary_prefix) (e.g. kibibyte/KiB, mebibyte/MiB, ...)
  1217. * are used in the formatting result.
  1218. *
  1219. * @param string|int|float $value value in bytes to be formatted.
  1220. * @param int $decimals the number of digits after the decimal point.
  1221. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
  1222. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
  1223. * @return string the formatted result.
  1224. * @throws InvalidArgumentException if the input value is not numeric or the formatting failed.
  1225. * @see sizeFormatBase
  1226. * @see asSize
  1227. */
  1228. public function asShortSize($value, $decimals = null, $options = [], $textOptions = [])
  1229. {
  1230. if ($value === null) {
  1231. return $this->nullDisplay;
  1232. }
  1233. list($params, $position) = $this->formatNumber($value, $decimals, 4, $this->sizeFormatBase, $options, $textOptions);
  1234. if ($this->sizeFormatBase == 1024) {
  1235. switch ($position) {
  1236. case 0:
  1237. return Yii::t('yii', '{nFormatted} B', $params, $this->locale);
  1238. case 1:
  1239. return Yii::t('yii', '{nFormatted} KiB', $params, $this->locale);
  1240. case 2:
  1241. return Yii::t('yii', '{nFormatted} MiB', $params, $this->locale);
  1242. case 3:
  1243. return Yii::t('yii', '{nFormatted} GiB', $params, $this->locale);
  1244. case 4:
  1245. return Yii::t('yii', '{nFormatted} TiB', $params, $this->locale);
  1246. default:
  1247. return Yii::t('yii', '{nFormatted} PiB', $params, $this->locale);
  1248. }
  1249. } else {
  1250. switch ($position) {
  1251. case 0:
  1252. return Yii::t('yii', '{nFormatted} B', $params, $this->locale);
  1253. case 1:
  1254. return Yii::t('yii', '{nFormatted} KB', $params, $this->locale);
  1255. case 2:
  1256. return Yii::t('yii', '{nFormatted} MB', $params, $this->locale);
  1257. case 3:
  1258. return Yii::t('yii', '{nFormatted} GB', $params, $this->locale);
  1259. case 4:
  1260. return Yii::t('yii', '{nFormatted} TB', $params, $this->locale);
  1261. default:
  1262. return Yii::t('yii', '{nFormatted} PB', $params, $this->locale);
  1263. }
  1264. }
  1265. }
  1266. /**
  1267. * Formats the value in bytes as a size in human readable form, for example `12 kilobytes`.
  1268. *
  1269. * If [[sizeFormatBase]] is 1024, [binary prefixes](http://en.wikipedia.org/wiki/Binary_prefix) (e.g. kibibyte/KiB, mebibyte/MiB, ...)
  1270. * are used in the formatting result.
  1271. *
  1272. * @param string|int|float $value value in bytes to be formatted.
  1273. * @param int $decimals the number of digits after the decimal point.
  1274. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
  1275. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
  1276. * @return string the formatted result.
  1277. * @throws InvalidArgumentException if the input value is not numeric or the formatting failed.
  1278. * @see sizeFormatBase
  1279. * @see asShortSize
  1280. */
  1281. public function asSize($value, $decimals = null, $options = [], $textOptions = [])
  1282. {
  1283. if ($value === null) {
  1284. return $this->nullDisplay;
  1285. }
  1286. list($params, $position) = $this->formatNumber($value, $decimals, 4, $this->sizeFormatBase, $options, $textOptions);
  1287. if ($this->sizeFormatBase == 1024) {
  1288. switch ($position) {
  1289. case 0:
  1290. return Yii::t('yii', '{nFormatted} {n, plural, =1{byte} other{bytes}}', $params, $this->locale);
  1291. case 1:
  1292. return Yii::t('yii', '{nFormatted} {n, plural, =1{kibibyte} other{kibibytes}}', $params, $this->locale);
  1293. case 2:
  1294. return Yii::t('yii', '{nFormatted} {n, plural, =1{mebibyte} other{mebibytes}}', $params, $this->locale);
  1295. case 3:
  1296. return Yii::t('yii', '{nFormatted} {n, plural, =1{gibibyte} other{gibibytes}}', $params, $this->locale);
  1297. case 4:
  1298. return Yii::t('yii', '{nFormatted} {n, plural, =1{tebibyte} other{tebibytes}}', $params, $this->locale);
  1299. default:
  1300. return Yii::t('yii', '{nFormatted} {n, plural, =1{pebibyte} other{pebibytes}}', $params, $this->locale);
  1301. }
  1302. } else {
  1303. switch ($position) {
  1304. case 0:
  1305. return Yii::t('yii', '{nFormatted} {n, plural, =1{byte} other{bytes}}', $params, $this->locale);
  1306. case 1:
  1307. return Yii::t('yii', '{nFormatted} {n, plural, =1{kilobyte} other{kilobytes}}', $params, $this->locale);
  1308. case 2:
  1309. return Yii::t('yii', '{nFormatted} {n, plural, =1{megabyte} other{megabytes}}', $params, $this->locale);
  1310. case 3:
  1311. return Yii::t('yii', '{nFormatted} {n, plural, =1{gigabyte} other{gigabytes}}', $params, $this->locale);
  1312. case 4:
  1313. return Yii::t('yii', '{nFormatted} {n, plural, =1{terabyte} other{terabytes}}', $params, $this->locale);
  1314. default:
  1315. return Yii::t('yii', '{nFormatted} {n, plural, =1{petabyte} other{petabytes}}', $params, $this->locale);
  1316. }
  1317. }
  1318. }
  1319. /**
  1320. * Formats the value as a length in human readable form for example `12 meters`.
  1321. * Check properties [[baseUnits]] if you need to change unit of value as the multiplier
  1322. * of the smallest unit and [[systemOfUnits]] to switch between [[UNIT_SYSTEM_METRIC]] or [[UNIT_SYSTEM_IMPERIAL]].
  1323. *
  1324. * @param float|int $value value to be formatted.
  1325. * @param int $decimals the number of digits after the decimal point.
  1326. * @param array $numberOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
  1327. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
  1328. * @return string the formatted result.
  1329. * @throws InvalidArgumentException if the input value is not numeric or the formatting failed.
  1330. * @throws InvalidConfigException when INTL is not installed or does not contain required information.
  1331. * @see asLength
  1332. * @since 2.0.13
  1333. * @author John Was <janek.jan@gmail.com>
  1334. */
  1335. public function asLength($value, $decimals = null, $numberOptions = [], $textOptions = [])
  1336. {
  1337. return $this->formatUnit(self::UNIT_LENGTH, self::FORMAT_WIDTH_LONG, $value, null, null, $decimals, $numberOptions, $textOptions);
  1338. }
  1339. /**
  1340. * Formats the value as a length in human readable form for example `12 m`.
  1341. * This is the short form of [[asLength]].
  1342. *
  1343. * Check properties [[baseUnits]] if you need to change unit of value as the multiplier
  1344. * of the smallest unit and [[systemOfUnits]] to switch between [[UNIT_SYSTEM_METRIC]] or [[UNIT_SYSTEM_IMPERIAL]].
  1345. *
  1346. * @param float|int $value value to be formatted.
  1347. * @param int $decimals the number of digits after the decimal point.
  1348. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
  1349. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
  1350. * @return string the formatted result.
  1351. * @throws InvalidArgumentException if the input value is not numeric or the formatting failed.
  1352. * @throws InvalidConfigException when INTL is not installed or does not contain required information.
  1353. * @see asLength
  1354. * @since 2.0.13
  1355. * @author John Was <janek.jan@gmail.com>
  1356. */
  1357. public function asShortLength($value, $decimals = null, $options = [], $textOptions = [])
  1358. {
  1359. return $this->formatUnit(self::UNIT_LENGTH, self::FORMAT_WIDTH_SHORT, $value, null, null, $decimals, $options, $textOptions);
  1360. }
  1361. /**
  1362. * Formats the value as a weight in human readable form for example `12 kilograms`.
  1363. * Check properties [[baseUnits]] if you need to change unit of value as the multiplier
  1364. * of the smallest unit and [[systemOfUnits]] to switch between [[UNIT_SYSTEM_METRIC]] or [[UNIT_SYSTEM_IMPERIAL]].
  1365. *
  1366. * @param float|int $value value to be formatted.
  1367. * @param int $decimals the number of digits after the decimal point.
  1368. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
  1369. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
  1370. * @return string the formatted result.
  1371. * @throws InvalidArgumentException if the input value is not numeric or the formatting failed.
  1372. * @throws InvalidConfigException when INTL is not installed or does not contain required information.
  1373. * @since 2.0.13
  1374. * @author John Was <janek.jan@gmail.com>
  1375. */
  1376. public function asWeight($value, $decimals = null, $options = [], $textOptions = [])
  1377. {
  1378. return $this->formatUnit(self::UNIT_WEIGHT, self::FORMAT_WIDTH_LONG, $value, null, null, $decimals, $options, $textOptions);
  1379. }
  1380. /**
  1381. * Formats the value as a weight in human readable form for example `12 kg`.
  1382. * This is the short form of [[asWeight]].
  1383. *
  1384. * Check properties [[baseUnits]] if you need to change unit of value as the multiplier
  1385. * of the smallest unit and [[systemOfUnits]] to switch between [[UNIT_SYSTEM_METRIC]] or [[UNIT_SYSTEM_IMPERIAL]].
  1386. *
  1387. * @param float|int $value value to be formatted.
  1388. * @param int $decimals the number of digits after the decimal point.
  1389. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
  1390. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
  1391. * @return string the formatted result.
  1392. * @throws InvalidArgumentException if the input value is not numeric or the formatting failed.
  1393. * @throws InvalidConfigException when INTL is not installed or does not contain required information.
  1394. * @since 2.0.13
  1395. * @author John Was <janek.jan@gmail.com>
  1396. */
  1397. public function asShortWeight($value, $decimals = null, $options = [], $textOptions = [])
  1398. {
  1399. return $this->formatUnit(self::UNIT_WEIGHT, self::FORMAT_WIDTH_SHORT, $value, null, null, $decimals, $options, $textOptions);
  1400. }
  1401. /**
  1402. * @param string $unitType one of [[UNIT_WEIGHT]], [[UNIT_LENGTH]]
  1403. * @param string $unitFormat one of [[FORMAT_WIDTH_SHORT]], [[FORMAT_WIDTH_LONG]]
  1404. * @param float|int $value to be formatted
  1405. * @param float $baseUnit unit of value as the multiplier of the smallest unit. When `null`, property [[baseUnits]]
  1406. * will be used to determine base unit using $unitType and $unitSystem.
  1407. * @param string $unitSystem either [[UNIT_SYSTEM_METRIC]] or [[UNIT_SYSTEM_IMPERIAL]]. When `null`, property [[systemOfUnits]] will be used.
  1408. * @param int $decimals the number of digits after the decimal point.
  1409. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
  1410. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
  1411. * @return string
  1412. * @throws InvalidConfigException when INTL is not installed or does not contain required information
  1413. */
  1414. private function formatUnit($unitType, $unitFormat, $value, $baseUnit, $unitSystem, $decimals, $options, $textOptions)
  1415. {
  1416. if ($value === null) {
  1417. return $this->nullDisplay;
  1418. }
  1419. if ($unitSystem === null) {
  1420. $unitSystem = $this->systemOfUnits;
  1421. }
  1422. if ($baseUnit === null) {
  1423. $baseUnit = $this->baseUnits[$unitType][$unitSystem];
  1424. }
  1425. $multipliers = array_values($this->measureUnits[$unitType][$unitSystem]);
  1426. list($params, $position) = $this->formatNumber(
  1427. $this->normalizeNumericValue($value) * $baseUnit,
  1428. $decimals,
  1429. null,
  1430. $multipliers,
  1431. $options,
  1432. $textOptions
  1433. );
  1434. $message = $this->getUnitMessage($unitType, $unitFormat, $unitSystem, $position);
  1435. return (new \MessageFormatter($this->locale, $message))->format([
  1436. '0' => $params['nFormatted'],
  1437. 'n' => $params['n'],
  1438. ]);
  1439. }
  1440. /**
  1441. * @param string $unitType one of [[UNIT_WEIGHT]], [[UNIT_LENGTH]]
  1442. * @param string $unitFormat one of [[FORMAT_WIDTH_SHORT]], [[FORMAT_WIDTH_LONG]]
  1443. * @param string $system either [[UNIT_SYSTEM_METRIC]] or [[UNIT_SYSTEM_IMPERIAL]]. When `null`, property [[systemOfUnits]] will be used.
  1444. * @param int $position internal position of size unit
  1445. * @return string
  1446. * @throws InvalidConfigException when INTL is not installed or does not contain required information
  1447. */
  1448. private function getUnitMessage($unitType, $unitFormat, $system, $position)
  1449. {
  1450. if (isset($this->_unitMessages[$unitType][$system][$position])) {
  1451. return $this->_unitMessages[$unitType][$system][$position];
  1452. }
  1453. if (!$this->_intlLoaded) {
  1454. throw new InvalidConfigException('Format of ' . $unitType . ' is only supported when PHP intl extension is installed.');
  1455. }
  1456. if ($this->_resourceBundle === null) {
  1457. try {
  1458. $this->_resourceBundle = new \ResourceBundle($this->locale, 'ICUDATA-unit');
  1459. } catch (\IntlException $e) {
  1460. throw new InvalidConfigException('Current ICU data does not contain information about measure units. Check system requirements.');
  1461. }
  1462. }
  1463. $unitNames = array_keys($this->measureUnits[$unitType][$system]);
  1464. $bundleKey = 'units' . ($unitFormat === self::FORMAT_WIDTH_SHORT ? 'Short' : '');
  1465. $unitBundle = $this->_resourceBundle[$bundleKey][$unitType][$unitNames[$position]];
  1466. if ($unitBundle === null) {
  1467. throw new InvalidConfigException('Current ICU data version does not contain information about unit type "' . $unitType . '" and unit measure "' . $unitNames[$position] . '". Check system requirements.');
  1468. }
  1469. $message = [];
  1470. foreach ($unitBundle as $key => $value) {
  1471. if ($key === 'dnam') {
  1472. continue;
  1473. }
  1474. $message[] = "$key{{$value}}";
  1475. }
  1476. return $this->_unitMessages[$unitType][$system][$position] = '{n, plural, ' . implode(' ', $message) . '}';
  1477. }
  1478. /**
  1479. * Given the value in bytes formats number part of the human readable form.
  1480. *
  1481. * @param string|int|float $value value in bytes to be formatted.
  1482. * @param int $decimals the number of digits after the decimal point
  1483. * @param int $maxPosition maximum internal position of size unit, ignored if $formatBase is an array
  1484. * @param array|int $formatBase the base at which each next unit is calculated, either 1000 or 1024, or an array
  1485. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
  1486. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
  1487. * @return array [parameters for Yii::t containing formatted number, internal position of size unit]
  1488. * @throws InvalidArgumentException if the input value is not numeric or the formatting failed.
  1489. */
  1490. private function formatNumber($value, $decimals, $maxPosition, $formatBase, $options, $textOptions)
  1491. {
  1492. $value = $this->normalizeNumericValue($value);
  1493. $position = 0;
  1494. if (is_array($formatBase)) {
  1495. $maxPosition = count($formatBase) - 1;
  1496. }
  1497. do {
  1498. if (is_array($formatBase)) {
  1499. if (!isset($formatBase[$position + 1])) {
  1500. break;
  1501. }
  1502. if (abs($value) < $formatBase[$position + 1]) {
  1503. break;
  1504. }
  1505. } else {
  1506. if (abs($value) < $formatBase) {
  1507. break;
  1508. }
  1509. $value /= $formatBase;
  1510. }
  1511. $position++;
  1512. } while ($position < $maxPosition + 1);
  1513. if (is_array($formatBase) && $position !== 0) {
  1514. $value /= $formatBase[$position];
  1515. }
  1516. // no decimals for smallest unit
  1517. if ($position === 0) {
  1518. $decimals = 0;
  1519. } elseif ($decimals !== null) {
  1520. $value = round($value, $decimals);
  1521. }
  1522. // disable grouping for edge cases like 1023 to get 1023 B instead of 1,023 B
  1523. $oldThousandSeparator = $this->thousandSeparator;
  1524. $this->thousandSeparator = '';
  1525. if ($this->_intlLoaded && !isset($options[NumberFormatter::GROUPING_USED])) {
  1526. $options[NumberFormatter::GROUPING_USED] = false;
  1527. }
  1528. // format the size value
  1529. $params = [
  1530. // this is the unformatted number used for the plural rule
  1531. // abs() to make sure the plural rules work correctly on negative numbers, intl does not cover this
  1532. // http://english.stackexchange.com/questions/9735/is-1-singular-or-plural
  1533. 'n' => abs($value),
  1534. // this is the formatted number used for display
  1535. 'nFormatted' => $this->asDecimal($value, $decimals, $options, $textOptions),
  1536. ];
  1537. $this->thousandSeparator = $oldThousandSeparator;
  1538. return [$params, $position];
  1539. }
  1540. /**
  1541. * Normalizes a numeric input value.
  1542. *
  1543. * - everything [empty](http://php.net/manual/en/function.empty.php) will result in `0`
  1544. * - a [numeric](http://php.net/manual/en/function.is-numeric.php) string will be casted to float
  1545. * - everything else will be returned if it is [numeric](http://php.net/manual/en/function.is-numeric.php),
  1546. * otherwise an exception is thrown.
  1547. *
  1548. * @param mixed $value the input value
  1549. * @return float|int the normalized number value
  1550. * @throws InvalidArgumentException if the input value is not numeric.
  1551. */
  1552. protected function normalizeNumericValue($value)
  1553. {
  1554. if (empty($value)) {
  1555. return 0;
  1556. }
  1557. if (is_string($value) && is_numeric($value)) {
  1558. $value = (float) $value;
  1559. }
  1560. if (!is_numeric($value)) {
  1561. throw new InvalidArgumentException("'$value' is not a numeric value.");
  1562. }
  1563. return $value;
  1564. }
  1565. /**
  1566. * Creates a number formatter based on the given type and format.
  1567. *
  1568. * You may override this method to create a number formatter based on patterns.
  1569. *
  1570. * @param int $style the type of the number formatter.
  1571. * Values: NumberFormatter::DECIMAL, ::CURRENCY, ::PERCENT, ::SCIENTIFIC, ::SPELLOUT, ::ORDINAL
  1572. * ::DURATION, ::PATTERN_RULEBASED, ::DEFAULT_STYLE, ::IGNORE
  1573. * @param int $decimals the number of digits after the decimal point.
  1574. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
  1575. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
  1576. * @return NumberFormatter the created formatter instance
  1577. */
  1578. protected function createNumberFormatter($style, $decimals = null, $options = [], $textOptions = [])
  1579. {
  1580. $formatter = new NumberFormatter($this->locale, $style);
  1581. // set text attributes
  1582. foreach ($this->numberFormatterTextOptions as $name => $attribute) {
  1583. $formatter->setTextAttribute($name, $attribute);
  1584. }
  1585. foreach ($textOptions as $name => $attribute) {
  1586. $formatter->setTextAttribute($name, $attribute);
  1587. }
  1588. // set attributes
  1589. foreach ($this->numberFormatterOptions as $name => $value) {
  1590. $formatter->setAttribute($name, $value);
  1591. }
  1592. foreach ($options as $name => $value) {
  1593. $formatter->setAttribute($name, $value);
  1594. }
  1595. if ($decimals !== null) {
  1596. $formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimals);
  1597. $formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimals);
  1598. }
  1599. // set symbols
  1600. if ($this->decimalSeparator !== null) {
  1601. $formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, $this->decimalSeparator);
  1602. }
  1603. if ($this->thousandSeparator !== null) {
  1604. $formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, $this->thousandSeparator);
  1605. $formatter->setSymbol(NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL, $this->thousandSeparator);
  1606. }
  1607. foreach ($this->numberFormatterSymbols as $name => $symbol) {
  1608. $formatter->setSymbol($name, $symbol);
  1609. }
  1610. return $formatter;
  1611. }
  1612. }