我正在使用联盟的CommonMark package,并创建自定义扩展程序以使用自定义标记降价显示<img>
代码,如下所示:@image(image_id)
。
标记为:@image(image_id)
我预期的结果:
<figure>
<img src="image_url" alt="image_alt"></img>
</figure>
我试过的代码:ImageParser.php
<?php
namespace App\Markdown\Extensions\Image;
use League\CommonMark\Inline\Element\HtmlInline;
use League\CommonMark\Inline\Parser\AbstractInlineParser;
use League\CommonMark\InlineParserContext;
use App\Storage\Image;
class ImageParser extends AbstractInlineParser
{
/**
* @return string[]
*/
public function getCharacters()
{
return ['@'];
}
/**
* @param InlineParserContext $inlineContext
*
* @return bool
*/
public function parse(InlineParserContext $inlineContext)
{
$cursor = $inlineContext->getCursor();
$previous = $cursor->peek(-1);
if ($previous !== null && $previous !== ' ') {
return false;
}
$previousState = $cursor->saveState();
$cursor->advance();
$handle = $cursor->match('/image\((\d+)\)/');
if (empty($handle)) {
$cursor->restoreState($previousState);
return false;
}
$imageId = preg_replace("/image\((\d+)\)/", "$1", $handle);
$image = Image::find($imageId);
if (is_null($image)) {
return false;
}
$inlineContext->getContainer()->appendChild(new HtmlInline($this->render($image)));
return true;
}
/**
* Render the image figure.
*
* @param \PYM\Storage\Image $image
*
* @return string
*/
protected function render(Image $image)
{
$source = empty($image->source) ? null : "<figcaption>{$image->source}</figcaption>";
return '<figure><img src="' . $image->getUrl('wide') . '" alt="' . $image->alt_tag . '">' . $source . '</figure>';
}
}
测试代码:ImageExtensionText.php
<?php
namespace Tests\Unit\Markdown;
use Tests\TestCase;
class ImageExtensionTest extends TestCase
{
/** @test */
public function converts_to_a_image_tag()
{
$image = factoryImage();
$string = \Markdown::convertToHtml("First paragraph
@image({$image->id})
Last paragraph");
dd($string);
$expected = '<img src="'.$image->getUrl('wide').'" alt="'.$image->alt_tag.'">';
$this->assertEquals($string, $expected);
}
}
测试文件@image(image_id)
上的始终在<p></p>
标记内返回,这不是我预期的结果。