Skip to content

Instantly share code, notes, and snippets.

@salcode
Forked from JasonTheAdams/PostStatus.php
Last active October 10, 2019 17:23
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 salcode/d6fcfdb9105ca3b1942ff13e1dbdeffa to your computer and use it in GitHub Desktop.
Save salcode/d6fcfdb9105ca3b1942ff13e1dbdeffa to your computer and use it in GitHub Desktop.
Enumeration example of the Object Value Design Pattern
<?php
class PostStatus
{
const PRIVATE = 'private';
const DRAFT = 'draft';
const PUBLISHED = 'published';
const TRASHED = 'trash';
/**
* @var string
*/
private $value;
public static function all()
{
return [
self::PRIVATE,
self::DRAFT,
self::PUBLISHED,
self::TRASHED
];
}
public function __construct($value)
{
if (! in_array($value, self::all())) {
throw new InvalidArgumentException("Invalid PostStatus value: {$value}");
}
$this->value = $value;
}
public function __toString()
{
return $this->value;
}
public function is($comparison)
{
if ($comparison instanceof self) {
return $comparison->value === $this->value;
} else {
return (string) $comparison === $this->value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment