PHP code example of pwm / bitset

1. Go to this page and download the library: Download pwm/bitset library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pwm / bitset example snippets


class Group
{
    const G1 = 'Group 1';
    const G2 = 'Group 2';
    const G3 = 'Group 3';
    const G4 = 'Group 4';
    const G5 = 'Group 5';

    private const MAP = [
        self::G1 => BitSet::B1,
        self::G2 => BitSet::B2,
        self::G3 => BitSet::B3,
        self::G4 => BitSet::B4,
        self::G5 => BitSet::B5,
    ];

    public static function fromGroups(array $groups): array
    {
        return array_values(array_intersect_key(self::MAP, array_flip($groups)));
    }

    public static function toGroups(array $bitValues): array
    {
        return array_values(array_intersect_key(array_flip(self::MAP), array_flip($bitValues)));
    }
}

class User
{
    private $groups = BitSet::EMPTY;

    public function getGroups(): array
    {
        return Group::toGroups(BitSet::get($this->groups));
    }

    public function setGroups(array $groups): void
    {
        $this->groups = BitSet::set(Group::fromGroups($groups));
    }

    public function addGroups(array $groups): void
    {
        $this->groups = BitSet::add($this->groups, Group::fromGroups($groups));
    }

    public function removeGroups(array $groups): void
    {
        $this->groups = BitSet::remove($this->groups, Group::fromGroups($groups));
    }

    public function hasGroup(string $group): bool
    {
        $a = Group::fromGroups([$group]);
        return isset($a[0])
            ? BitSet::has($this->groups, $a[0])
            : false;
    }
}

$user = new User();
$user->setGroups([Group::G1, Group::G2]);

assert($user->getGroups() === [Group::G1, Group::G2]);
assert($user->hasGroup(Group::G1) === true);

$user->addGroups([Group::G4, Group::G5]);
$user->removeGroups([Group::G1, Group::G4]);

assert($user->getGroups() === [Group::G2, Group::G5]);
assert($user->hasGroup(Group::G1) === false);