This repository was archived by the owner on Jan 30, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHighlightEventSubscriber.php
More file actions
66 lines (51 loc) · 1.6 KB
/
HighlightEventSubscriber.php
File metadata and controls
66 lines (51 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
namespace Carew\Plugin\Highlight;
use Carew\Event\Events;
use Carew\Document;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class HighlightEventSubscriber implements EventSubscriberInterface
{
private $highlighter;
public function __construct(HighlighterInterface $highlighter)
{
$this->highlighter = $highlighter;
}
public function onDocument($event)
{
$document = $event->getSubject();
if (Document::TYPE_POST == $document->getType()) {
$this->highlight($document);
} elseif (Document::TYPE_PAGE == $document->getType()) {
$this->highlight($document);
}
}
public static function getSubscribedEvents()
{
return array(
Events::DOCUMENT => array(
array('onDocument', 256),
),
);
}
private function highlight($document)
{
$body = $document->getBody();
if (preg_match('/^(\s|\n)+$/', $body)) {
return;
}
$body = preg_replace_callback('#<pre><code>(.*)</code></pre>#sU', array($this,'doHighlight'), $body);
$document->setBody($body);
}
private function doHighlight($matches)
{
$code = $matches[1];
list($language) = preg_split("/[\s,]+/", $code, 2);
if (!$this->highlighter->support($language)) {
return $matches[0];
}
$code = substr_replace($code, '', 0, strlen($language));
$code = html_entity_decode($code);
$code = trim($code);
return $this->highlighter->highlight($code, $language);
}
}