4 // This script reads the project composer.lock file to generate
5 // clear license details for our PHP dependencies.
7 $rootPath = dirname(__DIR__, 2);
8 $outputPath = "{$rootPath}/dev/licensing/php-library-licenses.txt";
9 $composerLock = json_decode(file_get_contents($rootPath . "/composer.lock"));
10 $outputSeparator = "\n-----------\n";
13 $packages = $composerLock->packages;
14 $packageOutput = array_map(packageToOutput(...), $packages);
16 $licenseInfo = implode($outputSeparator, $packageOutput) . "\n";
17 file_put_contents($outputPath, $licenseInfo);
19 echo "License information written to {$outputPath}\n";
20 echo implode("\n", $warnings);
22 function packageToOutput(stdClass $package) : string {
23 $output = ["{$package->name}"];
25 $licenses = is_array($package->license) ? $package->license : [$package->license];
26 $output[] = "License: " . implode(' ', $licenses);
28 $licenseFile = findLicenseFile($package->name);
30 $output[] = "License File: {$licenseFile}";
31 $copyright = findCopyright($licenseFile);
33 $output[] = "Copyright: {$copyright}";
35 warn("Package {$package->name} has no copyright found in its license");
39 $source = $package->source->url;
41 $output[] = "Source: {$source}";
44 $link = $package->homepage ?? $package->source->url ?? '';
46 $output[] = "Link: {$link}";
49 return implode("\n", $output);
52 function findLicenseFile(string $packageName): string {
54 $licenseNameOptions = ['license', 'LICENSE', 'license.*', 'LICENSE.*'];
56 $packagePath = "vendor/{$packageName}";
57 $filePath = "{$rootPath}/{$packagePath}";
60 foreach ($licenseNameOptions as $option) {
61 $search = glob("{$filePath}/$option");
62 array_push($foundLicenses, ...$search);
65 if (count($foundLicenses) > 1) {
66 warn("Package {$packagePath} has more than one license file found");
69 if (count($foundLicenses) > 0) {
70 $fileName = basename($foundLicenses[0]);
71 return "{$packagePath}/{$fileName}";
74 warn("Package {$packageName} has no license files found");
78 function findCopyright(string $licenseFile): string {
79 $fileContents = file_get_contents($licenseFile);
80 $pattern = '/^.*?copyright (\(c\)|\d{4})[\s\S]*?(\n\n|\.\n)/mi';
82 preg_match($pattern, $fileContents, $matches);
83 $copyright = trim($matches[0] ?? '');
85 $emailPattern = '/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/i';
86 return preg_replace_callback($emailPattern, obfuscateEmail(...), $copyright);
89 function obfuscateEmail(array $matches): string {
90 return preg_replace('/[^@.]/', '*', $matches[1]);
93 function warn(string $text): void {
95 $warnings[] = "WARN:" . $text;