1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace JPBernius\FMeat\Services; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Client as HttpClient; |
6
|
|
|
use JPBernius\FMeat\Utilities\UrlBuilder; |
7
|
|
|
use JPBernius\FMeat\Entities\{ |
8
|
|
|
CalendarWeek, |
9
|
|
|
Week |
10
|
|
|
}; |
11
|
|
|
use Stash\Driver\FileSystem as FileSystemDriver; |
12
|
|
|
use Stash\Pool as CachePool; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Class CachedNetworkService |
16
|
|
|
* @package JPBernius\FMeat\Services |
17
|
|
|
*/ |
18
|
|
|
class CachedNetworkService extends NetworkService |
19
|
|
|
{ |
20
|
|
|
/** @var CachePool */ |
21
|
|
|
private $pool; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* CachedNetworkService constructor. |
25
|
|
|
* @param HttpClient $httpClient |
26
|
|
|
* @param UrlBuilder $urlBuilder |
27
|
|
|
* @param FileSystemDriver $fileSystemDriver |
28
|
|
|
* @param CachePool $pool |
29
|
|
|
*/ |
30
|
|
|
public function __construct(HttpClient $httpClient, UrlBuilder $urlBuilder, |
31
|
|
|
FileSystemDriver $fileSystemDriver, CachePool $pool) |
32
|
|
|
{ |
33
|
|
|
parent::__construct($httpClient, $urlBuilder); |
34
|
|
|
|
35
|
|
|
$pool->setDriver($fileSystemDriver); |
36
|
|
|
$this->pool = $pool; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param CalendarWeek $calendarWeek |
41
|
|
|
* @param string $location |
42
|
|
|
* @return Week |
43
|
|
|
* @throws \JPBernius\FMeat\Exeptions\NetworkingException |
44
|
|
|
*/ |
45
|
|
|
public function getWeekWithLocation(CalendarWeek $calendarWeek, string $location): Week |
46
|
|
|
{ |
47
|
|
|
$cacheKey = $this->buildCacheKey($location, $calendarWeek); |
48
|
|
|
$cacheItem = $this->pool->getItem($cacheKey); |
49
|
|
|
|
50
|
|
|
if($cacheItem->isHit()) { |
51
|
|
|
$jsonString = $cacheItem->get(); |
52
|
|
|
$jsonObject = json_decode($jsonString); |
53
|
|
|
|
54
|
|
|
return Week::fromJson($jsonObject); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
$retrievedWeek = parent::getWeekWithLocation($calendarWeek, $location); |
58
|
|
|
|
59
|
|
|
$retrievedWeekJson = json_encode($retrievedWeek); |
60
|
|
|
$this->pool->save($cacheItem->set($retrievedWeekJson)); |
61
|
|
|
|
62
|
|
|
return $retrievedWeek; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param string $location |
67
|
|
|
* @param CalendarWeek $calendarWeek |
68
|
|
|
* @return string |
69
|
|
|
*/ |
70
|
|
|
private function buildCacheKey(string $location, CalendarWeek $calendarWeek): string |
71
|
|
|
{ |
72
|
|
|
return sprintf('%s/%s/%s', $location, $calendarWeek->getYear(), $calendarWeek->getWeek()); |
73
|
|
|
} |
74
|
|
|
} |