InMemoryFileFetcher::__construct()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 7
cts 7
cp 1
rs 9.9332
c 0
b 0
f 0
cc 4
nc 3
nop 2
crap 4
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace FileFetcher;
6
7
use InvalidArgumentException;
8
9
/**
10
 * @since 3.1
11
 *
12
 * @licence BSD-3-Clause
13
 * @author Jeroen De Dauw < [email protected] >
14
 */
15
class InMemoryFileFetcher implements FileFetcher {
16
17
	private $files;
18
	private $defaultContent;
19
20
	/**
21
	 * @param string[] $files
22
	 * @param string|null $defaultContent Content that is returned when there is no matching entry in $files
23
	 * @throws InvalidArgumentException
24
	 */
25 10
	public function __construct( array $files, string $defaultContent = null ) {
26 10
		foreach ( $files as $url => $fileContents ) {
27 5
			if ( !is_string( $url ) || !is_string( $fileContents ) ) {
28 1
				throw new InvalidArgumentException( 'Both file url and file contents need to be of type string' );
29
			}
30
		}
31
32 9
		$this->files = $files;
33 9
		$this->defaultContent = $defaultContent;
34 9
	}
35
36
	/**
37
	 * @see FileFetcher::fetchFile
38
	 * @throws FileFetchingException
39
	 */
40 9
	public function fetchFile( string $fileUrl ): string {
41 9
		if ( array_key_exists( $fileUrl, $this->files ) ) {
42 3
			return $this->files[$fileUrl];
43
		}
44
45 6
		if ( $this->defaultContent === null ) {
46 5
			throw new FileFetchingException( $fileUrl );
47
		}
48
49 1
		return $this->defaultContent;
50
	}
51
52
}
53