Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Spdx Licenses Laravel Package

composer/spdx-licenses

SPDX licenses list and validation library extracted from Composer. Look up licenses and exceptions by identifier or name, check OSI approval and deprecation, and validate SPDX license expressions using official SPDX License List data.

View on GitHub
Deep Wiki
Context7

Getting Started

Install via Composer:

composer require composer/spdx-licenses

First use case: Validate a license in composer.json or a package submission.

use Composer\Spdx\SpdxLicenses;

$validator = new SpdxLicenses();

// Basic validation (returns bool)
$isValid = $validator->validate('MIT'); // true
$isValid = $validator->validate('PROPRIETARY'); // false

// Get license details
$license = $validator->getLicenseByIdentifier('MIT');
echo $license['name']; // "MIT License"

Where to look first:

  • SPDX License List for reference identifiers.
  • SpdxLicenses::validate() for quick checks.
  • SpdxLicenses::getLicenses() to iterate all licenses programmatically.

Implementation Patterns

1. Dependency Validation in Composer

Workflow: Enforce SPDX compliance during dependency resolution.

// In a Composer plugin or script
$validator = new SpdxLicenses();
$requiredLicenses = ['MIT', 'Apache-2.0', 'GPL-3.0-only'];

foreach ($requiredLicenses as $license) {
    if (!$validator->validate($license)) {
        throw new \RuntimeException("Invalid SPDX license: {$license}");
    }
}

Integration Tip:


2. OSI Compliance Checks

Use Case: Block non-OSI-approved licenses in open-source projects.

$validator = new SpdxLicenses();
$license = 'MIT';

if ($validator->isOsiApprovedByIdentifier($license)) {
    // Allow open-source distribution
} else {
    // Trigger compliance workflow (e.g., GitHub issue, CI failure)
}

Pattern:

  • Cache OSI approval results for performance:
    $osiApproved = $validator->isOsiApprovedByIdentifier('AGPL-3.0-only'); // true
    

3. License Lookup in Laravel

Use Case: Display license metadata in admin panels or API responses.

// In a Laravel service or controller
public function getLicenseDetails(string $spdxId): array
{
    $validator = new SpdxLicenses();
    $license = $validator->getLicenseByIdentifier($spdxId);

    return [
        'id' => $spdxId,
        'name' => $license['name'] ?? 'Unknown',
        'url' => $license['licenseUrl'] ?? null,
        'osi_approved' => $validator->isOsiApprovedByIdentifier($spdxId),
    ];
}

Integration Tip:

  • Bind SpdxLicenses to Laravel’s IoC container:
    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(SpdxLicenses::class);
    }
    

4. Batch Validation

Use Case: Validate licenses in bulk (e.g., Packagist submissions).

$validator = new SpdxLicenses();
$licenses = ['MIT', 'GPL-2.0', 'INVALID-LICENSE'];

$results = array_map(
    fn($id) => [
        'id' => $id,
        'valid' => $validator->validate($id),
        'details' => $validator->getLicenseByIdentifier($id),
    ],
    $licenses
);

Performance Tip:

  • Use SpdxLicenses::getLicenses() to preload all licenses into memory if validating many IDs.

5. License Expression Validation

Use Case: Validate complex SPDX expressions (e.g., MIT AND Apache-2.0).

$validator = new SpdxLicenses();
$expression = 'MIT AND (Apache-2.0 OR GPL-3.0)';

if ($validator->validate($expression)) {
    // Parse expression further (e.g., with `spdx-expression` package)
}

Extension Point:


Gotchas and Tips

Pitfalls

  1. Case Sensitivity:

    • Identifiers are case-insensitive (MIT = mit), but names are case-sensitive.
    • Example: getIdentifierByName('MIT License')getIdentifierByName('mit license').
  2. Deprecated Licenses:

    • Some licenses (e.g., BSD-2-Clause-FreeBSD) are deprecated but still valid.
    • Use isDeprecatedByIdentifier() to handle gracefully:
      if ($validator->isDeprecatedByIdentifier('BSD-2-Clause-FreeBSD')) {
          logWarning("Deprecated license detected");
      }
      
  3. SPDX Expression Limits:

    • The validate() method supports SPDX 3.0+ expressions, but complex nested expressions may fail.
    • Test edge cases like:
      $validator->validate('(MIT AND GPL-3.0) OR (Apache-2.0 WITH LLVM-exception)');
      
  4. PHP Version:

    • Dropped PHP 5.3–7.1 support in v1.6.0. Ensure your project uses PHP ≥7.2.
  5. License Exceptions:

    • Exceptions (e.g., GPL-2.0 WITH Classpath-exception-2.0) are not auto-validated by default.
    • Use getExceptionByIdentifier() to check exceptions explicitly.

Debugging Tips

  1. List All Licenses:

    $allLicenses = $validator->getLicenses();
    print_r(array_keys($allLicenses)); // Debug available IDs
    
  2. Validate Against SPDX Spec:

  3. Update License Data:

    • The package auto-updates with SPDX releases, but you can manually trigger an update via SpdxLicensesUpdater (advanced use).
  4. Performance:

    • For high-throughput validation (e.g., CI pipelines), instantiate SpdxLicenses once and reuse it.

Extension Points

  1. Custom License Rules:

    • Extend validation logic by wrapping SpdxLicenses:
      class CustomSpdxValidator extends SpdxLicenses {
          public function isAllowedInProject(string $licenseId): bool {
              $allowed = ['MIT', 'Apache-2.0', 'BSD-3-Clause'];
              return in_array($licenseId, $allowed, true);
          }
      }
      
  2. SPDX-RDF Generation:

    • Combine with spdx-tools to generate SPDX documents for compliance reporting.
  3. Laravel Artisan Command:

    • Create a spdx:audit command to scan dependencies:
      // app/Console/Commands/AuditLicenses.php
      public function handle() {
          $validator = new SpdxLicenses();
          $composer = include base_path('composer.json');
          $license = $composer['license'] ?? 'UNLICENSED';
      
          if (!$validator->validate($license)) {
              $this->error("Invalid SPDX license: {$license}");
              exit(1);
          }
      }
      
  4. GitHub Actions Integration:

    • Use in CI to block non-compliant licenses:
      # .github/workflows/license-check.yml
      jobs:
        check-license:
          runs-on: ubuntu-latest
          steps:
            - uses: actions/checkout@v4
            - run: composer require composer/spdx-licenses
            - run: |
                php -r "
                require 'vendor/autoload.php';
                \$validator = new \Composer\Spdx\SpdxLicenses();
                \$license = json_decode(file_get_contents('composer.json'), true)['license'];
                if (!$validator->validate(\$license)) exit(1);
                "
      

Pro Tips

  • Cache License Data: If validating repeatedly (e.g., in a web app), cache the SpdxLicenses instance or its data.
  • Laravel Package: Consider wrapping this in a Laravel package (e.g., laravel-spdx) for easier adoption.
  • SPDX 3.0+ Features: Leverage newer features like license matching for fuzzy matching (e.g., getIdentifierByName()).
  • Composer Plugin: Build a plugin to auto-fix invalid licenses in composer.json (e.g., suggest alternatives).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope