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

Utils Laravel Package

nette/utils

Handy PHP utility classes from the Nette Framework: strings, arrays, JSON, dates/times, file system helpers, safe reflection, and more. Lightweight, well-tested, and framework-agnostic—useful building blocks for everyday PHP and Laravel projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nette/utils
    

    Ensure PHP 8.2+ is used (v4.1.0+ requirement).

  2. First Use Case: String/Array Manipulation (most common entry point):

    use Nette\Utils\Strings;
    use Nette\Utils\Arrays;
    
    // Slugify a string
    $slug = Strings::webalize('Hello World!');
    
    // Filter an array
    $filtered = Arrays::filter([1, 2, 'a'], 'is_int');
    
  3. Where to Look First:

    • Documentation: Nette Utils API Docs (auto-generated, comprehensive).
    • Key Classes:
      • Strings (for text processing)
      • Arrays (for array operations)
      • FileSystem (for file/path handling)
      • Image (for GD-based image ops)
      • Process (for subprocess management, v4.1.4+).

Implementation Patterns

1. String/Array Workflows

  • Chaining Operations:
    $cleaned = Strings::trim($input)
        ->webalize()
        ->toAscii();
    
  • Predicates in Arrays:
    $activeUsers = Arrays::first($users, fn($user) => $user['active']);
    

2. File/Image Handling

  • Safe Filename Validation:
    if (!FileSystem::isValidFilename($filename)) {
        throw new \InvalidArgumentException('Invalid filename');
    }
    
  • Image Processing with Warnings:
    $image = Image::fromFile('photo.jpg', $warnings);
    if ($warnings !== null) {
        log($warnings); // Handle GD warnings
    }
    

3. Process Management (v4.1.4+)

  • Secure Subprocess Execution:
    $process = Process::runExecutable('git', ['log', '--oneline']);
    $output = $process->consumeStdOutput();
    
  • Piping Processes:
    $grep = Process::runExecutable('grep', ['error']);
    $process->pipeTo($grep);
    

4. Validation/Type Safety

  • Dynamic Type Checks:
    if (Type::isSimple($value, 'string|int')) {
        // Handle scalar types
    }
    
  • Custom Validators:
    use Nette\Utils\Validators;
    Validators::assert($email, 'email');
    

5. Integration with Laravel

  • Service Provider Binding:
    // config/app.php
    'aliases' => [
        'Utils' => Nette\Utils\Helpers::class,
    ],
    
  • Helper Macros:
    Strings::extend('laravelize', function ($str) {
        return strtolower(str_replace(' ', '-', $str));
    });
    

Gotchas and Tips

Pitfalls

  1. PHP Version Mismatches:

    • v4.x requires PHP 8.2+. Use composer require nette/utils:^3.2 for PHP 7.4+.
    • Gotcha: Strings::webalize() requires the INTL extension (throws MissingExtensionException otherwise).
  2. Image Handling Quirks:

    • GD Warnings: Always pass $warnings to Image::fromFile()/Image::fromString() to avoid suppressed PHP warnings.
    • AVIF Support: Requires GD 2.3.3+ (check with Image::isTypeSupported('avif')).
  3. Process Execution Risks:

    • Shell Injection: Use Process::runExecutable() (array args) instead of runCommand() (shell string).
    • Timeouts: Set ->setTimeout(30) to avoid hanging processes.
  4. Filename Validation:

    • False Positives: FileSystem::isValidFilename() rejects trailing dots/spaces (common in user uploads). Use FileSystem::normalizePath() to clean paths first.
  5. Type System Caveats:

    • Union Types: Type::isSimple() may not handle complex unions (e.g., array<int, string>|null). Use Type::fromValue() for runtime checks.

Debugging Tips

  1. Process Output:
    $process = Process::runExecutable('ls', ['-la']);
    $process->consumeStdError(); // Check for errors
    
  2. Image Errors:
    try {
        $image = Image::fromString($data);
    } catch (UnknownImageFileException $e) {
        log("Unsupported format: " . $e->getMessage());
    }
    
  3. String Offsets:
    • Use Strings::offsetGet() for UTF-8-aware substring access (avoids mb_substr boilerplate).

Extension Points

  1. Custom Validators:
    Validators::addRule('custom', function ($value) {
        return preg_match('/^user_\d+$/', $value);
    });
    
  2. Process Hooks:
    • Extend Process with custom output parsers:
      $process->onStdOutput(function ($line) {
          yield "Processed: " . $line;
      });
      
  3. Image Filters:
    • Chain Image methods for custom effects:
      $image->resize(800, 600)
            ->sharpen(15)
            ->save('output.jpg');
      

Performance Notes

  • Memoization: Use Iterables::memoize() for expensive array operations:
    $memoized = Iterables::memoize($expensiveArray, fn($item) => $item * 2);
    
  • Batch Processing: For large arrays, prefer Arrays::batch() over loops:
    Arrays::batch($items, 100, fn($batch) => processBatch($batch));
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
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