Skip to main content

Custom value objects

Most of the time you only need to extend a base class and override a few constants. Marshal and unmarshal mappers for n2n Bind are inherited and use your constants as well.

CleanString​

A string without non-printable characters, leading/trailing whitespace or double whitespaces.

ConstantDefaultDescription
MIN_LENGTH1min. length, must be at least 1
MAX_LENGTH255max. length
SIMPLE_WHITESPACES_ONLYtruefalse allows line breaks and tabs
use valobj\string\CleanString;

final class ArticleTitle extends CleanString {
const MIN_LENGTH = 3;
const MAX_LENGTH = 120;
}

final class ArticleBody extends CleanString {
const MAX_LENGTH = 20000;
const SIMPLE_WHITESPACES_ONLY = false;
}
ArticleTitle::from('Hi'); // IllegalStateException: Value too short: Hi
ArticleTitle::from(' Hello World ', true); // "Hello World"
ArticleBody::from("Para 1\n\nPara 2"); // ok

DirtyString​

Like CleanString, but only the length is checked. Use it for values you must not modify, e.g. data from external systems.

use valobj\string\DirtyString;

final class ExternalReference extends DirtyString {
const MAX_LENGTH = 64;
}

NonSpecialCharsString​

Only a-z, A-Z, 0-9, ., _ and -. Useful for codes, keys and URL parts.

ConstantDefaultDescription
MIN_LENGTH3min. length
MAX_LENGTH63max. length
LOWER_CASE_ONLYtruereject uppercase letters
use valobj\string\NonSpecialCharsString;

final class ProductCode extends NonSpecialCharsString {
const MIN_LENGTH = 4;
const MAX_LENGTH = 16;
}
ProductCode::from('abc-123'); // ok
ProductCode::from('ABC-123'); // IllegalStateException: Value not lowercase: ABC-123
ProductCode::from('abc 123'); // IllegalStateException: Value contains special chars: abc 123

CleanGzBin​

Stores a CleanString gz-compressed. Use it for long texts in binary columns.

use valobj\string\CleanGzBin;

final class CompressedLog extends CleanGzBin {
const MAX_LENGTH = 100000;
}

$log = CompressedLog::fromUncompressed('Hello');
$log->toScalar(); // compressed binary string
$log->uncompress(); // "Hello"

Numbers​

use valobj\int\PositiveInt;
use valobj\int\NbId;
use valobj\float\TypicalTwoDigitDecimal;

final class Price extends TypicalTwoDigitDecimal {
}

final class ArticleId extends NbId {
}
Price::from(12.5)->toScalar(); // 12.5
ArticleId::from(7)->toScalar(); // 7

Additional rules​

You can add rules in the constructor. Also override the unmarshal mapper, so that n2n Bind reports a validation error instead of throwing an exception.

use valobj\int\PositiveInt;
use n2n\spec\valobj\err\IllegalValueException;
use n2n\bind\attribute\impl\Unmarshal;
use n2n\bind\mapper\Mapper;
use n2n\bind\mapper\impl\Mappers;

final class Quantity extends PositiveInt {

function __construct(int $value) {
parent::__construct($value);
IllegalValueException::assertTrue($value <= 999, 'Quantity too large: ' . $value);
}

#[Unmarshal]
static function unmarshalMapper(): Mapper {
return Mappers::pipe(Mappers::int(false, 1, 999),
Mappers::valueNotNullClosure(fn (int $value) => new Quantity($value)));
}
}
Quantity::from(1000); // IllegalStateException: Quantity too large: 1000

$result = Bind::attrs(['qty' => '1000'])->prop('qty', Mappers::unmarshal(Quantity::class))->toArray()->exec();
$result->isValid(); // false, error message: "Max [max = 999]"

From scratch​

Extend StringValueObjectAdapter, IntValueObjectAdapter or FloatValueObjectAdapter. You get from(), checkedFrom(), equals(), toScalar(), __toString() and jsonSerialize(). Add the validation and the mappers yourself.

use valobj\string\StringValueObjectAdapter;
use n2n\spec\valobj\err\IllegalValueException;
use n2n\bind\attribute\impl\Marshal;
use n2n\bind\attribute\impl\Unmarshal;
use n2n\bind\mapper\Mapper;
use n2n\bind\mapper\impl\Mappers;

final class CountryCode extends StringValueObjectAdapter {

function __construct(string $value) {
parent::__construct($value);
IllegalValueException::assertTrue(preg_match('/^[A-Z]{2}$/', $value) === 1,
'Invalid country code: ' . $value);
}

#[Marshal]
static function marshalMapper(): Mapper {
return Mappers::valueClosure(fn (CountryCode $code) => $code->toScalar());
}

#[Unmarshal]
static function unmarshalMapper(): Mapper {
return Mappers::pipe(
Mappers::cleanString(minlength: 2, maxlength: 2),
Mappers::valueNotNullClosure(fn (string $value) => new CountryCode(strtoupper($value))));
}
}
CountryCode::from('CH'); // ok
CountryCode::from('ch'); // IllegalStateException: Invalid country code: ch

// n2n Bind normalizes the input:
Bind::attrs(['country' => 'ch'])->prop('country', Mappers::unmarshal(CountryCode::class))->toArray()->exec();
// ['country' => CountryCode("CH")]

Arrays of value objects​

Extend StringValueObjectArrayAdapter (or IntValueObjectArrayAdapter) and define the element type with #[ValueType]:

use valobj\string\CleanString;
use valobj\string\StringValueObjectArrayAdapter;
use n2n\util\col\attribute\ValueType;

final class Tag extends CleanString {
const MAX_LENGTH = 30;
}

#[ValueType(Tag::class)]
final class TagArray extends StringValueObjectArrayAdapter {
}
$tags = new TagArray([Tag::from('php'), Tag::from('n2n')]);

Use NullableStringValueObjectArrayAdapter if the array may contain null elements:

#[ValueType(Email::class, nullable: true)]
final class NullableEmailArray extends NullableStringValueObjectArrayAdapter {
}