1
0
mirror of https://github.com/erusev/parsedown.git synced 2023-08-10 21:13:06 +03:00

Replacing all function to TransformableRenderable

This commit is contained in:
Aidan Woods 2021-10-13 19:26:07 +01:00
parent a9f41548d3
commit e9dec33dc6
No known key found for this signature in database
GPG Key ID: 9A6A8EFAA512BBB9
4 changed files with 85 additions and 1 deletions

View File

@ -15,7 +15,7 @@ final class Container implements TransformableRenderable
/**
* @param Renderable[] $Contents
*/
public function __construct($Contents)
public function __construct($Contents = [])
{
$this->Contents = $Contents;
}
@ -67,4 +67,18 @@ final class Container implements TransformableRenderable
$this->Contents
));
}
public function replacingAll(string $search, Renderable $Replacement): Renderable
{
return new Container(\array_map(
function (Renderable $R) use ($search, $Replacement): Renderable {
if (! $R instanceof TransformableRenderable) {
return $R;
}
return $R->replacingAll($search, $Replacement);
},
$this->Contents
));
}
}

View File

@ -214,4 +214,22 @@ final class Element implements TransformableRenderable
$this->Contents
));
}
public function replacingAll(string $search, Renderable $Replacement): Renderable
{
if (! isset($this->Contents)) {
return $this;
}
return new self($this->name, $this->attributes, \array_map(
function (Renderable $R) use ($search, $Replacement): Renderable {
if (! $R instanceof TransformableRenderable) {
return $R;
}
return $R->replacingAll($search, $Replacement);
},
$this->Contents
));
}
}

View File

@ -41,4 +41,50 @@ final class Text implements TransformableRenderable
{
return $Transform($this->text);
}
public function replacingAll(string $search, Renderable $Replacement): Renderable
{
$searchLen = \strlen($search);
if ($searchLen < 1) {
return $this;
}
$result = \preg_match_all(
'/\b'.\preg_quote($search, '/').'\b/',
$this->text,
$matches,
\PREG_OFFSET_CAPTURE
);
if (empty($result)) {
return $this;
}
$lastEndPos = 0;
$Container = new Container;
foreach ($matches[0] as $match) {
$pos = $match[1];
$endPos = $pos + $searchLen;
if ($pos !== $lastEndPos) {
$Container = $Container->adding(
new Text(\substr($this->text, $lastEndPos, $pos - $lastEndPos))
);
}
$Container = $Container->adding($Replacement);
$lastEndPos = $endPos;
}
if (\strlen($this->text) -1 !== $lastEndPos) {
$Container = $Container->adding(
new Text(\substr($this->text, $lastEndPos))
);
}
return $Container;
}
}

View File

@ -22,4 +22,10 @@ interface TransformableRenderable extends Renderable
* @return Renderable
*/
public function transformingContent(\Closure $Transform): Renderable;
/**
* Similar to transformingContent, but replace the string $search in text content
* with the renderable $Replacement and return the result.
*/
public function replacingAll(string $search, Renderable $Replacement): Renderable;
}