1
0
mirror of https://github.com/danog/psalm.git synced 2024-12-15 10:57:08 +01:00
psalm/src/Psalm/Checker/ClassLikeChecker.php

843 lines
26 KiB
PHP
Raw Normal View History

2016-01-08 00:28:27 +01:00
<?php
namespace Psalm\Checker;
2016-01-08 00:28:27 +01:00
2016-11-02 07:29:00 +01:00
use PhpParser;
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
use Psalm\Aliases;
use Psalm\CodeLocation;
2016-11-02 07:29:00 +01:00
use Psalm\Config;
use Psalm\Context;
use Psalm\FileManipulation\FileManipulationBuffer;
use Psalm\Issue\DuplicateClass;
use Psalm\Issue\InaccessibleProperty;
use Psalm\Issue\InvalidClass;
use Psalm\Issue\ReservedWord;
2016-07-26 00:37:44 +02:00
use Psalm\Issue\UndefinedClass;
use Psalm\IssueBuffer;
use Psalm\Provider\FileReferenceProvider;
use Psalm\StatementsSource;
use Psalm\Storage\ClassLikeStorage;
2016-11-02 07:29:00 +01:00
use Psalm\Type;
2016-08-05 21:11:20 +02:00
use ReflectionProperty;
2016-01-08 00:28:27 +01:00
2016-11-21 03:49:06 +01:00
abstract class ClassLikeChecker extends SourceChecker implements StatementsSource
2016-01-08 00:28:27 +01:00
{
const VISIBILITY_PUBLIC = 1;
const VISIBILITY_PROTECTED = 2;
const VISIBILITY_PRIVATE = 3;
2016-10-31 20:42:20 +01:00
/**
* @var array
*/
public static $SPECIAL_TYPES = [
'int' => 'int',
'string' => 'stirng',
'float' => 'float',
'bool' => 'bool',
'false' => 'false',
'object' => 'object',
'empty' => 'empty',
'callable' => 'callable',
'array' => 'array',
'iterable' => 'iterable',
'null' => 'null',
'mixed' => 'mixed',
2016-11-02 07:29:00 +01:00
];
2017-09-11 17:52:34 +02:00
/**
* @var array
*/
public static $GETTYPE_TYPES = [
'boolean' => true,
'integer' => true,
'double' => true,
'string' => true,
'array' => true,
'object' => true,
'resource' => true,
'NULL' => true,
'unknown type' => true,
];
2016-09-09 15:13:41 +02:00
/**
* @var PhpParser\Node\Stmt\ClassLike
*/
protected $class;
2016-09-09 15:13:41 +02:00
2016-11-21 04:02:26 +01:00
/**
* @var StatementsSource
*/
protected $source;
/** @var FileChecker */
public $file_checker;
2016-09-09 15:13:41 +02:00
/**
* @var string
*/
protected $fq_class_name;
2016-09-09 15:13:41 +02:00
/**
* The parent class
*
2016-10-03 17:38:59 +02:00
* @var string|null
2016-09-09 15:13:41 +02:00
*/
2017-01-07 20:35:07 +01:00
protected $parent_fq_class_name;
/**
* @var array<string, array<string, string>>|null
*/
protected static $property_map;
/**
* @var PhpParser\Node\Stmt[]
*/
protected $leftover_stmts = [];
/** @var ClassLikeStorage */
protected $storage;
2016-11-02 07:29:00 +01:00
/**
* @param PhpParser\Node\Stmt\ClassLike $class
* @param StatementsSource $source
* @param string $fq_class_name
2016-11-02 07:29:00 +01:00
*/
public function __construct(PhpParser\Node\Stmt\ClassLike $class, StatementsSource $source, $fq_class_name)
2016-01-08 00:28:27 +01:00
{
$this->class = $class;
2016-11-13 00:51:48 +01:00
$this->source = $source;
$this->file_checker = $source->getFileChecker();
$this->fq_class_name = $fq_class_name;
2016-01-08 00:28:27 +01:00
$this->storage = $this->file_checker->project_checker->classlike_storage_provider->get($fq_class_name);
if ($this->storage->location) {
$storage_file_path = $this->storage->location->file_path;
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
$source_file_path = $this->source->getCheckedFilePath();
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
if (!Config::getInstance()->use_case_sensitive_file_names) {
$storage_file_path = strtolower($storage_file_path);
$source_file_path = strtolower($source_file_path);
}
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
if ($storage_file_path !== $source_file_path ||
$this->storage->location->getLineNumber() !== $class->getLine()
) {
2017-02-10 02:35:17 +01:00
if (IssueBuffer::accepts(
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
new DuplicateClass(
'Class ' . $fq_class_name . ' has already been defined at ' .
$storage_file_path . ':' . $this->storage->location->getLineNumber(),
new CodeLocation($this, $class, null, true)
2017-02-10 02:35:17 +01:00
)
)) {
// fall through
}
}
2017-01-07 21:57:25 +01:00
}
}
2017-01-12 03:37:53 +01:00
/**
* @param string $method_name
* @param Context $context
2017-05-27 02:16:18 +02:00
*
2017-01-12 03:37:53 +01:00
* @return void
*/
public function getMethodMutations(
$method_name,
Context $context
) {
$project_checker = $this->getFileChecker()->project_checker;
$codebase = $project_checker->codebase;
2017-01-12 03:37:53 +01:00
foreach ($this->class->stmts as $stmt) {
if ($stmt instanceof PhpParser\Node\Stmt\ClassMethod &&
strtolower($stmt->name) === strtolower($method_name)
) {
2017-01-12 06:54:41 +01:00
$method_id = $this->fq_class_name . '::' . $stmt->name;
if ($codebase->canCacheCheckers()) {
$method_checker = $codebase->getCachedMethodChecker($method_id);
2017-01-12 06:54:41 +01:00
if (!$method_checker) {
$method_checker = new MethodChecker($stmt, $this);
$codebase->cacheMethodChecker($method_id, $method_checker);
2017-01-12 06:54:41 +01:00
}
} else {
$method_checker = new MethodChecker($stmt, $this);
2017-01-12 06:54:41 +01:00
}
2017-01-12 03:37:53 +01:00
$method_checker->analyze($context, null, true);
} elseif ($stmt instanceof PhpParser\Node\Stmt\TraitUse) {
foreach ($stmt->traits as $trait) {
2017-01-12 03:37:53 +01:00
$fq_trait_name = self::getFQCLNFromNameObject(
$trait,
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
$this->source->getAliases()
);
$trait_file_checker = $codebase->getFileCheckerForClassLike($project_checker, $fq_trait_name);
$trait_node = $codebase->getTraitNode($fq_trait_name);
$trait_aliases = $codebase->getTraitAliases($fq_trait_name);
2018-01-21 18:44:46 +01:00
$trait_checker = new TraitChecker(
$trait_node,
$trait_file_checker,
$fq_trait_name,
$trait_aliases
);
2017-01-12 03:37:53 +01:00
foreach ($trait_node->stmts as $trait_stmt) {
2017-01-12 03:37:53 +01:00
if ($trait_stmt instanceof PhpParser\Node\Stmt\ClassMethod &&
strtolower($trait_stmt->name) === strtolower($method_name)
) {
$method_checker = new MethodChecker($trait_stmt, $trait_checker);
$actual_method_id = (string)$method_checker->getMethodId();
2017-01-12 03:37:53 +01:00
if ($context->self && $context->self !== $this->fq_class_name) {
$analyzed_method_id = (string)$method_checker->getMethodId($context->self);
$declaring_method_id = MethodChecker::getDeclaringMethodId(
$project_checker,
$analyzed_method_id
);
2017-01-12 03:37:53 +01:00
if ($actual_method_id !== $declaring_method_id) {
break;
}
}
$method_checker->analyze($context, null, true);
}
}
}
}
}
}
/**
2016-09-09 15:13:41 +02:00
* Check whether a class/interface exists
*
* @param string $fq_class_name
* @param ProjectChecker $project_checker
2017-02-27 22:38:43 +01:00
* @param CodeLocation $code_location
2017-05-27 02:16:18 +02:00
*
* @return bool
*/
public static function classOrInterfaceExists(
ProjectChecker $project_checker,
$fq_class_name,
2017-02-27 22:38:43 +01:00
CodeLocation $code_location = null
) {
if (!ClassChecker::classExists($project_checker, $fq_class_name) &&
!InterfaceChecker::interfaceExists($project_checker, $fq_class_name)
2017-02-27 22:35:24 +01:00
) {
return false;
}
if ($project_checker->getCodeBase()->collect_references && $code_location) {
$class_storage = $project_checker->classlike_storage_provider->get($fq_class_name);
2017-02-28 00:24:20 +01:00
if ($class_storage->referencing_locations === null) {
$class_storage->referencing_locations = [];
}
$class_storage->referencing_locations[$code_location->file_path][] = $code_location;
2017-02-27 22:35:24 +01:00
}
return true;
2016-07-25 05:38:52 +02:00
}
/**
* @param string $fq_class_name
* @param string $possible_parent
2017-05-27 02:16:18 +02:00
*
2016-07-25 05:38:52 +02:00
* @return bool
*/
public static function classExtendsOrImplements(
ProjectChecker $project_checker,
$fq_class_name,
$possible_parent
) {
return ClassChecker::classExtends($project_checker, $fq_class_name, $possible_parent) ||
ClassChecker::classImplements($project_checker, $fq_class_name, $possible_parent);
2016-07-25 05:38:52 +02:00
}
/**
* @param string $fq_class_name
2016-11-05 01:10:59 +01:00
* @param array<string> $suppressed_issues
* @param bool $inferred - whether or not the type was inferred
2017-05-27 02:16:18 +02:00
*
2016-07-25 05:38:52 +02:00
* @return bool|null
2016-04-27 00:42:48 +02:00
*/
2016-11-08 01:16:51 +01:00
public static function checkFullyQualifiedClassLikeName(
StatementsSource $statements_source,
$fq_class_name,
CodeLocation $code_location,
array $suppressed_issues,
$inferred = true
2016-11-02 07:29:00 +01:00
) {
if (empty($fq_class_name)) {
2016-04-12 17:59:27 +02:00
throw new \InvalidArgumentException('$class cannot be empty');
}
$project_checker = $statements_source->getFileChecker()->project_checker;
$codebase = $project_checker->codebase;
$fq_class_name = preg_replace('/^\\\/', '', $fq_class_name);
2016-03-17 19:06:01 +01:00
2017-05-27 02:05:57 +02:00
if (in_array($fq_class_name, ['callable', 'iterable'], true)) {
return true;
}
if (preg_match(
'/(^|\\\)(int|float|bool|string|void|null|false|true|resource|object|numeric|mixed)$/i',
$fq_class_name
)
) {
$class_name_parts = explode('\\', $fq_class_name);
$class_name = array_pop($class_name_parts);
if (IssueBuffer::accepts(
new ReservedWord(
$class_name . ' is a reserved word',
$code_location
),
$suppressed_issues
)) {
// fall through
}
return null;
}
$class_exists = ClassChecker::classExists($project_checker, $fq_class_name);
$interface_exists = InterfaceChecker::interfaceExists($project_checker, $fq_class_name);
if (!$class_exists && !$interface_exists) {
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
2016-11-02 07:29:00 +01:00
new UndefinedClass(
'Class or interface ' . $fq_class_name . ' does not exist',
$code_location
2016-11-02 07:29:00 +01:00
),
$suppressed_issues
)) {
return false;
}
2016-11-02 07:29:00 +01:00
return null;
2016-01-08 00:28:27 +01:00
}
if ($project_checker->getCodeBase()->collect_references && !$inferred) {
$class_storage = $project_checker->classlike_storage_provider->get($fq_class_name);
2017-02-28 00:24:20 +01:00
if ($class_storage->referencing_locations === null) {
$class_storage->referencing_locations = [];
}
$class_storage->referencing_locations[$code_location->file_path][] = $code_location;
}
if (($class_exists && !$codebase->classHasCorrectCasing($fq_class_name)) ||
($interface_exists && !$codebase->interfaceHasCorrectCasing($fq_class_name))
) {
if (ClassLikeChecker::isUserDefined($project_checker, $fq_class_name)) {
if (IssueBuffer::accepts(
new InvalidClass(
'Class or interface ' . $fq_class_name . ' has wrong casing',
$code_location
),
$suppressed_issues
)) {
// fall through here
}
2016-08-10 07:09:47 +02:00
}
2016-03-17 19:06:01 +01:00
}
FileReferenceProvider::addFileReferenceToClass(
$code_location->file_path,
strtolower($fq_class_name)
);
if (!$inferred) {
$plugins = $codebase->config->getPlugins();
if ($plugins) {
$file_manipulations = [];
foreach ($plugins as $plugin) {
$plugin->afterClassLikeExistsCheck(
$statements_source,
$fq_class_name,
$code_location,
$file_manipulations
);
}
if ($file_manipulations) {
FileManipulationBuffer::add($code_location->file_path, $file_manipulations);
}
}
}
return true;
2016-01-08 00:28:27 +01:00
}
/**
2016-11-02 07:29:00 +01:00
* Gets the fully-qualified class name from a Name object
*
* @param PhpParser\Node\Name $class_name
2018-01-18 21:10:57 +01:00
* @param Aliases $aliases
2017-05-27 02:16:18 +02:00
*
* @return string
*/
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
public static function getFQCLNFromNameObject(PhpParser\Node\Name $class_name, Aliases $aliases)
{
2016-01-08 00:28:27 +01:00
if ($class_name instanceof PhpParser\Node\Name\FullyQualified) {
return implode('\\', $class_name->parts);
2016-01-08 00:28:27 +01:00
}
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
if (in_array($class_name->parts[0], ['self', 'static', 'parent'], true)) {
return $class_name->parts[0];
}
return self::getFQCLNFromString(
implode('\\', $class_name->parts),
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
$aliases
);
2016-01-08 00:28:27 +01:00
}
2016-10-12 07:38:29 +02:00
/**
* @param string $class
2018-01-18 21:10:57 +01:00
* @param Aliases $aliases
2017-05-27 02:16:18 +02:00
*
2016-10-12 07:38:29 +02:00
* @return string
*/
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
public static function getFQCLNFromString($class, Aliases $aliases)
{
2016-04-12 17:59:27 +02:00
if (empty($class)) {
throw new \InvalidArgumentException('$class cannot be empty');
}
2016-01-08 00:28:27 +01:00
if ($class[0] === '\\') {
return substr($class, 1);
2016-01-08 00:28:27 +01:00
}
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
$imported_namespaces = $aliases->uses;
2017-01-07 20:35:07 +01:00
2016-01-08 00:28:27 +01:00
if (strpos($class, '\\') !== false) {
$class_parts = explode('\\', $class);
$first_namespace = array_shift($class_parts);
if (isset($imported_namespaces[strtolower($first_namespace)])) {
return $imported_namespaces[strtolower($first_namespace)] . '\\' . implode('\\', $class_parts);
2016-01-08 00:28:27 +01:00
}
} elseif (isset($imported_namespaces[strtolower($class)])) {
return $imported_namespaces[strtolower($class)];
2016-01-08 00:28:27 +01:00
}
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
$namespace = $aliases->namespace;
2017-01-07 20:35:07 +01:00
return ($namespace ? $namespace . '\\' : '') . $class;
2016-01-08 00:28:27 +01:00
}
2016-11-02 07:29:00 +01:00
/**
* @return ?string
2016-11-02 07:29:00 +01:00
*/
public function getNamespace()
{
2017-01-07 20:35:07 +01:00
return $this->source->getNamespace();
}
2016-11-13 00:51:48 +01:00
/**
* @return array<string, string>
*/
public function getAliasedClassesFlipped()
{
2016-11-13 17:24:46 +01:00
if ($this->source instanceof NamespaceChecker || $this->source instanceof FileChecker) {
return $this->source->getAliasedClassesFlipped();
}
return [];
2016-11-13 00:51:48 +01:00
}
2016-11-02 07:29:00 +01:00
/**
* @return string
*/
2016-11-08 01:16:51 +01:00
public function getFQCLN()
{
return $this->fq_class_name;
}
2016-11-02 07:29:00 +01:00
/**
* @return string|null
2016-11-02 07:29:00 +01:00
*/
public function getClassName()
{
return $this->class->name;
}
/**
* @return string|null
*/
2017-01-07 20:35:07 +01:00
public function getParentFQCLN()
{
2017-01-07 20:35:07 +01:00
return $this->parent_fq_class_name;
}
2016-04-27 00:42:48 +02:00
/**
* @return bool
*/
public function isStatic()
{
return false;
}
2016-11-21 03:49:06 +01:00
/**
* Gets the Psalm type from a particular value
*
* @param mixed $value
2017-05-27 02:16:18 +02:00
*
2016-11-21 03:49:06 +01:00
* @return Type\Union
*/
public static function getTypeFromValue($value)
{
switch (gettype($value)) {
case 'boolean':
return Type::getBool();
case 'integer':
return Type::getInt();
case 'double':
return Type::getFloat();
case 'string':
return Type::getString();
case 'array':
return Type::getArray();
case 'NULL':
return Type::getNull();
default:
return Type::getMixed();
}
}
2016-10-12 07:38:29 +02:00
/**
* @param string $class_name
* @param mixed $visibility
2017-05-27 02:16:18 +02:00
*
2016-10-12 07:38:29 +02:00
* @return array<string,Type\Union>
*/
public static function getConstantsForClass(ProjectChecker $project_checker, $class_name, $visibility)
{
2017-01-09 05:58:06 +01:00
$class_name = strtolower($class_name);
$class_name = strtolower($class_name);
$storage = $project_checker->classlike_storage_provider->get($class_name);
if ($visibility === ReflectionProperty::IS_PUBLIC) {
return $storage->public_class_constants;
}
if ($visibility === ReflectionProperty::IS_PROTECTED) {
return array_merge(
$storage->public_class_constants,
$storage->protected_class_constants
);
}
if ($visibility === ReflectionProperty::IS_PRIVATE) {
return array_merge(
$storage->public_class_constants,
$storage->protected_class_constants,
$storage->private_class_constants
);
}
throw new \InvalidArgumentException('Must specify $visibility');
}
2016-11-02 07:29:00 +01:00
/**
* @param string $class_name
* @param string $const_name
* @param Type\Union $type
* @param int $visibility
2017-05-27 02:16:18 +02:00
*
2016-11-02 07:29:00 +01:00
* @return void
*/
public static function setConstantType(
ProjectChecker $project_checker,
$class_name,
$const_name,
Type\Union $type,
$visibility
) {
$storage = $project_checker->classlike_storage_provider->get($class_name);
if ($visibility === ReflectionProperty::IS_PUBLIC) {
$storage->public_class_constants[$const_name] = $type;
} elseif ($visibility === ReflectionProperty::IS_PROTECTED) {
$storage->protected_class_constants[$const_name] = $type;
} elseif ($visibility === ReflectionProperty::IS_PRIVATE) {
$storage->private_class_constants[$const_name] = $type;
}
}
/**
* Whether or not a given property exists
*
* @param string $property_id
2017-05-27 02:16:18 +02:00
*
* @return bool
*/
public static function propertyExists(
ProjectChecker $project_checker,
$property_id,
CodeLocation $code_location = null
) {
// remove trailing backslash if it exists
$property_id = preg_replace('/^\\\\/', '', $property_id);
list($fq_class_name, $property_name) = explode('::$', $property_id);
$class_storage = $project_checker->classlike_storage_provider->get($fq_class_name);
if (isset($class_storage->declaring_property_ids[$property_name])) {
if ($project_checker->getCodeBase()->collect_references && $code_location) {
$declaring_property_id = $class_storage->declaring_property_ids[$property_name];
list($declaring_property_class, $declaring_property_name) = explode('::$', $declaring_property_id);
$declaring_class_storage = $project_checker->classlike_storage_provider->get($declaring_property_class);
$declaring_property_storage = $declaring_class_storage->properties[$declaring_property_name];
if ($declaring_property_storage->referencing_locations === null) {
$declaring_property_storage->referencing_locations = [];
}
$declaring_property_storage->referencing_locations[$code_location->file_path][] = $code_location;
}
return true;
}
return false;
}
/**
* @param string $property_id
* @param string|null $calling_context
* @param StatementsSource $source
* @param CodeLocation $code_location
* @param array $suppressed_issues
* @param bool $emit_issues
2017-05-27 02:16:18 +02:00
*
* @return bool|null
*/
public static function checkPropertyVisibility(
$property_id,
$calling_context,
StatementsSource $source,
CodeLocation $code_location,
array $suppressed_issues,
$emit_issues = true
) {
$project_checker = $source->getFileChecker()->project_checker;
$declaring_property_class = self::getDeclaringClassForProperty($project_checker, $property_id);
$appearing_property_class = self::getAppearingClassForProperty($project_checker, $property_id);
if (!$declaring_property_class || !$appearing_property_class) {
throw new \UnexpectedValueException(
'Appearing/Declaring classes are not defined for ' . $property_id
);
}
2017-02-11 01:10:13 +01:00
list(, $property_name) = explode('::$', (string)$property_id);
// if the calling class is the same, we know the property exists, so it must be visible
if ($appearing_property_class === $calling_context) {
return $emit_issues ? null : true;
}
if ($source->getSource() instanceof TraitChecker && $declaring_property_class === $source->getFQCLN()) {
return $emit_issues ? null : true;
}
$class_storage = $project_checker->classlike_storage_provider->get($declaring_property_class);
if (!isset($class_storage->properties[$property_name])) {
throw new \UnexpectedValueException('$storage should not be null for ' . $property_id);
}
$storage = $class_storage->properties[$property_name];
switch ($storage->visibility) {
case self::VISIBILITY_PUBLIC:
return $emit_issues ? null : true;
case self::VISIBILITY_PRIVATE:
if (!$calling_context || $appearing_property_class !== $calling_context) {
2018-01-13 08:08:53 +01:00
if ($emit_issues && IssueBuffer::accepts(
new InaccessibleProperty(
'Cannot access private property ' . $property_id . ' from context ' . $calling_context,
$code_location
),
$suppressed_issues
)) {
return false;
}
return null;
}
return $emit_issues ? null : true;
case self::VISIBILITY_PROTECTED:
if ($appearing_property_class === $calling_context) {
return null;
}
if (!$calling_context) {
2018-01-13 08:08:53 +01:00
if ($emit_issues && IssueBuffer::accepts(
new InaccessibleProperty(
'Cannot access protected property ' . $property_id,
$code_location
),
$suppressed_issues
)) {
return false;
}
return null;
}
if (ClassChecker::classExtends($project_checker, $appearing_property_class, $calling_context)) {
return $emit_issues ? null : true;
}
if (!ClassChecker::classExtends($project_checker, $calling_context, $appearing_property_class)) {
2018-01-13 08:08:53 +01:00
if ($emit_issues && IssueBuffer::accepts(
new InaccessibleProperty(
'Cannot access protected property ' . $property_id . ' from context ' . $calling_context,
$code_location
),
$suppressed_issues
)) {
return false;
}
return null;
}
}
return $emit_issues ? null : true;
}
/**
* @param string $property_id
2017-05-27 02:16:18 +02:00
*
* @return string|null
*/
public static function getDeclaringClassForProperty(ProjectChecker $project_checker, $property_id)
{
list($fq_class_name, $property_name) = explode('::$', $property_id);
2017-01-09 05:58:06 +01:00
$fq_class_name = strtolower($fq_class_name);
$class_storage = $project_checker->classlike_storage_provider->get($fq_class_name);
if (isset($class_storage->declaring_property_ids[$property_name])) {
$declaring_property_id = $class_storage->declaring_property_ids[$property_name];
return explode('::$', $declaring_property_id)[0];
}
}
/**
* Get the class this property appears in (vs is declared in, which could give a trait)
*
* @param string $property_id
2017-05-27 02:16:18 +02:00
*
* @return string|null
*/
public static function getAppearingClassForProperty(ProjectChecker $project_checker, $property_id)
{
list($fq_class_name, $property_name) = explode('::$', $property_id);
2017-01-09 05:58:06 +01:00
$fq_class_name = strtolower($fq_class_name);
$class_storage = $project_checker->classlike_storage_provider->get($fq_class_name);
if (isset($class_storage->appearing_property_ids[$property_name])) {
$appearing_property_id = $class_storage->appearing_property_ids[$property_name];
return explode('::$', $appearing_property_id)[0];
}
}
2016-11-02 07:29:00 +01:00
/**
* @param string $file_path
2017-05-27 02:16:18 +02:00
*
* @return array<string>
2016-11-02 07:29:00 +01:00
*/
public static function getClassesForFile(ProjectChecker $project_checker, $file_path)
{
try {
return $project_checker->file_storage_provider->get($file_path)->classes_in_file;
} catch (\InvalidArgumentException $e) {
return [];
}
}
2016-10-30 16:14:36 +01:00
/**
* @param string $fq_class_name
2017-05-27 02:16:18 +02:00
*
2017-05-25 04:07:49 +02:00
* @return bool
2016-10-30 16:14:36 +01:00
*/
public static function isUserDefined(ProjectChecker $project_checker, $fq_class_name)
{
return $project_checker->classlike_storage_provider->get($fq_class_name)->user_defined;
}
/**
* Gets the method/function call map
*
* @return array<string, array<string, string>>
* @psalm-suppress MixedInferredReturnType as the use of require buggers things up
2017-01-09 05:58:06 +01:00
* @psalm-suppress MixedAssignment
*/
public static function getPropertyMap()
{
if (self::$property_map !== null) {
return self::$property_map;
}
/** @var array<string, array<string, string>> */
2017-05-25 04:07:49 +02:00
$property_map = require_once(__DIR__ . '/../PropertyMap.php');
self::$property_map = [];
foreach ($property_map as $key => $value) {
$cased_key = strtolower($key);
self::$property_map[$cased_key] = $value;
}
return self::$property_map;
}
2016-11-02 07:29:00 +01:00
/**
* @param string $class_name
2017-05-27 02:16:18 +02:00
*
2016-11-02 07:29:00 +01:00
* @return bool
*/
public static function inPropertyMap($class_name)
{
return isset(self::getPropertyMap()[strtolower($class_name)]);
}
/**
* @return FileChecker
*/
public function getFileChecker()
{
return $this->file_checker;
}
2016-01-08 00:28:27 +01:00
}