Str.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. declare(strict_types=1);
  3. namespace Dotenv\Util;
  4. use GrahamCampbell\ResultType\Error;
  5. use GrahamCampbell\ResultType\Success;
  6. use PhpOption\Option;
  7. /**
  8. * @internal
  9. */
  10. final class Str
  11. {
  12. /**
  13. * This class is a singleton.
  14. *
  15. * @codeCoverageIgnore
  16. *
  17. * @return void
  18. */
  19. private function __construct()
  20. {
  21. //
  22. }
  23. /**
  24. * Convert a string to UTF-8 from the given encoding.
  25. *
  26. * @param string $input
  27. * @param string|null $encoding
  28. *
  29. * @return \GrahamCampbell\ResultType\Result<string,string>
  30. */
  31. public static function utf8(string $input, string $encoding = null)
  32. {
  33. if ($encoding !== null && !\in_array($encoding, \mb_list_encodings(), true)) {
  34. /** @var \GrahamCampbell\ResultType\Result<string,string> */
  35. return Error::create(
  36. \sprintf('Illegal character encoding [%s] specified.', $encoding)
  37. );
  38. }
  39. $converted = $encoding === null ?
  40. @\mb_convert_encoding($input, 'UTF-8') :
  41. @\mb_convert_encoding($input, 'UTF-8', $encoding);
  42. /**
  43. * this is for support UTF-8 with BOM encoding
  44. * @see https://en.wikipedia.org/wiki/Byte_order_mark
  45. * @see https://github.com/vlucas/phpdotenv/issues/500
  46. */
  47. if (\substr($converted, 0, 3) == "\xEF\xBB\xBF") {
  48. $converted = \substr($converted, 3);
  49. }
  50. /** @var \GrahamCampbell\ResultType\Result<string,string> */
  51. return Success::create($converted);
  52. }
  53. /**
  54. * Search for a given substring of the input.
  55. *
  56. * @param string $haystack
  57. * @param string $needle
  58. *
  59. * @return \PhpOption\Option<int>
  60. */
  61. public static function pos(string $haystack, string $needle)
  62. {
  63. /** @var \PhpOption\Option<int> */
  64. return Option::fromValue(\mb_strpos($haystack, $needle, 0, 'UTF-8'), false);
  65. }
  66. /**
  67. * Grab the specified substring of the input.
  68. *
  69. * @param string $input
  70. * @param int $start
  71. * @param int|null $length
  72. *
  73. * @return string
  74. */
  75. public static function substr(string $input, int $start, int $length = null)
  76. {
  77. return \mb_substr($input, $start, $length, 'UTF-8');
  78. }
  79. /**
  80. * Compute the length of the given string.
  81. *
  82. * @param string $input
  83. *
  84. * @return int
  85. */
  86. public static function len(string $input)
  87. {
  88. return \mb_strlen($input, 'UTF-8');
  89. }
  90. }