Skip to content

Commit 1e7c3b0

Browse files
Christian Bläulmglaman
authored andcommitted
Entities: Allow FieldItemList access through magic __get/__set methods
PHPStan said "Access to an undefined property". A custom entity may define fields in ::baseFieldDefinitions(). Other ways to define a field are though hook implementations like hook_entity_base_field_info(), or through config entites created from the Drupal admin UI. Thus, it seems very hard to track all cases in PHPStan. While ContentEntityBase::__get() will return a FieldItemListInterface, ContentEntityBase::__set may be used to set fields directly, thus I decided to tell PHPStan that the type is mixed. For example, the following code can be valid: ````php $entity = SomeCustomEntity(); $entity->some_int_field = 34; $entity->save(); ````
1 parent 306a034 commit 1e7c3b0

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

extension.neon

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,6 @@ services:
3535
-
3636
class: PHPStan\Type\ServiceDynamicReturnTypeExtension
3737
tags: [phpstan.broker.dynamicMethodReturnTypeExtension]
38+
-
39+
class: PHPStan\Reflection\EntityFieldsViaMagic
40+
tags: [phpstan.broker.propertiesClassReflectionExtension]
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<?php
2+
3+
namespace PHPStan\Reflection;
4+
5+
use Drupal\Core\Entity\ContentEntityBase;
6+
use PHPStan\Type\MixedType;
7+
8+
/**
9+
* Allows field access via magic methods
10+
*
11+
* See \Drupal\Core\Entity\ContentEntityBase::__get and ::__set.
12+
*/
13+
class EntityFieldsViaMagic implements PropertiesClassReflectionExtension {
14+
15+
public function hasProperty(ClassReflection $classReflection, string $propertyName): bool {
16+
return $classReflection->isSubclassOf(ContentEntityBase::class) &&
17+
!$classReflection->hasNativeProperty($propertyName);
18+
}
19+
20+
public function getProperty(ClassReflection $classReflection, string $propertyName): PropertyReflection {
21+
return new class implements PropertyReflection {
22+
23+
public function getType(): \PHPStan\Type\Type {
24+
return new MixedType();
25+
}
26+
27+
public function getDeclaringClass(): ClassReflection {
28+
return $classReflection;
29+
}
30+
31+
public function isStatic(): bool {
32+
return FALSE;
33+
}
34+
35+
public function isPrivate(): bool {
36+
return FALSE;
37+
}
38+
39+
public function isPublic(): bool {
40+
return TRUE;
41+
}
42+
43+
public function isReadable(): bool {
44+
return TRUE;
45+
}
46+
47+
public function isWritable(): bool {
48+
return TRUE;
49+
}
50+
51+
};
52+
}
53+
}

0 commit comments

Comments
 (0)