This repository has been archived by the owner on Jan 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
markdown.php
112 lines (99 loc) · 2.82 KB
/
markdown.php
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
declare(strict_types=1);
namespace herbie\plugin\markdown;
use Herbie\Config;
use Herbie\Event;
use Herbie\EventManager;
use Herbie\PluginInterface;
use Herbie\StringValue;
class MarkdownPlugin implements PluginInterface
{
/**
* @var Config
*/
private $config;
/**
* MarkdownPlugin constructor.
* @param Config $config
*/
public function __construct(Config $config)
{
$this->config = $config;
}
/**
* @param EventManager $events
* @param int $priority
*/
public function attach(EventManager $events, int $priority = 1): void
{
// add twig function / filter
if ((bool)$this->config->plugins->markdown->twig) {
$events->attach('onTwigInitialized', [$this, 'onTwigInitialized'], $priority);
}
// add shortcode
if ((bool)$this->config->get('plugins.config.markdown.shortcode', true)) {
$events->attach('onShortcodeInitialized', [$this, 'onShortcodeInitialized'], $priority);
}
$events->attach('onRenderContent', [$this, 'onRenderContent'], $priority);
}
/**
* @param Event $event
*/
public function onTwigInitialized(Event $event)
{
/** @var Twig_Environment $twig */
$twig = $event->getTarget();
$options = ['is_safe' => ['html']];
$twig->addFunction(
new \Twig_SimpleFunction('markdown', [$this, 'parseMarkdown'], $options)
);
$twig->addFilter(
new \Twig_SimpleFilter('markdown', [$this, 'parseMarkdown'], $options)
);
}
/**
* @param Event $event
* @throws \Exception
*/
public function onRenderContent(Event $event)
{
if (!in_array($event->getParam('format'), ['markdown', 'md'])) {
return;
}
/** @var StringValue $stringValue */
$stringValue = $event->getTarget();
$parsed = $this->parseMarkdown($stringValue->get());
$stringValue->set($parsed);
}
/**
* @param Event $event
*/
public function onShortcodeInitialized(Event $event)
{
/** @var \herbie\plugin\shortcode\classes\Shortcode $shortcode */
$shortcode = $event->getTarget();
$shortcode->add('markdown', [$this, 'markdownShortcode']);
}
/**
* @param string $string
* @return string
* @throws \Exception
*/
public function parseMarkdown(string $string): string
{
$parser = new \ParsedownExtra();
$parser->setUrlsLinked(false);
$html = $parser->text($string);
return $html;
}
/**
* @param mixed $attribs
* @param string $content
* @return string
* @throws \Exception
*/
public function markdownShortcode($attribs, string $content): string
{
return $this->parseMarkdown($content);
}
}