Skip to content

Added Enum stubs to make method purity precise #4079

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

Draft
wants to merge 1 commit into
base: 2.1.x
Choose a base branch
from
Draft
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
9 changes: 7 additions & 2 deletions src/PhpDoc/ReflectionEnumStubFilesExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,16 @@ public function getFiles(): array
return [];
}

$files = [
__DIR__ . '/../../stubs/UnitEnum.stub',
__DIR__ . '/../../stubs/BackedEnum.stub',
];

if (!$this->phpVersion->supportsLazyObjects()) {
return [__DIR__ . '/../../stubs/ReflectionEnum.stub'];
return [__DIR__ . '/../../stubs/ReflectionEnum.stub', ...$files];
}

return [__DIR__ . '/../../stubs/ReflectionEnumWithLazyObjects.stub'];
return [__DIR__ . '/../../stubs/ReflectionEnumWithLazyObjects.stub', ...$files];
}

}
14 changes: 14 additions & 0 deletions stubs/BackedEnum.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

interface BackedEnum extends UnitEnum
{
/**
* @pure
*/
public static function from(int|string $value): static;

/**
* @pure
*/
public static function tryFrom(int|string $value): ?static;
}
10 changes: 10 additions & 0 deletions stubs/UnitEnum.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

interface UnitEnum
{
/**
* @return list<static>
* @pure
*/
public static function cases(): array;
}
6 changes: 6 additions & 0 deletions tests/PHPStan/Rules/Pure/PureFunctionRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -174,4 +174,10 @@ public function testBug12224(): void
]);
}

#[RequiresPhp('>= 8.1')]
public function testBug13201(): void
{
$this->analyse([__DIR__ . '/data/bug-13201.php'], []);
}

}
19 changes: 19 additions & 0 deletions tests/PHPStan/Rules/Pure/data/bug-13201.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php // lint >= 8.1

namespace PHPStan\Rules\Pure\data\Bug13201;

enum Foo: string
{

case Bar = 'bar';
case Unknown = 'unknown';

}

/**
* @pure
*/
function createWithFallback(string $type): Foo
{
return Foo::tryFrom($type) ?? Foo::Unknown;
}
Loading