Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- trait EnumValuesTrait
- {
- /** @var static[] */
- private static $values = [];
- /**
- * @return static[]
- */
- public static function values()
- {
- if (empty(self::$values)) {
- self::$values = self::initValues();
- }
- return self::$values;
- }
- }
- class SomeStrategy
- {
- use EnumValuesTrait;
- private static function initValues()
- {
- return [
- 'TRAVERSE' => new self(1, 'Traverse'),
- 'DIRECT' => new self(2, 'Direct'),
- ];
- }
- /** @var int */
- private $id;
- /** @var string */
- private $title;
- /**
- * Private constructor avoids extrernal creation of the instances.
- * @param int $id
- * @param string $title
- */
- private function __construct($id, $title)
- {
- $this->id = $id;
- $this->title = $title;
- }
- /**
- * @return SomeStrategy
- */
- public static function TRAVERSE()
- {
- return self::values()['TRAVERSE'];
- }
- /**
- * @return SomeStrategy
- */
- public static function DIRECT()
- {
- return self::values()['DIRECT'];
- }
- /**
- * @param string $title
- * @return null|SomeStrategy
- */
- public static function getByTitle(string $title)
- {
- $title2upper = mb_strtoupper($title);
- foreach (self::values() as $value) {
- if (mb_strtoupper($value->title) === $title2upper) {
- return $value;
- }
- }
- return null;
- }
- // Helper methods...
- /**
- * @return bool
- */
- public function isTraverse()
- {
- return $this === self::TRAVERSE();
- }
- /**
- * @return bool
- */
- public function isDirect()
- {
- return $this === self::DIRECT();
- }
- // Getters...
- /**
- * @return int
- */
- public function getId(): int
- {
- return $this->id;
- }
- /**
- * @return string
- */
- public function getTitle(): string
- {
- return $this->title;
- }
- }
- class UsageExample {
- public function lookMa()
- {
- // direct pointer
- $strategy1 = SomeStrategy::TRAVERSE();
- // dinamyc pointer
- $strategy2 = SomeStrategy::getByTitle('traverse');
- // calling regular methods
- if ($strategy1->isTraverse() && $strategy2->isTraverse()) {
- echo $strategy1->getId() . ': ' . $strategy2->getTitle();
- }
- // comparing pointers
- echo $strategy1 === $strategy2 ? 'true' : 'false';
- // iterating over the values with type hinting
- foreach (SomeStrategy::values() as $value) {
- echo $value->getId() . PHP_EOL;
- }
- // using in switch cases
- switch ($strategy1) {
- case SomeStrategy::TRAVERSE():
- echo 'Traverse';
- break;
- case SomeStrategy::DIRECT():
- echo 'Direct';
- break;
- }
- }
- }
Add Comment
Please, Sign In to add comment