8 namespace Fossology\Lib\Data;
16 const VALID_IDSTRING_PATTERN =
'/^[a-zA-Z0-9.\-]+$/';
18 public static function isValidLicenseRef(
string $licenseId):
bool
20 if (empty($licenseId) || !self::isLicenseRef($licenseId)) {
24 $idstring = self::extractIdstring($licenseId);
25 return !empty($idstring) && preg_match(self::VALID_IDSTRING_PATTERN, $idstring);
28 public static function isLicenseRef(
string $licenseId):
bool
30 return strpos($licenseId, LicenseRef::SPDXREF_PREFIX) === 0;
33 public static function extractIdstring(
string $licenseId):
string
35 if (!self::isLicenseRef($licenseId)) {
38 return substr($licenseId, strlen(LicenseRef::SPDXREF_PREFIX));
41 public static function getValidationErrors(
string $licenseId): array
43 if (empty($licenseId)) {
44 return [
"License identifier is empty"];
47 if (!self::isLicenseRef($licenseId)) {
51 $idstring = self::extractIdstring($licenseId);
52 if (empty($idstring)) {
53 return [
"LicenseRef- prefix found but no idstring follows"];
57 for ($i = 0; $i < strlen($idstring); $i++) {
58 $char = $idstring[$i];
59 if (!preg_match(
'/[a-zA-Z0-9.\-]/', $char) && !in_array($char, $invalidChars)) {
60 $invalidChars[] = $char;
64 if (!empty($invalidChars)) {
65 return [
"Contains invalid characters: " . implode(
', ', array_map(fn($c) =>
"'$c'", $invalidChars))];
71 public static function sanitizeLicenseRef(
string $licenseId):
string
73 if (empty($licenseId) || !self::isLicenseRef($licenseId)) {
77 $idstring = self::extractIdstring($licenseId);
78 if (empty($idstring)) {
82 $sanitized = preg_replace(
'/[^a-zA-Z0-9.\-]/',
'-', $idstring);
83 $sanitized = preg_replace(
'/-+/',
'-', $sanitized);
84 $sanitized =
trim($sanitized,
'-');
86 return empty($sanitized) ? $licenseId : LicenseRef::SPDXREF_PREFIX . $sanitized;
Validate and sanitize SPDX LicenseRef identifiers.
char * trim(char *ptext)
Trimming whitespace.