|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace TypeLang\PHPDoc\DocBlock\Tag\LicenseTag; |
| 6 | + |
| 7 | +use Composer\Spdx\SpdxLicenses; |
| 8 | +use League\Uri\Uri; |
| 9 | +use TypeLang\PHPDoc\DocBlock\Tag\Factory\TagFactoryInterface; |
| 10 | +use TypeLang\PHPDoc\DocBlock\Tag\Shared\Reference\UriReference; |
| 11 | +use TypeLang\PHPDoc\Parser\Content\Stream; |
| 12 | +use TypeLang\PHPDoc\Parser\Content\UriReferenceReader; |
| 13 | +use TypeLang\PHPDoc\Parser\Description\DescriptionParserInterface; |
| 14 | + |
| 15 | +/** |
| 16 | + * This class is responsible for creating "`@license`" tags. |
| 17 | + * |
| 18 | + * See {@see LicenseTag} for details about this tag. |
| 19 | + */ |
| 20 | +final class LicenseTagFactory implements TagFactoryInterface |
| 21 | +{ |
| 22 | + private readonly ?SpdxLicenses $licenses; |
| 23 | + |
| 24 | + public function __construct() |
| 25 | + { |
| 26 | + $this->licenses = $this->createSpdxLicenses(); |
| 27 | + } |
| 28 | + |
| 29 | + private function createSpdxLicenses(): ?SpdxLicenses |
| 30 | + { |
| 31 | + if (\class_exists(SpdxLicenses::class)) { |
| 32 | + return new SpdxLicenses(); |
| 33 | + } |
| 34 | + |
| 35 | + return null; |
| 36 | + } |
| 37 | + |
| 38 | + public function create(string $tag, string $content, DescriptionParserInterface $descriptions): LicenseTag |
| 39 | + { |
| 40 | + $stream = new Stream($tag, $content); |
| 41 | + |
| 42 | + try { |
| 43 | + $uri = $stream->apply(new UriReferenceReader()); |
| 44 | + } catch (\Throwable) { |
| 45 | + $uri = null; |
| 46 | + } |
| 47 | + |
| 48 | + $description = $identifier = ($suffix = \trim($stream->value)) === '' ? null : $suffix; |
| 49 | + |
| 50 | + if ($this->licenses !== null && $identifier !== null) { |
| 51 | + /** @var array{0:non-empty-string, 1:bool, 2:non-empty-string, 3:bool}|null $info */ |
| 52 | + $info = $this->licenses->getLicenseByIdentifier($identifier); |
| 53 | + |
| 54 | + if ($info !== null) { |
| 55 | + $uri ??= new UriReference(Uri::new($info[2])); |
| 56 | + $description = $info[0]; |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + return new LicenseTag( |
| 61 | + name: $tag, |
| 62 | + uri: $uri, |
| 63 | + license: $identifier, |
| 64 | + description: $description, |
| 65 | + ); |
| 66 | + } |
| 67 | +} |
0 commit comments