PHP code example of henrywhitaker3 / bitmasked-properties

1. Go to this page and download the library: Download henrywhitaker3/bitmasked-properties 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/ */

    

henrywhitaker3 / bitmasked-properties example snippets


class Person
{
    public function __construct(
        public bool $sms,
        public bool $email
    ) {}

    public function isOptedIn(string $type): bool
    {
        // Should really check the value of type is valid first...
        return $this->{$type};
    }

    public function optin(string $type): void
    {
        $this->updateOptin($type, true);
    }

    public function optout(string $type): void
    {
        $this->updateOptin($type, false);
    }

    private function updateOptin(string $type, bool $value): void
    {
        switch($type) {
            case 'sms':
                $this->sms = $value;
                break;
            case 'email':
                $this->email = $value;
                break;
        }
    }
}

enum Optin: int implements BitmaskEnum
{
    case SMS = 1 << 0; // 1
    case EMAIL = 1 << 1; // 2
}

class Person
{
    use HasBitmaskedProperties;

    public function __construct(
        public bool $optin
    ) {}

    public function isOptedIn(Optin $type): bool
    {
        return $this->getFlag('optin', $type);
    }

    public function optin(Optin $type): void
    {
        $this->setFlag('optin', $type, true);
    }

    public function optout(Optin $type): void
    {
        $this->setFlag('optin', $type, false);
    }

    public function getOptins(): WeakMap
    {
        return $this->flagToWeakmap('optin', Optin::class);
    }
}

$person = new Person; // $optin === 0

$person->isOptedIn(Optin::SMS); // returns false
$person->optin(Optin::SMS); // $optin === 1
$person->isOptedIn(Optin::SMS); // returns true

$person->optin(Optin::EMAIL); // $optin === 3
$person->isOptedIn(Optin::EMAIL); // returns true

$person->optout(Optin::SMS); // $optin === 2
$person->isOptedIn(Optin::SMS); // returns false

$person->getOptins()[Optin::EMAIL]; // return true