1. Go to this page and download the library: Download zahran/mapper library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
zahran / mapper example snippets
use Zahran\Mapper\Mapper;
$mapper = Mapper::default();
$mapping = $mapper->compile($template); // validate once
$mapping->map($payload); // reuse for every payload
"where": {"path": ["active"], "condition_type": "eq", "value": true} // A, C
"sort": {"path": ["price"]} // B, C, A
"sort": {"path": ["price"], "direction": "desc"} // A, C, B
"limit": 2 // A, B
"offset": 1, "limit": 1 // B
"offset": -1 // C
Mapper::default()->map('{}', $template);
// InvalidPayloadException: Cannot map the payload at "Sku":
// is
// Cannot map the payload at "Orders.Lines.Sku": is
$mapper = Mapper::default()->strict();
// {"count": "abc"}
{"name": "Count", "path": ["count"], "cast": {"type": "integer"}}
Mapper::default()->map($payload, $template); // ['Count' => 0]
Mapper::default()->strict()->map($payload, $template);
// InvalidPayloadException: Cannot map the payload at "Count":
// "abc" (string) cannot be cast to "integer" without losing its meaning.
Mapper::default()->strict()->map('{"items": "nope"}', $template);
// InvalidPayloadException: Cannot map the payload at "Items":
// expects a list, but the payload holds string.
// {"when": "the day before never"} with a date cast
// InvalidPayloadException: Cannot map the payload at "When":
// DateTimeImmutable::__construct(): Failed to parse time string …
use Zahran\Mapper\Condition\Predicate;
$mapper = Mapper::default()->withCondition('starts_with', new class implements Predicate {
public function matches(mixed $value, mixed $compare): bool
{
return is_string($value) && is_string($compare) && str_starts_with($value, $compare);
}
});
// {"sku": "AB-1"}
{"name": "Kind", "path": ["sku"],
"conditions": [{"condition_type": "starts_with", "value": "AB-", "then": "internal", "otherwise": "external"}]}
// "internal"
use Zahran\Mapper\Cast\Cast;
use Zahran\Mapper\Cast\Validating;
// Implementing Validating as well is optional: it is what a strict mapper asks before
// handing the cast a value. A cast that does not implement it is trusted with anything.
$mapper = Mapper::default()->withCast('cents', new class implements Cast, Validating {
public function cast(mixed $value, ?string $format): mixed
{
return (int) round(((float) $value) * 100);
}
public function accepts(mixed $value): bool
{
return is_numeric($value);
}
});
// {"price": "40.50"} with {"cast": {"type": "cents"}} => 4050
use Zahran\Mapper\Mutator\Mutator;
$mapper = Mapper::default()->withMutator('suffix', new class implements Mutator {
public function apply(mixed $value, array $arguments): mixed
{
return $value . ($arguments[0] ?? '');
}
});
// {"sku": "A"} with {"mutators": [{"name": "suffix", "arguments": ["-EU"]}]} => "A-EU"