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

Implement Emphasis

This commit is contained in:
Aidan Woods 2019-01-20 02:34:41 +00:00
parent f2a3a2fb08
commit 164a39f3e9
No known key found for this signature in database
GPG Key ID: 9A6A8EFAA512BBB9
2 changed files with 86 additions and 29 deletions

View File

@ -0,0 +1,86 @@
<?php
namespace Erusev\Parsedown\Components\Inlines;
use Erusev\Parsedown\AST\Handler;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Inline;
use Erusev\Parsedown\Html\Renderables\Element;
use Erusev\Parsedown\Html\Renderables\Text;
use Erusev\Parsedown\Parsedown;
use Erusev\Parsedown\Parsing\Excerpt;
use Erusev\Parsedown\State;
final class Emphasis implements Inline
{
use WidthTrait, DefaultBeginPosition;
/** @var string */
private $text;
/** @var 'em'|'strong' */
private $type;
const STRONG_REGEX = [
'*' => '/^[*]{2}((?:\\\\\*|[^*]|[*][^*]*+[*])+?)[*]{2}(?![*])/s',
'_' => '/^__((?:\\\\_|[^_]|_[^_]*+_)+?)__(?!_)/us',
];
const EM_REGEX = [
'*' => '/^[*]((?:\\\\\*|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s',
'_' => '/^_((?:\\\\_|[^_]|__[^_]*__)+?)_(?!_)\b/us',
];
/**
* @param string $text
* @param 'em'|'strong' $type
* @param int $width
*/
public function __construct($text, $type, $width)
{
$this->text = $text;
$this->type = $type;
$this->width = $width;
}
/**
* @param Excerpt $Excerpt
* @param State $State
* @return static|null
*/
public static function build(Excerpt $Excerpt, State $State)
{
if (! isset($Excerpt->text()[1])) {
return null;
}
$marker = $Excerpt->text()[0] === '*' ? '*' : '_';
if ($Excerpt->text()[1] === $marker and \preg_match(self::STRONG_REGEX[$marker], $Excerpt->text(), $matches)) {
$emphasis = 'strong';
} elseif (\preg_match(self::EM_REGEX[$marker], $Excerpt->text(), $matches)) {
$emphasis = 'em';
} else {
return null;
}
return new self($matches[1], $emphasis, \strlen($matches[0]));
}
/**
* @return Handler<Element>
*/
public function stateRenderable(Parsedown $Parsedown)
{
return new Handler(
/** @return Element */
function (State $State) use ($Parsedown) {
return new Element(
$this->type,
[],
$State->applyTo($Parsedown->lineElements($this->text))
);
}
);
}
}

View File

@ -411,35 +411,6 @@ class Parsedown
return $Elements;
}
protected function inlineEmphasis($Excerpt)
{
if (! isset($Excerpt['text'][1])) {
return;
}
$marker = $Excerpt['text'][0];
if ($Excerpt['text'][1] === $marker and \preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches)) {
$emphasis = 'strong';
} elseif (\preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches)) {
$emphasis = 'em';
} else {
return;
}
return [
'extent' => \strlen($matches[0]),
'element' => [
'name' => $emphasis,
'handler' => [
'function' => 'lineElements',
'argument' => $matches[1],
'destination' => 'elements',
]
],
];
}
protected function inlineEscapeSequence($Excerpt)
{
if (isset($Excerpt['text'][1]) and \in_array($Excerpt['text'][1], $this->specialCharacters, true)) {