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 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js)
11 *  - (c) John MacFarlane
12 *
13 * For the full copyright and license information, please view the LICENSE
14 * file that was distributed with this source code.
15 */
16
17namespace League\CommonMark\Extension\Mention;
18
19use League\CommonMark\Extension\CommonMark\Node\Inline\Link;
20use League\CommonMark\Node\Inline\Text;
21
22class Mention extends Link
23{
24    private string $name;
25
26    private string $prefix;
27
28    private string $identifier;
29
30    public function __construct(string $name, string $prefix, string $identifier, ?string $label = null)
31    {
32        $this->name       = $name;
33        $this->prefix     = $prefix;
34        $this->identifier = $identifier;
35
36        parent::__construct('', $label ?? \sprintf('%s%s', $prefix, $identifier));
37    }
38
39    public function getLabel(): ?string
40    {
41        if (($labelNode = $this->findLabelNode()) === null) {
42            return null;
43        }
44
45        return $labelNode->getLiteral();
46    }
47
48    public function getIdentifier(): string
49    {
50        return $this->identifier;
51    }
52
53    public function getName(): ?string
54    {
55        return $this->name;
56    }
57
58    public function getPrefix(): string
59    {
60        return $this->prefix;
61    }
62
63    public function hasUrl(): bool
64    {
65        return $this->url !== '';
66    }
67
68    /**
69     * @return $this
70     */
71    public function setLabel(string $label): self
72    {
73        if (($labelNode = $this->findLabelNode()) === null) {
74            $labelNode = new Text();
75            $this->prependChild($labelNode);
76        }
77
78        $labelNode->setLiteral($label);
79
80        return $this;
81    }
82
83    private function findLabelNode(): ?Text
84    {
85        foreach ($this->children() as $child) {
86            if ($child instanceof Text) {
87                return $child;
88            }
89        }
90
91        return null;
92    }
93}
94