Passed
Push — PsrCacheFileFetcher ( 3e20c0 )
by Jeroen De
05:30
created

PsrCacheFileFetcher::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
declare( strict_types=1 );
4
5
namespace FileFetcher;
6
7
use Psr\SimpleCache\CacheException;
8
use Psr\SimpleCache\CacheInterface;
9
10
/**
11
 * Decorator that caches files using psr/simple-cache.
12
 * https://packagist.org/packages/psr/simple-cache
13
 *
14
 * @since 5.0
15
 *
16
 * @licence BSD-3-Clause
17
 * @author Jeroen De Dauw < [email protected] >
18
 */
19
class PsrCacheFileFetcher implements FileFetcher {
20
21
	private $fileFetcher;
22
	private $cache;
23
24
	public function __construct( FileFetcher $fileFetcher, CacheInterface $cache ) {
25
		$this->fileFetcher = $fileFetcher;
26
		$this->cache = $cache;
27
	}
28
29
	/**
30
	 * @see FileFetcher::fetchFile
31
	 * @throws FileFetchingException
32
	 */
33
	public function fetchFile( string $fileUrl ): string {
34
		$fileContents = $this->getFileContentsFromCache( $fileUrl );
35
36
		if ( $fileContents === null ) {
37
			return $this->retrieveAndCacheFile( $fileUrl );
38
		}
39
40
		return $fileContents;
41
	}
42
43
	private function getFileContentsFromCache( string $fileUrl ): ?string {
44
		try {
45
			return $this->cache->get( $fileUrl );
46
		}
47
		catch ( CacheException $ex ) {
48
			return null;
49
		}
50
	}
51
52
	private function retrieveAndCacheFile( $fileUrl ): string {
53
		$fileContents = $this->fileFetcher->fetchFile( $fileUrl );
54
55
		try {
56
			$this->cache->set( $fileUrl, $fileContents );
57
		}
58
		catch ( CacheException $ex ) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
59
		}
60
61
		return $fileContents;
62
	}
63
64
}
65