Skip to content

Instantly share code, notes, and snippets.

@nikolaposa
Last active June 26, 2018 15:32
Show Gist options
  • Save nikolaposa/2e33b42fdc895f92e7e03ec08e835454 to your computer and use it in GitHub Desktop.
Save nikolaposa/2e33b42fdc895f92e7e03ec08e835454 to your computer and use it in GitHub Desktop.
Person entity with mandatory birthdate that can either be set or uknown
<?php
final class BirthDate
{
private $date;
private function __construct(\DateTimeInterface $date = null)
{
$this->date = $date;
}
public static function on(\DateTimeInterface $date) : self
{
return new self($date);
}
public static function unknown() : self
{
return new self();
}
public function toString() : string
{
return $this->date ? $this->date->format('Y-m-d') : 'unknown';
}
}
<?php
final class Person
{
private $firstName;
private $lastName;
private $birthDate;
public function __construct(Firstname $firstName, Lastname $lastName, BirthDate $birthDate)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->birthDate = $birthDate;
}
public function getFirstName() : Firstname
{
return $this->firstName;
}
public function getLastName() : Lastname
{
return $this->lastName;
}
public function getBirthDate() : BirthDate
{
return $this->birthDate;
}
}
<?php
final class Person
{
private $firstName;
private $lastName;
private $birthDate;
public function __construct(Firstname $firstName, Lastname $lastName, BirthDate $birthDate = null)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->birthDate = $birthDate;
}
public function getFirstName() : Firstname
{
return $this->firstName;
}
public function getLastName() : Lastname
{
return $this->lastName;
}
public function hasBirthDate() : bool
{
return null !== $this->birthDate;
}
public function getBirthDate() : BirthDate
{
if (! $this->hasBirthDate()) {
throw new BirthDateNotSetException();
}
return $this->birthDate;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment