generated from spatie/package-skeleton-laravel
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathFragment.php
110 lines (83 loc) · 3.05 KB
/
Fragment.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
<?php
namespace Tonysm\RichTextLaravel;
use DOMDocument;
use DOMNode;
use DOMXPath;
use Illuminate\Support\Collection;
class Fragment
{
private $cachedPlainText;
private $cachedHtml;
public static function wrap(string|Fragment|DOMDocument $fragmentOrHtml)
{
if ($fragmentOrHtml instanceof Fragment) {
return $fragmentOrHtml;
}
if ($fragmentOrHtml instanceof DOMDocument) {
return new static($fragmentOrHtml);
}
return static::fromHtml($fragmentOrHtml);
}
public static function fromHtml(?string $html = null): self
{
return HtmlConversion::fragmentForHtml($html);
}
public function __construct(public DOMDocument $source) {}
public function findAll(string $selector): Collection
{
$xpath = new DOMXPath($this->source);
$elements = $xpath->query($selector);
if ($elements === false) {
return collect([]);
}
$result = collect([]);
foreach ($elements as $element) {
$result->add($element);
}
return $result;
}
public function update(?callable $callback = null): static
{
$callback = $callback ?: fn ($source) => $source;
return new static($callback($this->source->cloneNode(deep: true)));
}
public function replace(string $selector, callable $callback): static
{
$fragment = $this->update();
$fragment->findAll($selector)
->each(function (DOMNode $node) use ($callback) {
$value = $callback($node);
if ($value instanceof Fragment) {
// Each fragment source is wrapped in a div, so we can ignore it when appending.
$newNode = $value->source;
foreach ($newNode->firstChild->childNodes as $child) {
if ($importedNode = $node->ownerDocument->importNode($child, deep: true)) {
$node->parentNode->insertBefore($importedNode, $node);
}
}
$node->parentNode->removeChild($node);
} elseif (is_string($value)) {
$newNode = $node->ownerDocument->createTextNode($value);
$node->parentNode->replaceChild($newNode, $node);
} elseif ($value instanceof Attachment) {
if ($importedNode = $node->ownerDocument->importNode($value->node, deep: true)) {
$node->parentNode->insertBefore($importedNode, $node);
}
$node->parentNode->removeChild($node);
}
});
return $fragment;
}
public function toPlainText(): string
{
return $this->cachedPlainText ??= PlainTextConversion::nodeToPlainText($this->source);
}
public function toHtml(): string
{
return $this->cachedHtml ??= HtmlConversion::nodeToHtml($this->source);
}
public function __toString(): string
{
return $this->toHtml();
}
}