mle86/value

A base class for immutable single-value-wrapper classes

v2.2.2 2021-12-21 08:58 UTC

This package is auto-updated.

Last update: 2024-04-21 13:49:18 UTC


README

Build Status Coverage Status Latest Stable Version PHP 7.0 License

This PHP library provides a simple base class for Immutable Value Objects. Those are objects which wrap exactly one value, cannot be changed in any way, have no additional state, and carry some validation logic in the constructor.

It is released under the MIT License.

Simple use case:

class OddNumber extends \mle86\Value\AbstractValue
{

    // The base class requires this boolean test method:
    public static function isValid($input): bool
    {
        return (is_int($input) && ($input % 2) === 1);
    }

    // Nothing else is needed.
}

function myFunction(OddNumber $oddArgument)
{
    /* No further validation of $oddArgument is necessary in this function,
     * it's guaranteed to contain an odd number. */
    print "Got an odd number here: " . $oddArgument->value();
}

$odd1 = new OddNumber(61);       // works as expected, $odd1->value() will return 61
$odd2 = new OddNumber(40);       // throws an InvalidArgumentException
$odd3 = new OddNumber("string"); // throws an InvalidArgumentException
$odd4 = new OddNumber(null);     // throws an InvalidArgumentException

$odd5   = OddNumber::optional(33);   // works as expected, $odd5->value() will return 33
$nonodd = OddNumber::optional(null); // $nonodd is now null
$odd6   = OddNumber::optional(40);   // throws an InvalidArgumentException

Installation:

Via Composer: composer require mle86/value

Or insert this into your project's composer.json file:

"require": {
    "mle86/value": "^2"
}

Minimum PHP version:

PHP 7.0

Classes and interfaces:

  1. Value (interface)
  2. AbstractValue (abstract class)
  3. AbstractSerializableValue (abstract class)
  4. InvalidArgumentException (exception)
  5. NotImplementedException (exception)

Value

This interface specifies that all Value classes should have

  • a constructor which takes exactly one argument,
  • a value() method without arguments.

AbstractValue

This immutable class wraps a single value per instance. The constructor enforces validity checks on the input value. Therefore, every class instance's wrapped value can be considered valid.

The validity checks are located in the isValid class method which all subclasses must implement. It is a class method to allow validity checks of external values without wrapping them in an instance.

  • public function __construct($rawValue)

    The constructor uses the isValid class method to test its input argument. Valid values are stored in the new instance, invalid values cause an InvalidArgumentException to be thrown. Other instances of the same class are always considered valid (re-wrapping).

  • public static function optional($rawValue): ?static

    Same as the default constructor, but also accepts null values (which will be returned unchanged).

  • abstract public static function isValid($testValue): bool

    Checks the validity of a raw value. If it returns true, a new object can be instantiated with that value. Implement this in every subclass!

  • final public function value(): mixed

    Returns the object's wrapped initializer value.

  • final public function equals($testValue): bool

    Equality test. This method performs an equality check on other instances or raw values. Objects are considered equal if and only if they are instances of the same subclass and carry the same value(). All other values are considered equal if and only if they are identical (===) to the current objects's value().

  • final public static function wrap(&$value)

    Replaces a value (by-reference) with instance wrapping that value. This means of course that the call will fail with an InvalidArgumentException if the input value fails the subclass' isValid check. If the value already is an instance, it won't be replaced.

  • final public static function wrapOptional(&$value)

    Like wrap(), but won't change null values.

  • final public static function wrapArray(array &$array): array

    Will replace all values in an array with instances. The array will only be altered (by-reference) if all its values are valid. Array keys will be preserved.

  • final public static function wrapOptionalsArray(array &$array): array

    Will replace all non-null values in an array with instances. The array will only be changed (by-reference) if all its values are valid (or null). Array keys will be preserved.

AbstractSerializableValue

This extension of AbstractValue provides easy serializability for the Value objects. It implements the JsonSerializable interface.

Standard PHP serialization via serialize/unserialize is always supported. This class contains an extra __wakeup() implementation to make sure that unserialized instances always contain a valid value.

  • public function __toString(): string

    Returns the wrapped value like value(), but with an explicit string typecast. This allows string concatenation of Value objects.

  • public function jsonSerialize(): mixed

    Returns the wrapped value – like value(). This enables json_encode() to encode the object.

InvalidArgumentException

An empty extension of PHP's InvalidArgumentException.