-
-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathDocsContent.php
More file actions
99 lines (83 loc) · 2.17 KB
/
Copy pathDocsContent.php
File metadata and controls
99 lines (83 loc) · 2.17 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
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
<?php
namespace App\View\Components;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Str;
use Illuminate\View\Component;
use JoliTypo\Fixer;
use Symfony\Component\DomCrawler\Crawler;
class DocsContent extends Component implements Htmlable
{
/**
* @var string
*/
protected $content;
/**
* Create a new component instance.
*
* @return void
*/
public function __construct(string $content)
{
$this->content = $content;
}
/**
* Get the view / contents that represent the component.
*
* @return \App\View\Components\DocsContent
*
* @throws \DOMException
*/
public function render()
{
return $this;
}
/**
* @param $contents
* @return string
*
* @throws \DOMException
*/
private function detectAnchors()
{
$crawler = new Crawler();
$crawler->addContent($this->content);
$crawler
->filter('h2,h3,h4,h5,h6')
->each(function (Crawler $elm) use (&$anchors) {
/** @var \DOMElement $node */
$node = $elm->getNode(0);
$content = $node->textContent;
$id = Str::slug($content);
$tag = $node->nodeName;
$this->content = Str::of($this->content)
->replace("<$tag>$content</$tag>", "<$tag><a href='#$id' id='$id'>$content</a></$tag>");
});
$fixer = new Fixer([
'Ellipsis',
'Dimension',
'Unit',
'Dash',
'SmartQuotes',
'NoSpaceBeforeComma',
'CurlyQuote',
'Trademark',
]);
$crawler
->filter('p,li')
->each(function (Crawler $elm) use ($fixer) {
$content = $elm->html();
$paragraph = $fixer->fix($content);
$this->content = Str::of($this->content)->replace($content, $paragraph);
});
return $this->content;
}
/**
* @return string
*
* @throws \DOMException
*/
public function toHtml(): string
{
return $this->detectAnchors();
}
}