-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhashable_enum.php
67 lines (48 loc) · 1.38 KB
/
hashable_enum.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
declare(strict_types=1);
namespace Zlikavac32\ZEnum\Examples;
use Ds\Hashable;
use Ds\Set;
use Zlikavac32\ZEnum\ZEnum;
require_once __DIR__ . '/../vendor/autoload.php';
if (
!interface_exists(Hashable::class)
||
!class_exists(Set::class)
) {
fwrite(STDERR, "You need the ds library to run this example (composer or native version both should work well)");
exit(1);
}
/**
* Example that show how to extend Enum with custom behaviour
*/
abstract class HashableEnum extends ZEnum implements Hashable
{
public function equals($object): bool
{
return $object === $this;
}
public function hash(): string
{
// this works under assumption that you use this library correctly (same object has same hash)
return spl_object_hash($this);
}
}
/**
* @method static YesNo YES
* @method static YesNo NO
*/
abstract class YesNo extends HashableEnum
{
}
var_dump(YesNo::YES() instanceof Hashable); // bool(true)
$set = new Set();
$set->add(YesNo::NO());
var_dump($set->contains(YesNo::NO())); // bool(true)
var_dump($set->contains(YesNo::YES())); // bool(false)
$set->add(YesNo::YES());
var_dump($set->contains(YesNo::NO())); // bool(true)
var_dump($set->contains(YesNo::YES())); // bool(true)
$set->remove(YesNo::NO());
var_dump($set->contains(YesNo::NO())); // bool(false)
var_dump($set->contains(YesNo::YES())); // bool(true)