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.
Installation:
composer require nette/utils
No configuration required—use classes directly via Nette\Utils\*.
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
}
Where to Look First:
Strings, Arrays, FileSystem, and Process).Strings::*, Arrays::*, and Validators::* for 80% of use cases.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"
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
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();
}
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
Input Validation:
use Nette\Utils\Validators;
if (Validators::isEmail($input)) {
// Valid email
}
Type Checking:
use Nette\Utils\Type;
if (Type::isString($value)) {
// Handle string
}
Cross-Platform Paths:
use Nette\Utils\FileSystem;
$path = FileSystem::platformSlashes('folder/file.txt');
Permissions:
FileSystem::makeWritable('storage/logs', 0644);
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>>
PHP Version Requirements:
v3.x for older PHP versions.Strings::webalize() require the intl extension (throws E_USER_NOTICE if missing).Case Sensitivity in Constants:
ImageType::PNG), not snake_case.imageType::PNG (will fail).GD Warnings in Images:
$warnings parameter to capture them:
$image = Image::fromFile('image.jpg', $warnings);
if ($warnings !== null) {
error_log($warnings);
}
Process Timeouts:
Process::run*() to avoid hanging:
$process = Process::runExecutable('slow-command', [], 30); // 30-second timeout
Windows-Specific Quirks:
FileSystem::isValidFilename() rejects Windows reserved names (e.g., CON, PRN).FileSystem::platformSlashes() for cross-platform paths.Deprecated Methods:
Reflection::getReturnType() (use getReturnTypes() for PHP 8.1+).Callback::closure() triggers deprecation notices.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}"
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');
}
Enable GD Warnings:
$image = Image::fromFile('image.jpg', $warnings);
error_log($warnings); // Log captured warnings
Process Debugging:
consumeStdError() to captureHow can I help you explore Laravel packages today?