Skip to content

Commit

Permalink
feature: introduce literal float methods to Union type
Browse files Browse the repository at this point in the history
- Added `Psalm\Type\Union#isSingleFloatLiteral`
- Added `Psalm\Type\Union#getSingleFloatLiteral`
- Added `Psalm\Type\Union#hasLiteralFloat`

Signed-off-by: Maximilian Bösing <2189546+boesing@users.noreply.github.com>
  • Loading branch information
boesing committed Aug 6, 2021
1 parent 457695e commit 9d59fbe
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/Psalm/Type/Union.php
Original file line number Diff line number Diff line change
Expand Up @@ -1489,4 +1489,31 @@ public function getChildNodes() : array
{
return $this->types;
}

/**
* @return bool true if this is a float literal with only one possible value
*/
public function isSingleFloatLiteral(): bool
{
return count($this->types) === 1 && count($this->literal_float_types) === 1;
}

/**
* @throws \InvalidArgumentException if isSingleFloatLiteral is false
*
* @return TLiteralFloat the only float literal represented by this union type
*/
public function getSingleFloatLiteral(): TLiteralFloat
{
if (count($this->types) !== 1 || count($this->literal_float_types) !== 1) {
throw new \InvalidArgumentException('Not a float literal');
}

return reset($this->literal_float_types);
}

public function hasLiteralFloat(): bool
{
return count($this->literal_float_types) > 0;
}
}
31 changes: 31 additions & 0 deletions tests/Type/UnionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);

namespace Psalm\Tests\Type;

use InvalidArgumentException;
use Psalm\Tests\TestCase;
use Psalm\Type\Atomic\TFloat;
use Psalm\Type\Atomic\TLiteralFloat;
use Psalm\Type\Union;

final class UnionTest extends TestCase
{

public function testWillDetectSingleLiteralFloat(): void
{
$literalFloat = new TLiteralFloat(1.0);
$union = new Union([$literalFloat]);

self::assertTrue($union->isSingleFloatLiteral());
self::assertTrue($union->hasLiteralFloat());
self::assertSame($literalFloat, $union->getSingleFloatLiteral());
}

public function testWillThrowInvalidArgumentExceptionWhenSingleFloatLiteralIsRequestedButNoneExists(): void
{
$this->expectException(InvalidArgumentException::class);
$union = new Union([new TFloat()]);
$union->getSingleFloatLiteral();
}
}

0 comments on commit 9d59fbe

Please sign in to comment.