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

Trying to implement psalm plugin #7

Open
wants to merge 1 commit into
base: 0.1.x
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 .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
/vendor/
/var/
/.idea/
/.idea/
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@
"normalize-all": [
"@composer normalize --diff",
"@composer normalize --diff src/PHPStan/composer.json",
"@composer normalize --diff src/Serializer/composer.json"
"@composer normalize --diff src/Serializer/composer.json",
"@composer normalize --diff src/Psalm/composer.json"
],
"phpstan": "phpstan -v",
"psalm": "./vendor/bin/psalm --show-info --no-diff --no-cache",
Expand Down
26 changes: 26 additions & 0 deletions example/test.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

final class Request
{
/**
* @param array<string, int32> $id
*/
public function __construct(
public readonly array $id,
) {}

/** @return array<string, int32> */
public static function getId(): array
{
/** @var int32 $id */
$id = -1;

return ['id' => $id];
}
}

$request = new Request(Request::getId());

print_r($request->id['id']);
1 change: 1 addition & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ parameters:
level: 9
paths:
- src/PHPStan
- src/Psalm
- src/Serializer
- tests/Serializer
excludePaths:
Expand Down
5 changes: 3 additions & 2 deletions psalm.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@
findUnusedCode="true"
>
<projectFiles>
<directory name="src" />
<directory name="tests" />
<directory name="example" />
<ignoreFiles>
<directory name="vendor" />
<directory name="src/**/vendor" />
<directory name="tests/Serializer/Fixtures"/>
</ignoreFiles>
</projectFiles>
<plugins>
<pluginClass class="Psalm\PhpUnitPlugin\Plugin"/>
<pluginClass class="Prototype\Psalm\ProtobufTypePlugin"/>
</plugins>

<issueHandlers>
Expand Down
7 changes: 3 additions & 4 deletions src/PHPStan/.gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
vendor/
composer.lock
var/
.idea/
/vendor/
/var/
/.idea/
4 changes: 4 additions & 0 deletions src/Psalm/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.gitattributes export-ignore
.gitignore export-ignore
LICENSE export-ignore
README.md export-ignore
4 changes: 4 additions & 0 deletions src/Psalm/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
vendor/
composer.lock
var/
.idea/
204 changes: 204 additions & 0 deletions src/Psalm/ProtobufTypePlugin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
<?php

/**
* MIT License
* Copyright (c) 2024 kafkiansky.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

declare(strict_types=1);

namespace Prototype\Psalm;

use Psalm\Plugin\EventHandler\AfterClassLikeVisitInterface;
use Psalm\Plugin\EventHandler\AfterExpressionAnalysisInterface;
use Psalm\Plugin\EventHandler\AfterFunctionLikeAnalysisInterface;
use Psalm\Plugin\EventHandler\Event\AfterClassLikeVisitEvent;
use Psalm\Plugin\EventHandler\Event\AfterExpressionAnalysisEvent;
use Psalm\Plugin\EventHandler\Event\AfterFunctionLikeAnalysisEvent;
use Psalm\Plugin\PluginEntryPointInterface;
use Psalm\Plugin\RegistrationInterface;
use Psalm\Type;

/**
* @api
*/
final class ProtobufTypePlugin implements
PluginEntryPointInterface,
AfterClassLikeVisitInterface,
AfterExpressionAnalysisInterface,
AfterFunctionLikeAnalysisInterface
{
public function __invoke(RegistrationInterface $registration, ?\SimpleXMLElement $config = null): void
{
$registration->registerHooksFromClass(self::class);
}

public static function afterExpressionAnalysis(AfterExpressionAnalysisEvent $event): ?bool
{
self::fixTypes($event);

return null;
}

/**
* {@inheritdoc}
*/
public static function afterClassLikeVisit(AfterClassLikeVisitEvent $event): void
{
self::fixTypes($event);
}

public static function afterStatementAnalysis(AfterFunctionLikeAnalysisEvent $event): ?bool
{
self::fixTypes($event);

return null;
}

private static function fixTypes(AfterClassLikeVisitEvent|AfterExpressionAnalysisEvent|AfterFunctionLikeAnalysisEvent $event): void
{
$types = iterator_to_array(self::types());

$fixType =
/**
* @psalm-return ($type is null ? null|Type\Union : Type\Union)
*/
static fn (?Type\Union $type = null): ?Type\Union => self::fixType($types, $type);

if ($event instanceof AfterClassLikeVisitEvent) {
foreach ($event->getStorage()->methods as $method) {
/** @psalm-suppress InvalidArgument */
$method->return_type = $fixType($method->return_type);

foreach ($method->params as $param) {
/** @psalm-suppress InvalidArgument */
$param->type = $fixType($param->type);
}
}

foreach ($event->getStorage()->properties as $property) {
/** @psalm-suppress InvalidArgument */
$property->type = $fixType($property->type);
}
}

if ($event instanceof AfterExpressionAnalysisEvent) {
foreach ($event->getContext()->vars_in_scope as $varName => $varType) {
$event->getContext()->vars_in_scope[$varName] = $fixType($varType); /** @phpstan-ignore-line */
}

$event
->getStatementsSource()
->addSuppressedIssues(['UndefinedDocblockClass'])
;
}
}

/**
* @param array<non-empty-string, Type\Atomic> $prototypes
* @psalm-return ($union is null ? null|Type\Union : Type\Union)
*/
private static function fixType(array $prototypes, ?Type\Union $union = null): ?Type\Union
{
if (null !== $union) {
if ($union->hasArray()) {
$array = $union->getArray();

if ($array instanceof Type\Atomic\TKeyedArray) {
$arrayProperties = $array->properties;

foreach ($array->properties as $idx => $type) {
$arrayProperties[$idx] = self::fixType($prototypes, $type);
}

/** @psalm-suppress DocblockTypeContradiction, RedundantConditionGivenDocblockType */
$union = new Type\Union(['array' => new Type\Atomic\TKeyedArray(
$arrayProperties,
$array->class_strings,
null === $array->fallback_params ? null : [
self::fixType($prototypes, $array->fallback_params[0]),
self::fixType($prototypes, $array->fallback_params[1]),
],
$array->is_list,
$array->from_docblock,
)]);
} else if ($array instanceof Type\Atomic\TArray) {
$union = new Type\Union(['array' => new Type\Atomic\TArray([
self::fixType($prototypes, $array->type_params[0]),
self::fixType($prototypes, $array->type_params[1]),
])]);
}
}

$atomicTypes = $union->getAtomicTypes();

foreach ($atomicTypes as $typeId => $type) {
$nonNamespacedTypeId = self::typeWithoutNamespace($typeId);

if (isset($prototypes[$nonNamespacedTypeId])) {
$type = $prototypes[$nonNamespacedTypeId];
}

$atomicTypes[$typeId] = $type;
}

$union = $union->setTypes($atomicTypes);
}

return $union;
}

/**
* @return non-empty-string
*/
private static function typeWithoutNamespace(string $typeId): string
{
/** @psalm-suppress RiskyTruthyFalsyComparison */
$pos = strrpos($typeId, '\\') ?: -1;

/** @var non-empty-string */
return substr($typeId, $pos + 1);
}

/**
* @return \Traversable<non-empty-string, Type\Atomic>
*/
private static function types(): \Traversable
{
foreach (['int32', 'uint32', 'fixed32'] as $type) {
yield $type => new Type\Atomic\TIntRange(0, 4294967295);
}

foreach (['sint32', 'sfixed32'] as $type) {
yield $type => new Type\Atomic\TIntRange(-2147483648, 2147483647);
}

foreach (['int64', 'uint64', 'fixed64'] as $type) {
yield $type => new Type\Atomic\TIntRange(0, null);
}

foreach (['sint64', 'sfixed64'] as $type) {
yield $type => new Type\Atomic\TInt();
}

yield 'bytes' => new Type\Atomic\TString();
}
}
27 changes: 27 additions & 0 deletions src/Psalm/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "prototype/psalm-plugin",
"description": "Psalm plugin to resolve protobuf types.",
"license": "MIT",
"type": "psalm-plugin",
"authors": [
{
"name": "kafkiansky",
"email": "[email protected]"
}
],
"require": {
"php": "^8.1",
"vimeo/psalm": "^5.25"
},
"minimum-stability": "stable",
"prefer-stable": true,
"autoload": {
"psr-4": {
"Prototype\\Psalm\\": ""
}
},
"config": {
"lock": false,
"sort-packages": true
}
}
7 changes: 3 additions & 4 deletions src/Serializer/.gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
vendor/
composer.lock
var/
.idea/
/vendor/
/var/
/.idea/
2 changes: 1 addition & 1 deletion src/Serializer/Internal/Type/ValueType.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public function __construct()
[$this->readers, $this->writers] = [
[
self::NULL_TYPE => static function (Binary\Buffer $buffer): mixed {
(new VaruintType())->readFrom($buffer);
$_ = (new VaruintType())->readFrom($buffer);

return null;
},
Expand Down