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

Support Laravel Package

dragon-code/support

Dragon Code Support is a lightweight helper toolkit for PHP/Laravel projects, providing a growing collection of utilities and facades to speed up development. Easy to extend—add new methods or classes with tests following the package structure.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require dragon-code/support
    

    No additional configuration is required—facades are auto-discoverable in Laravel.

  2. First Use Case: Replace a common utility function with the package’s helpers. For example:

    use DragonCode\Support\Facades\Arr;
    use DragonCode\Support\Facades\Str;
    
    // Flatten an array
    $flattened = Arr::flatten(['a' => ['b', 'c']]);
    
    // Generate a slug
    $slug = Str::slug('Hello World');
    
  3. Key Facades to Explore:

    • Arr (array manipulation)
    • Str (string operations)
    • File/Directory (filesystem utilities)
    • Digit (number formatting)
    • Instance (object/type checks)
  4. Where to Look First:


Implementation Patterns

Core Workflows

1. Array Manipulation

  • Chaining Methods:
    $result = Arr::of(['a', 'b', 'c'])
        ->filter(fn($item) => $item !== 'b')
        ->map(fn($item) => strtoupper($item))
        ->toArray();
    
  • Nested Operations:
    $flattened = Arr::flattenKeys(['user.data' => ['name' => 'John']]);
    // Returns: ['user' => ['data' => ['name' => 'John']]]
    

2. String Utilities

  • Common Patterns:
    $trimmed = Str::trim('  hello  ');
    $slug = Str::slug('Hello World', '-');
    $matches = Str::matchAll('/\d+/', 'Order 123');
    
  • Invokable Helpers:
    $string = Str::of('hello')->reverse()->toString();
    

3. Filesystem Operations

  • Directory Handling:
    $paths = Directory::allPaths(storage_path('app'));
    Directory::copy(storage_path('old'), storage_path('new'));
    
  • File Validation:
    $content = File::load(public_path('file.txt'), true); // Validates readability
    

4. Type Safety and Instances

  • Dynamic Instance Checks:
    if (Instance::of($obj)->is(Model::class)) {
        // Handle Eloquent models
    }
    

5. Number Formatting

  • Short Notation:
    $short = Digit::toShort(1000, 'k'); // '1k'
    

Integration Tips

Laravel-Specific Patterns

  • Service Providers: Bind facades explicitly if auto-discovery fails (unlikely, but possible in older Laravel versions):

    public function register()
    {
        $this->app->bind('DragonCode\Support\Facades\Arr', function ($app) {
            return new \DragonCode\Support\Facades\Arr;
        });
    }
    
  • Blade Directives: Create custom Blade helpers for frontend templates:

    Blade::directive('slug', function ($expression) {
        return "<?php echo DragonCode\Support\Facades\Str::slug({$expression}); ?>";
    });
    

    Usage:

    <h1>{{ slug('Hello World') }}</h1>>
    
  • Form Request Validation: Use Arr and Str facades in FormRequest classes for dynamic validation:

    public function rules()
    {
        $slug = Str::slug($this->input('title'));
        return [
            'title' => ['required', Rule::unique('posts')->ignore($this->post)->where('slug', $slug)],
        ];
    }
    

Testing

  • Mock Facades: Use DragonCode\Support\Facades\Arr::shouldReceive() in PHPUnit:

    Arr::shouldReceive('flatten')
        ->once()
        ->andReturn(['a', 'b', 'c']);
    
  • Data Factories: Generate test data with Arr::of():

    $user = Arr::of([
        'name' => 'John',
        'email' => 'john@example.com',
    ])->toInstance(User::class);
    

Performance Considerations

  • Avoid Overhead: For simple operations (e.g., array_merge), prefer native PHP functions if benchmarking shows negligible gains. Example:

    // Benchmark first:
    // Native PHP: ~0.1ms
    // Arr::merge(): ~0.3ms
    $merged = array_merge($array1, $array2); // Use native if critical path
    
  • Lazy Loading: Use Arr::of()->method() for deferred execution in loops:

    foreach ($items as $item) {
        $processed = Arr::of($item)->map(...)->toArray();
    }
    

Gotchas and Tips

Pitfalls

  1. Facade Caching:

    • Facades are not singleton by default in Laravel, but the underlying classes may be. Avoid relying on facade state between requests.
    • Example of bad practice:
      // ❌ Avoid: Facade state may reset between requests
      Arr::of([])->add('key', 'value'); // State lost on next request
      
  2. PHP Version Mismatches:

    • The package requires PHP 8.1+. Test thoroughly if upgrading from PHP 8.0.
    • Example of compatibility issue:
      // ❌ Fails in PHP 8.0
      Str::matchAll('/\d+/', '123'); // Throws error in older PHP
      
  3. Recursive Method Behavior:

    • Methods like Arr::map or Arr::flatten may behave unexpectedly with mixed-type arrays. Always validate input:
      // ❌ Potential bug: mixed arrays may break flattenKeys
      $data = ['a' => ['b' => 1, 2], 'c' => null];
      Arr::flattenKeys($data); // May throw in some versions
      
  4. Filesystem Permissions:

    • File::load() and Directory::copy() will throw exceptions if permissions are insufficient. Handle gracefully:
      try {
          File::load($path);
      } catch (\DragonCode\Support\Exceptions\FileNotReadable $e) {
          // Fallback logic
      }
      
  5. Facade Method Naming:

    • Some methods have renamed counterparts (e.g., doesntEmptyisNotEmpty). Check the changelog for deprecated aliases.

Debugging Tips

  1. Enable Facade Logging: Add this to AppServiceProvider to log facade calls (useful for debugging):

    public function boot()
    {
        \DragonCode\Support\Facades\Arr::setLogger(function ($method, $args) {
            \Log::debug("Arr::{$method} called with: " . json_encode($args));
        });
    }
    
  2. Test Edge Cases:

    • Empty Arrays:
      Arr::of([])->count(); // Should return 0
      
    • Null Values:
      Arr::of([null, null])->filter()->toArray(); // Should return []
      
    • Nested Structures:
      Arr::flattenKeys(['a.b.c' => 1, 'a.b.d' => 2]);
      // Returns: ['a' => ['b' => ['c' => 1, 'd' => 2]]]
      
  3. Common Errors and Fixes:

    Error Solution
    Class 'DragonCode\Support\Facades\Arr' not found Run composer dump-autoload or check config/app.php for aliases.
    Method doesNotExist does not exist Update the package (composer update dragon-code/support).
    String offset cannot be accessed in Arr::flattenKeys Ensure all array values are arrays or strings.
    Directory copy failed Verify write permissions on the target directory.

Extension Points

  1. Adding Custom Methods:
    • Follow the contribution guide:
      1. Add a method to an existing class (e.g., src/Arr.php).
      2. Update the facade (e.g., `src/F
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai