Passed
Pull Request — master (#7)
by Lesnykh
02:12
created

example.php ➔ checkFlags()   B

Complexity

Conditions 7
Paths 1

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 9
nc 1
nop 1
dl 0
loc 11
rs 8.2222
c 0
b 0
f 0
1
<?php
2
3
require_once realpath(__DIR__ . '/../vendor/autoload.php');
4
5
/*
6
 * For example, we have big project with users stored in some storage.
7
 * The main entity for us – users.
8
 * Users could have the dozens of flags (true/false states). For example:
9
 * - is premium user;
10
 * - has wizard already shown;
11
 * - has paid ever;
12
 * - is referral user, bought from somewhere;
13
 * - ... etc ...
14
 * - is banned;
15
 * - ... etc ...
16
 * - has already notified today...
17
 *
18
 * We can create dozens of columns with type BOOLEAN for each flags
19
 * or just one column with array of integers (simple bitmasks).
20
 */
21
22
define('IS_PREMIUM', 1);
23
define('HAS_WIZARD_ALREADY_SHOWN', 2);
24
define('HAS_PAID_EVER', 3);
25
define('IS_REFERRAL', 4);
26
// ...
27
define('IS_BANNED', 64); // bitmask number greater than 64*1-1
28
// ...
29
define('HAS_ALREADY_NOTIFIED', 128);  // bitmask number greater than 64*2-1
30
31
// some users from storage
32
$user = [
33
    'bitmasks' => [], // default empty bitmasks
34
];
35
36
// create a Bitmask object, passing user bitmask from storage
37
$Bitmask = new \Aliance\InfiniteBitmask\InfiniteBitmask($user['bitmasks']);
38
39
checkFlags($Bitmask);
40
41
// set user some flags
42
$Bitmask->setBit(HAS_PAID_EVER);
43
$Bitmask->setBit(IS_BANNED);
44
$Bitmask->setBit(HAS_ALREADY_NOTIFIED);
45
46
checkFlags($Bitmask);
47
48
var_dump($Bitmask->getMaskSlices());
49
50
// unset daily flag
51
$Bitmask->unsetBit(HAS_ALREADY_NOTIFIED);
52
53
checkFlags($Bitmask);
54
55
var_dump($Bitmask->getMaskSlices());
56
57
function checkFlags(\Aliance\InfiniteBitmask\InfiniteBitmask $Bitmask)
58
{
59
    echo 'Check user for all flags:', PHP_EOL;
60
    echo 'Premium: ', $Bitmask->issetBit(IS_PREMIUM) ? 'yes' : 'no', PHP_EOL;
61
    echo 'Wizard already shown: ', $Bitmask->issetBit(HAS_WIZARD_ALREADY_SHOWN) ? 'yes' : 'no', PHP_EOL;
62
    echo 'Paid ever: ', $Bitmask->issetBit(HAS_PAID_EVER) ? 'yes' : 'no', PHP_EOL;
63
    echo 'Referral: ', $Bitmask->issetBit(IS_REFERRAL) ? 'yes' : 'no', PHP_EOL;
64
    echo 'Banned: ', $Bitmask->issetBit(IS_BANNED) ? 'yes' : 'no', PHP_EOL;
65
    echo 'Already notified: ', $Bitmask->issetBit(HAS_ALREADY_NOTIFIED) ? 'yes' : 'no', PHP_EOL;
66
    echo str_repeat('–', 35), PHP_EOL;
67
}
68