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 facades, utilities, and common support classes. Designed to be extended with your own methods, with a clear structure for adding features and tests.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dragon-code/support
    

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

  2. First Use Case: Replace native PHP/array operations with facade methods for consistency.

    use DragonCode\Support\Facades\Arr;
    use DragonCode\Support\Facades\Str;
    
    // Array operations
    $flattened = Arr::of(['a' => ['b' => 1]])->flattenKeys();
    $count = Arr::count(['a', 'b', 'c']); // Returns 3
    
    // String operations
    $trimmed = Str::trim('  hello  ');
    $matches = Str::matchAll('/\d+/', 'Order #123');
    
  3. Where to Look First:

    • Facade Classes: DragonCode\Support\Facades\Arr, Str, File, Digit, etc.
    • Method Index: Browse the GitHub releases for recent additions (e.g., Arr::toInstance(), Str::matchAll()).
    • Tests: Tests/Unit/ for usage examples and edge cases.

Implementation Patterns

Core Workflows

1. Array Manipulation

  • Fluent Chaining:
    $result = Arr::of($array)
        ->filter(fn($v) => $v > 0)
        ->map(fn($v) => $v * 2)
        ->toArray();
    
  • Invokable Helpers:
    $count = Arr::of($collection)->count(); // Alternative to `count()`
    $instance = Arr::of(['key' => 'value'])->toInstance(stdClass::class);
    

2. String Processing

  • Regex and Cleanup:
    $cleaned = Str::squish('  extra   spaces  ');
    $numbers = Str::matchAll('/\d+/', $text); // Returns array of matches
    
  • Locale-Agnostic Trimming:
    $trimmed = Str::trim('  hello  ', ' !'); // Custom characters
    

3. Filesystem Automation

  • Directory Operations:
    $paths = Directory::allPaths(storage_path('app'));
    Directory::copy(storage_path('old'), storage_path('new'));
    
  • File Validation:
    $content = File::load('file.txt'); // Throws exception if unreadable
    

4. Type Safety and Instances

  • Dynamic Instantiation:
    $model = Instance::of(User::class)->new(['name' => 'John']);
    $isModel = Instance::of($variable)->is(User::class);
    

Integration Tips

Laravel-Specific Patterns

  • Service Providers: Register custom facade aliases if needed:
    Facades\Support::alias('Arr', 'DragonCode\Support\Facades\Arr');
    
  • Blade Directives: Extend Blade with package methods:
    Blade::directive('flatten', function ($expr) {
        return "<?php echo Arr::of({$expr})->flattenKeys(); ?>";
    });
    
    Usage:
    @flatten($array)
    

Testing

  • Mock Facades: Use DragonCode\Support\Facades\Arr::shouldReceive() in PHPUnit:
    Arr::shouldReceive('flattenKeys')->once()->andReturn(['a' => 1]);
    
  • Test Helpers: Leverage existing test classes (e.g., ArrFlattenKeysTest) as templates.

Performance

  • Avoid Overhead: For simple operations (e.g., count()), native PHP may still be faster. Benchmark with:
    $start = microtime(true);
    Arr::count($array);
    $time = microtime(true) - $start;
    

Gotchas and Tips

Pitfalls

  1. Facade Initialization:

    • Issue: Facades may not resolve if auto-discovery is disabled.
    • Fix: Ensure DragonCode\Support\SupportServiceProvider is registered in config/app.php under providers.
  2. Method Naming Conflicts:

    • Issue: Overlapping with Laravel’s native helpers (e.g., Arr::first() vs. Laravel’s collect()->first()).
    • Tip: Prefix custom methods (e.g., Arr::dragonFirst()) or document conflicts in a README.
  3. PHP Version Quirks:

    • Issue: Methods like Str::matchAll() require PHP 8.2+. Check composer.json constraints.
    • Fix: Use feature flags or fallbacks:
      if (function_exists('preg_match_all')) {
          return Str::matchAll($pattern, $subject);
      }
      return [];
      
  4. Filesystem Permissions:

    • Issue: File::load() or Directory::copy() may fail silently on restricted paths.
    • Debug: Enable verbose logging:
      File::load('file.txt', true); // $verbose = true
      
  5. Invokable Helpers:

    • Issue: Arr::of()->toInstance() may throw if the array is malformed.
    • Tip: Validate input:
      if (!Arr::isAssoc($array)) {
          throw new \InvalidArgumentException('Array must be associative.');
      }
      

Debugging Tips

  1. Facade Calls:

    • Log Facade Calls: Override the facade to log method invocations:
      Arr::macro('debug', function () {
          \Log::debug('Arr facade called with:', func_get_args());
          return $this;
      });
      
  2. Array Methods:

    • Visualize Flattening: Use dd() to inspect Arr::flattenKeys() output:
      dd(Arr::of(['a' => ['b' => 1]])->flattenKeys());
      
  3. String Regex:

    • Test Patterns: Use preg_last_error() to debug Str::matchAll():
      $matches = Str::matchAll('/invalid[pattern/', 'text');
      if (preg_last_error()) {
          \Log::error('Regex error:', preg_last_error());
      }
      

Extension Points

  1. Add Custom Methods:

    • Steps:
      1. Extend a facade class (e.g., DragonCode\Support\Facades\Arr):
        public static function customMerge(array $array1, array $array2): array {
            return array_merge($array1, $array2);
        }
        
      2. Add a test: Tests/Unit/ArrCustomMergeTest.
      3. Submit a PR or use locally via composer require with a custom fork.
  2. Override Existing Methods:

    • Example: Replace Arr::flattenKeys() in a service provider:
      Arr::macro('flattenKeys', function () {
          // Custom logic
          return $this->array;
      });
      
  3. Publish Config:

    • Note: The package has no config, but you can publish a stub:
      php artisan vendor:publish --tag="support-config"
      

Pro Tips

  • Alias Facades: Shorten usage in large projects:
    use Arr = DragonCode\Support\Facades\Arr;
    
  • Laravel Mix: Integrate with Laravel Mix for asset processing:
    const { Arr } = require('dragon-code/support');
    mix.webpackConfig({
        plugins: [new CustomPlugin(Arr.of(config).flattenKeys())]
    });
    
  • API Responses: Use Arr::toInstance() to convert collections to DTOs:
    return response()->json(
        Arr::of($users)->mapTo(UserResource::class)->toInstance()
    );
    
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
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
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