chuk-shirley
4/16/2015 - 4:04 PM

ValueObjects

ValueObjects

<?php
use Sabel\AbstractValue;
use Sabel\AbstractValueInterface;

class PriceValue extends AbstractValue implements AbstractValueInterface
{
    const MINIMUM_ALLOWED = 0;
    const MAXIMUM_ALLOWED = 99999.9999;

    public static function fromString($string)
    {
        $price = new PriceValue;
        $price->setValue($string)->filter()->validate();

        return $price;
    }

    protected function filter()
    {
        return $this;
    }

    protected function validate()
    {
        if ($this->value < self::MINIMUM_ALLOWED || $this->value > self::MAXIMUM_ALLOWED)
        {
            throw new \InvalidArgumentException("Price must be between 0 and 99999.9999");
        }

        return $this;
    }

    protected function setValue($value)
    {
        $this->value = (float) $value;

        return $this;
    }
}
<?php
interface AbstractValueInterface
{
    public function getValue();
}
<?php

abstract class AbstractValue
{
    protected $value;

    private function __construct(){}

    protected function filter()
    {
        $this->setValue(trim($this->value));

        return $this;
    }

    public function getValue()
    {
        return $this->value;
    }

}