|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* @author Matthias Glaub <[email protected]> |
|
5
|
|
|
*/ |
|
6
|
|
|
|
|
7
|
|
|
namespace MaglMarkdown\Cache; |
|
8
|
|
|
|
|
9
|
|
|
use Zend\Cache\Storage\StorageInterface; |
|
10
|
|
|
use Zend\EventManager\Event; |
|
11
|
|
|
use Zend\EventManager\EventManagerInterface; |
|
12
|
|
|
use Zend\EventManager\ListenerAggregateInterface; |
|
13
|
|
|
use Zend\EventManager\ListenerAggregateTrait; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Class CacheListener |
|
17
|
|
|
* |
|
18
|
|
|
* @package MaglMarkdown\Cache |
|
19
|
|
|
*/ |
|
20
|
|
|
class CacheListener implements ListenerAggregateInterface |
|
21
|
|
|
{ |
|
22
|
|
|
|
|
23
|
|
|
use ListenerAggregateTrait; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* |
|
27
|
|
|
* @var StorageInterface |
|
28
|
|
|
*/ |
|
29
|
|
|
private $cache; |
|
30
|
|
|
|
|
31
|
2 |
|
public function __construct(StorageInterface $cache) |
|
32
|
|
|
{ |
|
33
|
2 |
|
$this->cache = $cache; |
|
34
|
2 |
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* @param EventManagerInterface $events |
|
38
|
|
|
* @param int $priority |
|
39
|
|
|
*/ |
|
40
|
1 |
|
public function attach(EventManagerInterface $events, $priority = 1) |
|
41
|
|
|
{ |
|
42
|
1 |
|
$this->listeners[] = $events->attach('markdown.render.pre', [$this, 'preRender'], $priority); |
|
43
|
1 |
|
$this->listeners[] = $events->attach('markdown.render.post', [$this, 'postRender'], $priority); |
|
44
|
1 |
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* Searches the cache for rendered markdown. |
|
48
|
|
|
* |
|
49
|
|
|
* @param \Zend\EventManager\Event $event |
|
50
|
|
|
* @return mixed the rendered markdown, if found, false otherwise |
|
51
|
|
|
* @throws \Zend\Cache\Exception\ExceptionInterface |
|
52
|
|
|
*/ |
|
53
|
1 |
|
public function preRender(Event $event) |
|
54
|
|
|
{ |
|
55
|
1 |
|
$markdown = $event->getParam('markdown'); |
|
56
|
|
|
|
|
57
|
1 |
|
$markdownHash = md5($markdown); |
|
58
|
|
|
|
|
59
|
1 |
|
$success = false; |
|
60
|
1 |
|
$renderedMarkdown = $this->cache->getItem($markdownHash, $success); |
|
61
|
1 |
|
if ($success) { |
|
62
|
1 |
|
$event->stopPropagation(true); |
|
63
|
|
|
|
|
64
|
1 |
|
return $renderedMarkdown; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
1 |
|
return false; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
/** |
|
71
|
|
|
* Saves the rendered markdown within the cache. |
|
72
|
|
|
* |
|
73
|
|
|
* @param \Zend\EventManager\Event $event |
|
74
|
|
|
* @return mixed |
|
75
|
|
|
* @throws \Zend\Cache\Exception\ExceptionInterface |
|
76
|
|
|
*/ |
|
77
|
1 |
|
public function postRender(Event $event) |
|
78
|
|
|
{ |
|
79
|
1 |
|
$markdown = $event->getParam('markdown'); |
|
80
|
1 |
|
$renderedMarkdown = $event->getParam('renderedMarkdown'); |
|
81
|
|
|
|
|
82
|
1 |
|
$markdownHash = md5($markdown); |
|
83
|
|
|
|
|
84
|
1 |
|
return $this->cache->setItem($markdownHash, $renderedMarkdown); |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|