Formatter.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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\base;
  8. use Yii;
  9. use DateTime;
  10. use yii\helpers\HtmlPurifier;
  11. use yii\helpers\Html;
  12. /**
  13. * Formatter provides a set of commonly used data formatting methods.
  14. *
  15. * The formatting methods provided by Formatter are all named in the form of `asXyz()`.
  16. * The behavior of some of them may be configured via the properties of Formatter. For example,
  17. * by configuring [[dateFormat]], one may control how [[asDate()]] formats the value into a date string.
  18. *
  19. * Formatter is configured as an application component in [[yii\base\Application]] by default.
  20. * You can access that instance via `Yii::$app->formatter`.
  21. *
  22. * @author Qiang Xue <[email protected]>
  23. * @since 2.0
  24. */
  25. class Formatter extends Component
  26. {
  27. /**
  28. * @var string the default format string to be used to format a date using PHP date() function.
  29. */
  30. public $dateFormat = 'Y/m/d';
  31. /**
  32. * @var string the default format string to be used to format a time using PHP date() function.
  33. */
  34. public $timeFormat = 'h:i:s A';
  35. /**
  36. * @var string the default format string to be used to format a date and time using PHP date() function.
  37. */
  38. public $datetimeFormat = 'Y/m/d h:i:s A';
  39. /**
  40. * @var string the text to be displayed when formatting a null. Defaults to '<span class="not-set">(not set)</span>'.
  41. */
  42. public $nullDisplay;
  43. /**
  44. * @var array the text to be displayed when formatting a boolean value. The first element corresponds
  45. * to the text display for false, the second element for true. Defaults to `['No', 'Yes']`.
  46. */
  47. public $booleanFormat;
  48. /**
  49. * @var string the character displayed as the decimal point when formatting a number.
  50. * If not set, "." will be used.
  51. */
  52. public $decimalSeparator;
  53. /**
  54. * @var string the character displayed as the thousands separator character when formatting a number.
  55. * If not set, "," will be used.
  56. */
  57. public $thousandSeparator;
  58. /**
  59. * Initializes the component.
  60. */
  61. public function init()
  62. {
  63. if (empty($this->booleanFormat)) {
  64. $this->booleanFormat = [Yii::t('yii', 'No'), Yii::t('yii', 'Yes')];
  65. }
  66. if ($this->nullDisplay === null) {
  67. $this->nullDisplay = '<span class="not-set">' . Yii::t('yii', '(not set)') . '</span>';
  68. }
  69. }
  70. /**
  71. * Formats the value based on the given format type.
  72. * This method will call one of the "as" methods available in this class to do the formatting.
  73. * For type "xyz", the method "asXyz" will be used. For example, if the format is "html",
  74. * then [[asHtml()]] will be used. Format names are case insensitive.
  75. * @param mixed $value the value to be formatted
  76. * @param string|array $format the format of the value, e.g., "html", "text". To specify additional
  77. * parameters of the formatting method, you may use an array. The first element of the array
  78. * specifies the format name, while the rest of the elements will be used as the parameters to the formatting
  79. * method. For example, a format of `['date', 'Y-m-d']` will cause the invocation of `asDate($value, 'Y-m-d')`.
  80. * @return string the formatting result
  81. * @throws InvalidParamException if the type is not supported by this class.
  82. */
  83. public function format($value, $format)
  84. {
  85. if (is_array($format)) {
  86. if (!isset($format[0])) {
  87. throw new InvalidParamException('The $format array must contain at least one element.');
  88. }
  89. $f = $format[0];
  90. $format[0] = $value;
  91. $params = $format;
  92. $format = $f;
  93. } else {
  94. $params = [$value];
  95. }
  96. $method = 'as' . $format;
  97. if (method_exists($this, $method)) {
  98. return call_user_func_array([$this, $method], $params);
  99. } else {
  100. throw new InvalidParamException("Unknown type: $format");
  101. }
  102. }
  103. /**
  104. * Formats the value as is without any formatting.
  105. * This method simply returns back the parameter without any format.
  106. * @param mixed $value the value to be formatted
  107. * @return string the formatted result
  108. */
  109. public function asRaw($value)
  110. {
  111. if ($value === null) {
  112. return $this->nullDisplay;
  113. }
  114. return $value;
  115. }
  116. /**
  117. * Formats the value as an HTML-encoded plain text.
  118. * @param mixed $value the value to be formatted
  119. * @return string the formatted result
  120. */
  121. public function asText($value)
  122. {
  123. if ($value === null) {
  124. return $this->nullDisplay;
  125. }
  126. return Html::encode($value);
  127. }
  128. /**
  129. * Formats the value as an HTML-encoded plain text with newlines converted into breaks.
  130. * @param mixed $value the value to be formatted
  131. * @return string the formatted result
  132. */
  133. public function asNtext($value)
  134. {
  135. if ($value === null) {
  136. return $this->nullDisplay;
  137. }
  138. return nl2br(Html::encode($value));
  139. }
  140. /**
  141. * Formats the value as HTML-encoded text paragraphs.
  142. * Each text paragraph is enclosed within a `<p>` tag.
  143. * One or multiple consecutive empty lines divide two paragraphs.
  144. * @param mixed $value the value to be formatted
  145. * @return string the formatted result
  146. */
  147. public function asParagraphs($value)
  148. {
  149. if ($value === null) {
  150. return $this->nullDisplay;
  151. }
  152. return str_replace('<p></p>', '',
  153. '<p>' . preg_replace('/[\r\n]{2,}/', "</p>\n<p>", Html::encode($value)) . '</p>'
  154. );
  155. }
  156. /**
  157. * Formats the value as HTML text.
  158. * The value will be purified using [[HtmlPurifier]] to avoid XSS attacks.
  159. * Use [[asRaw()]] if you do not want any purification of the value.
  160. * @param mixed $value the value to be formatted
  161. * @param array|null $config the configuration for the HTMLPurifier class.
  162. * @return string the formatted result
  163. */
  164. public function asHtml($value, $config = null)
  165. {
  166. if ($value === null) {
  167. return $this->nullDisplay;
  168. }
  169. return HtmlPurifier::process($value, $config);
  170. }
  171. /**
  172. * Formats the value as a mailto link.
  173. * @param mixed $value the value to be formatted
  174. * @return string the formatted result
  175. */
  176. public function asEmail($value)
  177. {
  178. if ($value === null) {
  179. return $this->nullDisplay;
  180. }
  181. return Html::mailto(Html::encode($value), $value);
  182. }
  183. /**
  184. * Formats the value as an image tag.
  185. * @param mixed $value the value to be formatted
  186. * @return string the formatted result
  187. */
  188. public function asImage($value)
  189. {
  190. if ($value === null) {
  191. return $this->nullDisplay;
  192. }
  193. return Html::img($value);
  194. }
  195. /**
  196. * Formats the value as a hyperlink.
  197. * @param mixed $value the value to be formatted
  198. * @return string the formatted result
  199. */
  200. public function asUrl($value)
  201. {
  202. if ($value === null) {
  203. return $this->nullDisplay;
  204. }
  205. $url = $value;
  206. if (strpos($url, 'http://') !== 0 && strpos($url, 'https://') !== 0) {
  207. $url = 'http://' . $url;
  208. }
  209. return Html::a(Html::encode($value), $url);
  210. }
  211. /**
  212. * Formats the value as a boolean.
  213. * @param mixed $value the value to be formatted
  214. * @return string the formatted result
  215. * @see booleanFormat
  216. */
  217. public function asBoolean($value)
  218. {
  219. if ($value === null) {
  220. return $this->nullDisplay;
  221. }
  222. return $value ? $this->booleanFormat[1] : $this->booleanFormat[0];
  223. }
  224. /**
  225. * Formats the value as a date.
  226. * @param integer|string|DateTime $value the value to be formatted. The following
  227. * types of value are supported:
  228. *
  229. * - an integer representing a UNIX timestamp
  230. * - a string that can be parsed into a UNIX timestamp via `strtotime()`
  231. * - a PHP DateTime object
  232. *
  233. * @param string $format the format used to convert the value into a date string.
  234. * If null, [[dateFormat]] will be used. The format string should be one
  235. * that can be recognized by the PHP `date()` function.
  236. * @return string the formatted result
  237. * @see dateFormat
  238. */
  239. public function asDate($value, $format = null)
  240. {
  241. if ($value === null) {
  242. return $this->nullDisplay;
  243. }
  244. $value = $this->normalizeDatetimeValue($value);
  245. return date($format === null ? $this->dateFormat : $format, $value);
  246. }
  247. /**
  248. * Formats the value as a time.
  249. * @param integer|string|DateTime $value the value to be formatted. The following
  250. * types of value are supported:
  251. *
  252. * - an integer representing a UNIX timestamp
  253. * - a string that can be parsed into a UNIX timestamp via `strtotime()`
  254. * - a PHP DateTime object
  255. *
  256. * @param string $format the format used to convert the value into a date string.
  257. * If null, [[timeFormat]] will be used. The format string should be one
  258. * that can be recognized by the PHP `date()` function.
  259. * @return string the formatted result
  260. * @see timeFormat
  261. */
  262. public function asTime($value, $format = null)
  263. {
  264. if ($value === null) {
  265. return $this->nullDisplay;
  266. }
  267. $value = $this->normalizeDatetimeValue($value);
  268. return date($format === null ? $this->timeFormat : $format, $value);
  269. }
  270. /**
  271. * Formats the value as a datetime.
  272. * @param integer|string|DateTime $value the value to be formatted. The following
  273. * types of value are supported:
  274. *
  275. * - an integer representing a UNIX timestamp
  276. * - a string that can be parsed into a UNIX timestamp via `strtotime()`
  277. * - a PHP DateTime object
  278. *
  279. * @param string $format the format used to convert the value into a date string.
  280. * If null, [[datetimeFormat]] will be used. The format string should be one
  281. * that can be recognized by the PHP `date()` function.
  282. * @return string the formatted result
  283. * @see datetimeFormat
  284. */
  285. public function asDatetime($value, $format = null)
  286. {
  287. if ($value === null) {
  288. return $this->nullDisplay;
  289. }
  290. $value = $this->normalizeDatetimeValue($value);
  291. return date($format === null ? $this->datetimeFormat : $format, $value);
  292. }
  293. /**
  294. * Normalizes the given datetime value as one that can be taken by various date/time formatting methods.
  295. * @param mixed $value the datetime value to be normalized.
  296. * @return integer the normalized datetime value
  297. */
  298. protected function normalizeDatetimeValue($value)
  299. {
  300. if (is_string($value)) {
  301. return is_numeric($value) || $value === '' ? (int)$value : strtotime($value);
  302. } elseif ($value instanceof DateTime) {
  303. return $value->getTimestamp();
  304. } else {
  305. return (int)$value;
  306. }
  307. }
  308. /**
  309. * Formats the value as an integer.
  310. * @param mixed $value the value to be formatted
  311. * @return string the formatting result.
  312. */
  313. public function asInteger($value)
  314. {
  315. if ($value === null) {
  316. return $this->nullDisplay;
  317. }
  318. if (is_string($value) && preg_match('/^(-?\d+)/', $value, $matches)) {
  319. return $matches[1];
  320. } else {
  321. $value = (int)$value;
  322. return "$value";
  323. }
  324. }
  325. /**
  326. * Formats the value as a double number.
  327. * Property [[decimalSeparator]] will be used to represent the decimal point.
  328. * @param mixed $value the value to be formatted
  329. * @param integer $decimals the number of digits after the decimal point
  330. * @return string the formatting result.
  331. * @see decimalSeparator
  332. */
  333. public function asDouble($value, $decimals = 2)
  334. {
  335. if ($value === null) {
  336. return $this->nullDisplay;
  337. }
  338. if ($this->decimalSeparator === null) {
  339. return sprintf("%.{$decimals}f", $value);
  340. } else {
  341. return str_replace('.', $this->decimalSeparator, sprintf("%.{$decimals}f", $value));
  342. }
  343. }
  344. /**
  345. * Formats the value as a number with decimal and thousand separators.
  346. * This method calls the PHP number_format() function to do the formatting.
  347. * @param mixed $value the value to be formatted
  348. * @param integer $decimals the number of digits after the decimal point
  349. * @return string the formatted result
  350. * @see decimalSeparator
  351. * @see thousandSeparator
  352. */
  353. public function asNumber($value, $decimals = 0)
  354. {
  355. if ($value === null) {
  356. return $this->nullDisplay;
  357. }
  358. $ds = isset($this->decimalSeparator) ? $this->decimalSeparator: '.';
  359. $ts = isset($this->thousandSeparator) ? $this->thousandSeparator: ',';
  360. return number_format($value, $decimals, $ds, $ts);
  361. }
  362. }