Search by

gisostallenberg / bitwise-constant-calculator

gisostallenberg

This package is abandoned and no longer maintained. The author suggests using the symfony/expression-language package instead.

Calculates the value of bitwise operations on a list of constants

Package info

github.com/gisostallenberg/bitwise-constant-calculator

pkg:composer/gisostallenberg/bitwise-constant-calculator

Statistics

Installs: 82

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

1.0.0 2017-02-22 15:12 UTC

This package is auto-updated.

Last update: 2026-10-27 20:46:55 UTC


README

Calculates the value of bitwise operations on a list of constants

⚠️ Avoid in new code

This is not a security problem, but the calculation is wrong for mixed operators. It folds strictly left to right, while PHP binds bitwise operators & > ^ > |. So the result can silently disagree with the equivalent PHP expression this package is meant to mirror:

// with A = 1, B = 3, C = 2
// native PHP:  A | B & C  ==  A | (B & C)  ==  1 | (3 & 2)  ==  1 | 2  ==  3
// this class:  (A | B) & C             ==  (1 | 3) & 2      ==  3 & 2  ==  2  // wrong

It also passes parsed input straight to constant(), where an undefined constant is a fatal Error on PHP 8.

What to use instead

There is no like-for-like replacement package, so pick by use case:

  • Only OR-ing flags from config (A | B | C) needs no package:

    array_reduce(preg_split('/\s*\|\s*/', $string), fn($acc, $n) => $acc | constant($n), 0);
  • Arbitrary & ^ | ~ expressions with correct precedence — use symfony/expression-language, which has a real parser. It does not resolve constant names on its own, so register a constant() function (or pass the values in as variables):

    use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
    
    $el = new ExpressionLanguage();
    $el->register('constant', fn($n) => "constant($n)", fn($args, $n) => constant($n));
    
    $el->evaluate('constant("E_ALL") | constant("E_STRICT")'); // correct precedence
    // or feed values directly:
    $el->evaluate('E_ALL | E_STRICT', ['E_ALL' => E_ALL, 'E_STRICT' => E_STRICT]);
  • Specifically an error_reporting level from config — use neither. PHP's own ini parser already evaluates strings like E_ALL & ~E_DEPRECATED.

Installation

composer require gisostallenberg/bitwise-constant-calculator

Usage examples

use GisoStallenberg\BitwiseConstantCalculator\BitwiseConstantCalculator;

$result = BitwiseConstantCalculator::create()
            ->calculate("E_ALL | E_STRICT");
($result === E_ALL | E_STRICT); // true