Skip to content

Commit eb1682a

Browse files
committed
Add function to find links and parse index
1 parent 4b9c631 commit eb1682a

File tree

1 file changed

+57
-2
lines changed

1 file changed

+57
-2
lines changed

classes/TOCTrait.php

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,29 @@ protected function findHeadlines($markdown, $fromLevel = 1, $toLevel = 6) {
6767
return $headlines;
6868
}
6969

70+
/**
71+
* @param string $markdown
72+
* @param callable $filter
73+
* @return array
74+
*/
75+
public function findLinks($markdown, $filter = NULL) {
76+
if ( ! $filter) {
77+
$filter = function() { return TRUE; };
78+
}
79+
elseif ( ! is_callable($filter)) {
80+
throw new InvalidArgumentException('Expected 2nd argument to be a callable function');
81+
}
82+
$this->prepareMarkers($markdown);
83+
$content = $this->parseInline($markdown);
84+
$links = [];
85+
foreach ($content as $item) {
86+
if ($this->isItemOfType($item, 'link') && $filter($item['url'])) {
87+
$links[] = $item;
88+
}
89+
}
90+
return $links;
91+
}
92+
7093
/**
7194
* @param string $markdown markdown source.
7295
* @param string $url source URL.
@@ -113,6 +136,25 @@ protected function isItemOfType( & $item, $type) {
113136
return isset($item[0]) && $item[0] === $type;
114137
}
115138

139+
/**
140+
* @param string $markdown
141+
* @param string $baseUrl
142+
* @param callable $linkFilter
143+
* @return array
144+
*/
145+
public function parseIndex($markdown, $baseUrl = '', $linkFilter = NULL) {
146+
$headlines = $this->findHeadlines($markdown);
147+
$firstHeadline = isset($headlines[0]['content']) ? $this->renderAbsy($headlines[0]['content']) : NULL;
148+
$links = [];
149+
foreach ($this->findLinks($markdown, $linkFilter) as $link) {
150+
$links[] = [
151+
'url' => $baseUrl.$link['url'],
152+
'text' => $this->renderAbsy($link['text']),
153+
];
154+
}
155+
return ['title' => $firstHeadline, 'links' => $links];
156+
}
157+
116158
/**
117159
* @param array $headlines
118160
* @param string $url
@@ -244,12 +286,25 @@ protected static function webalize($s, $charlist = NULL, $lower = TRUE) {
244286
}
245287

246288
/**
247-
* @param array $lines
289+
* @param array $lines
290+
* @return array
248291
*/
249292
abstract protected function parseBlocks($lines);
250293

251294
/**
252-
* @param array $blocks
295+
* @param string $text
296+
* @return array
297+
*/
298+
abstract protected function parseInline($text);
299+
300+
/**
301+
* @param array $markdown
302+
*/
303+
abstract protected function prepareMarkers($markdown);
304+
305+
/**
306+
* @param array $blocks
307+
* @return string
253308
*/
254309
abstract protected function renderAbsy($blocks);
255310
}

0 commit comments

Comments
 (0)