Skip to content

Commit 997e693

Browse files
mfnbrendt
authored andcommitted
Add extension for PHPStan to support checkUninitializedProperties
1 parent 999efd6 commit 997e693

File tree

4 files changed

+49
-0
lines changed

4 files changed

+49
-0
lines changed

CHANGELOG.md

+3
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
All notable changes to `data-transfer-object` will be documented in this file
44

5+
## Unreleased
6+
- Add PHPStan extension to support `checkUninitializedProperties: true`
7+
58
## 2.2.1 - 2020-05-13
69

710
- Validator for typed 7.4 properties (#109)

README.md

+16
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,22 @@ $dto = new PostData([
422422
$dto->toArray(); // ['content' => 'blah blah']
423423
```
424424

425+
### PHPStan
426+
427+
If you're using [phpstan](https://phpstan.org/) and set `checkUninitializedProperties: true`, phpstan by default doesn't understand that the DTO properties will always be correctly initialized.
428+
429+
To help with that, this package provides a rule you can add to your `.neon` config file:
430+
```yaml
431+
services:
432+
-
433+
class: Spatie\DataTransferObject\PHPstan\PropertiesAreAlwaysInitializedExtension
434+
tags:
435+
- phpstan.properties.readWriteExtension
436+
#
437+
parameters:
438+
checkUninitializedProperties: true
439+
```
440+
425441
### Testing
426442
427443
``` bash

composer.json

+3
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@
2323
"larapack/dd": "^1.0",
2424
"phpunit/phpunit": "^7.0"
2525
},
26+
"suggest": {
27+
"phpstan/phpstan": "Take advantage of checkUninitializedProperties with \\Spatie\\DataTransferObject\\PHPstan\\PropertiesAreAlwaysInitializedExtension"
28+
},
2629
"autoload": {
2730
"psr-4": {
2831
"Spatie\\DataTransferObject\\": "src"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Spatie\DataTransferObject\PHPstan;
6+
7+
use PHPStan\Reflection\PropertyReflection;
8+
use PHPStan\Rules\Properties\ReadWritePropertiesExtension;
9+
use Spatie\DataTransferObject\DataTransferObject;
10+
11+
class PropertiesAreAlwaysInitializedExtension implements ReadWritePropertiesExtension
12+
{
13+
public function isAlwaysRead(PropertyReflection $property, string $propertyName): bool
14+
{
15+
return false;
16+
}
17+
18+
public function isAlwaysWritten(PropertyReflection $property, string $propertyName): bool
19+
{
20+
return false;
21+
}
22+
23+
public function isInitialized(PropertyReflection $property, string $propertyName): bool
24+
{
25+
return $property->getDeclaringClass()->isSubclassOf(DataTransferObject::class);
26+
}
27+
}

0 commit comments

Comments
 (0)