PHP Classes
elePHPant
Icontem

PHP Binary Flags: Manage a group of boolean flags using integers

Recommend this page to a friend!
  Info   View files Documentation   View files View files (14)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2018-05-06 (7 months ago) RSS 2.0 feedNot enough user ratingsTotal: 96 All time: 9,098 This week: 396Up
Version License PHP version Categories
binary-flags 1.0.0Custom (specified...5PHP 5, Data types, Traits
Description Author

This package can manage a group of boolean flags using integers.

It provides a trait that can perform operations to change integers that hold a set of bit values.

The package also provides an abstract class that uses the trait, so it can be used to create objects to manipulate binary flags.

The trait can manipulate integers with up to 64 bits. Currently the trait can:

- Register a function to be called when the binary flags are modified
- Check, get, set or remove a mask number from the binary flags

Innovation Award
PHP Programming Innovation award winner
June 2018
Winner


Prize: One big elePHPant Plush Mascott
An integer number can be stored as a set of bits of different lengths.

Sometimes classes need to manage sets of bits to store groups flag values.

This package provides a trait that allows developers to use bit sets in many different types of classes.

Manuel Lemos
  Performance   Level  
Name: Reinder Reinders is available for providing paid consulting. Contact Reinder Reinders .
Classes: 1 package by
Country: The Netherlands The Netherlands
Age: 35
All time rank: 4189102 in The Netherlands The Netherlands
Week rank: 750 Up20 in The Netherlands The Netherlands Up
Innovation award
Innovation award
Nominee: 1x

Winner: 1x

Details

Build Status Coverage Status

BinaryFlags

With this class you can easily add flags to your projects.

The number of flags you can use is limited to the architecture of your system, e.g.: 32 flags on a 32-bit system or 64 flags on 64-bit system. To store 64-bits flags in a database, you will need to store it as UNSIGNED BIGINT in MySQL or an equivalant in your datastorage.

This package also comes with a trait which you can use to implement binary flags directly in your own class.

Installing

To install this package simply run the following command in the root of your project.

composer require reinder83/binary-flags

Methods

The following methods can be used:

setMask(int $mask)

Overwrite the current mask. This can be passed as first argument in the constructor.

getMask(): int

Retrieve the current mask.

setOnModifyCallback(callable $onModify)

Set a callback function which is called when the mask changes. This can be passed as second argument in the constructor.

getFlagNames([int $mask, [bool $asArray=false]])

Give the name(s) for the given $mask or the current mask when omitted. When $asArray is true the method will return an array with the names, otherwise an comma separated string will be returned (default).

addFlag(int $flag)

Adds one or multiple flags to the current mask.

removeFlag(int $flag)

Removes one or multiple flags from the current mask.

checkFlag(int $flag, [bool $checkAll=true]): bool

Check if given flag(s) are set in the current mask. By default it will check all bits in the given flag. When you want to match any of the given flags set $checkAll to false.

checkAnyFlag(int $mask): bool

For you convenient I've added an alias to checkFlag with $checkAll set to false.

Example usage

Below some example usage code

Create classes
// example classes which the following examples will refer to
use Reinder83\BinaryFlags\BinaryFlags;
use Reinder83\BinaryFlags\Bits;

class ExampleFlags extends BinaryFlags
{
    const FOO = Bits::BIT_1;
    const BAR = Bits::BIT_2;
    const BAZ = Bits::BIT_3;
}

Simple usage
$exampleFlags = new ExampleFlags();

// add BAR flag
$exampleFlags->addFlag(ExampleFlags::BAR);

var_export($exampleFlags->checkFlag(ExampleFlags::FOO)); 
// false
var_export($exampleFlags->checkFlag(ExampleFlags::BAR)); 
// true

// remove BAR flag
$exampleFlags->removeFlag(ExampleFlags::BAR);

var_export($exampleFlags->checkFlag(ExampleFlags::BAR)); 
// false

Usage with multiple flags
$exampleFlags = new ExampleFlags();

// add FOO and BAR
$exampleFlags->addFlag(ExampleFlags::FOO | ExampleFlags::BAR); 

var_export($exampleFlags->checkFlag(ExampleFlags::FOO)); 
// true

var_export($exampleFlags->checkFlag(ExampleFlags::FOO | ExampleFlags::BAZ)); 
// false because BAZ is not set

var_export($exampleFlags->checkFlag(ExampleFlags::FOO | ExampleFlags::BAR)); 
// true because both flags are set

var_export($exampleFlags->checkFlag(ExampleFlags::FOO | ExampleFlags::BAZ, false)); 
// true because one of the flags is set (FOO)

// alias of the above method
var_export($exampleFlags->checkAnyFlag(ExampleFlags::FOO | ExampleFlags::BAZ)); 
// true

Flag names example

_By default the flag names are based on the constant names_

$exampleFlags = new ExampleFlags();

$exampleFlags->addFlag(ExampleFlags::FOO | ExampleFlags::BAR | ExampleFlags::BAZ);
var_export($exampleFlags->getFlagNames());
// 'Foo, Bar, Baz'

// null will force current mask
var_export($exampleFlags->getFlagNames(null, true));
/*
array (
  0 => 'Foo',
  1 => 'Bar',
  2 => 'Baz',
)
*/

// get flag names of given mask
var_export($exampleFlags->getFlagNames(ExampleFlags::FOO | ExampleFlags::BAR));
// 'Foo, Bar'

Custom flag names example

If you want custom flag names that are not equal to the constant names, you can override these with getAllFlags()

class ExampleFlagsWithNames extends BinaryFlags
{
    const FOO = Bits::BIT_1;
    const BAR = Bits::BIT_2;
    const BAZ = Bits::BIT_3;
    
    public static function getAllFlags()
    {
        return [
            static::FOO => 'My foo description',
            static::BAR => 'My bar description',
            static::BAZ => 'My baz description',
        ];
    }
}

$exampleFlags = new ExampleFlagsWithNames();

$exampleFlags->addFlag(ExampleFlags::FOO | ExampleFlags::BAR | ExampleFlags::BAZ);

// null will force current mask
var_export($exampleFlags->getFlagNames(null, true));
/*
array (
  0 => 'My foo description',
  1 => 'My bar description',
  2 => 'My baz description',
)
*/

Example usage with Eloquent models

use Illuminate\Database\Eloquent\Model;

class Test extends Model
{
    /
     * Retrieve flags
     * @return ExampleFlags
     */
    public function getFlagsAttribute()
    {
        static $flags = null;
        if ($flags === null) {
            $model = $this;
            $flags = new ExampleFlags(
                $this->attributes['flags'], // set current flags mask
                function (ExampleFlags $flags) use ($model) { // set callback function
                    // update the flags in this model
                    $model->flags = $flags->getMask();
                }
            );
        }
        return $flags;
    }
}

// retrieve object from DB
$test = Test::find(1);

// do binary operations on the flags class as described earlier
$test->flags->checkFlag(ExampleFlag::FOO);

Support

For bugs or feature requests feel free to contact me or submit an issue or pull request.

  Files folder image Files  
File Role Description
Files folder imagebuild (3 files)
Files folder imagesrc (2 files, 1 directory)
Files folder imagetests (2 files)
Accessible without login Plain text file .coveralls.yml Data Auxiliary data
Accessible without login Plain text file .travis.yml Data Auxiliary data
Accessible without login Plain text file build.xml Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files  /  build  
File Role Description
  Accessible without login Plain text file phpcs.xml Data Auxiliary data
  Accessible without login Plain text file phpmd.xml Data Auxiliary data
  Accessible without login Plain text file phpunit.xml Data Auxiliary data

  Files folder image Files  /  src  
File Role Description
Files folder imageTraits (1 file)
  Plain text file BinaryFlags.php Class Class source
  Plain text file Bits.php Class Class source

  Files folder image Files  /  src  /  Traits  
File Role Description
  Plain text file BinaryFlags.php Class Class source

  Files folder image Files  /  tests  
File Role Description
  Plain text file BinaryFlagsTest.php Class Class source
  Plain text file bootstrap.php Class Class source

 Version Control Unique User Downloads Download Rankings  
 100%
Total:96
This week:0
All time:9,098
This week:396Up