Skill v1.0.1
currentAutomated scan100/1006 files
version: "1.0.1" name: nette-utils description: Provides Nette Utils helper classes. Use when working with Arrays, Strings, Image, Finder, FileSystem, Json, Validators, DateTime, Html element builder, Random, Callback, Type, or SmartObject from nette/utils. Do NOT use for Nette Schema, Nette Forms, Nette Database, Latte filters, or DI configuration.
Nette Utils
A collection of useful PHP utility classes for everyday tasks.
composer require nette/utils
For detailed references:
DateTime
Extended DateTime class with strict validation and DST fixes.
use Nette\Utils\DateTime;// Create from various formatsDateTime::from(1138013640); // from timestampDateTime::from('2024-02-26 04:15:32'); // from stringDateTime::from($dateTimeInterface); // from object// Create from parts (throws on invalid date)DateTime::fromParts(2024, 2, 26, 4, 15);// Immutable modification$clone = $original->modifyClone('+1 day');// Convert relative time to secondsDateTime::relativeToSeconds('10 minutes'); // 600DateTime::relativeToSeconds('-1 hour'); // -3600// JSON serialization (ISO 8601)echo json_encode($dateTime); // "2024-02-26T04:15:32+01:00"
Json
Safe JSON encoding/decoding with exceptions.
use Nette\Utils\Json;// Encode$json = Json::encode($data);$json = Json::encode($data, pretty: true); // formatted$json = Json::encode($data, asciiSafe: true); // escape unicode$json = Json::encode($data, htmlSafe: true); // escape < > &$json = Json::encode($data, forceObjects: true); // arrays as objects// Decode$data = Json::decode($json); // returns stdClass$data = Json::decode($json, forceArray: true); // returns array// Both throw Nette\Utils\JsonException on error
Validators
Value validation and type checking.
use Nette\Utils\Validators;// Type checkingValidators::is($value, 'int'); // true/falseValidators::is($value, 'int|string|bool'); // union typesValidators::is($value, 'int:0..100'); // rangeValidators::is($value, 'string:10..20'); // length rangeValidators::is($value, 'array:1..5'); // count range// Specific validatorsValidators::isEmail('user@example.com'); // trueValidators::isUrl('https://nette.org'); // trueValidators::isUri('mailto:info@nette.org'); // trueValidators::isNumeric('123'); // true (string number)Validators::isNumericInt('123'); // true (string integer)Validators::isUnicode($string); // valid UTF-8?Validators::isInRange($value, [0, 100]); // in range?Validators::isNone($value); // 0, '', false, null, []?// Assertion (throws on failure)Validators::assert($value, 'string:5..10');Validators::assertField($array, 'key', 'int');
Expected Types
| Type | Description | ||||
|---|---|---|---|---|---|
int, float, bool, string, array, null | PHP types | ||||
scalar | `int\ | float\ | bool\ | string` | |
list | indexed array | ||||
number | `int\ | float` | |||
numeric | number or numeric string | ||||
unicode | valid UTF-8 string | ||||
email, url, uri | format validation | ||||
alnum, alpha, digit, lower, upper | character classes | ||||
class, interface | existing class/interface | ||||
file, directory | existing path |
FileSystem
File operations with exception handling.
use Nette\Utils\FileSystem;// Read/Write$content = FileSystem::read('/path/to/file');FileSystem::write('/path/to/file', $content);// Read large files line by lineforeach (FileSystem::readLines('/path/to/file') as $line) {echo $line;}// Copy/Move/DeleteFileSystem::copy($source, $target);FileSystem::rename($source, $target);FileSystem::delete($path); // works on directories too// Directory operationsFileSystem::createDir('/path/to/dir');FileSystem::makeWritable('/path');// Path utilitiesFileSystem::isAbsolute('../path'); // falseFileSystem::normalizePath('/file/../path'); // '/path'FileSystem::joinPaths('a', 'b', 'file.txt'); // 'a/b/file.txt'FileSystem::resolvePath('/base', '../file.txt'); // '/file.txt'FileSystem::unixSlashes('path\\to\\file'); // 'path/to/file'
Floats
Safe floating-point comparisons.
use Nette\Utils\Floats;// Compare floats (handles precision issues)Floats::isZero(0.0); // trueFloats::areEqual(0.1 + 0.2, 0.3); // true (!)Floats::isLessThan($a, $b);Floats::isLessThanOrEqualTo($a, $b);Floats::isGreaterThan($a, $b);Floats::isGreaterThanOrEqualTo($a, $b);// Compare with resultFloats::compare($a, $b); // -1, 0, or 1
Random
Cryptographically secure random values.
use Nette\Utils\Random;// Random string (default: 0-9, a-z)Random::generate(10); // 'a4b3c2d1e0'Random::generate(10, 'A-Z'); // 'XYZABCDEF'Random::generate(10, '0-9A-Za-z'); // 'aB3cD4eF5g'Random::generate(10, 'A-Za-z!@#$%'); // 'aBc!@Def#$'
Paginator
Pagination calculations.
use Nette\Utils\Paginator;$paginator = new Paginator;$paginator->setItemCount(100); // total items$paginator->setItemsPerPage(10);$paginator->setPage(3);echo $paginator->getPageCount(); // 10echo $paginator->getOffset(); // 20 (for SQL OFFSET)echo $paginator->getLength(); // 10 (for SQL LIMIT)echo $paginator->isFirst(); // falseecho $paginator->isLast(); // false
Html
HTML element builder.
use Nette\Utils\Html;// Create element$el = Html::el('a', ['href' => 'https://nette.org']);$el->setText('Nette');echo $el; // <a href="https://nette.org">Nette</a>// Fluent interface$el = Html::el('div')->id('container')->class('main active')->data('id', 123)->setHtml('<p>Content</p>');// ShorthandHtml::el('input', ['type' => 'text', 'name' => 'email']);Html::el('div class="box"'); // from string
Callback
Working with PHP callables.
use Nette\Utils\Callback;// Normalize to closure$closure = Callback::closure($callable);$closure = Callback::closure($obj, 'method');$closure = Callback::closure('Class::method');// Check validityCallback::check($callable); // throws if invalid// Invoke with exception wrappingCallback::invokeSafe($callable, $args, $onError);// Reflection$reflection = Callback::toReflection($callable);
Type
PHP type utilities.
use Nette\Utils\Type;// Get type from reflection$type = Type::fromReflection($reflectionProperty);$type = Type::fromReflection($reflectionParameter);// Parse type string$type = Type::fromString('int|string|null');// Type info$type->getSingleName(); // 'int' or null if union$type->getNames(); // ['int', 'string', 'null']$type->isUnion(); // true$type->isIntersection(); // false$type->isBuiltin(); // true$type->allowsNull(); // true$type->isClass(); // false
SmartObject Trait
Modern PHP object features for classes.
use Nette\SmartObject;class MyClass{use SmartObject;private string $name;public function getName(): string{return $this->name;}public function setName(string $name): void{$this->name = $name;}}$obj = new MyClass;$obj->name = 'John'; // calls setName()echo $obj->name; // calls getName()
Online Documentation
For detailed information, use WebFetch on these URLs:
- Arrays – array helpers
- Strings – string functions and regex
- Images – image manipulation
- FileSystem – file operations
- Finder – file searching
- JSON – safe JSON handling
- Validators – type checking and validation