| 148 |
lars |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
declare(strict_types=1);
|
|
|
4 |
|
|
|
5 |
namespace Dotenv\Parser;
|
|
|
6 |
|
|
|
7 |
use Dotenv\Exception\InvalidFileException;
|
|
|
8 |
use Dotenv\Util\Regex;
|
|
|
9 |
use GrahamCampbell\ResultType\Result;
|
|
|
10 |
use GrahamCampbell\ResultType\Success;
|
|
|
11 |
|
|
|
12 |
final class Parser implements ParserInterface
|
|
|
13 |
{
|
|
|
14 |
/**
|
|
|
15 |
* Parse content into an entry array.
|
|
|
16 |
*
|
|
|
17 |
* @param string $content
|
|
|
18 |
*
|
|
|
19 |
* @throws \Dotenv\Exception\InvalidFileException
|
|
|
20 |
*
|
|
|
21 |
* @return \Dotenv\Parser\Entry[]
|
|
|
22 |
*/
|
|
|
23 |
public function parse(string $content)
|
|
|
24 |
{
|
|
|
25 |
return Regex::split("/(\r\n|\n|\r)/", $content)->mapError(static function () {
|
|
|
26 |
return 'Could not split into separate lines.';
|
|
|
27 |
})->flatMap(static function (array $lines) {
|
|
|
28 |
return self::process(Lines::process($lines));
|
|
|
29 |
})->mapError(static function (string $error) {
|
|
|
30 |
throw new InvalidFileException(\sprintf('Failed to parse dotenv file. %s', $error));
|
|
|
31 |
})->success()->get();
|
|
|
32 |
}
|
|
|
33 |
|
|
|
34 |
/**
|
|
|
35 |
* Convert the raw entries into proper entries.
|
|
|
36 |
*
|
|
|
37 |
* @param string[] $entries
|
|
|
38 |
*
|
|
|
39 |
* @return \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Entry[],string>
|
|
|
40 |
*/
|
|
|
41 |
private static function process(array $entries)
|
|
|
42 |
{
|
|
|
43 |
/** @var \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Entry[],string> */
|
|
|
44 |
return \array_reduce($entries, static function (Result $result, string $raw) {
|
|
|
45 |
return $result->flatMap(static function (array $entries) use ($raw) {
|
|
|
46 |
return EntryParser::parse($raw)->map(static function (Entry $entry) use ($entries) {
|
|
|
47 |
/** @var \Dotenv\Parser\Entry[] */
|
|
|
48 |
return \array_merge($entries, [$entry]);
|
|
|
49 |
});
|
|
|
50 |
});
|
|
|
51 |
}, Success::create([]));
|
|
|
52 |
}
|
|
|
53 |
}
|