3838
3939use Fidry \FileSystem \FS ;
4040use PHPUnit \Framework \TestCase ;
41+ use RuntimeException ;
4142use Stringable ;
4243use function array_map ;
4344use function array_values ;
45+ use function chdir ;
4446use function dirname ;
47+ use function getcwd ;
4548use function is_array ;
4649use function iterator_to_array ;
4750use function natcasesort ;
4851use function natsort ;
49- use function Safe \ getcwd ;
52+ use function sprintf ;
5053use function str_replace ;
5154use const DIRECTORY_SEPARATOR ;
5255
@@ -74,21 +77,21 @@ public static function tearDownAfterClass(): void
7477
7578 protected function setUp (): void
7679 {
77- $ this ->cwd = getcwd ();
80+ $ this ->cwd = self :: safeGetCurrentWorkingDirectory ();
7881 $ this ->tmp = FS ::makeTmpDir (
7982 static ::getTmpDirNamespace (),
8083 static ::class,
8184 );
8285 static ::$ lastKnownTmpNamespace = dirname ($ this ->tmp );
83- chdir ($ this ->tmp );
86+ self :: safeChdir ($ this ->tmp );
8487 }
8588
8689 protected function tearDown (): void
8790 {
8891 $ wasSetupSkipped = '' === $ this ->cwd && '' === $ this ->tmp ;
8992
9093 if (!$ wasSetupSkipped ) {
91- chdir ($ this ->cwd );
94+ self :: safeChdir ($ this ->cwd );
9295 FS ::remove ($ this ->tmp );
9396 }
9497 }
@@ -114,4 +117,29 @@ final protected function normalizePaths(iterable $paths): array
114117
115118 return array_values ($ normalizedPaths );
116119 }
120+
121+ private static function safeChdir (string $ directory ): void
122+ {
123+ $ chdirResult = chdir ($ directory );
124+
125+ if (!$ chdirResult ) {
126+ throw new RuntimeException (
127+ sprintf (
128+ 'Could not change the current working directory to "%s". ' ,
129+ $ directory ,
130+ ),
131+ );
132+ }
133+ }
134+
135+ private static function safeGetCurrentWorkingDirectory (): string
136+ {
137+ $ result = getcwd ();
138+
139+ if (false === $ result ) {
140+ throw new RuntimeException ('Could not get the current working directory. ' );
141+ }
142+
143+ return $ result ;
144+ }
117145}
0 commit comments