1
0
mirror of https://github.com/danog/psalm.git synced 2024-12-11 00:39:38 +01:00
psalm/examples/plugins/ClassUnqualifier.php

58 lines
2.0 KiB
PHP
Raw Normal View History

<?php
namespace Psalm\Example\Plugin;
use Psalm\FileManipulation;
use Psalm\Internal\Type\TypeTokenizer;
use Psalm\Plugin\EventHandler\AfterClassLikeExistenceCheckInterface;
use Psalm\Plugin\EventHandler\Event\AfterClassLikeExistenceCheckEvent;
use function strpos;
use function strtolower;
use function implode;
use function array_map;
class ClassUnqualifier implements AfterClassLikeExistenceCheckInterface
{
2018-11-06 03:57:36 +01:00
public static function afterClassLikeExistenceCheck(
AfterClassLikeExistenceCheckEvent $event
): void {
$fq_class_name = $event->getFqClassName();
$code_location = $event->getCodeLocation();
$statements_source = $event->getStatementsSource();
$file_replacements = $event->getFileReplacements();
$candidate_type = $code_location->getSelectedText();
$aliases = $statements_source->getAliasedClassesFlipped();
2018-11-06 03:57:36 +01:00
if ($statements_source->getFilePath() !== $code_location->file_path) {
return;
}
if (strpos($candidate_type, '\\' . $fq_class_name) !== false) {
$type_tokens = TypeTokenizer::tokenize($candidate_type, false);
foreach ($type_tokens as &$type_token) {
if ($type_token[0] === ('\\' . $fq_class_name)
&& isset($aliases[strtolower($fq_class_name)])
) {
$type_token[0] = $aliases[strtolower($fq_class_name)];
}
}
unset($type_token);
2019-06-23 06:19:41 +02:00
$new_candidate_type = implode(
'',
array_map(
2022-01-05 23:45:11 +01:00
fn($f) => $f[0],
2019-06-23 06:19:41 +02:00
$type_tokens
)
);
if ($new_candidate_type !== $candidate_type) {
$bounds = $code_location->getSelectionBounds();
$file_replacements[] = new FileManipulation($bounds[0], $bounds[1], $new_candidate_type);
}
$event->setFileReplacements($file_replacements);
}
}
}