Skip to content

Commit c988660

Browse files
Loader refactoring
1 parent 58ac8e7 commit c988660

File tree

6 files changed

+350
-273
lines changed

6 files changed

+350
-273
lines changed

src/Lines.php

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
<?php
2+
3+
namespace Dotenv;
4+
5+
class Lines
6+
{
7+
/**
8+
* Process the array of lines of environment variables.
9+
*
10+
* This will produce an array of entries, one per variable.
11+
*
12+
* @param string[] $lines
13+
*
14+
* @return string[]
15+
*/
16+
public static function process(array $lines)
17+
{
18+
$output = [];
19+
$multiline = false;
20+
$multilineBuffer = [];
21+
22+
foreach ($lines as $line) {
23+
list($multiline, $line, $multilineBuffer) = self::multilineProcess($multiline, $line, $multilineBuffer);
24+
25+
if (!$multiline && !self::isComment($line) && self::looksLikeSetter($line)) {
26+
$output[] = $line;
27+
}
28+
}
29+
30+
return $output;
31+
}
32+
33+
/**
34+
* Used to make all multiline variable process.
35+
*
36+
* @param bool $multiline
37+
* @param string $line
38+
* @param string[] $buffer
39+
*
40+
* @return string[]
41+
*/
42+
private static function multilineProcess($multiline, $line, array $buffer)
43+
{
44+
// check if $line can be multiline variable
45+
if (self::looksLikeMultilineStart($line)) {
46+
$multiline = true;
47+
}
48+
49+
if ($multiline) {
50+
array_push($buffer, $line);
51+
52+
if (self::looksLikeMultilineStop($line)) {
53+
$multiline = false;
54+
$line = implode("\n", $buffer);
55+
$buffer = [];
56+
}
57+
}
58+
59+
return [$multiline, $line, $buffer];
60+
}
61+
62+
/**
63+
* Determine if the given line can be the start of a multiline variable.
64+
*
65+
* @param string $line
66+
*
67+
* @return bool
68+
*/
69+
private static function looksLikeMultilineStart($line)
70+
{
71+
return strpos($line, '="') !== false && substr_count($line, '"') === 1;
72+
}
73+
74+
/**
75+
* Determine if the given line can be the start of a multiline variable.
76+
*
77+
* @param string $line
78+
*
79+
* @return bool
80+
*/
81+
private static function looksLikeMultilineStop($line)
82+
{
83+
return strpos($line, '"') !== false && substr_count($line, '="') === 0;
84+
}
85+
86+
/**
87+
* Determine if the line in the file is a comment, e.g. begins with a #.
88+
*
89+
* @param string $line
90+
*
91+
* @return bool
92+
*/
93+
private static function isComment($line)
94+
{
95+
$line = ltrim($line);
96+
97+
return isset($line[0]) && $line[0] === '#';
98+
}
99+
100+
/**
101+
* Determine if the given line looks like it's setting a variable.
102+
*
103+
* @param string $line
104+
*
105+
* @return bool
106+
*/
107+
private static function looksLikeSetter($line)
108+
{
109+
return strpos($line, '=') !== false;
110+
}
111+
}

0 commit comments

Comments
 (0)