From d4394d044ed69a8f244f3445bcedf8a0d7fe2403 Mon Sep 17 00:00:00 2001 From: Hossein Hosni <47793698+hosni@users.noreply.github.com> Date: Wed, 10 Nov 2021 04:38:39 +0330 Subject: [PATCH] Add support for BOM-signed env files (#501) --- src/Util/Str.php | 16 ++++++++++++---- tests/Dotenv/Store/StoreTest.php | 11 +++++++++++ tests/fixtures/env/utf8-with-bom-encoding.env | 3 +++ 3 files changed, 26 insertions(+), 4 deletions(-) create mode 100644 tests/fixtures/env/utf8-with-bom-encoding.env diff --git a/src/Util/Str.php b/src/Util/Str.php index 582c2144..087e236a 100644 --- a/src/Util/Str.php +++ b/src/Util/Str.php @@ -41,11 +41,19 @@ public static function utf8(string $input, string $encoding = null) \sprintf('Illegal character encoding [%s] specified.', $encoding) ); } - + $converted = $encoding === null ? + @\mb_convert_encoding($input, 'UTF-8') : + @\mb_convert_encoding($input, 'UTF-8', $encoding); + /** + * this is for support UTF-8 with BOM encoding + * @see https://en.wikipedia.org/wiki/Byte_order_mark + * @see https://github.com/vlucas/phpdotenv/issues/500 + */ + if (\substr($converted, 0, 3) == "\xEF\xBB\xBF") { + $converted = \substr($converted, 3); + } /** @var \GrahamCampbell\ResultType\Result */ - return Success::create( - $encoding === null ? @\mb_convert_encoding($input, 'UTF-8') : @\mb_convert_encoding($input, 'UTF-8', $encoding) - ); + return Success::create($converted); } /** diff --git a/tests/Dotenv/Store/StoreTest.php b/tests/Dotenv/Store/StoreTest.php index 0d953bdc..6b4d9672 100644 --- a/tests/Dotenv/Store/StoreTest.php +++ b/tests/Dotenv/Store/StoreTest.php @@ -127,4 +127,15 @@ public function testFileReadMultipleWithoutShortCircuitMode() $builder->make()->read() ); } + public function testFileReadWithUtf8WithBomEncoding() + { + self::assertSame( + [ + self::$folder.\DIRECTORY_SEPARATOR.'utf8-with-bom-encoding.env' => "FOO=bar\nBAR=baz\nSPACED=\"with spaces\"\n", + ], + Reader::read( + Paths::filePaths([self::$folder], ['utf8-with-bom-encoding.env']) + ) + ); + } } diff --git a/tests/fixtures/env/utf8-with-bom-encoding.env b/tests/fixtures/env/utf8-with-bom-encoding.env new file mode 100644 index 00000000..29c07697 --- /dev/null +++ b/tests/fixtures/env/utf8-with-bom-encoding.env @@ -0,0 +1,3 @@ +FOO=bar +BAR=baz +SPACED="with spaces"