Skip to content

Commit

Permalink
Add support for BOM-signed env files (#501)
Browse files Browse the repository at this point in the history
  • Loading branch information
hosni authored Nov 10, 2021
1 parent 7261bb0 commit d4394d0
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/Util/Str.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<string,string> */
return Success::create(
$encoding === null ? @\mb_convert_encoding($input, 'UTF-8') : @\mb_convert_encoding($input, 'UTF-8', $encoding)
);
return Success::create($converted);
}

/**
Expand Down
11 changes: 11 additions & 0 deletions tests/Dotenv/Store/StoreTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'])
)
);
}
}
3 changes: 3 additions & 0 deletions tests/fixtures/env/utf8-with-bom-encoding.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
FOO=bar
BAR=baz
SPACED="with spaces"

0 comments on commit d4394d0

Please sign in to comment.