|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace PPP\Wikidata\Cache; |
|
4
|
|
|
|
|
5
|
|
|
use Doctrine\Common\Cache\Cache; |
|
6
|
|
|
use OutOfBoundsException; |
|
7
|
|
|
use PPP\Wikidata\Wikipedia\SiteLinkProvider; |
|
8
|
|
|
use RuntimeException; |
|
9
|
|
|
use Wikibase\DataModel\SiteLink; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Cache whose keys are based on SiteLink |
|
13
|
|
|
* |
|
14
|
|
|
* @licence GPLv2+ |
|
15
|
|
|
* @author Thomas Pellissier Tanon |
|
16
|
|
|
*/ |
|
17
|
|
|
class PerSiteLinkCache { |
|
18
|
|
|
|
|
19
|
|
|
const CACHE_ID_PREFIX = 'ppp-wd-pslc-'; |
|
20
|
|
|
|
|
21
|
|
|
const CACHE_LIFE_TIME = 86400; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @var Cache |
|
25
|
|
|
*/ |
|
26
|
|
|
private $cache; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @var string |
|
30
|
|
|
*/ |
|
31
|
|
|
private $name; |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @param Cache $cache |
|
35
|
|
|
* @param string $name |
|
36
|
|
|
*/ |
|
37
|
3 |
|
public function __construct(Cache $cache, $name) { |
|
38
|
3 |
|
$this->cache = $cache; |
|
39
|
3 |
|
$this->name = $name; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @param SiteLink $siteLink |
|
44
|
|
|
* @return SiteLinkProvider |
|
45
|
|
|
*/ |
|
46
|
2 |
|
public function fetch(SiteLink $siteLink) { |
|
47
|
|
|
$result = $this->cache->fetch($this->getCacheId($siteLink)); |
|
48
|
|
|
|
|
49
|
2 |
|
if($result === false) { |
|
50
|
|
|
throw new OutOfBoundsException('The search is not in the cache.'); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
1 |
|
return $result; |
|
54
|
2 |
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* @param SiteLink $siteLink |
|
58
|
|
|
* @return bool |
|
59
|
|
|
*/ |
|
60
|
2 |
|
public function contains(SiteLink $siteLink) { |
|
61
|
|
|
return $this->cache->contains($this->getCacheId($siteLink)); |
|
62
|
2 |
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* @param SiteLinkProvider $value |
|
66
|
|
|
*/ |
|
67
|
3 |
|
public function save(SiteLinkProvider $value) { |
|
68
|
3 |
|
if(!$this->cache->save( |
|
69
|
|
|
$this->getCacheId($value->getSiteLink()), |
|
70
|
|
|
$value, |
|
71
|
3 |
|
self::CACHE_LIFE_TIME |
|
72
|
|
|
)) { |
|
73
|
|
|
throw new RuntimeException('The cache failed to save.'); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
1 |
|
private function getCacheId(SiteLink $siteLink) { |
|
78
|
|
|
return self::CACHE_ID_PREFIX . '-' . $this->name . '-' . $siteLink->getSiteId() . '-' . md5($this->normalizeTitle($siteLink->getPageName())); |
|
79
|
1 |
|
} |
|
80
|
|
|
|
|
81
|
|
|
private function normalizeTitle($title) { |
|
82
|
|
|
return str_replace('_', ' ', $title); |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|