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

Tools Laravel Package

nekland/tools

Small, dependency-free PHP utility library (semver) with high-quality helpers: StringTools (camelize, starts/endsWith, contains, multibyte ucfirst), ArrayTools, equality interface, DateTimeComparator, and temporary file/directory management.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require nekland/tools
    

    No additional configuration or service provider registration is required.

  2. First Use Case: Use StringTools::camelize() to convert snake_case or kebab-case strings to camelCase in Laravel models, controllers, or form requests:

    use Nekland\Tools\StringTools;
    
    $snakeCase = "user_profile_name";
    $camelCase = StringTools::camelize($snakeCase); // "userProfileName"
    
  3. Where to Look First:

    • String Manipulation: StringTools for naming conventions (e.g., mb_ucfirst, startsWith).
    • Temporary Resources: TemporaryFile/TemporaryDirectory for testing or file processing.
    • Date Logic: DateTimeComparator for scheduling or analytics.

Implementation Patterns

Usage Patterns

  1. String Normalization:

    • Pattern: Use StringTools in Laravel’s FormRequest or ApiResource to standardize input/output names.
      // In a FormRequest
      protected function prepareForValidation(): void
      {
          $this->merge([
              'user_profile_name' => StringTools::camelize($this->input('user_profile_name')),
          ]);
      }
      
    • Workflow: Chain methods for complex transformations:
      $cleaned = StringTools::removeStart($dirtyString, 'prefix_')
                           ->removeEnd($dirtyString, '_suffix')
                           ->camelize($dirtyString);
      
  2. Temporary Resource Management:

    • Pattern: Use TemporaryDirectory in Laravel’s tests/Feature for isolated file operations:
      public function test_file_upload()
      {
          $tempDir = new TemporaryDirectory();
          $tempFile = $tempDir->getTemporaryFile();
          $tempFile->setContent('test content');
      
          // Test logic using $tempFile->getPathname()
      
          $tempDir->remove(); // Auto-cleanup
      }
      
    • Workflow: Integrate with Laravel’s Storage facade for testing file uploads:
      use Illuminate\Support\Facades\Storage;
      
      $tempDir = new TemporaryDirectory();
      Storage::fake('local');
      Storage::disk('local')->put('test.txt', $tempDir->getTemporaryFile()->getContent());
      
  3. Date Comparisons:

    • Pattern: Use DateTimeComparator in Laravel’s Event listeners or Job classes:
      use Nekland\Tools\DateTimeComparator;
      
      $latest = DateTimeComparator::greatest(
          now(),
          Carbon::yesterday(),
          Carbon::tomorrow()
      );
      
    • Workflow: Combine with Laravel’s Carbon for scheduling:
      $deadline = DateTimeComparator::greatest(...$userSubmissions);
      if ($deadline->isPast()) {
          // Trigger notification
      }
      
  4. Array Operations:

    • Pattern: Use ArrayTools::removeValue in Laravel’s ServiceProvider or Middleware:
      $allowedRoles = ['admin', 'editor'];
      ArrayTools::removeValue($allowedRoles, 'guest'); // Removes 'guest' in-place
      

Integration Tips

  • Laravel Service Container: Bind utilities to the container for global access:

    // In AppServiceProvider
    $this->app->singleton('stringTools', function () {
        return new StringTools();
    });
    

    Then inject via constructor:

    public function __construct(private StringTools $stringTools) {}
    
  • Testing: Replace Laravel’s Storage::fake() with TemporaryDirectory for filesystem tests:

    public function test_file_generation()
    {
        $tempDir = new TemporaryDirectory();
        $this->app->instance('path.temporary', $tempDir->getPathname());
        // Test logic
    }
    
  • Domain-Specific Extensions: Extend EqualableInterface for Laravel models:

    class User implements EqualableInterface
    {
        public function equals($other): bool
        {
            return $this->id === $other->id;
        }
    }
    

Gotchas and Tips

Pitfalls

  1. camelize Normalization:

    • Issue: Default normalize=true in StringTools::camelize() may strip unexpected characters (e.g., accents, symbols).
      StringTools::camelize('café au lait'); // May return "cafeAuLait" (normalized)
      
    • Fix: Set $normalize=false for non-ASCII strings:
      StringTools::camelize('café au lait', '_', 'UTF-8', false);
      
  2. Temporary Resource Leaks:

    • Issue: Forgetting to call remove() on TemporaryFile/TemporaryDirectory can fill /tmp.
    • Fix: Use Laravel’s registering event to auto-cleanup:
      // In AppServiceProvider
      TemporaryDirectory::registering(function ($dir) {
          app()->terminating(function () use ($dir) {
              $dir->remove(true);
          });
      });
      
  3. DateTimeComparator Edge Cases:

    • Issue: Non-DateTimeInterface arguments are silently ignored. Explicit checks may be needed:
      $latest = DateTimeComparator::greatest(
          now(),
          'invalid', // Ignored
          Carbon::tomorrow()
      );
      
    • Fix: Validate inputs:
      $dates = array_filter(func_get_args(), fn ($arg) => $arg instanceof DateTimeInterface);
      
  4. ArrayTools In-Place Modification:

    • Issue: ArrayTools::removeValue modifies the array by reference, which can cause unintended side effects.
    • Fix: Clone the array first:
      $filtered = array_values(array_filter($originalArray));
      ArrayTools::removeValue($filtered, $value);
      
  5. PHP 8.x Deprecations:

    • Issue: Some methods may trigger deprecation warnings in PHP 8.2+ (e.g., mb_* functions).
    • Fix: Update to the latest version (2.6.2+) and suppress warnings if needed:
      $str = @StringTools::mb_ucfirst($str); // Use with caution
      

Debugging Tips

  • Temporary File Paths: Log paths for debugging:
    $tempFile = new TemporaryFile();
    logger()->debug('Temp file path:', [$tempFile->getPathname()]);
    
  • String Normalization: Inspect normalized output:
    $normalized = StringTools::camelize($str, '_', 'UTF-8', true);
    logger()->debug('Normalized:', [$normalized]);
    
  • Date Comparisons: Verify input types:
    dd(get_debug_type($date), $date); // Check if DateTimeInterface
    

Extension Points

  1. Custom String Tools: Extend StringTools by creating a wrapper class:

    class LaravelStringTools extends StringTools
    {
        public static function laravelSnakeCase(string $str): string
        {
            return strtolower(parent::camelize($str, '_', 'UTF-8', false));
        }
    }
    
  2. Temporary Resource Hooks: Override TemporaryDirectory to integrate with Laravel’s filesystem:

    class LaravelTemporaryDirectory extends TemporaryDirectory
    {
        public function __construct()
        {
            parent::__construct(storage_path('app/temp'));
        }
    }
    
  3. Equality Logic: Implement EqualableInterface for Laravel models to enable custom equality checks in collections:

    class Post implements EqualableInterface
    {
        public function equals($other): bool
        {
            return $this->slug === $other->slug;
        }
    }
    
  4. DateTime Extensions: Add Laravel-specific comparisons:

    class LaravelDateTimeComparator extends DateTimeComparator
    {
        public static function greatestByCarbon(...$dates): ?Carbon
        {
            return parent::greatest(...$dates);
        }
    }
    

Config Quirks

  • No Configuration: The package has no config files, but ensure your Laravel environment supports:

    • Filesystem Permissions: For TemporaryFile/TemporaryDirectory operations.
    • PHP Extensions: mbstring for multi-byte string functions (e.g., mb_ucfirst).
  • Encoding Defaults: Methods like camelize default to UTF-8. Explicitly specify encodings for non-ASCII strings to avoid corruption.

Performance Notes

  • String Operations: StringTools methods are lightweight but may not outperform native PHP functions (e.g., str_starts_with vs. StringTools::startsWith). Benchmark for critical paths
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.
craftcms/url-validator
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