PHP code example of wilensky / bitmask-trait

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

    

wilensky / bitmask-trait example snippets




use Wilensky\Traits\BitmaskTrait;

class MyClass
{
    use BitmaskTrait; // Injecting trait in your class
}

const INVOICE_SENT = 0;
const INVOICE_OPENED = 1;

// ... for the sake of brevity

const PAYMENT_REFUSED = 10;
const PAYMENT_REFUNDED = 11;

// All further code assumed inside a class scope function as trait has no public methods

$state = 0; // Initial/Zero state

$sent = $this->setBit(
    $state, // Passing initial/existing state to assign few more to
    self::INVOICE_SENT, // (bit 0)
    self::INVOICE_OPENED // (bit 1)
); // 3 (bits 0/1)

// Adding `PAYMENT_INPROGRESS` state to already arranged mask with 2 states
$paymentInit = $this->setBit(
    $sent, // Passing existing mask `3` (with 2 states, 0 and 1 bits)
    self::PAYMENT_INPROGRESS // (bit 5)
); // 35 (bits 0/1/5)

// or the same stuff with use of another method (@see BitmaskTrait::manageMaskBit())
$paymentInit = $this->manageMaskBit($sent, self::PAYMENT_INPROGRESS, true);

// Proceeding to some terminal payment state
$noOpenInProgress = $this->unsetBit(
    $paymentInit, // 35
    self::PAYMENT_INPROGRESS, // Removing `PAYMENT_INPROGRESS` state (bit 5)
    self::INVOICE_OPENED // among with `INVOICE_OPENED` (bit 1)
); // 1 (bits 0)

// to add relevant terminal states
$invoiceClosed = $this->setBit(
    $noOpenInProgress, // Passing mask with relevant unset states
    self::PAYMENT_SUCCESSFUL, // (bit 6)
    self::INVOICE_CLOSED // (bit 2)
); // 69 (bits 0/2/6)

$state = 69; // Invoice closed

$isInvoiceSent = $this->hasBit($state, self::INVOICE_SENT); // true
$isPaymentSuccessful = $this->hasBit($state, self::PAYMENT_SUCCESSFUL); // true
$isRefunded = $this->hasBit($state, self::PAYMENT_REFUNDED); // false

$invoiceSegment = [0, 4]; // Segment range as a single variable

// No exception as state is in allowed range
$this->isBitInRange(self::INVOICE_CLOSED, ...$invoiceSegment);

// `BitAddressingException` will be thrown as payment state is not in allowed range
$this->isBitInRange(self::PAYMENT_SUCCESSFUL, ...$invoiceSegment);