|
@@ -8,7 +8,7 @@ namespace App\Yr\Forecast\Tabular\Time;
|
|
|
abstract class AbstractUnit implements DiffInterface {
|
|
|
const DEFAULT_VARIANCE = 2;
|
|
|
|
|
|
- private $value;
|
|
|
+ private $value = 0;
|
|
|
private $unit;
|
|
|
|
|
|
/**
|
|
@@ -20,6 +20,69 @@ abstract class AbstractUnit implements DiffInterface {
|
|
|
$this->unit = $unit;
|
|
|
}
|
|
|
|
|
|
+ private function canOperate(AbstractUnit $with, bool $throw = false): bool {
|
|
|
+ if ($with instanceof $this || $with instanceof CustomUnit)
|
|
|
+ return true;
|
|
|
+
|
|
|
+ if ($this instanceof CustomUnit && $with instanceof AbstractUnit)
|
|
|
+ return true;
|
|
|
+
|
|
|
+ if ($throw)
|
|
|
+ throw new \InvalidArgumentException(sprintf(
|
|
|
+ "Invalid type <%s>, expected of type \"%s\" or \"%s\"",
|
|
|
+ get_class($with), get_class($this), CustomUnit::class
|
|
|
+ ));
|
|
|
+
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
+ protected function transformClass(CustomUnit $cu): self {
|
|
|
+ return unserialize(preg_replace(
|
|
|
+ '/^O:\d+:"[^"]++"/',
|
|
|
+ sprintf('O:%d:"%s"', strlen(static::class), static::class),
|
|
|
+ serialize($cu)
|
|
|
+ ));
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * Addition method
|
|
|
+ *
|
|
|
+ * @param AbstractUnit $with Unit to add with
|
|
|
+ * @thows \InvalidArgumentException
|
|
|
+ * */
|
|
|
+ public function add(AbstractUnit $with): self {
|
|
|
+ $this->canOperate($with, true);
|
|
|
+ return $this->transformClass(
|
|
|
+ new CustomUnit($this->getValue() + $with->getValue(), $with->getUnit())
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * Multiplication method
|
|
|
+ *
|
|
|
+ * @param AbstractUnit $with Unit to multiply with
|
|
|
+ * @thows \InvalidArgumentException
|
|
|
+ * */
|
|
|
+ public function mul(AbstractUnit $with): self {
|
|
|
+ $this->canOperate($with, true);
|
|
|
+ return $this->transformClass(
|
|
|
+ new CustomUnit($this->getValue() * $with->getValue(), $with->getUnit())
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * Divide method
|
|
|
+ *
|
|
|
+ * @param AbstractUnit $with Unit to divide with
|
|
|
+ * @thows \InvalidArgumentException
|
|
|
+ * */
|
|
|
+ public function div(AbstractUnit $with): self {
|
|
|
+ $this->canOperate($with, true);
|
|
|
+ return $this->transformClass(
|
|
|
+ new CustomUnit($this->getValue() / $with->getValue(), $with->getUnit())
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* Get the value
|
|
|
*
|