Skip to content

Commit

Permalink
Feat: convert() method to expose calculate() - allows for complex calcs
Browse files Browse the repository at this point in the history
  • Loading branch information
jordanbrauer committed Oct 11, 2017
1 parent 08d9a81 commit 0be9e8e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
26 changes: 22 additions & 4 deletions src/UnitConverter/Unit/AbstractUnit.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,27 @@ protected function configure () : void
/**
* Calculate the amount of required base units to make up 1 unit.
*
* @param mixed $value Unused. Supposed to help determine conversion if using calculate.
* @param float $value
* @param UnitInterface $to
* @return null|float
*/
protected function calculate ($value) : ?float
protected function calculate (float $value, UnitInterface $to) : ?float
{
return null;
}

/**
* Exposes access to the ::calculate() method.
*
* @param float $value
* @param UnitInterface $to
* @return null|float
*/
public function convert (float $value, UnitInterface $to)
{
return $this->calculate($value, $to);
}

public function setName (string $name) : UnitInterface
{
$this->name = $name;
Expand Down Expand Up @@ -125,8 +138,13 @@ public function setUnits (float $units) : UnitInterface
return $this;
}

public function getUnits ($value = null) : float
public function getUnits () : float
{
return $this->units;
}

public function getBaseUnits () : float
{
return $this->calculate($value) ?? $this->units;
return $this->getBase()->getUnits();
}
}
10 changes: 10 additions & 0 deletions src/UnitConverter/UnitConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ protected function loadUnit(string $symbol) : UnitInterface
/**
* Calculate the conversion from one unit to another.
*
* @FIXME Gross use of a check for a null calculate() method ... 😑 Gotta
* figure out a better way to use the calulate method.
*
* @internal
* @param float $value The initial value being converted.
* @param UnitInterface $from The unit of measure being converted **from**.
Expand All @@ -100,6 +103,12 @@ protected function loadUnit(string $symbol) : UnitInterface
*/
protected function calculate (float $value, UnitInterface $from, UnitInterface $to): float
{
$selfConversion = $from->convert($value, $to);

if ($selfConversion)
return $selfConversion;

# If the unit does not implement the calculate() method, convert it manually.
return ($value * $from->getUnits()) / $to->getUnits();
}

Expand All @@ -125,6 +134,7 @@ public function from (string $unit)
public function to (string $unit)
{
$this->to = $this->loadUnit($unit);

return $this->calculate($this->convert, $this->from, $this->to);
}
}

0 comments on commit 0be9e8e

Please sign in to comment.