Просмотр файла app/Services/Str.php

Размер файла: 2.46Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Services;
  6.  
  7. class Str
  8. {
  9. /**
  10. * Return the length of the given string.
  11. *
  12. * @param string $value
  13. * @param string|null $encoding
  14. * @return int
  15. */
  16. public static function length($value, $encoding = null)
  17. {
  18. if ($encoding) {
  19. return mb_strlen($value, $encoding);
  20. }
  21.  
  22. return mb_strlen($value);
  23. }
  24.  
  25. /**
  26. * Limit the number of characters in a string.
  27. *
  28. * @param string $value
  29. * @param int $limit
  30. * @param string $end
  31. * @return string
  32. */
  33. public static function limit($value, $limit = 100, $end = '...')
  34. {
  35. if (mb_strwidth($value, 'UTF-8') <= $limit) {
  36. return $value;
  37. }
  38.  
  39. return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end;
  40. }
  41.  
  42. /**
  43. * Convert the given string to lower-case.
  44. *
  45. * @param string $value
  46. * @return string
  47. */
  48. public static function lower($value)
  49. {
  50. return mb_strtolower($value, 'UTF-8');
  51. }
  52.  
  53. /**
  54. * Convert the given string to upper-case.
  55. *
  56. * @param string $value
  57. * @return string
  58. */
  59. public static function upper($value)
  60. {
  61. return mb_strtoupper($value, 'UTF-8');
  62. }
  63.  
  64. /**
  65. * Limit the number of words in a string.
  66. *
  67. * @param string $value
  68. * @param int $words
  69. * @param string $end
  70. * @return string
  71. */
  72. public static function words($value, $words = 100, $end = '...')
  73. {
  74. preg_match('/^\s*+(?:\S++\s*+){1,'.$words.'}/u', $value, $matches);
  75.  
  76. if (! isset($matches[0]) || static::length($value) === static::length($matches[0])) {
  77. return $value;
  78. }
  79.  
  80. return rtrim($matches[0]).$end;
  81. }
  82.  
  83. /**
  84. * Get the number of words a string contains.
  85. *
  86. * @param string $string
  87. * @return int
  88. */
  89. public static function wordCount($string)
  90. {
  91. return count(preg_split('/[^\s*+]+/u', $string));
  92. }
  93.  
  94. /**
  95. * Generate a more truly "random" alpha-numeric string.
  96. *
  97. * @param int $length
  98. * @return string
  99. */
  100. public static function random($length = 16)
  101. {
  102. $string = '';
  103.  
  104. while (($len = strlen($string)) < $length) {
  105. $size = $length - $len;
  106.  
  107. $bytes = random_bytes($size);
  108.  
  109. $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
  110. }
  111.  
  112. return $string;
  113. }
  114. }