PHP code example of mohammedmanssour / super-simple-dto

1. Go to this page and download the library: Download mohammedmanssour/super-simple-dto 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/ */

    

mohammedmanssour / super-simple-dto example snippets



use MohammedManssour\DTO\Concerns\AsDTO;

class UserData
{
    use AsDTO;

    public string $name;

    public string $email;

    public BalanceData $balance;

    public Status $status;
}

UserData::fromCollection(collect([]));

UserData::fromArray([]);

UserData::fromModel($model);

UserData::fromRequest($request);

$data = [
    'name' => 'Mohammed Manssour',
    'email' => '[email protected]'
];
$dto = UserData::fromArray();

$this->assertEquals($data['name'], $dto->name);
$this->assertEquals($data['email'], $dto->email);

$this->assertFalse(isset($dto->balance));
$this->assertFalse(isset($dto->status));

use MohammedManssour\DTO\Concerns\AsDTO;

class BalanceData
{
    use AsDTO;

    public float $bitcoin;

    public int $usdollar;
}

enum Status: string
{
    case Active = 'active';
    case Suspended = 'suspended';
}

class UserData
{
    use AsDTO;

    ....

    public BalanceData $balance;

    public Status $status;

    public function balance($value)
    {
        return $this->balance = BalanceData::fromArray($value);
    }

    public function status($value)
    {
        return $this->status = Status::from($value);
    }
}

$data = [
    'balance' => [
        'bitcoin' => 10,
        'usdollar' => 100
    ],
    'status' => 'active'
];

$dto = UserData::fromArray($data)

$this->assertInstanceOf(BalanceData::class, $dto->balance);
$this->assertEquals($data['balance']['bitcoin'], $dto->balance->bitcoint);
$this->assertEquals($data['balance']['usdollar'], $dto->balance->usdollart);


$this->assertInstanceOf(Status::class, $dto->status);
$this->assertEquals(Status::Active, $dto->status);


$arr = $dto->toArray()