Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

provide mechanism of using a particular variant (uk/us) of a unit of measure #145

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
5 changes: 5 additions & 0 deletions src/Registry/UnitRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

namespace UnitConverter\Registry;

use RuntimeException;
use UnitConverter\Exception\BadMeasurement;
use UnitConverter\Exception\BadRegistry;
use UnitConverter\Measure;
Expand Down Expand Up @@ -64,6 +65,10 @@ public function isUnitRegistered(string $symbol): bool
{
foreach ($this->store as $measurement => $units) {
if (array_key_exists($symbol, $units)) {
if (is_array($units[$symbol])) {
throw new RuntimeException(sprintf('Encountered unit "%s" with variants: %s; but have no way to select one', $symbol, implode(', ', array_keys($units[$symbol]))));
}

return true;
}
}
Expand Down
25 changes: 23 additions & 2 deletions src/Unit/AbstractUnit.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,30 @@ abstract class AbstractUnit implements UnitInterface
*/
protected $value;

/**
* The variant (or "flavour") of the current unit instance. This determines
* it's amount of units and is meant to be used for
*
* @var string
*/
protected $variant;

/**
* A cached version of the unit instance's registry key.
*
* @var string
*/
private $cachedRegistryKey;

/**
* Public constructor function for units of measurement.
*
* @param int|float|string $value The amount of units to be reprsented by the final object as.
*/
public function __construct($value = 1)
public function __construct($value = 1, ?string $variant = null)
{
$this->value = $value;
$this->variant = $variant;
$this->formulae = [
self::RESERVED_FORMULA => UnitConversionFormula::class,
];
Expand Down Expand Up @@ -175,7 +191,12 @@ public function getName(): ?string

public function getRegistryKey(): ?string
{
return $this->unitOf.'.'.$this->symbol;
return $this->cachedRegistryKey
?? $this->cachedRegistryKey = implode('.', array_filter([
$this->unitOf,
$this->symbol,
$this->variant,
]));
}

public function getScientificSymbol(): ?string
Expand Down