orisai/object-mapper

Raw data mapping to validated objects

This package is auto-updated.

Last update: 2024-03-27 11:44:19 UTC


README

Raw data mapping to validated objects

Ideal for validation of POST data, configurations, serialized and any other raw data and automatic mapping of them to type-safe objects.

📄 Check out our documentation.

💸 If you like Orisai, please make a donation. Thank you!

badge.svg 68747470733a2f2f62616467656e2e6e65742f636f766572616c6c732f632f6769746875622f6f72697361692f6f626a6563742d6d61707065722f76312e783f63616368653d333030 68747470733a2f2f62616467652e737472796b65722d6d757461746f722e696f2f6769746875622e636f6d2f6f72697361692f6f626a6563742d6d61707065722f76312e78 68747470733a2f2f62616467656e2e6e65742f7061636b61676973742f64742f6f72697361692f6f626a6563742d6d61707065723f63616368653d33363030 68747470733a2f2f62616467656e2e6e65742f7061636b61676973742f762f6f72697361692f6f626a6563742d6d61707065723f63616368653d33363030 68747470733a2f2f62616467656e2e6e65742f62616467652f6c6963656e73652f4d504c2d322e302f626c75653f63616368653d33363030

use Orisai\ObjectMapper\MappedObject;
use Orisai\ObjectMapper\Rules\MappedObjectValue;
use Orisai\ObjectMapper\Rules\StringValue;

final class UserInput implements MappedObject
{

	/** @StringValue(notEmpty=true) */
	public string $firstName;

	/** @StringValue(notEmpty=true) */
	public string $lastName;

	/** @MappedObjectValue(UserAddressInput::class) */
	public UserAddressInput $address;

}
use Orisai\ObjectMapper\MappedObject;
use Orisai\ObjectMapper\Rules\StringValue;

final class UserAddressInput implements MappedObject
{

	/** @StringValue(notEmpty=true) */
	public string $street;

	// ...
}
use Orisai\ObjectMapper\Exception\InvalidData;
use Orisai\ObjectMapper\Printers\ErrorVisualPrinter;
use Orisai\ObjectMapper\Printers\TypeToStringConverter;
use Orisai\ObjectMapper\Processing\DefaultProcessor;

$processor = new DefaultProcessor(/* dependencies */);
$errorPrinter = new ErrorVisualPrinter(new TypeToStringConverter());

$data = [
	'firstName' => 'Tony',
	'lastName' => 'Stark',
	'address' => [
		'street' => '10880 Malibu Point',
	],
];

try {
	$user = $processor->process($data, UserInput::class);
} catch (InvalidData $exception) {
	$error = $errorPrinter->printError($exception);

	throw new Exception("Validation failed due to following error:\n$error");
}

echo "User name is: {$user->firstName} {$user->lastName}";