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

Helpers Laravel Package

elasticms/helpers

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Add the package via Composer in your Laravel project:

    composer require elasticms/helpers
    

    Ensure your project uses PHP 8.1+ and has PHPStan configured (minimum version ^1.0).

  2. First Use Case: Replace a loose PHP function with its PHPStan-compliant wrapper. For example:

    // Before (loose, triggers PHPStan errors)
    $filtered = array_filter($array, fn($item) => $item > 10);
    
    // After (typed, PHPStan-compliant)
    use Elastic\Helpers\ArrayHelper;
    $filtered = ArrayHelper::arrayFilter($array, fn(int $item): bool => $item > 10);
    
  3. PHPStan Configuration: Update phpstan.neon to recognize the package’s types:

    includes:
        - vendor/elasticms/helpers/phpstan/extension.neon
    
  4. Verify Compliance: Run PHPStan to confirm errors are resolved:

    vendor/bin/phpstan analyse app --level=max
    

Implementation Patterns

Usage Patterns

  1. Drop-in Replacements: Replace native PHP functions with typed alternatives:

    // Native (loose)
    $merged = array_merge($array1, $array2);
    
    // Typed (PHPStan-compliant)
    use Elastic\Helpers\ArrayHelper;
    $merged = ArrayHelper::arrayMerge($array1, $array2);
    
  2. Laravel Integration: Use alongside Laravel’s helpers for consistency:

    use Elastic\Helpers\StrHelper;
    use Illuminate\Support\Str;
    
    // Native Laravel (loose)
    $slug = Str::slug('Hello World');
    
    // Combined (typed string helper)
    $slug = StrHelper::slug('Hello World'); // Returns string|false with type hints
    
  3. Custom Callbacks: Leverage typed callbacks for array/string operations:

    use Elastic\Helpers\ArrayHelper;
    
    $result = ArrayHelper::arrayMap(
        $items,
        fn(array $item): string => StrHelper::ucfirst($item['name'])
    );
    
  4. File/HTTP Helpers: Use typed wrappers for I/O operations:

    use Elastic\Helpers\FileHelper;
    
    $content = FileHelper::fileGetContents('path/to/file.txt'); // Returns string|false
    

Workflows

  1. New Feature Development:

    • Use typed helpers from day one to avoid PHPStan errors in PRs.
    • Example: Replace json_encode with JsonHelper::encode() for typed responses.
  2. Legacy Code Refactoring:

    • Gradually replace loose functions in critical paths (e.g., API responses, data transformations).
    • Use IDE refactoring tools to bulk-replace functions (e.g., array_filterArrayHelper::arrayFilter).
  3. Testing:

    • Write tests with strict type assertions:
      $this->assertIsArray(ArrayHelper::arrayFilter($data));
      $this->assertIsString(JsonHelper::encode($data));
      
  4. CI/CD Enforcement:

    • Add PHPStan to your pipeline with the package’s extension:
      # .github/workflows/phpstan.yml
      - name: PHPStan
        run: vendor/bin/phpstan analyse --level=max
      

Integration Tips

  1. Alias Native Functions: Create aliases in a service provider to ease migration:

    // app/Providers/AppServiceProvider.php
    use Elastic\Helpers\ArrayHelper;
    
    if (!function_exists('array_filter_typed')) {
        function array_filter_typed(array $array, callable $callback): array {
            return ArrayHelper::arrayFilter($array, $callback);
        }
    }
    
  2. Custom PHPStan Rules: Extend the package’s rules for project-specific types:

    # phpstan.neon
    extends:
        - vendor/elasticms/helpers/phpstan/extension.neon
    rules:
        Elastic\Helpers\ArrayHelper::arrayMerge:
            - "Your custom rule for array shape validation"
    
  3. Performance Considerations:

    • Benchmark critical paths before/after replacement (e.g., array_map vs. ArrayHelper::arrayMap).
    • Use native functions in performance-sensitive code (e.g., loops) and typed helpers for safety.
  4. Documentation:

    • Add a HELPERS.md to your repo with:
      • List of replaced functions and their typed alternatives.
      • Examples for common use cases (e.g., Laravel Blade templates).

Gotchas and Tips

Pitfalls

  1. Type Mismatch Errors:

    • Issue: PHPStan may flag type mismatches if callbacks or arguments don’t align with the helper’s expectations.
      // Fails: Callback expects `int`, but `array_filter` passes `mixed`.
      ArrayHelper::arrayFilter($items, fn($item) => $item > 10); // Error: Argument 2 expects `int $item`
      
    • Fix: Explicitly type hint callbacks:
      ArrayHelper::arrayFilter($items, fn(int $item): bool => $item > 10);
      
  2. Null Handling:

    • Issue: Native PHP functions (e.g., file_get_contents) return false on failure, but typed helpers may return null or throw exceptions.
      $content = FileHelper::fileGetContents('nonexistent.txt'); // Returns null
      
    • Fix: Use null-safe operators or validate returns:
      $content = FileHelper::fileGetContents('file.txt') ?: throw new \RuntimeException('File not found');
      
  3. Laravel-Specific Conflicts:

    • Issue: Overlapping helpers (e.g., Str::slug vs. StrHelper::slug) may cause confusion.
    • Fix: Standardize on one package per namespace (e.g., prefer StrHelper for typed operations).
  4. PHPStan Configuration Overrides:

    • Issue: Custom PHPStan rules may conflict with the package’s defaults.
    • Fix: Merge configurations carefully:
      # phpstan.neon
      extends:
          - vendor/elasticms/helpers/phpstan/extension.neon
          - phpstan-custom-rules.neon
      
  5. Runtime vs. Static Analysis:

    • Issue: Typed helpers enforce static contracts but may not catch runtime errors (e.g., invalid JSON).
      JsonHelper::encode(invalid_data); // PHPStan passes, but may throw at runtime.
      
    • Fix: Combine with runtime validation:
      $data = JsonHelper::encode($array);
      if (json_last_error() !== JSON_ERROR_NONE) {
          throw new \InvalidArgumentException('Invalid JSON data');
      }
      

Debugging

  1. PHPStan False Positives:

    • If PHPStan still flags errors after replacement, check:
      • The helper’s PHPDoc annotations (@return types).
      • Your project’s PHPStan level (e.g., --level=max may be too strict).
  2. IDE Autocompletion:

    • If IDEs (e.g., PHPStorm) don’t recognize the helpers:
      • Ensure vendor/elasticms/helpers is included in PHPStan’s autoload.
      • Restart the IDE or invalidate caches.
  3. Performance Bottlenecks:

    • Profile wrapped functions with Xdebug:
      xdebug run-script -- php -d xdebug.mode=profile app/console
      
    • Compare against native functions using microtime(true).

Tips

  1. Partial Adoption:

    • Start with high-impact functions (e.g., array_map, json_encode) and expand gradually.
  2. Custom Helpers:

    • Extend the package’s base classes to add project-specific helpers:
      use Elastic\Helpers\BaseHelper;
      
      class AppHelper extends BaseHelper {
          public static function customMerge(array ...$arrays): array {
              return array_merge(...$arrays);
          }
      }
      
  3. PHPStan Baselines:

    • Use baselines to ignore legacy errors during migration:
      vendor/bin/phpstan analyse --generate-baseline
      
  4. Laravel Facades:

    • Create facades for helpers to integrate with Laravel’s IoC:
      // app/Facades/HelperFacade.php
      namespace App\Facades;
      use Elastic\Helpers\ArrayHelper;
      use Illuminate\Support\Facades\Facade;
      
      class HelperFacade extends Facade {
          protected static function getFacadeAccessor() { return ArrayHelper::class; }
      }
      
      Then use Helper::arrayFilter() globally.
  5. Changelog Awareness:

    • Monitor the package’s releases for breaking changes (e.g., type signature updates in minor versions).
  6. Community Gaps:

    • Contribute missing helpers (e.g., array_reduce, preg_match) via PRs to the [elasticMS
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