Quick actions

cmd+k|ctrl+k

Navigation

Languages

Value Object

Snippet info

Language

Php

Visibility

public

Author

sobchukvadim

Created

2022-08-25T13:20:33.214821Z

Updated

2022-08-25T13:20:33.214821Z

<?php

$data = [
    ['id' => 1, 'email' => '[email protected]'],
    ['id' => 2, 'email' => '[email protected]'],
    ['id' => 3, 'email' => 'ghf'],
];

class CustomerValueObject implements JsonSerializable {
    private $id;
    private $email;
    
    public function __construct(int $id, string $email) {
        $this->id = $id;
        
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new InvalidArgumentException(sprintf('"%s" is not a valid email', $email));
        }
        
        $this->email = $email;
    }
    
    public function toArray()
    {
        return [
            'id' => $this->id,
            'email' => $this->email
        ];
    }
    
    public function jsonSerialize()
    {
        return $this->toArray();
    }
}

$result = [];
foreach ($data as $customer) {
    $result[] = (new CustomerValueObject($customer['id'], $customer['email']))->toArray();
}

var_dump($result);
INFO