1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-27 04:45:20 +01:00
psalm/examples/StringChecker.php

70 lines
2.1 KiB
PHP
Raw Normal View History

2016-11-21 21:32:51 +01:00
<?php
namespace Psalm\Example\Plugin;
use Psalm\Checker;
use Psalm\Checker\StatementsChecker;
2016-11-21 21:51:38 +01:00
use Psalm\Context;
2016-12-12 22:07:45 +01:00
use Psalm\CodeLocation;
2016-11-21 21:32:51 +01:00
2016-11-21 21:39:04 +01:00
/**
* Checks all strings to see if they contain references to classes
2016-12-12 22:07:45 +01:00
* and, if so, checks that those classes exist.
*
2017-01-17 01:06:29 +01:00
* You will need to add `"nikic/PHP-Parser": ">=3.0.2"` to your
2016-12-12 22:07:45 +01:00
* composer.json.
2016-11-21 21:39:04 +01:00
*/
2016-11-21 21:32:51 +01:00
class StringChecker extends \Psalm\Plugin
{
/**
2016-12-12 22:07:45 +01:00
* Checks an expression
*
* @param StatementsChecker $statements_checker
2016-12-12 22:07:45 +01:00
* @param \PhpParser\Node\Expr $stmt
* @param Context $context
* @param CodeLocation $code_location
* @param array<string> $suppressed_issues
2016-11-21 21:32:51 +01:00
* @return null|false
*/
public function checkExpression(
StatementsChecker $statements_checker,
2016-12-12 22:07:45 +01:00
\PhpParser\Node\Expr $stmt,
Context $context,
CodeLocation $code_location,
array $suppressed_issues
) {
2016-11-21 21:32:51 +01:00
if ($stmt instanceof \PhpParser\Node\Scalar\String_) {
2016-12-12 22:07:45 +01:00
// Replace "Psalm" with your namespace
2016-11-21 21:32:51 +01:00
$class_or_class_method = '/^\\\?Psalm(\\\[A-Z][A-Za-z0-9]+)+(::[A-Za-z0-9]+)?$/';
if (preg_match($class_or_class_method, $stmt->value)) {
$fq_class_name = preg_split('/[:]/', $stmt->value)[0];
$project_checker = $statements_checker->getFileChecker()->project_checker;
2016-11-21 21:32:51 +01:00
if (Checker\ClassChecker::checkFullyQualifiedClassLikeName(
$project_checker,
2016-11-21 21:32:51 +01:00
$fq_class_name,
$code_location,
$suppressed_issues
) === false
2016-11-21 21:32:51 +01:00
) {
return false;
}
if ($fq_class_name !== $stmt->value) {
if (Checker\MethodChecker::checkMethodExists(
$project_checker,
2016-11-21 21:32:51 +01:00
$stmt->value,
$code_location,
$suppressed_issues
)
2016-11-21 21:32:51 +01:00
) {
return false;
}
}
}
}
}
}
return new StringChecker;