PageRenderTime 50ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Jalet/Util/Sprintf.php

https://github.com/jalet/util-sprintf-php
PHP | 88 lines | 42 code | 16 blank | 30 comment | 3 complexity | 33d9c670cbdae72433062690969fdfce MD5 | raw file
  1. <?php
  2. namespace Jalet\Util;
  3. /**
  4. *
  5. */
  6. class Sprintf
  7. {
  8. private static $string;
  9. /** No instances */
  10. private function __construct() {}
  11. /**
  12. * Replace patterns in string with mathing value of array $args.
  13. *
  14. * %key:bool:int% => 1 | 0
  15. * %key:bool:str% => true | false
  16. *
  17. * %key:int%
  18. * %key:float%
  19. * %key:bool%
  20. * %key% * default
  21. *
  22. * @param String $string String to be formated
  23. * @param Array $args Key/value pairs
  24. * @return String Formated string
  25. */
  26. public static function f($string, Array $args)
  27. {
  28. self::$string = $string;
  29. foreach($args as $key => $val) {
  30. // Forced formatting for boolean values
  31. if (preg_match('%(?P<key>'.$key.'(?:\:bool\:(?P<format>int|str)))%', self::$string, $matches)) {
  32. self::$string = self::replace($matches['key'], $val, 'bool', $matches['format']);
  33. continue;
  34. }
  35. // Forced formatting for any value
  36. if (preg_match('%(?P<key>'.$key.'(?:\:(?P<format>\w+)))%', self::$string, $matches)) {
  37. self::$string = self::replace($matches['key'], $val, $matches['format']);
  38. continue;
  39. }
  40. // Just replace as is.
  41. self::$string = self::replace($key, $val);
  42. }
  43. return self::$string;
  44. }
  45. /**
  46. * [replace description]
  47. * @param String $key Pattern to replace
  48. * @param String $val The value to replace it with
  49. * @param String $format Format, int, float or bool. Will default to string
  50. * @param String $output Only used for :bool:int|str
  51. * @return String
  52. */
  53. private static function replace($key, $val, $format = 'string', $output = null)
  54. {
  55. switch ($format) {
  56. case 'int':
  57. $string = preg_replace('/%'.$key.'%/', intval($val), self::$string);
  58. break;
  59. case 'float':
  60. $string = preg_replace('/%'.$key.'%/', floatval($val), self::$string);
  61. break;
  62. case 'bool':
  63. $string = $output === 'str' ? preg_replace('/%'.$key.'%/', (bool) $val ? 'true' : 'false', self::$string)
  64. : preg_replace('/%'.$key.'%/', (bool) $val, self::$string);
  65. break;
  66. default:
  67. $string = preg_replace('/%'.$key.'%/', strval($val), self::$string);
  68. break;
  69. }
  70. return $string;
  71. }
  72. }