From 6e4fa6e4738d450451372f00bab2d39160957681 Mon Sep 17 00:00:00 2001 From: Jordan Brauer Date: Wed, 2 Oct 2019 16:09:35 -0500 Subject: [PATCH 1/2] add variant property as well as cache registry key for current instance --- src/UnitConverter/Unit/AbstractUnit.php | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/src/UnitConverter/Unit/AbstractUnit.php b/src/UnitConverter/Unit/AbstractUnit.php index 409a6fff..1bf5a310 100644 --- a/src/UnitConverter/Unit/AbstractUnit.php +++ b/src/UnitConverter/Unit/AbstractUnit.php @@ -69,14 +69,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 = []; $this->configure(); @@ -158,7 +174,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 From e81657d42579cffef2e53652465fe15278f38283 Mon Sep 17 00:00:00 2001 From: Jordan Brauer Date: Wed, 2 Oct 2019 16:10:07 -0500 Subject: [PATCH 2/2] throw some exceptions for when variants are present but no selection is given --- src/UnitConverter/Registry/UnitRegistry.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/UnitConverter/Registry/UnitRegistry.php b/src/UnitConverter/Registry/UnitRegistry.php index 16e0ab5a..023b134c 100644 --- a/src/UnitConverter/Registry/UnitRegistry.php +++ b/src/UnitConverter/Registry/UnitRegistry.php @@ -14,6 +14,7 @@ namespace UnitConverter\Registry; +use RuntimeException; use UnitConverter\Exception\BadMeasurement; use UnitConverter\Exception\BadRegistry; use UnitConverter\Measure; @@ -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; } }