Skip to content

Commit

Permalink
Add support for standalone true, false and null types
Browse files Browse the repository at this point in the history
Signed-off-by: Ion Bazan <ion.bazan@gmail.com>
  • Loading branch information
IonBazan committed Nov 2, 2022
1 parent 1bfd72d commit 764d869
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 11 deletions.
19 changes: 16 additions & 3 deletions src/Generator/TypeGenerator/AtomicType.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,16 @@ final class AtomicType
'mixed' => 10,
'void' => 11,
'false' => 12,
'null' => 13,
'never' => 14,
'true' => 13,
'null' => 14,
'never' => 15,
];

/** @psalm-var array<non-empty-string, null> */
private const NOT_NULLABLE_TYPES = [
'null' => null,
'false' => null,
'true' => null,
'void' => null,
'mixed' => null,
'never' => null,
Expand Down Expand Up @@ -151,6 +153,17 @@ public function assertCanUnionWith(array $others): void
$other->type
));
}

if (
('true' === $other->type && 'false' === $this->type) ||
('false' === $other->type && 'true' === $this->type)
) {
throw new InvalidArgumentException(sprintf(
'Type "%s" cannot be composed in a union with type "%s"',
$this->type,
$other->type
));
}
}

if (
Expand Down Expand Up @@ -222,6 +235,6 @@ public function assertCanBeStandaloneNullable(): void

private function requiresUnionWithStandaloneType(): bool
{
return 'null' === $this->type || 'false' === $this->type;
return false;
}
}
23 changes: 15 additions & 8 deletions test/Generator/TypeGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -186,14 +186,24 @@ public function validType()
['null|foo', '\\foo|null'],
['foo|bar|null', '\\bar|\\foo|null'],

// The `false` type can only be used in combination with other types
// Standalone `false` type
['false', 'false'],
['foo|false', '\\foo|false'],
['string|false', 'string|false'],
['string|false|null', 'string|false|null'],

// `false` + `null` requires a third type
['Foo|false|null', '\\Foo|false|null'],

// The `true` type
['foo|true', '\\foo|true'],
['string|true', 'string|true'],
['true', 'true'],
['true|null', 'true|null'],

// Standalone `null` type
['null', 'null'],

// The `static` type should not be turned into a FQCN
['static', 'static'],
['?static', '?static'],
Expand Down Expand Up @@ -398,14 +408,11 @@ public function invalidType()
['never&null'],
['never&Foo'],
['never&\\foo'],

// `false` and `null` must always be used as part of a union type
['null'],
['false'],
['?null'],
['?false'],
['false|null'],
['null|false'],

// `false` and `true` cannot be used together
['true|false'],
['false|true'],

// Duplicate types are rejected
['A|A'],
Expand Down

0 comments on commit 764d869

Please sign in to comment.