All Projects → dbalabka → php-enumeration

dbalabka / php-enumeration

Licence: MIT license
Implementation of enumeration classes in PHP. The better alternative for enums

Programming Languages

PHP
23972 projects - #3 most used programming language
Dockerfile
14818 projects

Projects that are alternatives of or similar to php-enumeration

php-enum
Better PHP enum support
Stars: ✭ 23 (-57.41%)
Mutual labels:  enumeration, php-enum
ActiveDirectoryEnumeration
Enumerate AD through LDAP with a collection of helpfull scripts being bundled
Stars: ✭ 127 (+135.19%)
Mutual labels:  enumeration
Pspy
Monitor linux processes without root permissions
Stars: ✭ 2,470 (+4474.07%)
Mutual labels:  enumeration
Dirstalk
Modern alternative to dirbuster/dirb
Stars: ✭ 210 (+288.89%)
Mutual labels:  enumeration
Raccoon
A high performance offensive security tool for reconnaissance and vulnerability scanning
Stars: ✭ 2,312 (+4181.48%)
Mutual labels:  enumeration
Crosslinked
LinkedIn enumeration tool to extract valid employee names from an organization through search engine scraping
Stars: ✭ 223 (+312.96%)
Mutual labels:  enumeration
Asnlookup
Leverage ASN to look up IP addresses (IPv4 & IPv6) owned by a specific organization for reconnaissance purposes, then run port scanning on it.
Stars: ✭ 163 (+201.85%)
Mutual labels:  enumeration
Sudomy
Sudomy is a subdomain enumeration tool to collect subdomains and analyzing domains performing automated reconnaissance (recon) for bug hunting / pentesting
Stars: ✭ 1,572 (+2811.11%)
Mutual labels:  enumeration
reosploit
A Tool that Finds, Enumerates, and Exploits Reolink Cameras.
Stars: ✭ 89 (+64.81%)
Mutual labels:  enumeration
Bscan
an asynchronous target enumeration tool
Stars: ✭ 207 (+283.33%)
Mutual labels:  enumeration
Fdsploit
File Inclusion & Directory Traversal fuzzing, enumeration & exploitation tool.
Stars: ✭ 199 (+268.52%)
Mutual labels:  enumeration
Intrec Pack
Intelligence and Reconnaissance Package/Bundle installer.
Stars: ✭ 177 (+227.78%)
Mutual labels:  enumeration
Adcollector
A lightweight tool to quickly extract valuable information from the Active Directory environment for both attacking and defending.
Stars: ✭ 238 (+340.74%)
Mutual labels:  enumeration
Enumdb
Relational database brute force and post exploitation tool for MySQL and MSSQL
Stars: ✭ 167 (+209.26%)
Mutual labels:  enumeration
wordlists
Aggregated wordlist pulled from commonly used tools for discovery, enumeration, fuzzing, and exploitation.
Stars: ✭ 94 (+74.07%)
Mutual labels:  enumeration
Dirsearch
A Go implementation of dirsearch.
Stars: ✭ 164 (+203.7%)
Mutual labels:  enumeration
Phpenums
🔩 Provides enumerations for PHP & frameworks integrations
Stars: ✭ 194 (+259.26%)
Mutual labels:  enumeration
Activereign
A Network Enumeration and Attack Toolset for Windows Active Directory Environments.
Stars: ✭ 210 (+288.89%)
Mutual labels:  enumeration
findcdn
findCDN is a tool created to help accurately identify what CDN a domain is using.
Stars: ✭ 64 (+18.52%)
Mutual labels:  enumeration
enum-php
Enumeration implementation for PHP
Stars: ✭ 45 (-16.67%)
Mutual labels:  enumeration

PHP Enumeration classes

Build Status Coverage Status

Implementation of Enumeration Classes in PHP. The better alternative for Enums.

In contrast to existing solutions, this implementation avoids usage of Magic methods and Reflection to provide better performance and code autocompletion. The Enumeration class holds a reference to a single Enum element represented as an object (singleton) to provide the possiblity to use strict (===) comparision between the values. Also, it uses static properties that can utilize the power of Typed Properties. The Enumeration Classes are much closer to other language implementations like Java Enums and Python Enums.

Declaration

A basic way to declare a named Enumeration class:

<?php
use Dbalabka\Enumeration\Enumeration;

final class Action extends Enumeration
{
    public static $view;
    public static $edit;
}
Action::initialize();

Note! You should always call the Enumeration::initialize() method right after Enumeration Class declaration. To avoid manual initialization you can setup the StaticConstructorLoader provided in this library.

Declaration with Typed Properties support:

<?php
final class Day extends Enumeration
{
    public static Day $sunday;
    public static Day $monday;
    public static Day $tuesday;
    public static Day $wednesday;
    public static Day $thursday;
    public static Day $friday;
    public static Day $saturday; 
}
Day::initialize();

By default an enumeration class does not require the value to be provided. You can use the constructor to set any types of values.

  1. Flag enum implementation example:
    <?php
    final class Flag extends Enumeration
    {
        public static Flag $ok;
        public static Flag $notOk;
        public static Flag $unavailable;
    
        private int $flagValue;
    
        protected function __construct()
        {
            $this->flagValue = 1 << $this->ordinal();
        }
    
        public function getFlagValue() : int
        {
            return $this->flagValue;
        }
    }
  2. You should override initializeValues() method to set custom values for each Enum element.
    <?php
    
    final class Planet extends Enumeration
    {
        public static Planet $mercury;
        public static Planet $venus;
        public static Planet $earth;
        public static Planet $mars;
        public static Planet $jupiter;
        public static Planet $saturn;
        public static Planet $uranus;
        public static Planet $neptune;
    
        private float $mass;   // in kilograms
        private float $radius; // in meters
    
        // universal gravitational constant  (m3 kg-1 s-2)
        private const G = 6.67300E-11;
    
        protected function __construct(float $mass, float $radius)
        {
            $this->mass = $mass;
            $this->radius = $radius;
        }
        
        protected static function initializeValues() : void
        {
            self::$mercury = new self(3.303e+23, 2.4397e6);
            self::$venus   = new self(4.869e+24, 6.0518e6);
            self::$earth   = new self(5.976e+24, 6.37814e6);
            self::$mars    = new self(6.421e+23, 3.3972e6);
            self::$jupiter = new self(1.9e+27,   7.1492e7);
            self::$saturn  = new self(5.688e+26, 6.0268e7);
            self::$uranus  = new self(8.686e+25, 2.5559e7);
            self::$neptune = new self(1.024e+26, 2.4746e7);
        }
    
        public function surfaceGravity() : float 
        {
            return self::G * $this->mass / ($this->radius * $this->radius);
        }
    
        public function surfaceWeight(float $otherMass) {
            return $otherMass * $this->surfaceGravity();
        }
    }

Declaration rules that the developer should follow:

  1. The resulting Enumeration class should be marked as final. Abstract classes should be used to share functionality between multiple Enumeration classes.

    ...Allowing subclassing of enums that define members would lead to a violation of some important invariants of types and instances. On the other hand, it makes sense to allow sharing some common behavior between a group of enumerations... (from Python Enum documentation)

  2. Constructor should always be declared as non-public (private or protected) to avoid unwanted class instantiation.
  3. Implementation is based on assumption that all class static properties are elements of Enum.
  4. The method Dbalabka\Enumeration\Enumeration::initialize() should be called after each Enumeration class declaration. Please use the StaticConstructorLoader provided in this library to avoid boilerplate code.

Usage

Basic usage

<?php
use Dbalabka\Enumeration\Examples\Enum\Action;

$viewAction = Action::$view;

// it is possible to compare Enum elements
assert($viewAction === Action::$view);

// you can get Enum element by name 
$editAction = Action::valueOf('edit');
assert($editAction === Action::$edit);

// iterate over all Enum elements
foreach (Action::values() as $name => $action) {
    assert($action instanceof Action);
    assert($name === (string) $action);
    assert($name === $action->name());
}

Match expression

PHP 8 is going to support match expression which simplifies usage of enums:

<?php
use Dbalabka\Enumeration\Examples\Enum\Action;

$action = Action::$view;

echo match ($action) {
   Action::$view => 'View action',
   Action::$edit => 'Edit action',
}

More usage examples

Known issues

Readonly Properties

In the current implementation, static property value can be occasionally replaced. Readonly Properties is aimed to solve this issue. In an ideal world Enum values should be declared as a constants. Unfortunately, it is not possible in PHP right now.

<?php
// It is possible but don't do it
Action::$view = Action::$edit;
// Following isn't possible in PHP 7.4 with declared properties types
Action::$view = null;

Also, see most recent Write-Once Properties RFC that aimed to address this issue.

Class static initialization

This implementation relies on class static initialization which was proposed in Static Class Constructor. The RFC is still in Draft status but it describes possible workarounds. The simplest way is to call the initialization method right after the class declaration, but it requires the developer to keep this in mind. Thanks to Typed Properties we can control uninitialized properties - PHP will throw an error in case of access to an uninitialized property. It might be automated with custom autoloader Dbalabka\StaticConstructorLoader\StaticConstructorLoader provided in this library:

<?php 
use Dbalabka\StaticConstructorLoader\StaticConstructorLoader;

$composer = require_once(__DIR__ . '/vendor/autoload.php');
$loader = new StaticConstructorLoader($composer);

Also, it would be very helpful to have expression based properties initialization (see C# example):

class Enum {
    // this is not allowed
    public static $FOO = new Enum();
    public static $BAR = new Enum();
}

See examples/class_static_construct.php for example.

Serialization

There is no possibility to serialize the singleton. As a result, we have to restrict direct Enum object serialization.

<?php
// The following line will throw an exception
serialize(Action::$view);

New custom object serialization mechanism does not help with singleton serialization but it gives the possibility to control this in the class which holds the references to Enum instances. Also, it can be worked around with Serializable Interface in a similar way. For example, Java handles Enums serialization differently than other classes, but you can serialize it directly thanks to readResolve(). In PHP, we can't serialize Enums directly, but we can handle Enums serialization in class that holds the reference. We can serialize the name of the Enum constant and use valueOf() method to obtain the Enum constant value during unserialization. So this problem somewhat resolved the cost of a worse developer experience. Hope it will be solved in future RFCs.

class SomeClass
{
    public Action $action;

    public function __serialize()
    {
        return ['action' => $this->action->name()];
    }

    public function __unserialize($payload)
    {
        $this->action = Action::valueOf($payload['action']);
    }
}

See complete example in examples/serialization_php74.php.

Callable static properties syntax

Unfortunately, it is not easy to use callable that is stored in static property. There was a syntax change since PHP 7.0 which complicates the way to call callable.

// Instead of using syntax
Option::$some('1'); // this line will rise an error "Function name must be a string"
// you should use 
(Option::$some)('1');

It is the main disatvatige of static class properties.

It can be workarounded by magic calls using __callStatic but such option suffers from missing autosuggestion, negative performance impact and missing static analysis.

Option::some('1');

It would be helpful to have PHP built-in suppoort for late (in runtime) constants initialization or/and class constants initialization using simple expressions:

class Enum {
   // this is not allowed
   public const FOO = new Enum();
   public const BAR = new Enum();
}

Still, calling Enum::FOO() will try to find a method instead of trying to treat constant's value as a callable. We assume, that such PHP behavior can be improved.

Existing solutions

Libraries:

PHP native:

(there are a lot of other PHP implementations)

References

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].