Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/FactorUnitPart.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,12 @@ public function format(): string
{
return "{$this->getRatio()}";
}

#[\Override]
public function invert(): self
{
// A FactorUnitPart always has power = 1. So when inverting it,
// we calculate the reciprocal of the ratio instead of negating the power.
return new self(1 / $this->getRatio());
}
}
12 changes: 12 additions & 0 deletions tests/FactorUnitPartTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,16 @@ public function test_stringifies()
{
$this->assertEquals('100', (string)new FactorUnitPart(100));
}

public function test_inverts()
{
$factor = new FactorUnitPart(100);

$factorInverted = $factor->invert();

$this->assertEquals(FactorUnitPart::class, get_class($factorInverted));
$this->assertNull($factorInverted->getDimension());
$this->assertEquals(0.01, $factorInverted->getRatio());
$this->assertEquals(1, $factorInverted->getPower());
}
}
46 changes: 46 additions & 0 deletions tests/UnitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,4 +171,50 @@ public function test_divide()

$this->assertEquals($ms->getDimensions(), $meterDividedBySeconds->getDimensions());
}

public function test_invert()
{
$hundredSquareMeters = new Unit(
new FactorUnitPart(100),
new UnitPart(1, Dimension::LENGTH, 2),
);

$inverted = $hundredSquareMeters->invert();

$this->assertEquals(-2, $inverted->getDimensions()[Dimension::LENGTH->name]);
$this->assertEquals(0.01, $inverted->getRatio());
}

public function test_invert_twice()
{
$hundredSquareMeters = new Unit(
new FactorUnitPart(100),
new UnitPart(1, Dimension::LENGTH, 2),
);

$invertedTwice = $hundredSquareMeters->invert()->invert();

$this->assertEquals($invertedTwice->getRatio(), $hundredSquareMeters->getRatio());
$this->assertEquals($invertedTwice->getDimensions(), $hundredSquareMeters->getDimensions());
Comment on lines +197 to +198
}

public function test_unit_and_factor_mix()
{
// 100m^2
$hundredSquareMeters = new Unit(
new FactorUnitPart(100),
new UnitPart(1, Dimension::LENGTH, 2),
);

// (10m)^2
$tenMetersSquared = new Unit(
new UnitPart(10, Dimension::LENGTH, 2),
);

$this->assertEquals($hundredSquareMeters->getRatio(), $tenMetersSquared->getRatio());
$this->assertEquals($hundredSquareMeters->getDimensions(), $tenMetersSquared->getDimensions());

$this->assertEquals($hundredSquareMeters->invert()->getRatio(), $tenMetersSquared->invert()->getRatio());
$this->assertEquals($hundredSquareMeters->invert()->getDimensions(), $tenMetersSquared->invert()->getDimensions());
}
}
Loading