PHPackages                             alazzi-az/php-bitmask - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. alazzi-az/php-bitmask

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

alazzi-az/php-bitmask
=====================

php package to work with bitmasking

v1.0.2(1y ago)4759↓50%1[1 PRs](https://github.com/alazzi-az/php-bitmask/pulls)1MITPHPPHP ^8.1|^8.2CI passing

Since Oct 15Pushed 1y agoCompare

[ Source](https://github.com/alazzi-az/php-bitmask)[ Packagist](https://packagist.org/packages/alazzi-az/php-bitmask)[ Docs](https://github.com/alazzi-az/php-bitmask)[ GitHub Sponsors](https://github.com/mohammedazman)[ RSS](/packages/alazzi-az-php-bitmask/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (3)Versions (5)Used By (1)

PHP package to work with bitmasking
===================================

[](#php-package-to-work-with-bitmasking)

[![Latest Version on Packagist](https://camo.githubusercontent.com/6713f1a6040aa294263835a21eb49f1b9a4b81c5a6e08065e7192d94b763c63b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f616c617a7a692d617a2f7068702d6269746d61736b2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/alazzi-az/php-bitmask)[![GitHub Tests Action Status](https://camo.githubusercontent.com/0b1b696fd53c63f8d6d6f79dab839d7d1fc7e29d0f14c5031df1a81cdb263a7d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f616c617a7a692d617a2f7068702d6269746d61736b2f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473)](https://github.com/alazzi-az/php-bitmask/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/7065e91cec7040e58c186e7b4f4d41a5b8e739da2337b892d0596bb33d5c1387/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f616c617a7a692d617a2f7068702d6269746d61736b2f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65)](https://github.com/alazzi-az/php-bitmask/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/8fba9c1fe85d20b219abe019612b95bf2f87b93704bb59e233286f0c7df79b5b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f616c617a7a692d617a2f7068702d6269746d61736b2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/alazzi-az/php-bitmask)

**PHP Bitmask** is a powerful package for managing bitmask operations in php applications. It provides an elegant and intuitive interface for reading, validating, converting bitmasks, and casting them to and from enum values, enabling developers to leverage bitmasking techniques efficiently.

Features
--------

[](#features)

- **Bitmask Reading**: Easily retrieve active bits from a given bitmask.
- **Bitmask Validation**: Ensure that provided bits and masks are valid, including checks for single-bit settings.
- **Bitmask Conversion**: Convert indices to bitmasks and vice versa, along with conversions to binary string representations.
- **Casting for Masks and Enums**: Automatically handle the casting of bitmask values to and from enum types, providing a seamless experience when working with enumerated bitmasks.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require alazzi-az/php-bitmask
```

Usage
-----

[](#usage)

Bitmask Class
=============

[](#bitmask-class)

The `Bitmask` class provides a collection of static methods for handling bitmask operations. It includes functionality for creating bitmask handlers, converting between indexes and bitmasks, and validating bit values.

```
use Alazziaz\Bitmask\Bitmask;

// Create a bitmask handler with an initial mask of 3
$maskable = Bitmask::bitmaskHandler(3); // The mask value is initialized to 3
```

Creating an Enum Bitmask Handler
--------------------------------

[](#creating-an-enum-bitmask-handler)

You can create a bitmask handler that works with an enum by using the `enumBitmaskHandler` method.

### Example

[](#example)

```
use Alazziaz\Bitmask\Bitmask;

// Define an enum for demonstration
enum SomeEnum: int {
    case FIRST = 1;
    case SECOND = 2;
    case THIRD = 4;
}

$enumClass = SomeEnum::class;
// Create an enum bitmask handler with the FIRST and SECOND values
$enumMaskable = Bitmask::enumBitmaskHandler($enumClass, SomeEnum::FIRST, SomeEnum::SECOND);
```

Here’s the complete documentation, including the missing methods for both the `EnumBitmaskFactory` and `Bitmask` classes.

---

EnumBitmaskFactory
------------------

[](#enumbitmaskfactory)

The `EnumBitmaskFactory` provides methods to create and manipulate bitmask handlers for enum values.

### Example Usage

[](#example-usage)

```
use Alazziaz\Bitmask\Bitmask;

enum YourEnum: int {
    case FIRST = 1;
    case SECOND = 2;
    case THIRD = 4;
}

// Create a bitmask handler with FIRST and SECOND enum values
$enumHandler = Bitmask::enumBitmaskHandlerFactory()->create(
    YourEnum::class, YourEnum::FIRST, YourEnum::SECOND
);
```

### Here EnumBitmaskFactory Methods Overview

[](#here-enumbitmaskfactory-methods-overview)

1. **`create(string $enum, UnitEnum ...$bits): EnumBitmaskHandler`**
    Creates a handler with the specified enum cases.
2. **`createWithMask(string $enum, int $mask): EnumBitmaskHandler`**
    Creates a handler with a predefined bitmask.
3. **`createNone(string $enum): EnumBitmaskHandler`**
    Creates a handler with an empty bitmask (no bits set).
4. **`createAll(string $enum): EnumBitmaskHandler`**
    Creates a handler with all enum cases active.
5. **`without(string $enum, UnitEnum ...$bits): EnumBitmaskHandler`**
    Creates a handler with all cases except the specified ones.
6. **`none(string $enum): EnumBitmaskHandler`**
    Same as `createNone`—creates a handler with no bits set.

---

Here Extra Bitmask Class Methods
--------------------------------

[](#here-extra-bitmask-class-methods)

---

#### **1. Exposing BitmaskConverter Methods**

[](#1-exposing-bitmaskconverter-methods)

- **`indexToBitMask(int $index): int`**
    Converts an index to its corresponding bitmask.
    **Example:**

    ```
    Bitmask::indexToBitMask(3); // Output: 8
    ```
- **`bitMaskToIndex(int $mask): int`**
    Converts a bitmask to its index.
    **Example:**

    ```
    Bitmask::bitMaskToIndex(8); // Output: 3
    ```
- **`getEnumMaxBitValue(string $enum): int`**
    Retrieves the maximum bit value for the given enum.
- **`bitMaskToArray(int $mask): array`**
    Converts a bitmask into an array of active bit values.
    **Example:**

    ```
    Bitmask::bitMaskToArray(10); // Output: [2, 8]
    ```
- **`arrayToBitMask(array $bits): int`**
    Converts an array of bit values to a bitmask.
    **Example:**

    ```
    Bitmask::arrayToBitMask([2, 8]); // Output: 10
    ```

---

#### **2. Exposing BitmaskReader Methods**

[](#2-exposing-bitmaskreader-methods)

- **`getActiveBits(int $bitmask): array`**
    Retrieves the active bit values from a bitmask.
    **Example:**

    ```
    Bitmask::getActiveBits(10); // Output: [2, 8]
    ```
- **`getActiveIndexes(int $bitmask): array`**
    Retrieves the active bit indexes from a bitmask.
    **Example:**

    ```
    Bitmask::getActiveIndexes(10); // Output: [1, 3]
    ```
- **`countActiveBits(int $bitmask): int`**
    Counts the number of active bits in a bitmask.
    **Example:**

    ```
    Bitmask::countActiveBits(10); // Output: 2
    ```
- **`getMostSignificantBitIndex(int $bitmask): int`**
    Returns the index of the most significant active bit.
    **Example:**

    ```
    Bitmask::getMostSignificantBitIndex(10); // Output: 3
    ```
- **`getLeastSignificantBitIndex(int $bitmask): int`**
    Returns the index of the least significant active bit.
    **Example:**

    ```
    Bitmask::getLeastSignificantBitIndex(10); // Output: 1
    ```
- **`convertToBinaryString(int $bitmask): string`**
    Converts a bitmask to its binary string representation.
    **Example:**

    ```
    Bitmask::convertToBinaryString(10); // Output: '1010'
    ```

---

#### **3. Exposing BitmaskValidator Methods**

[](#3-exposing-bitmaskvalidator-methods)

- **`validateBit(int $bit): void`**
    Validates a single bit to ensure it's valid.
    **Example:**

    ```
    Bitmask::validateBit(2); // No exception
    ```
- **`validateBits(array $bits): void`**
    Validates an array of bits to ensure all are valid.
    **Example:**

    ```
    Bitmask::validateBits([2, 8]); // No exception
    ```

---

### BitmaskHandler

[](#bitmaskhandler)

The `BitmaskHandler` class provides an interface for managing bitmask operations in a Laravel application. It allows for the manipulation of bitmasks through various methods, including adding, deleting, and checking for specific bits.

```
use Alazziaz\Bitmask\Bitmask;

// Create a BitmaskHandler instance with the combined permissions
$permissions = 1 | 2 | 4;
$bitmask = Bitmask::bitmaskHandler($permissions);
$maskValue = $bitmask->getValue(); // Returns 7

// Create a BitmaskHandler with an initial mask of 0
$bitmaskHandler = Bitmask::bitmaskHandler(0);

// Create a BitmaskHandler with an initial mask and a highest bit
$bitmaskHandlerWithLimit = Bitmask::bitmaskHandler(0, 7);

// Returns the current mask (e.g., 0)
$currentValue = $bitmaskHandler->getValue();

// Returns the binary string representation
$binaryString = $bitmaskHandler->toString();

// Adds bits 1 and 2 to the current mask
$bitmaskHandler->add(1, 2);

// Deletes bit 1 from the current mask
$bitmaskHandler->delete(1);

// Returns true if bits 1 and 2 are set
$hasBits = $bitmaskHandler->has(1, 2);
```

### EnumBitmaskHandler

[](#enumbitmaskhandler)

The `EnumBitmaskHandler` class provides an interface for managing bitmask operations specific to enumerations in a Laravel application. It allows manipulation of bitmasks using enums, enabling you to add, delete, and check for specific bits represented by these enums.

```
use Alazziaz\Bitmask\Bitmask;

enum YourEnum: int {
    case FIRST = 1;
    case SECOND = 2;
    case THIRD = 4;
}
// Create an EnumBitmaskHandler with specific bits set
$enumBitmaskHandler = Bitmask::enumBitmaskHandler(YourEnum::class, YourEnum::BIT_ONE, YourEnum::BIT_TWO);

// Returns the current mask value (e.g., 0)
$currentValue = $enumBitmaskHandler->getValue();

// Add bits to the current mask
$enumBitmaskHandler->add(YourEnum::BIT_THREE);

// Delete a bit from the current mask
$enumBitmaskHandler->delete(YourEnum::BIT_ONE);

// Check if specific bits are set in the current mask
$hasBits = $enumBitmaskHandler->has(YourEnum::BIT_TWO, YourEnum::BIT_THREE);

// Convert the current mask to an array representation
$arrayRepresentation = $enumBitmaskHandler->toArray(); // e.g., ['bit_one' => false, 'bit_two' => true, 'bit_three' => true]
```

#### Methods Overview

[](#methods-overview)

- **`remove(UnitEnum ...$bits): self`**

    - Removes specified bits from the current instance.
- **`add(UnitEnum ...$bits): self`**

    - Adds specified bits to the current instance.
- **`getValue(): int`**

    - Returns the current mask value as an integer.
- **`toArray(): array`**

    - Returns an array representation of the current mask, indicating which bits are set.
- **`has(UnitEnum ...$bits): bool`**

    - Checks if the specified bits are set in the current mask.

#### Example Usage

[](#example-usage-1)

Here's an example that illustrates how to use the `EnumBitmaskHandler` class:

```
use \Alazziaz\Bitmask\Bitmask;
// Assuming you have an enum defined as:
enum YourEnum: int {
    case BIT_ONE = 1;
    case BIT_TWO = 2;
    case BIT_THREE = 4;
}

// Creating an instance with no bits set
$bitmaskHandler = Bitmask::enumBitmaskHandlerFactory()
->none(YourEnum::class);

// Adding bits
$bitmaskHandler->add(YourEnum::BIT_ONE, YourEnum::BIT_TWO);

// Checking current value
$currentValue = $bitmaskHandler->getValue(); // Returns 3

// Checking if specific bits are set
$hasBitOne = $bitmaskHandler->has(YourEnum::BIT_ONE); // Returns true

// Converting to an array
$arrayRepresentation = $bitmaskHandler->toArray(); // ['bit_one' => true, 'bit_two' => true, 'bit_three' => false]
```

#### Note on `toArray` Method

[](#note-on-toarray-method)

If you want to customize the keys in the resulting array from the `toArray` method, consider implementing the `Alazziaz\Bitmask\Contracts\MaskableEnum` interface for your enum. You can define a `toMaskKey` method to specify custom keys for each enum value. For example:

```
public function toMaskKey(): string
{
    return match ($this) {
        self::READ => 'read_permission',
        self::WRITE => 'write_permission',
        self::EXECUTE => 'execute_permission',
    };
}
```

With this approach, the `toArray` method in `EnumBitmaskHandler` can utilize the `toMaskKey` method to generate a more descriptive and meaningful array representation of the current mask.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Credits
-------

[](#credits)

- [Mohammed Azman](https://github.com/mohammedazman)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance40

Moderate activity, may be stable

Popularity21

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

571d ago

PHP version history (2 changes)v1.0.0PHP ^8.1

v1.0.1PHP ^8.1|^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/750a1566a9f2ed8de9e8da9fee372b4426d7585bfdabdb65a1932a40e409a3e3?d=identicon)[alazzi](/maintainers/alazzi)

---

Top Contributors

[![mohammedazman](https://avatars.githubusercontent.com/u/56982649?v=4)](https://github.com/mohammedazman "mohammedazman (12 commits)")

---

Tags

alazzi-azphp-bitmask

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/alazzi-az-php-bitmask/health.svg)

```
[![Health](https://phpackages.com/badges/alazzi-az-php-bitmask/health.svg)](https://phpackages.com/packages/alazzi-az-php-bitmask)
```

###  Alternatives

[paulredmond/html-to-amp

A PHP Library to Convert HTML to AMP HTML

6826.0k](/packages/paulredmond-html-to-amp)[mageprince/module-buynow

Magento2 Buy Now Module

829.7k](/packages/mageprince-module-buynow)[netzmacht/php-leaflet

PHP leaflet definition and javascript generator

1927.2k2](/packages/netzmacht-php-leaflet)[edofre/laravel-fullcalendar-scheduler

Laravel component for fullcalendar scheduler module

251.5k](/packages/edofre-laravel-fullcalendar-scheduler)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
