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

Version Laravel Package

herrera-io/version

PHP library for Semantic Versioning (SemVer 2.0.0): parse versions into a builder, increment major/minor/patch, edit pre-release/build metadata, validate formats, compare versions, and dump back to strings for release tooling.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package:

    composer require herrera-io/version:^1.1
    

    Note: Use ^1.1 to avoid potential PHP 8.x compatibility issues.

  2. First Use Case: Parsing and Validating Versions

    use Herrera\Version\Parser;
    use Herrera\Version\Validator;
    
    // Parse a version string
    $version = Parser::toVersion('1.2.3-alpha+build123');
    
    // Validate a version string
    if (Validator::isVersion('2.0.0')) {
        // Proceed with version logic
    }
    
  3. Where to Look First:


Implementation Patterns

Core Workflows

  1. Version Parsing and Manipulation

    // Parse and modify a version
    $builder = Parser::toBuilder('1.2.3-beta');
    $builder->incrementMajor()->clearPreRelease();
    $finalVersion = $builder->getVersion(); // "2.0.0"
    
  2. Version Comparison in Laravel Logic

    use Herrera\Version\Comparator;
    
    // Compare versions in a service
    public function shouldUpgrade(string $currentVersion, string $latestVersion): bool
    {
        return Comparator::isLessThan(
            Parser::toVersion($currentVersion),
            Parser::toVersion($latestVersion)
        );
    }
    
  3. Validation in Requests/Middleware

    // Validate version strings in API requests
    public function validateVersion(Request $request)
    {
        $version = $request->input('version');
        if (!Validator::isVersion($version)) {
            throw new \InvalidArgumentException("Invalid version format: $version");
        }
    }
    
  4. Version-Based Feature Flags

    // Enable features based on version ranges
    $userVersion = Parser::toVersion($user->version);
    if (Comparator::isGreaterThanOrEqual($userVersion, Parser::toVersion('1.5.0'))) {
        $this->enableNewFeature();
    }
    

Integration Tips

  • Laravel Service Container: Bind the parser/comparator for dependency injection:

    $this->app->singleton(Parser::class);
    $this->app->singleton(Comparator::class);
    
  • Facade for Cleaner Syntax: Create a Version facade to abstract the library:

    // app/Facades/Version.php
    namespace App\Facades;
    
    use Herrera\Version\Parser;
    use Illuminate\Support\Facades\Facade;
    
    class Version extends Facade
    {
        protected static function getFacadeAccessor()
        {
            return Parser::class;
        }
    }
    

    Usage:

    $version = Version::toVersion('1.2.3');
    
  • Artisan Commands: Use the library in release scripts:

    // app/Console/Commands/ReleaseCommand.php
    public function handle()
    {
        $builder = Parser::toBuilder(config('app.version'));
        $builder->incrementPatch();
        config(['app.version' => $builder->getVersion()]);
    }
    
  • Database Versioning: Store version strings in migrations and compare them:

    // Check if a schema update is needed
    $currentDbVersion = DB::table('schema_versions')->value('version');
    $latestVersion = Parser::toVersion('1.2.0');
    if (Comparator::isLessThan($currentDbVersion, $latestVersion)) {
        // Run migrations
    }
    

Gotchas and Tips

Pitfalls

  1. PHP Version Compatibility:

    • The package was last updated for PHP 5.3–5.6. PHP 8.x may break:
      • Use #[ReturnTypeWillChange] or return_type declarations in a fork.
      • Example fix for toComponents():
        #[ReturnTypeWillChange]
        public function toComponents(string $version): array { ... }
        
  2. Strict SemVer Enforcement:

    • The library strictly validates SemVer 2.0.0. Invalid inputs (e.g., 1.2 without patch) throw exceptions. Handle gracefully:
      try {
          $version = Parser::toVersion('1.2'); // Throws InvalidArgumentException
      } catch (\InvalidArgumentException $e) {
          // Fallback to default version or log error
      }
      
  3. Build Metadata Handling:

    • Build metadata (e.g., +build123) is ignored in comparisons by default. Explicitly clear it if needed:
      $builder = Parser::toBuilder('1.2.3+build123');
      $builder->clearBuild(); // Compare without build metadata
      
  4. Pre-Release Comparisons:

    • Pre-release versions (e.g., 1.0.0-alpha) are considered less than release versions (1.0.0). This may not match your use case. Override logic if needed:
      if (Comparator::isGreaterThan($preRelease, $release)) {
          // Custom logic for pre-releases
      }
      
  5. Performance in Loops:

    • Parsing/comparing versions in tight loops (e.g., batch processing) can be slow. Cache parsed versions:
      $cache = [];
      $parsedVersion = $cache[$versionString] ?? Parser::toVersion($versionString);
      

Debugging Tips

  1. Inspect Version Components: Use Parser::toComponents() to debug malformed versions:

    $components = Parser::toComponents('1.2.3-alpha+build123');
    // Returns: ['major' => 1, 'minor' => 2, 'patch' => 3, 'preRelease' => 'alpha', 'build' => 'build123']
    
  2. Comparator Edge Cases:

    • Test comparisons with:
      • Pre-release vs. release (1.0.0-alpha < 1.0.0).
      • Build metadata (1.0.0+build1 == 1.0.0).
      • Equal versions (1.2.3 == 1.2.3).
  3. Logging Invalid Versions: Log failed validations to identify user input issues:

    Validator::isVersion($input) || \Log::warning("Invalid version: $input");
    

Extension Points

  1. Custom Validation Rules: Extend Validator to add project-specific rules:

    class CustomValidator extends Validator
    {
        public static function isProjectVersion(string $version): bool
        {
            $components = Parser::toComponents($version);
            return $components['major'] >= 1 && $components['minor'] >= 0;
        }
    }
    
  2. Fork and Modernize: Fork the repository to:

    • Add PHP 8.x support.
    • Include Laravel-specific helpers (e.g., Version::config()).
    • Example: Add a VersionService class for Laravel:
      class VersionService
      {
          public function getAppVersion(): string
          {
              return config('app.version');
          }
      
          public function incrementVersion(): void
          {
              $builder = Parser::toBuilder($this->getAppVersion());
              $builder->incrementPatch();
              config(['app.version' => $builder->getVersion()]);
          }
      }
      
  3. Integration with Laravel Packages: Use the library in package manifests or service providers:

    // In a PackageServiceProvider
    public function boot()
    {
        $packageVersion = Parser::toVersion($this->packageVersion);
        if (Comparator::isLessThan($packageVersion, Parser::toVersion('2.0.0'))) {
            // Deprecation logic
        }
    }
    

Configuration Quirks

  1. Default Version Handling: The library does not provide a "default version." Define one in your config/versioning.php:

    return [
        'default' => '0.0.1',
    ];
    
  2. Build Metadata in Comparisons: By default, build metadata (e.g., +build123) is ignored in comparisons. To include it, modify the comparator logic or use a custom implementation.

  3. Case Sensitivity: Pre-release identifiers (e.g., alpha, ALPHA) are case-sensitive in comparisons. Normalize case if needed:

    $builder->setPreRelease(strtolower($builder->getPreRelease()));
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky