A small library that provides functionality to PHP 8.1 enums to act as BitMask flags

Related tags

API php-enum-bitmask
Overview

PHP Enum BitMask

Latest Stable Version Software License Build Status Total Downloads Dependents PHP Version Require Mutation testing badge Type Coverage

Email

A small library that provides functionality to PHP 8.1 enums to act as BitMask flags.

Why?

Sometimes you need some flags on the objects, to represent some features, most often its used simple property with the type of bool but then you start making several properties and then your object size (Serialized/JSON) starts growing quite a lot.

The most efficient storage option for flags was always bitmask value. It provides up to 32 unique flags inside a single int32 value.

Another big benefit is the ability to make AND, OR, NOT operations in one call instead of doing many if expressions to check all those property values.

Install

Via Composer

$ composer require framjet/enum-bitmask

Usage

The library provides a trait BitmaskFunctionality which is needed to include inside int backed enum.

Here is a tiny example of using Enum to provide flags using space-efficient bitmask int value:

<?php

use FramJet\Packages\EnumBitmask\BitmaskFunctionality;

enum Flag: int
{
    use BitmaskFunctionality;

    case Public = 0b000001;
    case Protected = 0b000010;
    case Private = 0b000100;
    case ReadOnly = 0b001000;
    case Static = 0b010000;
    case Final = 0b100000;
}

class Member
{
    public function __construct(private int $flags = 0)
    {
    }

    public function setPublic(): void
    {
        $this->flags = Flag::set(
            Flag::clear($this->flags, Flag::Private, Flag::Protected),
            Flag::Public
        );
    }

    public function isPublic(): bool
    {
        return Flag::on($this->flags, Flag::Public);
    }

    public function isReadOnly(): bool
    {
        return Flag::on($this->flags, Flag::ReadOnly);
    }

    /** @return list<Flag> */
    public function getFlags(): array
    {
        return Flag::parse($this->flags);
    }

    public function getFlagsValue(): int
    {
        return $this->flags;
    }
}

class Container
{
    /** @param list<Member> $members */
    public function __construct(private array $members = [])
    {
    }

    public function addMember(Member $member): void
    {
        $this->members[] = $member;
    }

    public function getMembers(Flag ...$flags): array
    {
        return array_filter($this->members, static fn(Member $m) => Flag::any($m->getFlagsValue(), ...$flags));
    }
}

$memberPublic = new Member();
$memberPublic->setPublic();

$memberPublic->getFlags(); // [Flag::Public]

$memberReadOnly = new Member(Flag::build(Flag::ReadOnly));

$memberReadOnly->isReadOnly(); // true
$memberReadOnly->isPublic();   // false

$memberPrivate = new Member(Flag::build(Flag::Private, Flag::ReadOnly));

$memberPrivate->isReadOnly(); // true
$memberPrivate->isPublic();   // false
$memberPrivate->getFlags();   // [Flag::Private, Flag::ReadOnly]

array_map(
    static fn(Flag $f) => $f->toString(),
    $memberPrivate->getFlags()
); // ['0b0000_0000_0000_0000_0000_0000_0000_0100', '0b0000_0000_0000_0000_0000_0000_0000_1000']

$container = new Container();
$container->addMember($memberPublic);
$container->addMember($memberReadOnly);
$container->addMember($memberPrivate);

$container->getMembers();                             // [$memberPublic, $memberReadOnly, $memberPrivate]
$container->getMembers(Flag::Public);                 // [$memberPublic]
$container->getMembers(Flag::ReadOnly);               // [$memberReadOnly, $memberPrivate]
$container->getMembers(Flag::ReadOnly, Flag::Public); // [$memberPublic, $memberReadOnly, $memberPrivate]

License

Please see License File for more information.

You might also like...
STEAM education curriculum centered on building a new civilization entirely from trash, which provides all human needs for free directly to the local community

TRASH ACADEMY STEAM(Science Technology Engineering Art Math) education curriculum centered around building self-replicating technology from trash whic

A Statamic Pro addon that provides alternative GraphQL queries for collections, entries and global sets.

Statamic Enhanced GraphQL A Statamic CMS GraphQL Addon that provides alternative GraphQL queries for collections, entries and global sets. ⚠️ This is

The PasswordHasher component provides password hashing utilities.

PasswordHasher Component The PasswordHasher component provides secure password hashing utilities. Getting Started $ composer require symfony/password-

Http-kernel - The HttpKernel component provides a structured process for converting a Request into a Response.

HttpKernel Component The HttpKernel component provides a structured process for converting a Request into a Response by making use of the EventDispatc

Provides tools for building modules that integrate Nosto into your e-commerce platform

php-sdk Provides tools for building modules that integrate Nosto into your e-commerce platform. Requirements The Nosto PHP SDK requires at least PHP v

A Symfony bundle that provides #StandWithUkraine banner and has some built-in features to block access to your resource for Russian-speaking users.
A Symfony bundle that provides #StandWithUkraine banner and has some built-in features to block access to your resource for Russian-speaking users.

StandWithUkraineBundle На русском? Смотри README.ru.md This bundle provides a built-in StandWithUkraine banner for your Symfony application and has so

Simple utility and class library for generating php classes from a wsdl file.

wsdl2phpgenerator Simple WSDL to PHP classes converter. Takes a WSDL file and outputs class files ready to use. Uses the MIT license. Announcement: We

A PHP library to support implementing representations for HATEOAS REST web services.

Hateoas A PHP library to support implementing representations for HATEOAS REST web services. Installation Working With Symfony Usage Introduction Conf

This PHP library will help you to work with your Pinterest account without using any API account credentials.
This PHP library will help you to work with your Pinterest account without using any API account credentials.

Pinterest Bot for PHP A PHP library to help you work with your Pinterest account without API credentials. The Pinterest API is painful: receiving an a

Releases(1.0.0)
Owner
FramJet
FramJet
This API provides functionality for creating and maintaining users to control a simple To-Do-List application. The following shows the API structure for users and tasks resources.

PHP API TO-DO-LIST v.2.0 This API aims to present a brief to consume a API resources, mainly for students in the early years of Computer Science cours

Edson M. de Souza 6 Oct 13, 2022
A small library for usage deepai.org api

deepai a small library for usage deepai.org api install via composer : composer require mkhab7/deepai usage use Solid\Deepai\Deepai; require_once 've

solid 1 Oct 23, 2022
The news bundle adds news functionality to Contao 4

Contao 4 news bundle The news bundle adds news functionality to Contao 4. Contao is an Open Source PHP Content Management System for people who want a

Contao 8 Jan 10, 2022
This small POC aims to show how Symfony is able, natively without modifications, to use subdirectories for Entities, Repositories, controllers, views…

POC - Using Sub Directories in a Symfony Project This small POC aims to show how Symfony is able, natively without modifications, to use subdirectorie

Yoan Bernabeu 2 May 12, 2022
A PHP replacement layer for the C intl extension that also provides access to the localization data of the ICU library.

A PHP replacement layer for the C intl extension that also provides access to the localization data of the ICU library.

Symfony 2.5k Dec 29, 2022
The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructure and leverage the power of 1Password Secrets Automation

1Password Connect PHP SDK The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructu

Michelangelo van Dam 12 Dec 26, 2022
The Facebook SDK for PHP provides a native interface to the Graph API and Facebook Login

Facebook SDK for PHP (v5) This repository contains the open source PHP SDK that allows you to access the Facebook Platform from your PHP app. Installa

Meta Archive 3.1k Dec 30, 2022
This bundle provides tools to build a complete GraphQL server in your Symfony App.

OverblogGraphQLBundle This Symfony bundle provides integration of GraphQL using webonyx/graphql-php and GraphQL Relay. It also supports: batching with

Webedia - Overblog 720 Dec 25, 2022
Provides a Middleware to integration Tideways into Symfony Messenger Processing

Tideways Middleware for Symfony Messenger This package is currently under development and might be moved into the Tideways PHP Extension or stay indep

Tideways 6 Jul 5, 2022
A RESTful and extendable Backend as a Service that provides instant backend to develop sites and apps faster, with dead-simple integration for JavaScript, iOS, Android and more.

Welcome to hook ![Gitter](https://badges.gitter.im/Join Chat.svg) hook is a RESTful, extendable Backend as a Service that provides instant backend to

doubleleft 762 Dec 30, 2022