PHP code example of fgremez / flagbag

1. Go to this page and download the library: Download fgremez/flagbag 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/ */

    

fgremez / flagbag example snippets


use FlagBag\FlagBag;
use FlagBag\Attribute\FlagBit;

class UserPermissions extends FlagBag
{
    #[FlagBit(1)]
    private bool $canRead = false;

    #[FlagBit(2)]
    private bool $canWrite = false;

    #[FlagBit(4)]
    private bool $canDelete = false;

    #[FlagBit(8)]
    private bool $isAdmin = false;
}

$permissions = UserPermissions::fromInt(9); // canRead (1) + isAdmin (8)

$permissions->get('canRead');  // true
$permissions->get('canWrite'); // false

$permissions->set('canWrite', true);

$permissions->toInt(); // 11 (1 + 2 + 8)

$value = UserPermissions::fromInt(0)
    ->set('canRead', true)
    ->set('isAdmin', true)
    ->toInt(); // 9

class User
{
    private int $permissions = 0;

    public function getPermissions(): UserPermissions
    {
        return UserPermissions::fromInt($this->permissions);
    }

    public function setPermissions(UserPermissions $bag): void
    {
        $this->permissions = $bag->toInt();
    }
}

$user->setPermissions(
    $user->getPermissions()->set('canWrite', true)
);