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

Cva Laravel Package

feature-ninja/cva

PHP implementation of Class Variance Authority (cva) for building composable CSS class strings. Define base classes, variants, compound variants, and defaults, then generate Tailwind-friendly class names via ClassVarianceAuthority or the cva() helper.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require feature-ninja/cva
    

    No additional configuration is required—just autoload.

  2. First Use Case: Basic Type Generation

    use FeatureNinja\CVA\CVA;
    
    $cva = new CVA();
    $result = $cva->generate([
        'name' => 'string',
        'age' => 'number',
        'isActive' => 'boolean',
    ]);
    
    // Outputs: `type User = { name: string; age: number; isActive: boolean; }`
    echo $result;
    
  3. First Use Case: Nullable Parameters

    $result = $cva->generate([
        'name' => 'string',
        'age' => ['type' => 'number', 'nullable' => true],
    ]);
    
    // Outputs: `type User = { name: string; age: number | null; }`
    echo $result;
    
  4. Where to Look First

    • Docs: Check the GitHub README for examples, including the new cva() helper function.
    • Source: Explore src/CVA.php for core logic and src/Contracts for interfaces.
    • Tests: Review tests/ for edge cases, including nullable parameter validation.

Implementation Patterns

Workflows

  1. TypeScript-like Type Generation Use CVA::generate() to create union types, interfaces, or complex nested structures:

    $union = $cva->generate([
        'variant' => ['type' => 'union', 'values' => ['string', 'number']],
    ]);
    // Output: `type Variant = string | number`
    
  2. Nullable Parameters Mark parameters as nullable directly in the schema:

    $nullableSchema = $cva->generate([
        'optionalField' => ['type' => 'string', 'nullable' => true],
        'requiredField' => 'number',
    ]);
    // Output: `type Schema = { optionalField: string | null; requiredField: number; }`
    
  3. Integration with Laravel

    • Validation: Use generated types to enforce request validation:
      $schema = $cva->generate([
          'email' => 'string',
          'role' => ['enum', ['admin', 'user']],
          'metadata' => ['type' => 'object', 'nullable' => true],
      ]);
      // Parse into Laravel rules dynamically.
      
    • API Responses: Auto-generate OpenAPI schemas from CVA output.
  4. Helper Function Usage Leverage the new cva() helper for concise syntax:

    $result = cva()->generate([
        'name' => 'string',
        'age' => ['type' => 'number', 'nullable' => true],
    ]);
    
  5. Dynamic Schema Building Combine with Laravel’s collect() for runtime schema adjustments:

    $dynamicSchema = collect($userRoles)
        ->map(fn($role) => ["$role" => ['type' => 'string', 'nullable' => true]])
        ->toArray();
    $result = $cva->generate($dynamicSchema);
    

Integration Tips

  • Laravel Service Provider: Bind CVA to the container for dependency injection:
    $this->app->singleton(CVA::class, fn() => new CVA());
    
  • Blade Directives: Create a custom directive to embed types in views:
    Blade::directive('type', fn($expr) => "<?php echo app(\\FeatureNinja\\CVA\\CVA::class)->generate($expr); ?>");
    
    Usage:
    @type(['title' => 'string', 'optional' => ['type' => 'string', 'nullable' => true]])
    

Gotchas and Tips

Pitfalls

  1. Nested Object Limits Deeply nested structures may hit PHP’s recursion limits. Use CVA::setMaxDepth():

    $cva->setMaxDepth(20); // Default is 10.
    
  2. Type Safety Invalid input (e.g., ['name' => 123]) throws InvalidArgumentException. Validate schemas pre-generation:

    if (!is_array($schema) || empty($schema)) {
        throw new \InvalidArgumentException('Schema must be a non-empty array.');
    }
    
  3. Nullable Parameter Misuse Ensure nullable is explicitly set as part of an array definition:

    // Correct:
    ['type' => 'string', 'nullable' => true]
    
    // Incorrect (will not work):
    'nullableString'
    
  4. Caching Regenerate schemas on every request by default. Cache results in Laravel:

    $cached = Cache::remember('cva_schema_key', now()->addHours(1), fn() =>
        $cva->generate($schema)
    );
    

Debugging

  • Verbose Output: Enable debug mode for detailed errors:
    $cva->debug(true); // Logs generation steps to storage/logs/cva.log.
    
  • Common Errors:
    • Undefined type 'customType' → Ensure custom types are registered via CVA::addType().
    • Maximum function nesting level exceeded → Increase xdebug.max_nesting_level or simplify schemas.
    • Invalid nullable configuration → Verify nullable is used correctly within an array definition.

Extension Points

  1. Custom Types Extend with domain-specific types (e.g., DateTime):

    $cva->addType('date', fn() => 'string'); // Maps to ISO-8601 string.
    
  2. Post-Processing Hook into CVA::afterGenerate() to modify output:

    $cva->afterGenerate(fn($output) => str_replace('string', 'String', $output));
    
  3. Laravel Events Dispatch events for schema changes (e.g., SchemaGenerated):

    event(new SchemaGenerated($schema, $output));
    
  4. Helper Function Overrides Override the cva() helper in your AppServiceProvider:

    app()->singleton('cva', fn() => new CVA(['customConfig' => true]));
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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