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

Ia Str Laravel Package

pragmarx/ia-str

Framework-agnostic extraction of Laravel’s Illuminate\Support\Str and string helper functions, repackaged under IlluminateAgnostic\Str to avoid namespace conflicts. Use Str:: methods or global str_* helpers in any PHP project, including Laravel apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require pragmarx/ia-str
    

    Add to composer.json if not using autoloading:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "IlluminateAgnostic\\": "vendor/pragmarx/ia-str/src"
        }
    }
    
  2. First Use Case: Replace native string operations with Str helpers in a non-Laravel project or to avoid Laravel namespace conflicts:

    use IlluminateAgnostic\Str\Support\Str;
    
    // Basic usage
    $result = Str::contains('Hello World', 'World'); // true
    $slug = Str::slug('Hello World'); // "hello-world"
    
  3. Where to Look First:

    • Documentation: Refer to Laravel’s 5.5 Str helpers (same API).
    • Source: Check vendor/pragmarx/ia-str/src/Support/Str.php for all available methods.
    • Tests: Browse tests/ for usage examples and edge cases.

Implementation Patterns

Core Workflows

  1. String Manipulation: Use Str for consistent string operations across projects:

    // Camel case, snake case, kebab case
    Str::camel('hello_world'); // "helloWorld"
    Str::snake('helloWorld');  // "hello_world"
    Str::kebab('helloWorld');  // "hello-world"
    
    // Trimming and padding
    Str::padLeft('hi', 5, '='); // "===hi"
    Str::trim('  hello  ');     // "hello"
    
  2. URL and Path Handling: Leverage Laravel’s built-in URL helpers without Laravel’s routing:

    Str::of('https://example.com/path?query=1')
        ->after('example.com/')
        ->before('?'); // "path"
    
  3. Character and Word Operations:

    // Substring, word counting, etc.
    Str::limit('Hello World', 5); // "Hello..."
    Str::words('Hello World', 1); // ["Hello"]
    Str
        ->of('Hello World')
        ->replaceFirst('World', 'Laravel')
        ->value(); // "Hello Laravel"
    
  4. Macroable Methods: Extend Str with custom logic:

    Str::macro('reverse', function ($string) {
        return strrev($string);
    });
    Str::reverse('hello'); // "olleh"
    
  5. Integration with Collections: Use Str with Illuminate\Support\Collection (if installed separately):

    collect(['Hello', 'World'])
        ->map(fn ($str) => Str::upper($str))
        ->values(); // ["HELLO", "WORLD"]
    

Best Practices

  • Consistency: Use Str::of($string) for fluent chaining to avoid repeated string literals.
  • Performance: For bulk operations, prefer native PHP functions (e.g., strtolower()) over Str helpers if micro-optimizations are critical.
  • Testing: Mock Str in unit tests to isolate string logic:
    $this->partialMock(Str::class, ['slug'])
        ->shouldReceive('slug')
        ->with('Test String')
        ->andReturn('test-string');
    

Gotchas and Tips

Pitfalls

  1. Namespace Conflicts:

    • If using Laravel, alias IlluminateAgnostic\Str\Support\Str to avoid collisions:
      use Illuminate\Support\Facades\Str as LaravelStr;
      use IlluminateAgnostic\Str\Support\Str as AgnosticStr;
      
    • Fix: Use the package’s namespace explicitly or rename the class in composer.json autoloading.
  2. Deprecated Methods:

    • Some methods (e.g., Str::ascii()) rely on voku/portable-ascii. Ensure compatibility:
      composer require voku/portable-ascii
      
    • Tip: Check changelog for breaking changes (e.g., v5.6.3 aligns with Laravel 5.6.3).
  3. Case Sensitivity:

    • Methods like Str::contains() are case-sensitive by default. Use Str::lower() or Str::upper() for case-insensitive checks:
      Str::contains(Str::lower($haystack), Str::lower($needle));
      
  4. Locale-Specific Operations:

    • Some methods (e.g., Str::title()) may not handle Unicode/locale-specific rules perfectly. Test with edge cases like:
      Str::title('jönköping'); // "Jönköping" (may vary by PHP locale)
      
  5. Fluent Method Chaining:

    • Chaining methods like Str::of()->upper()->slug() is efficient but can be less readable for complex logic. Break into steps if needed:
      $upper = Str::of($str)->upper()->value();
      $slug = Str::slug($upper);
      

Debugging Tips

  • Method Existence: Use get_class_methods(Str::class) to list available methods.
  • Edge Cases: Test with:
    • Empty strings (Str::of('')->slug()).
    • Non-string inputs (e.g., null, arrays). Str will cast them to strings.
    • Unicode characters (e.g., Str::ascii('café')).

Extension Points

  1. Custom Helpers: Add static methods to Str for project-specific needs:

    Str::macro('abbreviate', function ($string, $length = 20) {
        return Str::length($string) > $length
            ? Str::substr($string, 0, $length - 3) . '...'
            : $string;
    });
    
  2. Override Existing Methods: Use traits or extend the class (though this requires deeper integration):

    class CustomStr extends \IlluminateAgnostic\Str\Support\Str {
        public static function customMethod($string) { ... }
    }
    
  3. Configuration:

    • No built-in config, but you can inject dependencies (e.g., for locale-aware operations) via method overrides.

Performance Notes

  • Avoid Overhead: For simple operations (e.g., strtolower()), native PHP functions are faster. Reserve Str for complex or reusable logic.
  • Memoization: Cache results of expensive operations (e.g., Str::slug()) if called repeatedly:
    $cache = [];
    Str::macro('cachedSlug', function ($string) use (&$cache) {
        return $cache[$string] ?? $cache[$string] = Str::slug($string);
    });
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation