A simple way to use bitmask and bitwise operations in PHP.
Requires PHP 8.2+
composer require gksh/bitmaskStreamline flag handling by encoding boolean options into simple integers through bitmasking.
Please see ide.php for full example and playground for more.
useGksh\Bitmask\Bitmask;
enum Panel: int
{
case Project = 1;
case Terminal = 2;
case SourceControl = 4;
case Extensions = 8;
}
class Ide
{
publicBitmask$panels;
publicfunction__construct()
{
$this->panels = Bitmask::tiny(); // 8-bit
}
publicfunctiontogglePanel(Panel$panel): self
{
$this->panels = $this->panels->toggle($panel);
return$this;
}
}
$ide = (newIde())
->togglePanel(Panel::Project)
->togglePanel(Panel::Terminal);
$ide->panels->has(Panel::Terminal); // true$ide->panels->has(Panel::Extensions); // false- Immutable: Operations return new instances, original unchanged
- Enum support: Pass
BackedEnumdirectly — no->valueextraction needed - Size variants:
tiny()(8-bit),small()(16-bit),medium()(24-bit),make()(32-bit default)
Bitmask::make() // 32-bit (default)
Bitmask::tiny() // 8-bit, for TINYINT columns
Bitmask::small() // 16-bit, for SMALLINT columns
Bitmask::medium() // 24-bit, for MEDIUMINT columns$mask = Bitmask::tiny()
->set(Flag::A) // Set a flag
->unset(Flag::B) // Unset a flag
->toggle(Flag::C); // Toggle a flag$mask->has(Flag::A); // Check if flag is set$mask->value(); // Get integer value$mask->size(); // Get Size enumcomposer testPlease see CHANGELOG for more information on what has changed recently.
The MIT License (MIT). Please see License File for more information.
