1. Go to this page and download the library: Download tnapf/jsonmapper 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/ */
tnapf / jsonmapper example snippets
use Tnapf\JsonMapper\Mapper;
$mapper = new Mapper;
class User
{
public int $id;
public string $username;
public string $password;
}
use Tnapf\JsonMapper\Attributes\PrimitiveType;
use Tnapf\JsonMapper\Attributes\PrimitiveArrayType;
class User
{
public int $id;
public string $username;
public string $password;
#[PrimitiveArrayType(name: 'roles', type: PrimitiveType::STRING)]
public array $roles;
}
// what the new item will look like
$user = [
// ...
'roles' => [':name:', ':name:', ':name:']
];
use Tnapf\JsonMapper\Attributes\ObjectArrayType;
class User
{
public int $id;
public string $username;
public string $password;
#[ObjectArrayType(name: 'roles', type: Role::class)]
public array $roles;
}
class Role {
public int $id;
public string $name;
}
use Tnapf\JsonMapper\Attributes\EnumerationArrayType;
class User {
public int $id;
public string $username;
public string $password;
#[EnumerationArrayType(name: 'roles', type: Role::class))]
public array $roles;
}
enum Role: int
{
case USER = 1;
case ADMIN = 2;
case OWNER = 3;
}
// what the updated item will look like
$user = [
// ...
'roles' => [1, 3]
];
use Attribute;
use ReflectionException;
use Tnapf\JsonMapper\Attributes\MappableType;
use Tnapf\JsonMapper\MapperException;
use Tnapf\JsonMapper\MapperInterface;
#[Attribute(Attribute::TARGET_PROPERTY)]
class FriendsType extends MappableType
{
public function isType(mixed $data): bool
{
if (!is_array($data)) {
return false;
}
foreach ($data as $item) {
if (!$item instanceof User) {
return false;
}
}
return true;
}
/**
* @throws ReflectionException
* @throws MapperException
*/
public function map(mixed $data, MapperInterface $mapper): mixed
{
$friends = [];
foreach ($data as $item) {
$friend = $mapper->map(User::class, $item);
$friends[$friend->username] = $friend;
}
return $friends;
}
}
class User {
public string $username;
public string $password;
#[FriendsType(name: 'friends', nullable: true)]
public array $friends;
}
use Tnapf\JsonMapper\Attributes\SnakeToCamelCase;
use Tnapf\JsonMapper\Attributes\PrimitiveType;
use Tnapf\JsonMapper\Attributes\PrimitiveArrayType;
#[SnakeToCamelCase]
class User
{
public int $id;
public string $username;
public string $password;
#[PrimitiveArrayType(name: 'all_roles', type: PrimitiveType::STRING)]
public array $allRoles;
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.