Skip to content

Instantly share code, notes, and snippets.

@pocky
Created August 24, 2018 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pocky/83872ac0658192b4de58972308247d47 to your computer and use it in GitHub Desktop.
Save pocky/83872ac0658192b4de58972308247d47 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace App\Application\Request\Account;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Exception\ValidatorException;
use Symfony\Component\Validator\Validation;
class RegistrationRequest
{
private $username;
private $password;
private $email;
private function __construct()
{
}
public static function fromData(array $data = [])
{
$dto = new self;
$fields = ['username', 'password', 'email'];
$dto->validate($data, $fields);
$accessor = PropertyAccess::createPropertyAccessor();
foreach ($fields as $field) {
$dto->{$field} = $accessor->getValue($data, "[$field]");
}
return $dto;
}
public function getUsername(): string
{
return $this->username;
}
public function getPassword(): string
{
return $this->password;
}
public function getEmail(): string
{
return $this->email;
}
public function getData(): iterable
{
return [
'username' => $this->username,
'password' => $this->password,
'email' => $this->email,
];
}
private function validate(array $data = [], array $fields = []): void
{
$constraints = new Assert\Collection([
'username' => new Assert\NotBlank(),
'password' => [
new Assert\NotBlank(),
new Assert\NotIdenticalTo(['value' => $data['username']]),
],
'email' => new Assert\Email(),
]);
$violations = Validation::createValidator()->validate($data, $constraints, $fields);
if (0 !== $violations->count()) {
$errors = "";
foreach ($violations as $violation) {
$errors .= sprintf("%s: %s", $violation->getPropertyPath(), $violation->getMessage());
}
throw new ValidatorException("Malformed data : {$errors}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment