Skip to content

Commit 2ec260a

Browse files
endoramaGrahamCampbell
authored andcommitted
Add safeLoad method to suppress InvalidPathException (#242)
1 parent 7ac2c1c commit 2ec260a

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/Dotenv.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
namespace Dotenv;
44

5+
use Dotenv\Exception\InvalidPathException;
6+
57
/**
68
* This is the dotenv class.
79
*
@@ -48,6 +50,21 @@ public function load()
4850
return $this->loadData();
4951
}
5052

53+
/**
54+
* Load environment file in given directory, suppress InvalidPathException.
55+
*
56+
* @return array
57+
*/
58+
public function safeLoad()
59+
{
60+
try {
61+
return $this->loadData();
62+
} catch (InvalidPathException $e) {
63+
// suppressing exception
64+
return array();
65+
}
66+
}
67+
5168
/**
5269
* Load environment file in given directory.
5370
*

tests/Dotenv/DotenvTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,12 @@ public function testDotenvThrowsExceptionIfUnableToLoadFile()
2424
$dotenv->load();
2525
}
2626

27+
public function testDotenvSkipsLoadingIfFileIsMissing()
28+
{
29+
$dotenv = new Dotenv(__DIR__);
30+
$this->assertEmpty($dotenv->safeLoad());
31+
}
32+
2733
public function testDotenvLoadsEnvironmentVars()
2834
{
2935
$dotenv = new Dotenv($this->fixturesFolder);

0 commit comments

Comments
 (0)