Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added new type-safe API that allows validating a given value against a given class-string<Enum> #143

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@
"require-dev": {
"phpunit/phpunit": "^9.5",
"squizlabs/php_codesniffer": "1.*",
"vimeo/psalm": "^4.6.2"
"vimeo/psalm": "4.6.2"
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pinned: changing this dependency is too fragile for builds to be kept stable.

My suggestion is to instead use dependabot to regularly keep it updated.

}
}
5 changes: 5 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,9 @@
<directory suffix=".php">./tests</directory>
</testsuite>
</testsuites>
<coverage>
<include>
<directory>src</directory>
</include>
</coverage>
</phpunit>
7 changes: 3 additions & 4 deletions psalm.xml
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
<?xml version="1.0"?>
<psalm
totallyTyped="true"
resolveFromConfigFile="true"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
restrictReturnTypes="true"
findUnusedPsalmSuppress="true"
totallyTyped="true"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Psalm docs say this is deprecated, might be dropped as level is max already

https://psalm.dev/docs/running_psalm/configuration/#totallytyped

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WithtotallyTyped="true" the default level is 1, but without totallyTyped it would be 2: https://github.com/vimeo/psalm/pull/5340/files
So I think we should replace totallyTyped="true" with errorLevel="1".

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree, it's a bit out of scope but has been touched already so 🤷🏾

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I generally remove errorLevel wherever I go: it's just confusing.

>
<projectFiles>
<directory name="src" />
Expand All @@ -16,8 +17,6 @@
</projectFiles>

<issueHandlers>
<MixedAssignment errorLevel="info" />

<ImpureStaticProperty>
<!-- self::$... usages in Enum are used to populate an internal cache, and cause no side-effects -->
<errorLevel type="suppress">
Expand Down
40 changes: 34 additions & 6 deletions src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,10 @@ public function __wakeup()
}

/**
* @psalm-pure
* @param mixed $value
* @return static
* @psalm-return static<T>
* @psalm-return static
*/
public static function from($value): self
{
Expand Down Expand Up @@ -127,7 +128,6 @@ public function getKey()

/**
* @psalm-pure
* @psalm-suppress InvalidCast
* @return string
*/
public function __toString()
Expand Down Expand Up @@ -187,7 +187,6 @@ public static function values()
* Returns all possible values as an array
*
* @psalm-pure
* @psalm-suppress ImpureStaticProperty
*
* @psalm-return array<string, mixed>
* @return array Constant name in key, constant value in value
Expand All @@ -212,8 +211,9 @@ public static function toArray()
* @param $value
* @psalm-param mixed $value
* @psalm-pure
* @psalm-assert-if-true T $value
* @return bool
*
* deprecated use {@see Enum::isValidEnumValue()} instead
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not yet @deprecated - should I mark it as such, or should I drop the comment and leave it be?

*/
public static function isValid($value)
{
Expand All @@ -224,8 +224,23 @@ public static function isValid($value)
* Asserts valid enum value
*
* @psalm-pure
* @psalm-assert T $value
* @psalm-template CheckedValueType
* @psalm-param class-string<self<CheckedValueType>> $enumType
* @param mixed $value
* @psalm-assert-if-true CheckedValueType $value
*/
public static function isValidEnumValue(string $enumType, $value): bool
{
return $enumType::isValid($value);
}

/**
* Asserts valid enum value
*
* @psalm-pure
* @param mixed $value
*
* deprecated use {@see Enum::assertValidEnumValue()} instead
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not yet @deprecated - should I mark it as such, or should I drop the comment and leave it be?

*/
public static function assertValidValue($value): void
{
Expand All @@ -236,7 +251,20 @@ public static function assertValidValue($value): void
* Asserts valid enum value
*
* @psalm-pure
* @psalm-assert T $value
* @psalm-template ValueType
* @psalm-param class-string<self<ValueType>> $enumType
* @param mixed $value
* @psalm-assert ValueType $value
*/
public static function assertValidEnumValue(string $enumType, $value): void
{
$enumType::assertValidValue($value);
}

/**
* Asserts valid enum value
*
* @psalm-pure
* @param mixed $value
* @return string
*/
Expand Down
48 changes: 48 additions & 0 deletions static-analysis/EnumInstantiation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

declare(strict_types=1);

namespace MyCLabs\Tests\Enum\StaticAnalysis;

use MyCLabs\Enum\Enum;

/**
* @psalm-immutable
* @psalm-template T of 'A'|'C'
* @template-extends Enum<T>
*/
final class InstantiatedEnum extends Enum
{
const A = 'A';
const C = 'C';
}

/**
* @psalm-pure
* @psalm-return InstantiatedEnum<'A'>
*/
function canCallConstructorWithConstantValue(): InstantiatedEnum
{
return new InstantiatedEnum('A');
}

/**
* @psalm-pure
* @psalm-return InstantiatedEnum<'C'>
*/
function canCallConstructorWithConstantReference(): InstantiatedEnum
{
return new InstantiatedEnum(InstantiatedEnum::C);
}

/** @psalm-pure */
function canCallFromWithKnownValue(): InstantiatedEnum
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Notice how we CANNOT infer InstantiatedEnum<'C'> from this signature: this is a known problem with Enum::from() (static method), as I've described in the patch overview.

{
return InstantiatedEnum::from('C');
}

/** @psalm-pure */
function canCallFromWithUnknownValue(): InstantiatedEnum
{
return InstantiatedEnum::from(123123);
}
2 changes: 1 addition & 1 deletion static-analysis/EnumIsPure.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
* @method static PureEnum C()
*
* @psalm-immutable
* @psalm-template T of 'A'|'B'
* @psalm-template T of 'A'|'C'
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was a bug with this file - otherwise all good.

* @template-extends Enum<T>
*/
final class PureEnum extends Enum
Expand Down
83 changes: 83 additions & 0 deletions static-analysis/EnumValidation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

declare(strict_types=1);

namespace MyCLabs\Tests\Enum\StaticAnalysis;

use MyCLabs\Enum\Enum;

/**
* @psalm-immutable
* @psalm-template T of 'A'|'C'
* @template-extends Enum<T>
*/
final class ValidationEnum extends Enum
{
const A = 'A';
const C = 'C';
}

/**
* @psalm-pure
* @param mixed $input
* @psalm-return 'A'|'C'
*
* @psalm-suppress MixedReturnStatement
* @psalm-suppress MixedInferredReturnType at the time of this writing, we did not yet find
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment is kinda oudated - perhaps I can drop the static analysis check overall, now that I designed Enum::assertValidEnumValue() 🤔

* a proper approach to constraint input values through
* validation via static methods.
*/
function canValidateValue($input): string
{
ValidationEnum::assertValidValue($input);

return $input;
}

/**
* @psalm-pure
* @param mixed $input
* @psalm-return 'A'|'C'
*/
function canAssertValidEnumValue($input): string
{
ValidationEnum::assertValidEnumValue(ValidationEnum::class, $input);

return $input;
}

/**
* @psalm-pure
* @param mixed $input
* @psalm-return 'A'|'C'
*
* @psalm-suppress MixedReturnStatement
* @psalm-suppress MixedInferredReturnType at the time of this writing, we did not yet find
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment is kinda oudated - perhaps I can drop the static analysis check overall, now that I designed Enum::isValidEnumValue() 🤔

* a proper approach to constraint input values through
* validation via static methods.
*/
function canValidateValueThroughIsValid($input): string
{
if (! ValidationEnum::isValid($input)) {
throw new \InvalidArgumentException('Value not valid');
}

return $input;
}

/**
* @psalm-pure
* @param mixed $input
* @psalm-return 'A'|'C'|1
*
* @psalm-suppress InvalidReturnType https://github.com/vimeo/psalm/issues/5372
* @psalm-suppress InvalidReturnStatement https://github.com/vimeo/psalm/issues/5372
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

vimeo/psalm#5372 is still kinda blocking this

*/
function canValidateValueThroughIsValidEnumValue($input)
{
if (! ValidationEnum::isValidEnumValue(ValidationEnum::class, $input)) {
return 1;
}

return $input;
}
46 changes: 45 additions & 1 deletion tests/EnumTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

namespace MyCLabs\Tests\Enum;

use MyCLabs\Enum\Enum;

/**
* @author Matthieu Napoli <matthieu@mnapoli.fr>
* @author Daniel Costa <danielcosta@gmail.com>
Expand Down Expand Up @@ -59,6 +61,27 @@ public function testFailToCreateEnumWithInvalidValueThroughNamedConstructor($val
EnumFixture::from($value);
}

/**
* @dataProvider invalidValueProvider
* @param mixed $value
*/
public function testRejectInvalidEnumValueWhenAssertingOnIt($value): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessage('is not part of the enum MyCLabs\Tests\Enum\EnumFixture');

Enum::assertValidEnumValue(EnumFixture::class, $value);
}

/**
* @dataProvider invalidValueProvider
* @param mixed $value
*/
public function testReportsFalseOnNonValidEnumValueUponChecking($value): void
{
self::assertFalse(Enum::isValidEnumValue(EnumFixture::class, $value));
}

public function testFailToCreateEnumWithEnumItselfThroughNamedConstructor(): void
{
$this->expectException(\UnexpectedValueException::class);
Expand All @@ -67,6 +90,11 @@ public function testFailToCreateEnumWithEnumItselfThroughNamedConstructor(): voi
EnumFixture::from(EnumFixture::FOO());
}

public function testCreateEnumWithValidEnumValueThroughNamedConstructor(): void
{
self::assertEquals(EnumFixture::FOO(), EnumFixture::from('foo'));
}

/**
* Contains values not existing in EnumFixture
* @return array
Expand Down Expand Up @@ -179,7 +207,8 @@ public function testBadStaticAccess()
*/
public function testIsValid($value, $isValid)
{
$this->assertSame($isValid, EnumFixture::isValid($value));
self::assertSame($isValid, EnumFixture::isValid($value));
self::assertSame($isValid, Enum::isValidEnumValue(EnumFixture::class, $value));
}

public function isValidProvider()
Expand Down Expand Up @@ -381,4 +410,19 @@ public function testAssertValidValue($value, $isValid): void

self::assertTrue(EnumFixture::isValid($value));
}

/**
* @dataProvider isValidProvider
*/
public function testAssertValidValueWithTypedApi($value, $isValid): void
{
if (!$isValid) {
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessage("Value '$value' is not part of the enum " . EnumFixture::class);
}

Enum::assertValidEnumValue(EnumFixture::class, $value);

self::assertTrue(Enum::isValidEnumValue(EnumFixture::class, $value));
}
}