Skip to content

Commit f69886f

Browse files
kukulichondrejmirtes
authored andcommitted
It's not possible to instantiate enum
1 parent 0f2fbff commit f69886f

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

src/Rules/Classes/InstantiationRule.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,14 @@ private function checkClassName(string $class, bool $isName, Node $node, Scope $
137137
$classReflection = $this->reflectionProvider->getClass($class);
138138
}
139139

140+
if ($classReflection->isEnum() && $isName) {
141+
return [
142+
RuleErrorBuilder::message(
143+
sprintf('Cannot instantiate enum %s.', $classReflection->getDisplayName())
144+
)->build(),
145+
];
146+
}
147+
140148
if (!$isStatic && $classReflection->isInterface() && $isName) {
141149
return [
142150
RuleErrorBuilder::message(

tests/PHPStan/Rules/Classes/InstantiationRuleTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,4 +361,26 @@ public function testFirstClassCallable(): void
361361
$this->analyse([__DIR__ . '/data/first-class-instantiation-callable.php'], []);
362362
}
363363

364+
public function testEnumInstantiation(): void
365+
{
366+
if (PHP_VERSION_ID < 80100) {
367+
$this->markTestSkipped('Test requires PHP 8.1.');
368+
}
369+
370+
$this->analyse([__DIR__ . '/data/enum-instantiation.php'], [
371+
[
372+
'Cannot instantiate enum EnumInstantiation\Foo.',
373+
9,
374+
],
375+
[
376+
'Cannot instantiate enum EnumInstantiation\Foo.',
377+
14,
378+
],
379+
[
380+
'Cannot instantiate enum EnumInstantiation\Foo.',
381+
21,
382+
],
383+
]);
384+
}
385+
364386
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php // lint >= 8.1
2+
3+
namespace EnumInstantiation;
4+
5+
enum Foo
6+
{
7+
public function createSelf()
8+
{
9+
return new self();
10+
}
11+
12+
public function createStatic()
13+
{
14+
return new static();
15+
}
16+
}
17+
18+
class Boo
19+
{
20+
public static function createFoo() {
21+
return new Foo();
22+
}
23+
}

0 commit comments

Comments
 (0)