Passed
Push — master ( 915f9b...db478f )
by Jeroen De
05:06 queued 03:24
created

src/PsrCacheFileFetcher.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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 6
	public function __construct( FileFetcher $fileFetcher, CacheInterface $cache ) {
25 6
		$this->fileFetcher = $fileFetcher;
26 6
		$this->cache = $cache;
27 6
	}
28
29
	/**
30
	 * @see FileFetcher::fetchFile
31
	 * @throws FileFetchingException
32
	 */
33 6
	public function fetchFile( string $fileUrl ): string {
34 6
		$fileContents = $this->getFileContentsFromCache( $fileUrl );
35
36 6
		if ( $fileContents === null ) {
37 5
			return $this->retrieveAndCacheFile( $fileUrl );
38
		}
39
40 1
		return $fileContents;
41
	}
42
43 6
	private function getFileContentsFromCache( string $fileUrl ): ?string {
44
		try {
45 6
			return $this->cache->get( $fileUrl );
46
		}
47 1
		catch ( CacheException $ex ) {
48 1
			return null;
49
		}
50
	}
51
52 5
	private function retrieveAndCacheFile( $fileUrl ): string {
53 5
		$fileContents = $this->fileFetcher->fetchFile( $fileUrl );
54
55
		try {
56 4
			$this->cache->set( $fileUrl, $fileContents );
57
		}
58 1
		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 4
		return $fileContents;
62
	}
63
64
}
65