2018-01-02 03:17:23 +01:00
|
|
|
<?php
|
2022-12-18 17:15:15 +01:00
|
|
|
|
2018-01-02 03:17:23 +01:00
|
|
|
namespace Psalm\Example\Plugin;
|
|
|
|
|
2018-11-12 16:46:55 +01:00
|
|
|
use Psalm\FileManipulation;
|
2021-12-27 20:18:33 +01:00
|
|
|
use Psalm\Internal\Type\TypeTokenizer;
|
2021-01-06 15:05:53 +01:00
|
|
|
use Psalm\Plugin\EventHandler\AfterClassLikeExistenceCheckInterface;
|
|
|
|
use Psalm\Plugin\EventHandler\Event\AfterClassLikeExistenceCheckEvent;
|
2022-12-18 17:15:15 +01:00
|
|
|
|
|
|
|
use function array_map;
|
|
|
|
use function implode;
|
2021-12-27 20:18:33 +01:00
|
|
|
use function strpos;
|
2021-01-06 15:05:53 +01:00
|
|
|
use function strtolower;
|
2018-01-02 03:17:23 +01:00
|
|
|
|
2018-11-12 16:11:08 +01:00
|
|
|
class ClassUnqualifier implements AfterClassLikeExistenceCheckInterface
|
2018-01-02 03:17:23 +01:00
|
|
|
{
|
2018-11-06 03:57:36 +01:00
|
|
|
public static function afterClassLikeExistenceCheck(
|
2021-01-06 15:05:53 +01:00
|
|
|
AfterClassLikeExistenceCheckEvent $event
|
2020-10-12 21:02:52 +02:00
|
|
|
): void {
|
2021-01-06 15:05:53 +01:00
|
|
|
$fq_class_name = $event->getFqClassName();
|
|
|
|
$code_location = $event->getCodeLocation();
|
|
|
|
$statements_source = $event->getStatementsSource();
|
|
|
|
$file_replacements = $event->getFileReplacements();
|
|
|
|
|
2018-01-02 03:17:23 +01:00
|
|
|
$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) {
|
2018-01-02 03:17:23 +01:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-12-27 20:18:33 +01:00
|
|
|
if (strpos($candidate_type, '\\' . $fq_class_name) !== false) {
|
|
|
|
$type_tokens = TypeTokenizer::tokenize($candidate_type, false);
|
2018-01-02 03:17:23 +01:00
|
|
|
|
|
|
|
foreach ($type_tokens as &$type_token) {
|
2019-06-23 05:30:40 +02:00
|
|
|
if ($type_token[0] === ('\\' . $fq_class_name)
|
2018-01-02 03:17:23 +01:00
|
|
|
&& isset($aliases[strtolower($fq_class_name)])
|
|
|
|
) {
|
2019-06-23 05:30:40 +02:00
|
|
|
$type_token[0] = $aliases[strtolower($fq_class_name)];
|
2018-01-02 03:17:23 +01:00
|
|
|
}
|
|
|
|
}
|
2022-11-04 19:04:23 +01:00
|
|
|
unset($type_token);
|
2018-01-02 03:17:23 +01:00
|
|
|
|
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],
|
2022-12-18 17:15:15 +01:00
|
|
|
$type_tokens,
|
|
|
|
),
|
2019-06-23 06:19:41 +02:00
|
|
|
);
|
2018-01-02 03:17:23 +01:00
|
|
|
|
|
|
|
if ($new_candidate_type !== $candidate_type) {
|
|
|
|
$bounds = $code_location->getSelectionBounds();
|
|
|
|
$file_replacements[] = new FileManipulation($bounds[0], $bounds[1], $new_candidate_type);
|
|
|
|
}
|
2021-01-06 15:05:53 +01:00
|
|
|
$event->setFileReplacements($file_replacements);
|
2018-01-02 03:17:23 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|