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 library from Nette: strings, arrays, filesystem, safe JSON, and more. Includes proven helpers like Strings, Arrays, FileSystem, and Validators to simplify everyday tasks with clean APIs, good performance, and broad compatibility.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nette/utils
    

    No configuration required—use classes directly via Nette\Utils\*.

  2. First Use Case: String Manipulation (e.g., slug generation for a blog post):

    use Nette\Utils\Strings;
    
    $title = "Hello, World! 2024";
    $slug = Strings::webalize($title); // Output: "hello-world-2024"
    

    Array Transformation (e.g., converting an array of user data):

    use Nette\Utils\Arrays;
    
    $users = [
        ['name' => 'Alice', 'age' => 30],
        ['name' => 'Bob', 'age' => 25],
    ];
    $names = Arrays::map($users, fn($user) => $user['name']); // ['Alice', 'Bob']
    

    File Validation (e.g., sanitizing uploads):

    use Nette\Utils\FileSystem;
    
    $filename = "my-file.txt";
    if (FileSystem::isValidFilename($filename)) {
        // Safe to use
    }
    
  3. Where to Look First:

    • Documentation: GitHub README (focus on Strings, Arrays, FileSystem, and Process).
    • API Reference: Browse the source code for method signatures.
    • Common Patterns: Start with Strings::*, Arrays::*, and Validators::* for 80% of use cases.

Implementation Patterns

1. String Handling Workflows

  • Slug Generation:

    use Nette\Utils\Strings;
    
    $slug = Strings::webalize("User's Profile 2024"); // "users-profile-2024"
    

    Tip: Chain with Strings::lower() for consistency.

  • Text Sanitization:

    use Nette\Utils\Html;
    
    $safeHtml = Html::escapeHtml($userInput); // Prevents XSS
    
  • Unicode-Aware Operations:

    use Nette\Utils\Strings;
    
    $length = Strings::length("Café"); // 4 (handles UTF-8)
    $substring = Strings::substring("Hello, 世界", 0, 5); // "Hello"
    

2. Array/Collection Patterns

  • Transformations:

    use Nette\Utils\Arrays;
    
    $prices = [100, 200, 300];
    $formatted = Arrays::map($prices, fn($p) => '$' . number_format($p/100, 2));
    // ['$1.00', '$2.00', '$3.00']
    
  • Filtering with Predicates:

    use Nette\Utils\Arrays;
    
    $activeUsers = Arrays::filter($users, fn($user) => $user['active']);
    
  • Key-Based Operations:

    use Nette\Utils\Arrays;
    
    $renamed = Arrays::renameKey($data, 'oldKey', 'newKey');
    $firstKey = Arrays::firstKey($data); // Get first array key
    
  • Iterables:

    use Nette\Utils\Iterables;
    
    $memoized = Iterables::memoize($expensiveFunction); // Cache results
    

3. Process Management

  • Safe Subprocess Execution (e.g., running ffmpeg):

    use Nette\Utils\Process;
    
    $process = Process::runExecutable('ffmpeg', ['-i', 'input.mp4', 'output.mp4']);
    if ($process->isSuccess()) {
        echo "Success!";
    }
    
  • Streaming Output:

    $process = Process::runExecutable('tail', ['-f', '/var/log/syslog']);
    while ($process->consumeStdOutput()) {
        echo $process->getStdOutput();
    }
    

4. Image Processing

  • Dynamic Thumbnails:

    use Nette\Utils\Image;
    
    $image = Image::fromFile('upload.jpg');
    $image->resize(300, 200);
    $image->save('thumbnail.jpg');
    
  • Type Detection:

    $type = Image::detectTypeFromFile('image.png'); // Returns ImageType::PNG
    

5. Validation & Type Safety

  • Input Validation:

    use Nette\Utils\Validators;
    
    if (Validators::isEmail($input)) {
        // Valid email
    }
    
  • Type Checking:

    use Nette\Utils\Type;
    
    if (Type::isString($value)) {
        // Handle string
    }
    

6. File System Operations

  • Cross-Platform Paths:

    use Nette\Utils\FileSystem;
    
    $path = FileSystem::platformSlashes('folder/file.txt');
    
  • Permissions:

    FileSystem::makeWritable('storage/logs', 0644);
    

7. Integration with Laravel

  • Service Provider:

    // config/nette.php
    return [
        'default_locale' => 'en_US',
    ];
    
    // app/Providers/NetteServiceProvider.php
    public function register()
    {
        $this->app->singleton('nette.utils', function () {
            return new \Nette\Utils\Strings();
        });
    }
    
  • Facade (Optional): Create a facade to wrap Nette\Utils\* classes for cleaner syntax:

    // app/Facades/Nette.php
    public static function slug($text) {
        return Strings::webalize($text);
    }
    
  • Blade Directives:

    // app/Providers/BladeServiceProvider.php
    Blade::directive('slug', function ($text) {
        return "<?php echo \\Nette\\Utils\\Strings::webalize({$text}); ?>";
    });
    

    Usage in Blade:

    <h1>{{ slug($title) }}</h1>>
    

Gotchas and Tips

Pitfalls

  1. PHP Version Requirements:

    • v4.x requires PHP 8.2+. Use v3.x for older PHP versions.
    • Methods like Strings::webalize() require the intl extension (throws E_USER_NOTICE if missing).
  2. Case Sensitivity in Constants:

    • Constants are PascalCase (e.g., ImageType::PNG), not snake_case.
    • Avoid imageType::PNG (will fail).
  3. GD Warnings in Images:

    • By default, GD warnings are suppressed. Use $warnings parameter to capture them:
      $image = Image::fromFile('image.jpg', $warnings);
      if ($warnings !== null) {
          error_log($warnings);
      }
      
  4. Process Timeouts:

    • Always set timeouts for Process::run*() to avoid hanging:
      $process = Process::runExecutable('slow-command', [], 30); // 30-second timeout
      
  5. Windows-Specific Quirks:

    • FileSystem::isValidFilename() rejects Windows reserved names (e.g., CON, PRN).
    • Use FileSystem::platformSlashes() for cross-platform paths.
  6. Deprecated Methods:

    • Avoid Reflection::getReturnType() (use getReturnTypes() for PHP 8.1+).
    • Callback::closure() triggers deprecation notices.
  7. Unicode Edge Cases:

    • Strings::trim() may not handle all Unicode whitespace (e.g., \u{200B}). Test with:
      Strings::trim("\u{200B}text\u{200B}"); // May return "text" or "\u{200B}text\u{200B}"
      
  8. Image Type Detection:

    • Image::detectTypeFromFile() may return null for corrupted files. Always check:
      $type = Image::detectTypeFromFile('corrupt.jpg');
      if ($type === null) {
          throw new \RuntimeException('Invalid image');
      }
      

Debugging Tips

  1. Enable GD Warnings:

    $image = Image::fromFile('image.jpg', $warnings);
    error_log($warnings); // Log captured warnings
    
  2. Process Debugging:

    • Use consumeStdError() to capture
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle