1<?php
2
3/*
4 * This file is part of the league/commonmark package.
5 *
6 * (c) Colin O'Dell <colinodell@gmail.com>
7 *
8 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js)
9 *  - (c) John MacFarlane
10 *
11 * For the full copyright and license information, please view the LICENSE
12 * file that was distributed with this source code.
13 */
14
15namespace League\CommonMark\Extension\Mention;
16
17use League\CommonMark\Inline\Element\Link;
18use League\CommonMark\Inline\Element\Text;
19
20class Mention extends Link
21{
22    /** @var string */
23    private $symbol;
24
25    /** @var string */
26    private $identifier;
27
28    /**
29     * @param string $symbol
30     * @param string $identifier
31     * @param string $label
32     */
33    public function __construct(string $symbol, string $identifier, string $label = null)
34    {
35        $this->symbol = $symbol;
36        $this->identifier = $identifier;
37
38        parent::__construct('', $label ?? \sprintf('%s%s', $symbol, $identifier));
39    }
40
41    /**
42     * @return string|null
43     */
44    public function getLabel(): ?string
45    {
46        if (($labelNode = $this->findLabelNode()) === null) {
47            return null;
48        }
49
50        return $labelNode->getContent();
51    }
52
53    /**
54     * @return string
55     */
56    public function getIdentifier(): string
57    {
58        return $this->identifier;
59    }
60
61    /**
62     * @return string
63     */
64    public function getSymbol(): string
65    {
66        return $this->symbol;
67    }
68
69    /**
70     * @return bool
71     */
72    public function hasUrl(): bool
73    {
74        return !empty($this->url);
75    }
76
77    /**
78     * @param string $label
79     *
80     * @return $this
81     */
82    public function setLabel(string $label): self
83    {
84        if (($labelNode = $this->findLabelNode()) === null) {
85            $labelNode = new Text();
86            $this->prependChild($labelNode);
87        }
88
89        $labelNode->setContent($label);
90
91        return $this;
92    }
93
94    private function findLabelNode(): ?Text
95    {
96        foreach ($this->children() as $child) {
97            if ($child instanceof Text) {
98                return $child;
99            }
100        }
101
102        return null;
103    }
104}
105