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

Str Case Converter Laravel Package

nayjest/str-case-converter

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require nayjest/str-case-converter
    

    No additional configuration is required—use the package directly via its facade or class.

  2. First Use Case: Convert a snake_case string to camelCase in a Laravel controller:

    use Nayjest\StrCaseConverter\Str;
    
    $camelCase = Str::toCamelCase('user_first_name'); // 'UserFirstName'
    

    Or convert camelCase to snake_case:

    $snakeCase = Str::toSnakeCase('userFirstName'); // 'user_first_name'
    
  3. Where to Look First:

    • Facade: Nayjest\StrCaseConverter\Facades\Str (if published).
    • Class: Nayjest\StrCaseConverter\Str (direct usage).
    • Tests: tests/ directory for edge cases (e.g., mixed delimiters, empty strings).

Implementation Patterns

Core Workflows

  1. Model Attribute Mapping: Automatically convert database column names (snake_case) to Eloquent model attributes (camelCase):

    public function getTable()
    {
        return 'user_profiles'; // snake_case
    }
    
    // Convert to camelCase for API responses
    $tableName = Str::toCamelCase($this->getTable()); // 'UserProfiles'
    
  2. Request Validation: Normalize input case in FormRequest classes:

    public function rules()
    {
        return [
            'user_first_name' => 'required|string',
            // Convert to camelCase for model binding
            Str::toCamelCase('user_first_name') => 'sometimes|string',
        ];
    }
    
  3. API Response Transformation: Use in AppServiceProvider to standardize JSON responses:

    public function boot()
    {
        Response::macro('camelCase', function ($response) {
            $data = $response->getData();
            array_walk_recursive($data, function (&$value, $key) {
                $value = Str::toCamelCase($key);
            });
            return $response->setData($data);
        });
    }
    

Integration Tips

  1. Service Container Binding: Bind the converter as a singleton for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton('caseConverter', function () {
            return new \Nayjest\StrCaseConverter\Str();
        });
    }
    

    Usage:

    $converter = app('caseConverter');
    $camelCase = $converter->toCamelCase('snake_string');
    
  2. Custom Facade: Extend Laravel’s Str facade or create a dedicated facade:

    // app/Facades/CaseConverter.php
    namespace App\Facades;
    use Illuminate\Support\Facades\Facade;
    class CaseConverter extends Facade
    {
        protected static function getFacadeAccessor() { return 'caseConverter'; }
    }
    

    Usage:

    use App\Facades\CaseConverter;
    $snakeCase = CaseConverter::toSnakeCase('camelCaseString');
    
  3. Helper Functions: Add global helper functions in app/Helpers.php:

    if (!function_exists('to_camel_case')) {
        function to_camel_case($string) {
            return \Nayjest\StrCaseConverter\Str::toCamelCase($string);
        }
    }
    

    Usage:

    $camel = to_camel_case('snake_case_string');
    
  4. Eloquent Events: Use in model events to enforce case consistency:

    protected static function boot()
    {
        static::creating(function ($model) {
            $model->attributes = array_map(function ($value, $key) {
                return [$key => Str::toCamelCase($key) => $value];
            }, $model->attributes, array_keys($model->attributes));
        });
    }
    
  5. API Route Naming: Convert route names to snake_case for consistency:

    Route::get('user/{user}', function ($user) {
        $snakeRoute = Str::toSnakeCase('userShow'); // 'user_show'
        return response()->json(['route' => $snakeRoute]);
    });
    

Gotchas and Tips

Pitfalls

  1. No PHP 8.x Support:

    • The package lacks strict_types and may throw deprecation warnings in PHP 8.x.
    • Fix: Fork the repo and add:
      declare(strict_types=1);
      
      to the Str.php file.
  2. Edge Cases with Delimiters:

    • Fails on consecutive delimiters (e.g., user__nameuserName instead of userName).
    • Workaround: Pre-process strings with preg_replace('/_{2,}/', '_', $string).
  3. Reserved Words:

    • May produce invalid PHP identifiers (e.g., user_classuserClass if class is a reserved word).
    • Tip: Validate output with ctype_alnum() or a whitelist.
  4. Unicode Characters:

    • No handling for accented characters (e.g., cafécafe).
    • Alternative: Use Laravel’s Str::of() for Unicode support:
      Str::of('café')->camel(); // 'cafe'
      
  5. No Custom Separators in toCamelCase:

    • Only supports -, _, and space for toCamelCase.
    • Tip: Pre-process strings to standardize delimiters:
      $string = preg_replace('/[_\-\s]/', '_', $string);
      $camel = Str::toCamelCase($string);
      

Debugging Tips

  1. Input Validation:

    • Log problematic inputs:
      if (preg_match('/[^a-zA-Z0-9_\-\s]/', $string)) {
          Log::warning("Invalid characters in case conversion input: {$string}");
      }
      
  2. Test Edge Cases:

    • Test with:
      • Empty strings: Str::toCamelCase('')''.
      • Numbers: Str::toCamelCase('user_123')user123.
      • Mixed cases: Str::toCamelCase('User_Name')userName.
  3. Performance:

    • Benchmark against native PHP:
      $time = microtime(true);
      for ($i = 0; $i < 10000; $i++) {
          Str::toCamelCase('snake_case_string');
      }
      $duration = microtime(true) - $time;
      
    • Alternative: For high-throughput systems, use preg_replace_callback:
      function to_camel_case($str) {
          return preg_replace_callback('/_([a-z])/', function ($matches) {
              return strtoupper($matches[1]);
          }, $str);
      }
      

Configuration Quirks

  1. Facade Publishing:

    • The package does not auto-publish its facade. Manually add to config/app.php:
      'aliases' => [
          'Str' => Nayjest\StrCaseConverter\Facades\Str::class,
      ],
      
  2. Service Provider:

    • The package includes a service provider (StrCaseConverterServiceProvider), but it’s optional. If using the facade, ensure it’s registered.
  3. Custom Delimiters:

    • Only toSnakeCase supports custom delimiters:
      Str::toSnakeCase('camelCase', '-'); // 'camel-case'
      
    • Tip: Create a wrapper for toCamelCase with custom delimiters:
      function to_camel_case_custom($string, $delimiter = '_') {
          return Str::toCamelCase(str_replace($delimiter, ' ', $string));
      }
      

Extension Points

  1. Add New Case Types:

    • Extend the Str class to support PascalCase or kebab-case:
      namespace Nayjest\StrCaseConverter;
      class Str {
          public static function toPascalCase($string) {
              return ucfirst(self::toCamelCase($string));
          }
      }
      
  2. Locale-Aware Conversion:

    • Override methods to handle Unicode:
      public static function toCamelCase($string) {
          $string = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
          return parent::toCamelCase($string);
      }
      
  3. Integration with Laravel Helpers:

    • Merge with Laravel’s Str helper for unified API:
      if (!method_exists(\Str::class, 'toCamelCase')) {
          \Str::macro('toCamelCase', function
      
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony