Implement Image

This commit is contained in:
Aidan Woods 2019-01-20 02:35:51 +00:00
parent dad0088adb
commit 5e8905c455
No known key found for this signature in database
GPG Key ID: 9A6A8EFAA512BBB9
2 changed files with 81 additions and 33 deletions

View File

@ -0,0 +1,81 @@
<?php
namespace Erusev\Parsedown\Components\Inlines;
use Erusev\Parsedown\AST\Handler;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Inline;
use Erusev\Parsedown\Configurables\SafeMode;
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;
/** @psalm-type _Metadata=array{href: string, title?: string} */
final class Image implements Inline
{
use WidthTrait, DefaultBeginPosition;
/** @var Link */
private $Link;
/**
* @param Link $Link
*/
public function __construct(Link $Link)
{
$this->Link = $Link;
$this->width = $Link->width() + 1;
}
/**
* @param Excerpt $Excerpt
* @param State $State
* @return static|null
*/
public static function build(Excerpt $Excerpt, State $State)
{
if (\substr($Excerpt->text(), 0, 1) !== '!') {
return null;
}
$Excerpt = $Excerpt->addingToOffset(1);
$Link = Link::build($Excerpt, $State);
if (! isset($Link)) {
return null;
}
return new self($Link);
}
/**
* @return Handler<Element|Text>
*/
public function stateRenderable(Parsedown $Parsedown)
{
return new Handler(
/** @return Element|Text */
function (State $State) use ($Parsedown) {
$linkAttributes = $this->Link->attributes();
$attributes = [
'src' => $linkAttributes['href'],
'alt' => $this->Link->label(),
];
if (isset($linkAttributes['title'])) {
$attributes['title'] = $linkAttributes['title'];
}
if ($State->getOrDefault(SafeMode::class)->enabled()) {
$attributes['src'] = Element::filterUnsafeUrl($attributes['src']);
}
return Element::selfClosing('img', $attributes);
}
);
}
}

View File

@ -411,39 +411,6 @@ class Parsedown
return $Elements; return $Elements;
} }
protected function inlineImage($Excerpt)
{
if (! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[') {
return;
}
$Excerpt['text']= \substr($Excerpt['text'], 1);
$Link = $this->inlineLink($Excerpt);
if ($Link === null) {
return;
}
$Inline = [
'extent' => $Link['extent'] + 1,
'element' => [
'name' => 'img',
'attributes' => [
'src' => $Link['element']['attributes']['href'],
'alt' => $Link['element']['handler']['argument'],
],
'autobreak' => true,
],
];
$Inline['element']['attributes'] += $Link['element']['attributes'];
unset($Inline['element']['attributes']['href']);
return $Inline;
}
protected function inlineMarkup($Excerpt) protected function inlineMarkup($Excerpt)
{ {
if ($this->markupEscaped or $this->safeMode or \strpos($Excerpt['text'], '>') === false) { if ($this->markupEscaped or $this->safeMode or \strpos($Excerpt['text'], '>') === false) {