-
Notifications
You must be signed in to change notification settings - Fork 21
/
ExtensionName.php
92 lines (76 loc) · 2.93 KB
/
ExtensionName.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
declare(strict_types=1);
namespace Php\Pie;
use Composer\Package\PackageInterface;
use Webmozart\Assert\Assert;
use function array_key_exists;
use function assert;
use function explode;
use function is_string;
use function str_starts_with;
use function strlen;
use function substr;
/**
* @internal This is not public API for PIE, so should not be depended upon unless you accept the risk of BC breaks
*
* @immutable
*/
final class ExtensionName
{
/**
* PECL extension names must contain only alphanumeric characters and underscores, and must start with an
* alphabetical character. PIE does not change this requirement for consistency.
*
* @link https://github.com/pear/pear-core/blob/6f4c3a0b134626d238d75a44af01a2f7c4e688d9/PEAR/Common.php#L28
*/
private const VALID_PACKAGE_NAME_REGEX = '#^[A-Za-z][a-zA-Z0-9_]+$#';
// phpcs:disable SlevomatCodingStandard.Classes.RequireConstructorPropertyPromotion.RequiredConstructorPropertyPromotion
/** @var non-empty-string */
private readonly string $normalisedExtensionName;
// phpcs:enable
private function __construct(string $normalisedExtensionName)
{
Assert::regex(
$normalisedExtensionName,
self::VALID_PACKAGE_NAME_REGEX,
'The value %s is not a valid extension name. An extension must start with a letter, and only'
. ' contain alphanumeric characters or underscores',
);
assert($normalisedExtensionName !== '');
$this->normalisedExtensionName = $normalisedExtensionName;
}
public static function determineFromComposerPackage(PackageInterface $package): self
{
$phpExt = $package->getPhpExt();
/** @psalm-suppress DocblockTypeContradiction just in case runtime type is not correct */
if (
$phpExt === null
|| ! array_key_exists('extension-name', $phpExt)
|| ! is_string($phpExt['extension-name'])
|| $phpExt['extension-name'] === ''
) {
$packageNameParts = explode('/', $package->getPrettyName());
Assert::count($packageNameParts, 2, 'Expected a package name like vendor/package for ' . $package->getPrettyName());
Assert::keyExists($packageNameParts, 1);
return self::normaliseFromString($packageNameParts[1]);
}
return self::normaliseFromString($phpExt['extension-name']);
}
public static function normaliseFromString(string $extensionName): self
{
if (str_starts_with($extensionName, 'ext-')) {
return new self(substr($extensionName, strlen('ext-')));
}
return new self($extensionName);
}
/** @return non-empty-string */
public function name(): string
{
return $this->normalisedExtensionName;
}
/** @return non-empty-string */
public function nameWithExtPrefix(): string
{
return 'ext-' . $this->normalisedExtensionName;
}
}