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

Utilities Laravel Package

becklyn/utilities

Utility helpers for PHP/Laravel projects: small, reusable functions and classes to simplify common tasks, improve developer ergonomics, and reduce boilerplate across your application and packages.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Require the package via Composer:

    composer require becklyn/utilities
    

    No additional configuration is required unless using Laravel-specific features (e.g., service providers).

  2. Where to Look First

    • Source Code: Browse the src/Utilities directory for available classes.
    • Key Classes:
      • Enum for structured enumerated values.
      • IterableToCollectionConstructionTrait for converting iterables to Laravel Collections.
      • ArrayHelper, StringHelper, LaravelResponse (if Laravel-specific utilities exist).
  3. First Use Case Convert an array to a Laravel Collection using the trait:

    use Becklyn\Utilities\IterableToCollectionConstructionTrait;
    
    class MyService
    {
        use IterableToCollectionConstructionTrait;
    
        public function processData(array $data)
        {
            $collection = $this->toCollection($data);
            return $collection->filter(fn($item) => $item['active']);
        }
    }
    

Implementation Patterns

1. Leveraging the Enum Class

  • Define Custom Enums:
    use Becklyn\Utilities\Enum;
    
    class UserRole extends Enum
    {
        public const ADMIN = 'admin';
        public const EDITOR = 'editor';
        public const USER = 'user';
    
        protected static array $values = [
            self::ADMIN => 'Administrator',
            self::EDITOR => 'Editor',
            self::USER => 'User',
        ];
    }
    
  • Usage:
    $role = UserRole::ADMIN; // Returns 'admin'
    echo $role->value; // 'admin'
    echo $role->label; // 'Administrator'
    

2. Iterable to Collection Conversion

  • Trait Integration:
    use Becklyn\Utilities\IterableToCollectionConstructionTrait;
    
    class DataImporter
    {
        use IterableToCollectionConstructionTrait;
    
        public function import(array $rawData)
        {
            $collection = $this->toCollection($rawData);
            return $collection->map(fn($item) => $this->transform($item));
        }
    }
    
  • Works with Any Iterable:
    $generator = function() { yield 1; yield 2; yield 3; };
    $collection = $this->toCollection($generator());
    

3. Laravel-Specific Utilities

  • API Response Helper (if available):
    use Becklyn\Utilities\LaravelResponse;
    
    return LaravelResponse::success($data, 'Operation completed');
    
  • Custom Collection Macros:
    use Becklyn\Utilities\ArrayHelper;
    use Illuminate\Support\Collection;
    
    Collection::macro('deepFlatten', function() {
        return ArrayHelper::flatten($this->all());
    });
    

4. Extending Existing Utilities

  • Override Enum Behavior:
    class CustomEnum extends Enum
    {
        public function getDisplayValue(): string
        {
            return strtoupper($this->label);
        }
    }
    
  • Decorate Traits:
    trait ExtendedCollectionTrait
    {
        use IterableToCollectionConstructionTrait;
    
        public function customMethod()
        {
            return $this->filter(fn($item) => true);
        }
    }
    

5. Integration with Laravel Services

  • Service Container Binding:
    $this->app->bind(MyService::class, function ($app) {
        $service = new MyService();
        $service->setLogger($app->make(Logger::class));
        return $service;
    });
    
  • Dependency Injection:
    public function __construct(private MyService $myService) {}
    

Gotchas and Tips

Pitfalls

  1. PHP 8.2+ Requirement

    • Ensure your project uses PHP 8.2+. Test locally before deploying:
      php -v
      
    • Fix: Update your PHP version or use a Docker container with PHP 8.2+.
  2. Laravel Version Compatibility

    • The package supports Laravel 9+ (via illuminate/collections ^9). If using Laravel 10/11, verify no breaking changes exist.
    • Tip: Check the changelog for Laravel-specific updates.
  3. Enum Type Safety

    • Enums rely on PHP 8.0+ features. Incorrect usage may throw TypeError:
      $invalid = UserRole::INVALID; // Throws error if not defined
      
    • Fix: Use Enum::isValid() to check values:
      if (UserRole::isValid('admin')) { /* ... */ }
      
  4. Trait Method Conflicts

    • The IterableToCollectionConstructionTrait may conflict with existing toCollection() methods.
    • Solution: Rename the trait method or use a namespace alias:
      use Becklyn\Utilities\IterableToCollectionConstructionTrait as BecklynCollectionTrait;
      
  5. Undocumented Features

    • Some utilities may lack PHPDoc or tests. Use php artisan ide-helper:generate to auto-generate docs:
      composer require --dev barryvdh/laravel-ide-helper
      php artisan ide-helper:generate
      

Debugging Tips

  1. Enable Strict Typing Add to composer.json to catch type-related issues early:

    "config": {
        "platform-check": true,
        "optimize-autoloader": true,
        "preferred-install": "dist"
    }
    
  2. Log Utility Outputs Wrap utility calls in debug logs:

    \Log::debug('Enum value:', ['role' => $role->value]);
    
  3. Test Edge Cases

    • Empty iterables:
      $this->toCollection([])->dump(); // Should return empty collection
      
    • Invalid enum values:
      try {
          UserRole::from('invalid');
      } catch (\InvalidArgumentException $e) {
          \Log::error($e->getMessage());
      }
      

Extension Points

  1. Custom Enums Extend the base Enum class for domain-specific logic:

    class PaymentStatus extends Enum
    {
        public const PENDING = 'pending';
        public const COMPLETED = 'completed';
        public const FAILED = 'failed';
    
        public function isFinal(): bool
        {
            return in_array($this->value, [self::COMPLETED, self::FAILED]);
        }
    }
    
  2. Collection Macros Add reusable methods to Laravel Collections:

    use Becklyn\Utilities\ArrayHelper;
    use Illuminate\Support\Collection;
    
    Collection::macro('chunkBy', function ($key) {
        return ArrayHelper::chunkBy($this->all(), $key);
    });
    
  3. Service Provider Integration Bind utilities to the Laravel container for global access:

    public function register()
    {
        $this->app->singleton(MyService::class, function ($app) {
            $service = new MyService();
            $service->setConfig($app['config']['my_service']);
            return $service;
        });
    }
    

Performance Quirks

  1. Iterable Conversion Overhead The toCollection() trait may add minor overhead for large iterables. Benchmark:

    $microTime = microtime(true);
    $collection = $this->toCollection($largeArray);
    \Log::debug('Conversion time:', microtime(true) - $microTime);
    
  2. Enum Reflection Avoid heavy reflection in performance-critical paths:

    // Slow: Avoid in loops
    $enumValues = UserRole::getValues();
    
    // Fast: Cache results
    static $cachedValues = null;
    if (is_null($cachedValues)) {
        $cachedValues = UserRole::getValues();
    }
    

Configuration Quirks

  1. No Published Config The package may not publish a config file. Override defaults via environment variables or service binding:

    $this->app->bind('config', function () {
        return [
            'my_service' => [
                'timeout' => env('MY_SERVICE_TIMEOUT', 30),
            ],
        ];
    });
    
  2. Symfony Dependency If using Symfony components (e.g., HttpFoundation), ensure compatibility:

    composer require symfony/http-foundation ^6.4
    

Testing Strategies

  1. Unit Test Enums
    public function testEnumValidation()
    {
        $this->assertTrue(UserRole::isValid('admin'));
        $this->assertFalse(UserRole::isValid('invalid'));
    }
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor