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