diff --git a/src/Helper/Normalizer.php b/src/Helper/Normalizer.php new file mode 100644 index 0000000..043c8b0 --- /dev/null +++ b/src/Helper/Normalizer.php @@ -0,0 +1,68 @@ +$p) + $this->setPart($k, $p); + } + + /** + * Set the percentage of a component. + * + * @param mixed The key used to access this part later + * @param float The percent of this part + */ + public function setPart($key, float $percent) + { + $this->inputs[$key] = $percent; + $total = array_sum(array_values($this->inputs)); + $this->ratio = 100 / $total; + } + + /** + * Get the original percentage of the key. + * + * @param mixed The key + * @return float Original percentage as provided + */ + public function getPercent($key) + { + if (!array_key_exists($key, $this->inputs)) + throw new \Exception(); + + return floatval($this->inputs[$key]); + } + + /** + * Get the normalized percentage where the added total equals 100% + * + * @param mixed The key + * @return float Normalized percentage as provided + */ + public function getNormalizedPercent($key) + { + if (!array_key_exists($key, $this->inputs)) + throw new \Exception(); + + return floatval($this->inputs[$key]) * $this->ratio; + } + +} diff --git a/tests/Helper/NormalizerTest.php b/tests/Helper/NormalizerTest.php new file mode 100644 index 0000000..cfe6df0 --- /dev/null +++ b/tests/Helper/NormalizerTest.php @@ -0,0 +1,37 @@ + 10 + ]); + + $this->assertEquals(10, $normalizer->getPercent("A")); + $this->assertEquals(100, $normalizer->getNormalizedPercent("A")); + + $normalizer = new Normalizer([ + 'A' => 10, + 'B' => 10, + ]); + + $this->assertEquals(10, $normalizer->getPercent("A")); + $this->assertEquals(50, $normalizer->getNormalizedPercent("A")); + $this->assertEquals(10, $normalizer->getPercent("B")); + $this->assertEquals(50, $normalizer->getNormalizedPercent("B")); + + $normalizer = new Normalizer([ + 'A' => 2, + 'B' => 8, + ]); + + $this->assertEquals(20, $normalizer->getNormalizedPercent("A")); + $this->assertEquals(80, $normalizer->getNormalizedPercent("B")); + + } +}