<?php
namespace vendor\project\some\models;
/**
* Class User
*/
final class User implements \Serializable
{
const FIELD_USER_ID = 'userId';
const FIELD_NAME = 'name';
const FIELD_PASSWORD = 'password';
/** @var int */
private $userId;
/** @var string */
private $name;
/** @var string */
private $password;
/**
* User constructor
*
* @param string $userId
* @param string $name
* @param string $password
*/
public function __construct($userId, $password, $name)
{
if (empty($userId)) {
throw new \InvalidArgumentException('$userId MUST NOT be empty');
}
if (!is_int($userId)) {
throw new \InvalidArgumentException('$userId MUST be int');
}
if ($userId < 0) {
throw new \InvalidArgumentException('$userId MUST be more than 0');
}
if (empty($password)) {
throw new \InvalidArgumentException('$password MUST NOT be empty');
}
if (!is_string($password)) {
throw new \InvalidArgumentException('$password MUST be string');
}
if (mb_strlen($password) !== 32) {
throw new \InvalidArgumentException('$password MUST have length 32');
}
if (empty($name)) {
throw new \InvalidArgumentException('$name MUST NOT be empty');
}
if (!is_string($name)) {
throw new \InvalidArgumentException('$name MUST be string');
}
$this->userId = $userId;
$this->name = $name;
$this->password = $password;
}
/**
* @return string
*/
public function getUserId()
{
return $this->userId;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
* @return string
*/
public function serialize()
{
return serialize(
[
self::FIELD_USER_ID => $this->getUserId(),
self::FIELD_NAME => $this->getName(),
self::FIELD_PASSWORD => $this->getPassword()
]
);
}
/**
* @param string $serialized
*
* @return string
*/
public function unserialize($serialized)
{
if (!is_string($serialized)) {
throw new \InvalidArgumentException('$serialized MUST be string');
}
$data = unserialize($serialized);
if (
!isset($data[self::FIELD_USER_ID]) ||
!isset($data[self::FIELD_NAME]) ||
!isset($data[self::FIELD_PASSWORD]) ||
(count($data) !== 3)
) {
throw new \InvalidArgumentException('Invalid serialized data');
}
return new self(
$data[self::FIELD_USER_ID],
$data[self::FIELD_NAME],
$data[self::FIELD_PASSWORD]
);
}
}