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

Case Bundle Laravel Package

misatotremor/case-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel

  1. Install via Composer:
    composer require misatotremor/case-bundle
    
  2. Register the Bundle (Laravel-specific workaround since it's a Symfony bundle): Create a service provider to bind the CaseConverter:
    // app/Providers/AppServiceProvider.php
    use Avro\CaseBundle\Util\CaseConverter;
    use Illuminate\Support\ServiceProvider;
    
    class AppServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->app->singleton(CaseConverter::class, function ($app) {
                return new CaseConverter();
            });
        }
    }
    
  3. First Use Case: Inject and use the converter in a service:
    use Avro\CaseBundle\Util\CaseConverter;
    
    class StringNormalizer
    {
        public function __construct(private CaseConverter $converter) {}
    
        public function normalize(string $input, string $targetCase): string
        {
            return match ($targetCase) {
                'camel' => $this->converter->toCamelCase($input),
                'pascal' => $this->converter->toPascalCase($input),
                'kebab' => $this->converter->toKebabCase($input),
                'title' => $this->converter->toTitleCase($input),
                'underscore' => $this->converter->toUnderscoreCase($input),
                default => $input,
            };
        }
    }
    

Implementation Patterns

Core Workflows

  1. Single String Conversion:

    $converter->toCamelCase('user_first_name'); // "userFirstName"
    $converter->toPascalCase('user_first_name'); // "UserFirstName"
    
  2. Array Batch Processing:

    $converter->toCamelCase(['user_first_name', 'user_last_name']);
    // ["userFirstName", "userLastName"]
    
  3. Dynamic Case Handling in Controllers:

    public function transform(Request $request, CaseConverter $converter)
    {
        $case = $request->input('case', 'camel');
        $data = $converter->{"to{$case}Case"}($request->input('input'));
        return response()->json($data);
    }
    
  4. Eloquent Model Attribute Casting:

    use Avro\CaseBundle\Util\CaseConverter;
    
    class User extends Model
    {
        protected $casts = [
            'name' => 'string',
        ];
    
        public function getNameAttribute($value)
        {
            return app(CaseConverter::class)->toTitleCase($value);
        }
    
        public function setNameAttribute($value)
        {
            $this->attributes['name'] = app(CaseConverter::class)->toUnderscoreCase($value);
        }
    }
    
  5. API Response Normalization:

    public function show(User $user, CaseConverter $converter)
    {
        return response()->json([
            'user' => [
                'firstName' => $converter->toCamelCase($user->first_name),
                'lastName' => $converter->toCamelCase($user->last_name),
            ],
        ]);
    }
    

Integration Tips

  • Laravel Facade (Optional): Create a facade for cleaner syntax:

    // app/Facades/CaseConverterFacade.php
    namespace App\Facades;
    
    use Illuminate\Support\Facades\Facade;
    
    class CaseConverterFacade extends Facade
    {
        protected static function getFacadeAccessor()
        {
            return \Avro\CaseBundle\Util\CaseConverter::class;
        }
    }
    

    Then use:

    use App\Facades\CaseConverterFacade as Case;
    
    Case::toPascalCase('user_first_name'); // "UserFirstName"
    
  • Service Container Aliases: Add an alias in config/app.php:

    'aliases' => [
        // ...
        'Case' => App\Facades\CaseConverterFacade::class,
    ],
    
  • Request Filtering: Use middleware to auto-convert request data:

    public function handle(Request $request, Closure $next)
    {
        $request->merge([
            'camel_case_data' => app(CaseConverter::class)->toCamelCase($request->input('snake_case_data')),
        ]);
        return $next($request);
    }
    
  • Blade Directives (Alternative to Twig): Register a Blade directive for template usage:

    Blade::directive('camel', function ($expression) {
        return "<?php echo app(\\Avro\\CaseBundle\\Util\\CaseConverter::class)->toCamelCase({$expression}); ?>";
    });
    

    Usage:

    @camel($variable)
    

Gotchas and Tips

Pitfalls

  1. Symfony Dependency Injection:

    • The bundle expects Symfony’s DI container. In Laravel, manually bind the CaseConverter to avoid errors.
    • Fix: Use the service provider pattern shown in Getting Started.
  2. Twig Extension Conflicts:

    • The bundle includes a Twig extension, which is irrelevant for Laravel unless using Laravel Pint or similar tools.
    • Fix: Disable Twig integration via config (if using the bundle in a Laravel context, ignore this or mock the extension):
      # config/packages/avro_case.yaml (if manually configured)
      avro_case:
          use_twig: false
      
  3. Edge Case Handling:

    • The converter may not handle Unicode characters or mixed cases as expected (e.g., Title Case for üBER).
    • Tip: Test with:
      $converter->toTitleCase('über'); // May return "Über" or "Über" depending on implementation.
      
  4. Array Depth Limitations:

    • The bundle likely only flattens one-level arrays. Nested arrays may not be processed recursively.
    • Workaround: Use array_map with the converter:
      array_map([$converter, 'toCamelCase'], $nestedArray);
      
  5. Performance for Large Datasets:

    • Batch processing large arrays (e.g., 10,000+ items) may impact performance.
    • Tip: Benchmark and consider chunking:
      $chunkSize = 1000;
      $results = [];
      foreach (array_chunk($largeArray, $chunkSize) as $chunk) {
          $results = array_merge($results, array_map([$converter, 'toCamelCase'], $chunk));
      }
      

Debugging Tips

  1. Verify Converter Injection:

    • If the converter is null, ensure the service provider is registered and the binding is correct.
    • Debug:
      dd(app(CaseConverter::class)); // Should return an instance of Avro\CaseBundle\Util\CaseConverter
      
  2. Check for Method Existence:

    • The bundle may not support all case types in older versions. Verify available methods:
      $methods = get_class_methods(CaseConverter::class);
      // ['toCamelCase', 'toPascalCase', 'toKebabCase', 'toTitleCase', 'toUnderscoreCase']
      
  3. Handle Null/Empty Inputs:

    • The converter may throw errors on null or empty strings. Add guards:
      $input = $request->input('data') ?? '';
      $converted = empty($input) ? $input : $converter->toCamelCase($input);
      
  4. Locale-Specific Title Case:

    • toTitleCase may not respect locale rules (e.g., "iPhone" vs "iPad"). For advanced use, combine with Symfony\Component\String\UnicodeString:
      use Symfony\Component\String\UnicodeString;
      
      $titleCase = UnicodeString::from($str)->title();
      

Extension Points

  1. Custom Case Formats:

    • Extend the CaseConverter class to add new case types:
      class ExtendedCaseConverter extends CaseConverter
      {
          public function toSpaceCase(string $str): string
          {
              return str_replace('_', ' ', $str);
          }
      }
      
    • Bind the extended class in Laravel’s container:
      $this->app->singleton(ExtendedCaseConverter::class);
      
  2. Laravel-Specific Features:

    • Add a macro to Laravel’s Str helper for seamless integration:
      Str::macro('avroCase', function ($str, $case) {
          $converter = app(CaseConverter::class);
          return match ($case) {
              'camel' => $converter->toCamelCase($str),
              'pascal' => $converter->toPascalCase($str),
              // ...
              default => $str,
          };
      });
      
    • Usage:
      Str
      
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata