---
title: "Value Project"
description: "Composable value types, explicit scalar conversions, automatic parsing and value inspection"
type: "docs"
category: "doc"
tags: [php]
authors: [Anonymous]
date: "2026-11-15"
last_update: "2026-11-15"
time_minutes: 1
draft: false
unlisted: false
url: "https://www.derafu.dev/docs/data/value"
---

# Derafu Value



---

## Introduction

Validate, convert, interpret and inspect PHP values with explicit contracts

# Value Validation and Conversion

[![GitHub](https://img.shields.io/badge/github-derafu%2Fvalue-blue?logo=github)](https://github.com/derafu/value)
![GitHub last commit](https://img.shields.io/github/last-commit/derafu/value/main)
![CI Workflow](https://github.com/derafu/value/actions/workflows/ci.yml/badge.svg?branch=main&amp;event=push)
![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/derafu/value)
![GitHub Issues](https://img.shields.io/github/issues-raw/derafu/value)
![Total Downloads](https://poser.pugx.org/derafu/value/downloads)
![Monthly Downloads](https://poser.pugx.org/derafu/value/d/monthly)

`derafu/value` provides composable types, strict scalar reads, explicit conversions, automatic interpretation and value inspection. It requires PHP 8.5 or later and `derafu/translation`.

## Installation

```bash
composer require derafu/value
```

## Components

All four public utility classes live in `Derafu\Value`.

| Class | Responsibility | Guide |
| --- | --- | --- |
| `ValueCaster` | Read scalar values strictly or request explicit conversions. | [Casting](casting) |
| `ValueParser` | Interpret individual values, with optional numeric format and precision preservation. | [Parsing](parsing) |
| `ValueType` | Compose strict checks, explicit conversions, enums, dates and collection types. | [Types](types) |
| `ValueInspector` | Inspect values without converting or normalizing them. | [Inspection](inspection) |

`ValueType&lt;T&gt;` is a `final readonly` object. The other classes expose static methods. Errors support translation through [Derafu Translation](https://www.derafu.dev/docs/core/translation); see [Exceptions and Translations](translations).

## Choose an Operation

```php
use Derafu\Value\ValueCaster;
use Derafu\Value\ValueInspector;
use Derafu\Value\ValueParser;
use Derafu\Value\ValueType;

ValueCaster::requireInt(12);    // 12; rejects null and non-integers
ValueCaster::getInt(null);      // null; rejects other non-integers
ValueType::int()-&gt;parse(12);     // 12; strings would be rejected
ValueCaster::toInt(&#039;12.0&#039;);      // 12; the destination type is explicit
ValueParser::parse(&#039;12.0&#039;);      // 12; the parser chooses the interpretation
ValueInspector::isBlank(&#039;&#039;);    // true; inspection does not convert anything
```

Strict types validate the supplied PHP type. ValueCaster provides getXXX()/requireXXX() for strict scalar reads and toXXX() for explicit conversions. String reads additionally accept Stringable. The parser recognizes supported text representations and keeps unrecognized text intact. None of these operations reads array keys or assigns defaults.

## Null and Collections

`ValueCaster::getXXX()` and `toXXX()` preserve null; `requireXXX()` rejects it. A conversion type such as `ValueType::toInt()` rejects it unless `nullable()` is explicitly applied. The parser returns native non-text values unchanged, including `null`, arrays, objects without `Stringable` and resources.

Collection types validate or convert their elements because that traversal is explicitly part of their type definition. `ValueParser` processes one value and does not recurse into arrays.




---

## Casting

Read scalar values and objects strictly or convert scalars explicitly, with nullable and required read methods

# ValueCaster

`ValueCaster` exposes strict reads and explicit conversions. Every method accepts `mixed`; invalid input throws instead of silently becoming a default value.

## Strict Reads

`getXXX()` accepts null and otherwise requires the supported input type. `requireXXX()` rejects null as well as incorrect types. Reads preserve existing types, with Stringable accepted specifically by the string methods.

| Nullable read | Required read | Accepted non-null input |
| --- | --- | --- |
| `getString($value): ?string` | `requireString($value): string` | string or Stringable |
| `getInt($value): ?int` | `requireInt($value): int` | int only |
| `getFloat($value): ?float` | `requireFloat($value): float` | float only |
| `getNumber($value): int\|float\|null` | `requireNumber($value): int\|float` | int or float, preserving its type |
| `getBool($value): ?bool` | `requireBool($value): bool` | bool only |
| `getObject($value, $class): ?T` | `requireObject($value, $class): T` | instance of the class or interface, preserving the object |

```php
use Derafu\Value\Exception\TypeMismatchException;
use Derafu\Value\ValueCaster;

ValueCaster::getString(null);     // null
ValueCaster::requireString(&#039; text &#039;); // &#039; text &#039;
ValueCaster::requireInt(12);      // 12
ValueCaster::requireNumber(12.0); // 12.0, still a float
ValueCaster::getBool(false);      // false
ValueCaster::requireObject($pool, CacheItemPoolInterface::class); // $pool

try {
    ValueCaster::getString(5);
} catch (TypeMismatchException $exception) {
    // Numeric input is not accepted by strict string reads.
}
```

String reads convert Stringable objects through the existing `toString()` operation, without trimming. Numbers and booleans are rejected by those reads. `ValueType::string()` remains a strict check of a PHP string and does not accept Stringable.

```php
use Derafu\Value\ValueCaster;

$text = new class () implements Stringable {
    public function __toString(): string
    {
        return &#039; #ABCDEF &#039;;
    }
};

ValueCaster::getString($text);     // &#039; #ABCDEF &#039;
ValueCaster::requireString($text); // &#039; #ABCDEF &#039;
ValueCaster::toString(5);          // &#039;5&#039;: explicit conversion accepts numeric input
```

Strict read failures raise the translatable `TypeMismatchException`. A failing Stringable conversion preserves its ValueConversionException and the original throwable in the cause chain. These methods operate on one supplied value; they do not read keys or assign defaults.

## Explicit Conversions

The `toXXX()` methods preserve null and convert their supported inputs. Unsupported conversions raise `ValueConversionException`.

| Method | Return type |
| --- | --- |
| `toInt($value)` | `?int` |
| `toFloat($value)` | `?float` |
| `toNumber($value)` | `int\|float\|null` |
| `toBool($value)` | `?bool` |
| `toString($value)` | `?string` |

## Integers

`toInt()` accepts integers, integral finite floats within the platform integer range, and numeric strings representing an exact integer in that range. It rejects boolean inputs and never truncates a fraction.

```php
use Derafu\Value\ValueCaster;

ValueCaster::toInt(&#039;0012&#039;);  // 12
ValueCaster::toInt(&#039;12.0&#039;);  // 12
ValueCaster::toInt(&#039;1e3&#039;);   // 1000
ValueCaster::toInt(12.0);   // 12
ValueCaster::toInt(null);   // null
```

Numeric strings are interpreted without a float intermediate. For example, `&#039;1.0000000000000000001&#039;` is rejected as fractional even though converting it to float could hide its fraction. Accepted integers must fit between `PHP_INT_MIN` and `PHP_INT_MAX`.

## Floats

`toFloat()` accepts integers, floats and complete numeric strings according to PHP&#039;s `is_numeric()` rules. Numeric text may contain signs, decimal points, exponent notation and exterior numeric whitespace. Text such as `&#039;12abc&#039;`, `&#039;1,25&#039;`, `&#039;1_000&#039;`, `&#039;INF&#039;` and `&#039;NAN&#039;` is rejected. Booleans are also rejected.

```php
use Derafu\Value\ValueCaster;

ValueCaster::toFloat(&#039;0012&#039;);   // 12.0
ValueCaster::toFloat(&#039;1e3&#039;);    // 1000.0
ValueCaster::toFloat(&#039;1e400&#039;);  // INF
ValueCaster::toFloat(&#039;1e-400&#039;); // 0.0
ValueCaster::toFloat(INF);     // INF
is_nan(ValueCaster::toFloat(NAN)); // true
```

The conversion uses PHP&#039;s float representation, including rounding, infinity and underflow to zero. It does not preserve the spelling or all decimal digits of the source text. The optional policies in [ValueParser](parsing) can retain numeric text when interpretation would alter its format or significant decimal precision.

## Numbers

`toNumber()` calls `toInt()` first. If that conversion fails, it calls `toFloat()`. Failure of the second conversion is propagated as `ValueConversionException`.

```php
use Derafu\Value\ValueCaster;

ValueCaster::toNumber(&#039;12.0&#039;); // 12
ValueCaster::toNumber(12.0);   // 12
ValueCaster::toNumber(&#039;12.5&#039;); // 12.5
ValueCaster::toNumber(null);   // null
```

Use this method when either numeric PHP type is acceptable. It inherits both conversion contracts, including float overflow and underflow. Request `toFloat()` when the result must specifically be a float.

## Booleans

| Accepted input | Result |
| --- | --- |
| `true`, `1`, `1.0`, `&#039;1&#039;`, `&#039;true&#039;`, `&#039;yes&#039;`, `&#039;on&#039;` | `true` |
| `false`, `0`, `0.0`, `&#039;0&#039;`, `&#039;false&#039;`, `&#039;no&#039;`, `&#039;off&#039;`, `&#039;&#039;` | `false` |
| `null` | `null` |

String tokens use PHP&#039;s boolean validation filter, which trims exterior whitespace and compares case-insensitively. Whitespace-only text therefore becomes `false`. Other values, such as `2`, `0.5` or `&#039;unknown&#039;`, throw. This is not PHP&#039;s direct boolean cast: the text `&#039;false&#039;` becomes `false`.

## Strings

`toString()` accepts strings, integers, floats, booleans and `Stringable` objects. Existing text is preserved without trimming. Booleans become `&#039;1&#039;` and `&#039;0&#039;`; numbers use PHP&#039;s string representation, with native `NAN` represented as `&#039;NAN&#039;`.

```php
use Derafu\Value\ValueCaster;

ValueCaster::toString(false);     // &#039;0&#039;
ValueCaster::toString(true);      // &#039;1&#039;
ValueCaster::toString(12.5);      // &#039;12.5&#039;
ValueCaster::toString(&#039; text &#039;);  // &#039; text &#039;
ValueCaster::toString(null);      // null
```

Arrays, resources and objects without `Stringable` are rejected. Numeric and boolean conversions do not accept `Stringable` objects; use the parser when their text should be interpreted automatically. A failing `__toString()` is wrapped in `ValueConversionException`, retaining the original throwable as its cause.




---

## Parsing

Interpret scalar text and preserve numeric format or significant decimal precision when requested

# ValueParser

```php
ValueParser::parse(
    mixed $value,
    bool $preserveNumericFormat = false,
    bool $preserveNumericPrecision = false,
): mixed
```

The parser interprets one value. `Stringable` objects are converted to text through `ValueCaster::toString()`. Strings are interpreted using the sequence below. Every other value is returned unchanged, including native integers, floats, booleans, nulls, arrays, resources and other objects.

## Interpretation Order

1. Recognize the special literal representations.
2. Try `ValueCaster::toNumber()`, which tries int before float.
3. If numeric conversion fails, try `ValueCaster::toBool()`.
4. If boolean conversion also fails, return the original text.

The parser delegates conversion rules to ValueCaster. It does not define a separate numeric grammar. An unsuccessful interpretation of plain text is not an exception; a failing Stringable conversion is propagated as `ValueConversionException`.

| Literal text | Result |
| --- | --- |
| `&#039;null&#039;`, `&#039;(null)&#039;` | `null` |
| `&#039;empty&#039;`, `&#039;(empty)&#039;` | `&#039;&#039;` |
| `&#039;true&#039;`, `&#039;(true)&#039;` | `true` |
| `&#039;false&#039;`, `&#039;(false)&#039;` | `false` |

These tokens are recognized case-insensitively after trimming exterior whitespace. The word `&#039;nil&#039;` is not recognized.

```php
use Derafu\Value\ValueParser;

ValueParser::parse(&#039; (NULL) &#039;); // null
ValueParser::parse(&#039;empty&#039;);    // &#039;&#039;
ValueParser::parse(&#039;0012&#039;);     // 12
ValueParser::parse(&#039;12.0&#039;);     // 12
ValueParser::parse(&#039;12.5&#039;);     // 12.5
ValueParser::parse(&#039;1e3&#039;);      // 1000
ValueParser::parse(&#039;yes&#039;);      // true
ValueParser::parse(&#039;0&#039;);        // 0, not false
ValueParser::parse(&#039;1&#039;);        // 1, not true
ValueParser::parse(&#039;   &#039;);      // false, through toBool()
ValueParser::parse(&#039;&#039;);         // false, unlike the literal &#039;empty&#039;
ValueParser::parse(&#039; text &#039;);   // &#039; text &#039;
```

## Numeric Format Preservation

With `preserveNumericFormat: true`, a successful numeric conversion is returned only if converting the number back through `ValueCaster::toString()` reproduces the complete original text. Otherwise the original text is retained. Exterior whitespace is part of this comparison.

```php
use Derafu\Value\ValueParser;

ValueParser::parse(&#039;0012&#039;, preserveNumericFormat: true);  // &#039;0012&#039;
ValueParser::parse(&#039;19.90&#039;, preserveNumericFormat: true); // &#039;19.90&#039;
ValueParser::parse(&#039;12.0&#039;, preserveNumericFormat: true);  // &#039;12.0&#039;
ValueParser::parse(&#039;1e3&#039;, preserveNumericFormat: true);   // &#039;1e3&#039;
ValueParser::parse(&#039; 12 &#039;, preserveNumericFormat: true);  // &#039; 12 &#039;
ValueParser::parse(&#039;12&#039;, preserveNumericFormat: true);    // 12
ValueParser::parse(&#039;0.5&#039;, preserveNumericFormat: true);   // 0.5
```

This comparison follows ValueCaster&#039;s PHP number-to-string representation. It is a numeric policy: boolean words and special literals are still interpreted normally. Preserved numeric text does not fall through to boolean conversion.

## Numeric Precision Preservation

With `preserveNumericPrecision: true`, non-finite numeric results and floats that fail the significant-decimal-digit comparison retain their original text. Successfully converted integers are exact and need no float comparison.

For floats, the parser compares significant mantissa digits with the shortest decimal representation found by its formatting round trip. Signs, the decimal point and insignificant leading/trailing zeros are excluded from the digit comparison. This is a decimal interpretation policy, not a requirement that fractions be exactly representable in binary.

```php
use Derafu\Value\ValueParser;

ValueParser::parse(&#039;1.0000000000000000001&#039;, preserveNumericPrecision: true);
// &#039;1.0000000000000000001&#039;

ValueParser::parse(&#039;1e400&#039;, preserveNumericPrecision: true);   // &#039;1e400&#039;
ValueParser::parse(&#039;1e-400&#039;, preserveNumericPrecision: true);  // &#039;1e-400&#039;
ValueParser::parse(&#039;0.1&#039;, preserveNumericPrecision: true);     // 0.1
ValueParser::parse(&#039;12.5000&#039;, preserveNumericPrecision: true); // 12.5
ValueParser::parse(&#039;0012&#039;, preserveNumericPrecision: true);    // 12
```

Without this option, conversion follows ValueCaster, including float rounding, infinity and underflow. Precision preservation alone does not preserve spelling. Both options can be enabled together:

```php
use Derafu\Value\ValueParser;

ValueParser::parse(
    &#039;0012&#039;,
    preserveNumericFormat: true,
    preserveNumericPrecision: true,
); // &#039;0012&#039;
```

## Existing Values and Stringable Objects

```php
use Derafu\Value\ValueParser;

$text = new class () implements Stringable {
    public function __toString(): string
    {
        return &#039;0012&#039;;
    }
};

ValueParser::parse($text); // 12
ValueParser::parse($text, preserveNumericFormat: true); // &#039;0012&#039;
ValueParser::parse(12.0);  // 12.0; an existing float is returned unchanged
ValueParser::parse([&#039;null&#039;, &#039;2&#039;]); // [&#039;null&#039;, &#039;2&#039;]; arrays are not traversed
```

The numeric options apply to interpreted text, including Stringable text. They do not transform existing native numbers. Recursive array processing belongs to a caller that explicitly traverses the array.




---

## Types

Compose strict validation, scalar conversion, collections, enums, dates and custom types

# ValueType

`ValueType&lt;T&gt;` validates or explicitly converts a value and returns it as `T`. PHPStan follows the generic return type through collection and union compositions.

```php
use Derafu\Value\ValueType;

ValueType::int()-&gt;parse(12);       // 12
ValueType::toInt()-&gt;parse(&#039;12.0&#039;); // 12
ValueType::number()-&gt;parse(12.0);  // 12.0, unchanged
ValueType::toNumber()-&gt;parse(12.0); // 12
```

## Available Factories

| Factory | Contract |
| --- | --- |
| `mixed()` | Any value, including null. |
| `string()`, `int()`, `float()`, `bool()` | Exactly the indicated PHP type, without coercion. |
| `number()` | An existing integer or float, preserved unchanged. |
| `scalar()` | An existing boolean, integer, float or string. |
| `nonEmptyString()` | A string whose content is nonempty before and after PHP `trim()`. |
| `toInt()`, `toFloat()`, `toNumber()`, `toBool()`, `toString()` | Delegate to the corresponding ValueCaster method, excluding null. |
| `array()` | Any PHP array. |
| `map()` | An array with string keys only. |
| `indexed()` | An array with integer keys, including gaps, negative keys and lists. |
| `list()` | An array with consecutive integer keys starting at zero. |
| `arrayOf($type)` | Any array whose values match the supplied type. |
| `mapOf($type)` | A string-keyed array whose values match the supplied type. |
| `indexedOf($type)` | An integer-keyed array whose values are parsed by the supplied type. |
| `listOf($type)` | A list whose values match the supplied type. |
| `literal($first, ...$others)` | One of the supplied boolean, integer or string values, compared strictly. |
| `instanceOf($class)` | An object of the given class or interface, returned unchanged. |
| `classString($base = null)` | An existing class or enum name, optionally constrained to a base class or interface. |
| `backedEnum($class)` | An existing case or an exact int/string backing value of the requested backed enum. |
| `dateTime()` | A DateTimeInterface, integer timestamp or non-blank date string interpreted by PHP. |
| `oneOf($first, ...$others)` | The first type that accepts the value. |

The primitive `float()` rejects integers even though `ValueCaster::toFloat()` can convert them. Use an explicit conversion type when conversion is intended.

## Nullability

Apply `nullable()` to accept null in addition to a type&#039;s ordinary values:

```php
use Derafu\Value\ValueType;

ValueType::int()-&gt;nullable()-&gt;parse(null);    // null
ValueType::toInt()-&gt;nullable()-&gt;parse(null);  // null
```

ValueCaster preserves null directly, but conversion types reject it by default. `ValueType::toInt()-&gt;parse(null)` throws `TypeMismatchException`. This keeps nullability explicit in a composed type.

## Collections

Empty collections are accepted. Lists require consecutive integer keys starting at zero; indexed arrays require integer keys without a continuity requirement; maps require string keys; arbitrary arrays accept both. PHP converts some numeric string keys to integers, so `[&#039;123&#039; =&gt; &#039;value&#039;]` is not a map, while `[&#039;01&#039; =&gt; &#039;value&#039;]` is.

```php
use Derafu\Value\ValueType;

$type = ValueType::arrayOf(ValueType::mapOf(ValueType::toInt()));
$type-&gt;parse([3 =&gt; [&#039;quantity&#039; =&gt; &#039;12.0&#039;], 8 =&gt; [&#039;quantity&#039; =&gt; &#039;2&#039;]]);
// [3 =&gt; [&#039;quantity&#039; =&gt; 12], 8 =&gt; [&#039;quantity&#039; =&gt; 2]]
```

Collections preserve their keys and report nested errors with paths such as `rows.8.quantity`. These factories describe element types; `mapOf()` does not define required or optional named fields.

### Indexed Arrays

`indexed()` validates `array&lt;int, mixed&gt;`. `indexedOf($type)` validates the same
integer keys and parses each value with the supplied type, returning
`array&lt;int, T&gt;`. Keys may start anywhere, have gaps, or be negative. Their order
is preserved; rows are not reindexed.

```php
$rows = ValueType::indexedOf(ValueType::array())-&gt;parse([
    8 =&gt; [&#039;name&#039; =&gt; &#039;First&#039;],
    2 =&gt; [&#039;name&#039; =&gt; &#039;Last&#039;],
]);
// [8 =&gt; [&#039;name&#039; =&gt; &#039;First&#039;], 2 =&gt; [&#039;name&#039; =&gt; &#039;Last&#039;]]

ValueType::indexed()-&gt;parse([]); // []
ValueType::indexed()-&gt;parse([0 =&gt; &#039;a&#039;, 1 =&gt; &#039;b&#039;]); // a list is also indexed
ValueType::indexed()-&gt;parse([&#039;extra&#039; =&gt; &#039;value&#039;]); // TypeMismatchException

ValueType::indexedOf(ValueType::toInt())-&gt;parse([8 =&gt; &#039;12.0&#039;, 2 =&gt; &#039;1e3&#039;]);
// [8 =&gt; 12, 2 =&gt; 1000]
```

String keys are rejected without conversion. PHP itself converts a key such as
`&#039;123&#039;` to the integer `123` when creating an array, while `&#039;02&#039;` remains a string
and is rejected. `indexed()` preserves values unchanged; `indexedOf()` follows
the supplied value type&#039;s validation or conversion policy. `nullable()` permits
`null` for the collection or, when applied to the item type, for its values.

A string key produces a translatable type error with expected type `int key`,
the key&#039;s path (for example `rows.extra`), and the supplied source. Value errors
retain the row key in their path, such as `rows.8.quantity`.

## Unions and Literal Values

```php
use Derafu\Value\ValueType;

$type = ValueType::oneOf(ValueType::toInt(), ValueType::string());
$type-&gt;parse(&#039;12.0&#039;); // 12
$type-&gt;parse(&#039;text&#039;); // &#039;text&#039;

ValueType::literal(&#039;asc&#039;, &#039;desc&#039;)-&gt;parse(&#039;asc&#039;); // &#039;asc&#039;
ValueType::literal(false)-&gt;parse(false);        // false; 0 would be rejected
```

Union order matters because conversion types can interpret the input. `oneOf()` tries the next candidate when the current candidate throws a translatable invalid-argument exception. It does not catch arbitrary runtime failures.

## Class Names

`classString()` validates a class name without constructing an object. Input must
be a string naming an existing class or enum; lookup permits autoloading. Abstract
classes are accepted. Interfaces and traits are not accepted as input values.

An optional base class or interface constrains which classes are accepted:

```php
use Derafu\Value\ValueType;

ValueType::classString()-&gt;parse(stdClass::class); // &#039;stdClass&#039;
ValueType::classString(Exception::class)-&gt;parse(RuntimeException::class);
ValueType::classString(DateTimeInterface::class)-&gt;parse(DateTimeImmutable::class);

enum Status: string
{
    case Pending = &#039;pending&#039;;
    case Approved = &#039;approved&#039;;
}

$enumClass = ValueType::classString(BackedEnum::class)-&gt;parse(Status::class);
$enumClass::cases(); // [Status::Pending, Status::Approved]
```

The result retains its generic type: `classString(BackedEnum::class)` produces a
`ValueType&lt;class-string&lt;BackedEnum&gt;&gt;`. Without a base, the result is a
`class-string`. Names are returned unchanged, including their case and any leading
namespace separator. Padded names, objects (including `Stringable`), and values
that do not satisfy the class constraint throw `TypeMismatchException` with the
path and source passed to `parse()`.

Collection factories compose with this type. For example,
`ValueType::mapOf(ValueType::classString(BackedEnum::class))` validates a map of
enum class names. `nullable()` explicitly permits null.

`classString(BackedEnum::class)` validates the enum class itself;
`backedEnum(Status::class)` resolves a particular case or backing value.

## Backed Enums

```php
use Derafu\Value\ValueType;

enum Status: string
{
    case Pending = &#039;pending&#039;;
    case Approved = &#039;approved&#039;;
}

$type = ValueType::backedEnum(Status::class);
$type-&gt;parse(&#039;approved&#039;);       // Status::Approved
$type-&gt;parse(Status::Pending);  // the same enum case
```

Int-backed enums accept integer backing values; string-backed enums accept strings. Numeric strings are not coerced to integers, and another enum&#039;s case is not accepted just because it has the same backing value. Unknown values throw `TypeMismatchException`. Passing a class that is not a backed enum to the factory throws `ValueException`.

## Dates

`dateTime()` preserves an existing `DateTimeInterface`. An integer timestamp becomes a `DateTimeImmutable` using `@timestamp`; date text is parsed by `DateTimeImmutable`. Relative dates, timezones and date normalization follow PHP&#039;s parser. Empty or invalid input throws `TypeMismatchException`.

```php
use Derafu\Value\ValueType;

$date = ValueType::dateTime()-&gt;parse(&#039;2026-01-15&#039;);
$date-&gt;format(&#039;Y-m-d&#039;); // &#039;2026-01-15&#039;
```

## Custom Types and Error Context

The constructor takes a diagnostic name and a closure receiving the value, path and optional source. Return the typed result or throw `ValueType::mismatch()`:

```php
use Derafu\Value\ValueType;

$even = new ValueType(
    &#039;even&#039;,
    static fn (mixed $value, string $path, ?string $source): int
        =&gt; is_int($value) &amp;&amp; $value % 2 === 0
            ? $value
            : throw ValueType::mismatch($path, &#039;even&#039;, $value, $source),
);

$even-&gt;parse(4, &#039;workers&#039;, &#039;settings.php&#039;); // 4
```

`parse($value, $path = &#039;&#039;, $source = null)` attaches a diagnostic location and origin to failures. An empty root path is displayed as `$`. `ValueType::path($parent, $key)` joins a diagnostic path with a string or integer key; it does not navigate data. See [Exceptions and Translations](translations).




---

## Inspection

Inspect blank values without coercion, whitespace normalization or recursive traversal

# ValueInspector

`ValueInspector::isBlank(mixed $value): bool` returns true for exactly three values: `null`, `&#039;&#039;` and `[]`.

```php
use Derafu\Value\ValueInspector;

ValueInspector::isBlank(null);   // true
ValueInspector::isBlank(&#039;&#039;);     // true
ValueInspector::isBlank([]);     // true
ValueInspector::isBlank(false);  // false
ValueInspector::isBlank(0);      // false
ValueInspector::isBlank(&#039;0&#039;);    // false
ValueInspector::isBlank(&#039;   &#039;);  // false
ValueInspector::isBlank([null]); // false
```

This is an inspection of the supplied value, not PHP&#039;s `empty()` behavior. It does not determine whether a key exists, whether a value was supplied by a caller or whether an application requires it.

Whitespace is not trimmed, array elements are not inspected recursively, and objects are neither counted nor converted to text. Even an empty `Countable` object is treated as an object rather than as `[]`.

## Inspection and Interpretation

The parser performs conversions; the inspector does not:

```php
use Derafu\Value\ValueInspector;
use Derafu\Value\ValueParser;

ValueInspector::isBlank(&#039;null&#039;); // false; text exists
ValueParser::parse(&#039;null&#039;);      // null; a recognized literal
ValueInspector::isBlank(&#039; &#039;);    // false; the string contains a space
ValueParser::parse(&#039; &#039;);         // false; boolean interpretation
```

Choose the operation explicitly. A blank check does not imply a type conversion, and parsing does not decide application-level requiredness.




---

## Exceptions and Translations

Catch typed value failures, preserve their causes and translate package exceptions

# Exceptions and Translations

All package exceptions are translatable and can be caught as PHP&#039;s `InvalidArgumentException`.

| Exception in Derafu\Value\Exception | Parent | Cause |
| --- | --- | --- |
| `ValueException` | `TranslatableInvalidArgumentException` | Invalid value-type definitions, such as a non-backed enum class. |
| `TypeMismatchException` | `ValueException` | A value does not match a ValueType definition or a strict ValueCaster read. |
| `ValueConversionException` | `TranslatableInvalidArgumentException` | A requested scalar conversion fails. |

`ValueConversionException` is separate from `ValueException`. Catch the specific classes or their common `TranslatableInvalidArgumentException` parent when handling both categories.

Strict `ValueCaster::getXXX()` / `requireXXX()` methods reuse ValueType validation and raise TypeMismatchException for rejected input. If a Stringable read fails during conversion, the cause chain contains ValueConversionException followed by the original throwable. `ValueType::string()` itself still accepts PHP strings only.

## Conversion Failures

```php
use Derafu\Value\Exception\ValueConversionException;
use Derafu\Value\ValueCaster;

try {
    ValueCaster::toInt(&#039;text&#039;);
} catch (ValueConversionException $exception) {
    echo $exception-&gt;getMessage();
    // A value of type string cannot be converted to int.
}
```

`toNumber()` propagates the exception from its final `toFloat()` attempt if both conversions fail. A failing Stringable conversion is wrapped with the original throwable available through `getPrevious()`.

## Type Failures and Causes

```php
use Derafu\Value\Exception\TypeMismatchException;
use Derafu\Value\ValueType;

try {
    ValueType::toInt()-&gt;parse(&#039;text&#039;, &#039;quantity&#039;, &#039;settings.php&#039;);
} catch (TypeMismatchException $exception) {
    echo $exception-&gt;getMessage();
    // The value at &quot;quantity&quot; of settings.php must be of type int, string given.

    $cause = $exception-&gt;getPrevious(); // ValueConversionException
}
```

Conversion types wrap ValueConversionException as TypeMismatchException to add location and source context, retaining the original cause. Strict type mismatches do not need an underlying conversion failure. A missing path is displayed as `$`; a source is included only when one is supplied.

## Spanish Translations

The package supplies `resources/translations/errors+intl-icu.es.php` through `Derafu\Value\Translation\ValueTranslationResourceProvider`. The provider supplies resources; an application creates and configures its translator.

```php
use Derafu\Translation\TranslatorFactory;
use Derafu\Value\Exception\ValueConversionException;
use Derafu\Value\Translation\ValueTranslationResourceProvider;
use Derafu\Value\ValueCaster;

$translator = TranslatorFactory::create(
    defaultLocale: &#039;es&#039;,
    fallbackLocales: [&#039;es&#039;, &#039;en&#039;],
    resourceProviders: [new ValueTranslationResourceProvider()],
);

try {
    ValueCaster::toInt(&#039;text&#039;);
} catch (ValueConversionException $exception) {
    echo $exception-&gt;trans($translator);
    // Un valor de tipo string no se puede convertir a int.
}
```

## Dependency Injection

Applications using Symfony DependencyInjection can import the optional recipe:

```yaml
imports:
    - { resource: &#039;../vendor/derafu/value/resources/config/value-services.yaml&#039; }
```

It tags `ValueTranslationResourceProvider` with `derafu_translation.resource_provider`. Pass providers with that tag to `TranslatorFactory::create()` through `$resourceProviders`, following [Derafu Translation](https://www.derafu.dev/docs/core/translation). Symfony DependencyInjection is not a runtime requirement of the value utilities.





---
Last updated on 15/11/2026
#php
