MarkdownConverter.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of the league/commonmark package.
  5. *
  6. * (c) Colin O'Dell <colinodell@gmail.com>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace League\CommonMark;
  12. use League\CommonMark\Environment\EnvironmentInterface;
  13. use League\CommonMark\Exception\CommonMarkException;
  14. use League\CommonMark\Output\RenderedContentInterface;
  15. use League\CommonMark\Parser\MarkdownParser;
  16. use League\CommonMark\Parser\MarkdownParserInterface;
  17. use League\CommonMark\Renderer\HtmlRenderer;
  18. use League\CommonMark\Renderer\MarkdownRendererInterface;
  19. class MarkdownConverter implements ConverterInterface, MarkdownConverterInterface
  20. {
  21. /** @psalm-readonly */
  22. protected EnvironmentInterface $environment;
  23. /** @psalm-readonly */
  24. protected MarkdownParserInterface $markdownParser;
  25. /** @psalm-readonly */
  26. protected MarkdownRendererInterface $htmlRenderer;
  27. public function __construct(EnvironmentInterface $environment)
  28. {
  29. $this->environment = $environment;
  30. $this->markdownParser = new MarkdownParser($environment);
  31. $this->htmlRenderer = new HtmlRenderer($environment);
  32. }
  33. public function getEnvironment(): EnvironmentInterface
  34. {
  35. return $this->environment;
  36. }
  37. /**
  38. * Converts Markdown to HTML.
  39. *
  40. * @param string $input The Markdown to convert
  41. *
  42. * @return RenderedContentInterface Rendered HTML
  43. *
  44. * @throws CommonMarkException
  45. */
  46. public function convert(string $input): RenderedContentInterface
  47. {
  48. $documentAST = $this->markdownParser->parse($input);
  49. return $this->htmlRenderer->renderDocument($documentAST);
  50. }
  51. /**
  52. * Converts Markdown to HTML.
  53. *
  54. * @deprecated since 2.2; use {@link convert()} instead
  55. *
  56. * @param string $markdown The Markdown to convert
  57. *
  58. * @return RenderedContentInterface Rendered HTML
  59. *
  60. * @throws CommonMarkException
  61. */
  62. public function convertToHtml(string $markdown): RenderedContentInterface
  63. {
  64. \trigger_deprecation('league/commonmark', '2.2.0', 'Calling "convertToHtml()" on a %s class is deprecated, use "convert()" instead.', self::class);
  65. return $this->convert($markdown);
  66. }
  67. /**
  68. * Converts CommonMark to HTML.
  69. *
  70. * @see MarkdownConverter::convert()
  71. *
  72. * @throws CommonMarkException
  73. */
  74. public function __invoke(string $markdown): RenderedContentInterface
  75. {
  76. return $this->convert($markdown);
  77. }
  78. }