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 Laravel Package

php-standard-library/str

Lightweight string utility library for PHP, providing common helpers for formatting, parsing, and safe string handling. Designed as a simple “standard library” add-on with a small API surface and easy composer integration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require php-standard-library/str
    

    No additional configuration is needed—Laravel’s autoloader will handle the package.

  2. First Use Case: Replace repetitive mb_* or native string functions with this package’s methods. For example, in a Laravel controller:

    use Str\Str;
    
    // Replace: mb_strtolower(trim($input))
    $cleanInput = Str::of(request('username'))
        ->trim()
        ->lower()
        ->value();
    
  3. Where to Look First:

    • Core Class: Focus on Str\Str (aliased as Str in the package).
    • Key Methods: Start with of(), trim(), slug(), title(), lower(), upper(), and ascii().
    • Laravel Integration: Use the fluent interface (Str::of()->...->value()) for readability in Laravel’s service layer.

Implementation Patterns

Workflows in Laravel

1. Request Validation and Sanitization

Replace manual sanitization in FormRequest classes:

public function rules()
{
    return [
        'name' => 'required|string',
        'slug' => 'sometimes|string',
    ];
}

protected function prepareForValidation()
{
    $this->merge([
        'slug' => Str::of($this->name)->slug()->value(),
    ]);
}

2. Domain-Specific String Transformations

Create reusable traits or helpers for business logic:

// app/Helpers/StringHelper.php
use Str\Str;

if (!class_exists(StringHelper::class)) {
    class StringHelper
    {
        public static function formatPhone($phone)
        {
            return Str::of($phone)
                ->replace(['(', ')', '-', ' '], '')
                ->prepend('+1')
                ->value();
        }
    }
}

3. API Response Formatting

Standardize JSON payloads:

return response()->json([
    'data' => Str::of($user->name)
        ->title()
        ->ascii()
        ->value(),
]);

4. Blade Templates

Use static methods for one-liners:

<h1>{{ Str::title($post->title) }}</h1>
<a href="{{ route('post', Str::slug($post->title)) }}">{{ $post->title }}</a>

5. Database Model Accessors

Add computed properties to Eloquent models:

public function getSlugAttribute()
{
    return Str::of($this->title)->slug()->value();
}

Integration Tips

  • Service Providers: Bind the package to Laravel’s container for dependency injection:

    $this->app->singleton(Str::class, function ($app) {
        return new Str\Str();
    });
    
  • Testing: Mock Str\Str in unit tests:

    $mockStr = Mockery::mock(Str::class);
    $mockStr->shouldReceive('of')->andReturnSelf();
    $mockStr->shouldReceive('slug')->andReturn('test-slug');
    
  • Artisan Commands: Use the package for CLI input handling:

    $input = Str::of($this->argument('name'))
        ->trim()
        ->value();
    
  • Middleware: Sanitize input early in the pipeline:

    public function handle($request, Closure $next)
    {
        $request->merge([
            'search' => Str::of($request->search)->trim()->value(),
        ]);
        return $next($request);
    }
    

Gotchas and Tips

Pitfalls

  1. Null Handling:

    • Unlike Laravel’s Str helper, this package does not auto-convert null to an empty string. Explicitly handle null:
      $value = Str::of($nullableInput ?? '')->trim()->value();
      
  2. Multibyte Edge Cases:

    • While Unicode-aware, some edge cases (e.g., surrogate pairs) may require additional validation. Test with:
      $text = "👨‍👩‍👧‍👦"; // Family emoji (4-byte sequence)
      $slug = Str::of($text)->slug()->value(); // May not work as expected
      
  3. Performance in Loops:

    • Avoid chaining methods in tight loops (e.g., processing 10K records). Cache intermediate results:
      $slugs = collect($posts)->map(fn ($post) => cache()->remember(
          "slug-{$post->id}",
          now()->addHours(1),
          fn () => Str::of($post->title)->slug()->value()
      ));
      
  4. Laravel Facade Collisions:

    • If using Laravel’s Str facade, alias this package to avoid conflicts:
      // config/app.php
      'aliases' => [
          'StrHelper' => Str\Str::class,
      ];
      
  5. Static Method Overload:

    • Static methods (e.g., Str::slug()) cannot be mocked easily in tests. Prefer the fluent interface for testability.

Debugging Tips

  • Enable Strict Typing: Add this to composer.json to catch type issues early:

    "config": {
        "platform": {
            "php": "8.1"
        },
        "optimize-autoloader": true,
        "preferred-install": "dist"
    }
    
  • Log Intermediate Steps: Debug complex transformations by logging each step:

    $str = Str::of($input);
    \Log::debug('Trim:', $str->trim()->value());
    \Log::debug('Slug:', $str->slug()->value());
    
  • Benchmark Against Native PHP: Compare performance with mb_* functions:

    $time = microtime(true);
    Str::of($longText)->slug()->value();
    $strTime = microtime(true) - $time;
    
    $time = microtime(true);
    mb_strtolower(mb_str_slug($longText, '-'));
    $mbTime = microtime(true) - $time;
    
    \Log::info('Str vs mb_*:', [$strTime, $mbTime]);
    

Extension Points

  1. Custom Methods: Extend the class via traits or inheritance:

    use Str\Str;
    
    trait CustomStrMethods
    {
        public function customSlug()
        {
            return $this->slug()->prepend('custom-');
        }
    }
    
    class ExtendedStr extends Str
    {
        use CustomStrMethods;
    }
    
  2. Override Default Behavior: Replace the default slug() pattern:

    $str = new Str\Str();
    $str->setSlugPattern('/[^a-z0-9]+/u', '-');
    
  3. Add Laravel Service Provider: Register a custom instance with default configurations:

    $this->app->singleton(Str::class, function ($app) {
        $str = new Str\Str();
        $str->setDefaultLocale('en_US');
        return $str;
    });
    
  4. Composer Scripts: Auto-refactor legacy code using php-cs-fixer:

    "scripts": {
        "fix-strings": "php-cs-fixer fix --rules=@PHPStandardLibrary --allow-risky=yes"
    }
    

Configuration Quirks

  • Locale Sensitivity: Some methods (e.g., title()) rely on locale-specific rules. Set a default locale if needed:

    Str::setDefaultLocale('en_US');
    
  • Case Conversion: lower()/upper() use ICU rules. For ASCII-only operations, use ascii() first:

    Str::of('Café')->ascii()->lower()->value(); // 'cafe'
    
  • Empty String Handling: Methods like trim() return an empty string for null or whitespace inputs. Explicitly check if needed:

    if (Str::of($input)->trim()->isEmpty()) { ... }
    

Laravel-Specific Tips

  • Use with Illuminate\Support\Stringable: Combine with Laravel’s Stringable for hybrid workflows:

    use Illuminate\Support\Stringable;
    
    $str = Stringable::from('Hello World');
    $processed = Str::of($str->value())
        ->slug()
        ->value();
    
  • Artisan Commands: Access the container-bound instance:

    $str = app(Str::class);
    $input = $str->of($this->argument('name'))->trim()->value();
    
  • Testing: Use Laravel’s Testing facade to assert string transformations:

    $this->assertEquals(
        'test
    
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.
codraw/graphviz
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
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata