1
0
mirror of https://github.com/danog/psalm.git synced 2024-12-13 17:57:37 +01:00
psalm/src/Psalm/StatementsChecker.php

3628 lines
137 KiB
PHP
Raw Normal View History

<?php
2016-07-26 00:37:44 +02:00
namespace Psalm;
2016-02-04 15:22:46 +01:00
use PhpParser;
2016-07-26 00:37:44 +02:00
use Psalm\IssueBuffer;
use Psalm\Issue\ForbiddenCode;
use Psalm\Issue\InvalidArgument;
use Psalm\Issue\InvalidNamespace;
use Psalm\Issue\InvalidIterator;
use Psalm\Issue\MixedMethodCall;
2016-08-07 17:35:27 +02:00
use Psalm\Issue\MissingPropertyDeclaration;
use Psalm\Issue\NoInterfaceProperties;
2016-08-07 02:27:13 +02:00
use Psalm\Issue\NullPropertyFetch;
2016-07-26 00:37:44 +02:00
use Psalm\Issue\NullReference;
use Psalm\Issue\ParentNotFound;
use Psalm\Issue\PossiblyUndefinedVariable;
use Psalm\Issue\InvalidArrayAssignment;
use Psalm\Issue\InvalidArrayAccess;
use Psalm\Issue\InvalidPropertyAssignment;
use Psalm\Issue\InvalidScalarArgument;
use Psalm\Issue\InvalidScope;
use Psalm\Issue\InvalidStaticVariable;
use Psalm\Issue\FailedTypeResolution;
2016-08-07 17:35:27 +02:00
use Psalm\Issue\UndefinedClass;
2016-07-26 00:37:44 +02:00
use Psalm\Issue\UndefinedConstant;
use Psalm\Issue\UndefinedFunction;
use Psalm\Issue\UndefinedProperty;
use Psalm\Issue\UndefinedVariable;
use Psalm\Issue\TooFewArguments;
use Psalm\Issue\TooManyArguments;
2016-04-17 22:20:36 +02:00
class StatementsChecker
{
protected $_stmts;
protected $_source;
protected $_all_vars = [];
protected $_warn_vars = [];
protected $_check_classes = true;
protected $_check_variables = true;
protected $_check_methods = true;
protected $_check_consts = true;
2016-03-23 18:05:25 +01:00
protected $_check_functions = true;
protected $_class_name;
protected $_class_extends;
protected $_namespace;
protected $_aliased_classes;
protected $_file_name;
protected $_is_static;
protected $_absolute_class;
protected $_type_checker;
2016-03-23 18:05:25 +01:00
protected $_available_functions = [];
/**
* A list of suppressed issues
* @var array
*/
protected $_suppressed_issues;
2016-04-17 16:25:43 +02:00
protected $_require_file_name = null;
protected static $_method_call_index = [];
2016-03-23 18:05:25 +01:00
protected static $_existing_functions = [];
protected static $_reflection_functions = [];
protected static $_this_assignments = [];
protected static $_this_calls = [];
protected static $_mock_interfaces = [];
2016-07-23 16:58:53 +02:00
protected static $_class_consts = [];
public function __construct(StatementsSource $source, $enforce_variable_checks = false, $check_methods = true)
{
$this->_source = $source;
$this->_check_classes = true;
$this->_check_methods = $check_methods;
$this->_check_consts = true;
$this->_file_name = $this->_source->getFileName();
$this->_aliased_classes = $this->_source->getAliasedClasses();
$this->_namespace = $this->_source->getNamespace();
$this->_is_static = $this->_source->isStatic();
$this->_absolute_class = $this->_source->getAbsoluteClass();
$this->_class_name = $this->_source->getClassName();
$this->_class_extends = $this->_source->getParentClass();
$this->_suppressed_issues = $this->_source->getSuppressedIssues();
$config = Config::getInstance();
$this->_check_variables = !$config->excludeIssueInFile('UndefinedVariable', $this->_file_name) || $enforce_variable_checks;
$this->_type_checker = new TypeChecker($source, $this);
}
2016-06-18 20:45:55 +02:00
/**
* Checks an array of statements for validity
*
* @param array<PhpParser\Node> $stmts
* @param array<Type\Union> &$context->vars_in_scope
* @param array &$context->vars_possibly_in_scope
2016-06-18 20:45:55 +02:00
* @return null|false
*/
public function check(array $stmts, Context $context, array &$for_vars_possibly_in_scope = [])
{
$has_returned = false;
2016-03-23 18:05:25 +01:00
// register all functions first
foreach ($stmts as $stmt) {
if ($stmt instanceof PhpParser\Node\Stmt\Function_) {
$file_checker = FileChecker::getFileCheckerFromFileName($this->_file_name);
$file_checker->registerFunction($stmt);
2016-03-23 18:05:25 +01:00
}
}
foreach ($stmts as $stmt) {
2016-06-18 20:45:55 +02:00
foreach (Config::getInstance()->getPlugins() as $plugin) {
if ($plugin->checkStatement($stmt, $context, $this->_file_name) === false) {
2016-06-18 20:45:55 +02:00
return false;
}
}
if ($has_returned && !($stmt instanceof PhpParser\Node\Stmt\Nop) && !($stmt instanceof PhpParser\Node\Stmt\InlineHTML)) {
echo('Warning: Expressions after return/throw/continue in ' . $this->_file_name . ' on line ' . $stmt->getLine() . PHP_EOL);
break;
}
if ($stmt instanceof PhpParser\Node\Stmt\If_) {
$this->_checkIf($stmt, $context, $for_vars_possibly_in_scope);
} elseif ($stmt instanceof PhpParser\Node\Stmt\TryCatch) {
$this->_checkTryCatch($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Stmt\For_) {
$this->_checkFor($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Stmt\Foreach_) {
$this->_checkForeach($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Stmt\While_) {
$this->_checkWhile($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Stmt\Do_) {
$this->_checkDo($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Stmt\Const_) {
foreach ($stmt->consts as $const) {
$this->_checkExpression($const->value, $context);
}
} elseif ($stmt instanceof PhpParser\Node\Stmt\Unset_) {
// do nothing
} elseif ($stmt instanceof PhpParser\Node\Stmt\Return_) {
$has_returned = true;
$this->_checkReturn($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Stmt\Throw_) {
$has_returned = true;
$this->_checkThrow($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Stmt\Switch_) {
$this->_checkSwitch($stmt, $context, $for_vars_possibly_in_scope);
} elseif ($stmt instanceof PhpParser\Node\Stmt\Break_) {
// do nothing
} elseif ($stmt instanceof PhpParser\Node\Stmt\Continue_) {
$has_returned = true;
} elseif ($stmt instanceof PhpParser\Node\Stmt\Static_) {
$this->_checkStatic($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Stmt\Echo_) {
foreach ($stmt->exprs as $expr) {
$this->_checkExpression($expr, $context);
}
} elseif ($stmt instanceof PhpParser\Node\Stmt\Function_) {
$function_checker = new FunctionChecker($stmt, $this->_source);
$function_checker->check(new Context());
} elseif ($stmt instanceof PhpParser\Node\Expr) {
$this->_checkExpression($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Stmt\InlineHTML) {
// do nothing
} elseif ($stmt instanceof PhpParser\Node\Stmt\Use_) {
foreach ($stmt->uses as $use) {
$this->_aliased_classes[$use->alias] = implode('\\', $use->name->parts);
}
} elseif ($stmt instanceof PhpParser\Node\Stmt\Global_) {
foreach ($stmt->vars as $var) {
if ($var instanceof PhpParser\Node\Expr\Variable) {
if (is_string($var->name)) {
$context->vars_in_scope[$var->name] = Type::getMixed();
$context->vars_possibly_in_scope[$var->name] = true;
} else {
$this->_checkExpression($var, $context);
}
}
}
2016-01-26 20:11:56 +01:00
} elseif ($stmt instanceof PhpParser\Node\Stmt\Property) {
foreach ($stmt->props as $prop) {
if ($prop->default) {
$this->_checkExpression($prop->default, $context);
2016-06-24 00:45:46 +02:00
if (isset($prop->default->inferredType)) {
2016-08-07 02:27:13 +02:00
if ($this->_checkPropertyAssignment($prop, $prop->name, $prop->default->inferredType, $context) === false) {
2016-06-24 00:45:46 +02:00
return false;
}
}
2016-01-26 20:11:56 +01:00
}
}
} elseif ($stmt instanceof PhpParser\Node\Stmt\ClassConst) {
2016-07-23 16:58:53 +02:00
foreach ($stmt->consts as $const) {
self::$_class_consts[$this->_absolute_class . '::' . $const->name] = true;
}
2016-01-26 20:11:56 +01:00
} elseif ($stmt instanceof PhpParser\Node\Stmt\Class_) {
2016-03-23 18:05:25 +01:00
(new ClassChecker($stmt, $this->_source, $stmt->name))->check();
2016-03-14 17:38:08 +01:00
} elseif ($stmt instanceof PhpParser\Node\Stmt\Nop) {
// do nothing
2016-04-17 16:25:43 +02:00
} elseif ($stmt instanceof PhpParser\Node\Stmt\Namespace_) {
if ($this->_namespace) {
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new InvalidNamespace('Cannot redeclare namespace', $this->_require_file_name, $stmt->getLine()),
$this->_suppressed_issues
)) {
return false;
}
2016-04-17 16:25:43 +02:00
}
$namespace_checker = new NamespaceChecker($stmt, $this->_source);
$namespace_checker->check(true);
} else {
var_dump('Unrecognised statement in ' . $this->_file_name);
var_dump($stmt);
}
}
}
/**
* System of type substitution and deletion
*
* for example
*
* x: A|null
*
* if (x)
* (x: A)
* x = B -- effects: remove A from the type of x, add B
* else
* (x: null)
* x = C -- effects: remove null from the type of x, add C
*
*
* x: A|null
*
* if (!x)
* (x: null)
* throw new Exception -- effects: remove null from the type of x
*
*
* @param PhpParser\Node\Stmt\If_ $stmt
* @param array &$context->vars_in_scope
* @param array &$context->vars_possibly_in_scope
* @param array &$for_vars_possibly_in_scope
* @return null|false
*/
protected function _checkIf(PhpParser\Node\Stmt\If_ $stmt, Context $context, array &$for_vars_possibly_in_scope)
{
$if_context = clone $context;
// we need to clone the current context so our ongoing updates to $context don't mess with elseif/else blocks
2016-07-25 21:05:58 +02:00
$original_context = clone $context;
if ($this->_checkCondition($stmt->cond, $if_context) === false) {
return false;
}
2016-06-28 21:28:05 +02:00
if ($stmt->cond instanceof PhpParser\Node\Expr\BinaryOp) {
$reconcilable_if_types = $this->_type_checker->getReconcilableTypeAssertions($stmt->cond, true);
$negatable_if_types = $this->_type_checker->getNegatableTypeAssertions($stmt->cond, true);
}
else {
$reconcilable_if_types = $negatable_if_types = $this->_type_checker->getTypeAssertions($stmt->cond, true);
}
2016-06-30 00:30:27 +02:00
$has_ending_statments = ScopeChecker::doesReturnOrThrow($stmt->stmts);
$has_leaving_statments = $has_ending_statments || ScopeChecker::doesLeaveBlock($stmt->stmts, true, true);
2016-06-13 07:48:29 +02:00
// we only need to negate the if types if there are throw/return/break/continue or else/elseif blocks
$need_to_negate_if_types = $has_leaving_statments || $stmt->elseifs || $stmt->else;
2016-06-28 21:28:05 +02:00
$negated_types = $negatable_if_types && $need_to_negate_if_types
? TypeChecker::negateTypes($negatable_if_types)
2016-06-13 07:48:29 +02:00
: [];
2016-06-15 01:22:29 +02:00
$negated_if_types = $negated_types;
2016-06-13 07:48:29 +02:00
// if the if has an || in the conditional, we cannot easily reason about it
2016-06-28 21:28:05 +02:00
if ($reconcilable_if_types) {
$if_vars_in_scope_reconciled =
TypeChecker::reconcileKeyedTypes(
$reconcilable_if_types,
$if_context->vars_in_scope,
$this->_file_name,
$stmt->getLine()
);
if ($if_vars_in_scope_reconciled === false) {
return false;
}
2016-06-28 21:28:05 +02:00
$if_context->vars_in_scope = $if_vars_in_scope_reconciled;
2016-06-28 21:28:05 +02:00
$if_context->vars_possibly_in_scope = array_merge($reconcilable_if_types, $if_context->vars_possibly_in_scope);
}
$old_if_context = clone $if_context;
2016-06-20 22:18:31 +02:00
$context->vars_possibly_in_scope = array_merge($if_context->vars_possibly_in_scope, $context->vars_possibly_in_scope);
2016-04-04 06:17:19 +02:00
if ($this->check($stmt->stmts, $if_context, $for_vars_possibly_in_scope) === false) {
return false;
}
$new_vars = null;
$new_vars_possibly_in_scope = [];
2016-04-04 06:17:19 +02:00
$redefined_vars = null;
$possibly_redefined_vars = [];
2016-04-27 00:17:47 +02:00
$updated_vars = [];
$mic_drop = false;
if (count($stmt->stmts)) {
if (!$has_leaving_statments) {
$new_vars = array_diff_key($if_context->vars_in_scope, $context->vars_in_scope);
2016-04-30 20:14:22 +02:00
$redefined_vars = Context::getRedefinedVars($context, $if_context);
2016-04-30 20:14:22 +02:00
$possibly_redefined_vars = $redefined_vars;
}
elseif (!$stmt->else && !$stmt->elseifs && $negated_types) {
$context_vars_reconciled = TypeChecker::reconcileKeyedTypes($negated_types, $context->vars_in_scope, $this->_file_name, $stmt->getLine());
if ($context_vars_reconciled === false) {
return false;
}
$context->vars_in_scope = $context_vars_reconciled;
$mic_drop = true;
}
// update the parent context as necessary, but only if we can safely reason about type negation
2016-06-28 21:28:05 +02:00
if ($negatable_if_types && !$mic_drop) {
$context->update($old_if_context, $if_context, $has_leaving_statments, $updated_vars);
2016-04-27 00:17:47 +02:00
}
if (!$has_ending_statments) {
$vars = array_diff_key($if_context->vars_possibly_in_scope, $context->vars_possibly_in_scope);
2016-05-16 22:12:02 +02:00
// if we're leaving this block, add vars to outer for loop scope
if ($has_leaving_statments) {
$for_vars_possibly_in_scope = array_merge($for_vars_possibly_in_scope, $vars);
}
else {
$new_vars_possibly_in_scope = $vars;
}
}
}
foreach ($stmt->elseifs as $elseif) {
$elseif_context = clone $original_context;
if ($negated_types) {
$elseif_vars_reconciled = TypeChecker::reconcileKeyedTypes($negated_types, $elseif_context->vars_in_scope, $this->_file_name, $stmt->getLine());
if ($elseif_vars_reconciled === false) {
return false;
}
$elseif_context->vars_in_scope = $elseif_vars_reconciled;
}
2016-06-28 21:28:05 +02:00
if ($elseif->cond instanceof PhpParser\Node\Expr\BinaryOp) {
$reconcilable_elseif_types = $this->_type_checker->getReconcilableTypeAssertions($elseif->cond, true);
$negatable_elseif_types = $this->_type_checker->getNegatableTypeAssertions($elseif->cond, true);
}
else {
$reconcilable_elseif_types = $negatable_elseif_types = $this->_type_checker->getTypeAssertions($elseif->cond, true);
}
2016-06-28 21:28:05 +02:00
$negated_elseif_types = $negatable_elseif_types
? TypeChecker::negateTypes($negatable_elseif_types)
: [];
$negated_types = array_merge($negated_types, $negated_elseif_types);
// if the elseif has an || in the conditional, we cannot easily reason about it
if (!($elseif->cond instanceof PhpParser\Node\Expr\BinaryOp) || !self::_containsBooleanOr($elseif->cond)) {
2016-06-28 21:28:05 +02:00
$elseif_vars_reconciled = TypeChecker::reconcileKeyedTypes($reconcilable_elseif_types, $elseif_context->vars_in_scope, $this->_file_name, $stmt->getLine());
if ($elseif_vars_reconciled === false) {
return false;
}
$elseif_context->vars_in_scope = $elseif_vars_reconciled;
}
// check the elseif
if ($this->_checkCondition($elseif->cond, $elseif_context) === false) {
return false;
}
$old_elseif_context = clone $elseif_context;
if ($this->check($elseif->stmts, $elseif_context, $for_vars_possibly_in_scope) === false) {
return false;
}
if (count($elseif->stmts)) {
$has_leaving_statements = ScopeChecker::doesLeaveBlock($elseif->stmts, true, true);
if (!$has_leaving_statements) {
// update the parent context as necessary
$elseif_redefined_vars = Context::getRedefinedVars($original_context, $elseif_context);
2016-04-04 06:17:19 +02:00
if ($redefined_vars === null) {
$redefined_vars = $elseif_redefined_vars;
2016-04-30 20:14:22 +02:00
$possibly_redefined_vars = $redefined_vars;
2016-04-04 06:17:19 +02:00
}
else {
foreach ($redefined_vars as $redefined_var => $type) {
if (!isset($elseif_redefined_vars[$redefined_var])) {
unset($redefined_vars[$redefined_var]);
}
else {
2016-06-17 22:05:28 +02:00
$redefined_vars[$redefined_var] = Type::combineUnionTypes($elseif_redefined_vars[$redefined_var], $type);
}
2016-04-04 06:17:19 +02:00
}
2016-04-30 20:14:22 +02:00
foreach ($elseif_redefined_vars as $var => $type) {
2016-06-16 02:16:40 +02:00
if ($type->isMixed()) {
$possibly_redefined_vars[$var] = $type;
2016-04-30 20:14:22 +02:00
}
else if (isset($possibly_redefined_vars[$var])) {
2016-06-16 02:16:40 +02:00
$possibly_redefined_vars[$var] = Type::combineUnionTypes($type, $possibly_redefined_vars[$var]);
2016-04-30 20:14:22 +02:00
}
else {
$possibly_redefined_vars[$var] = $type;
}
}
2016-04-04 06:17:19 +02:00
}
if ($new_vars === null) {
$new_vars = array_diff_key($elseif_context->vars_in_scope, $context->vars_in_scope);
2016-04-04 06:17:19 +02:00
}
else {
foreach ($new_vars as $new_var => $type) {
if (!isset($elseif_context->vars_in_scope[$new_var])) {
unset($new_vars[$new_var]);
}
2016-06-16 07:19:52 +02:00
else {
$new_vars[$new_var] = Type::combineUnionTypes($type, $elseif_context->vars_in_scope[$new_var]);
2016-06-16 07:19:52 +02:00
}
}
}
}
2016-06-28 21:28:05 +02:00
if ($negatable_if_types) {
$context->update($old_elseif_context, $elseif_context, $has_leaving_statments, $updated_vars);
2016-04-27 00:17:47 +02:00
}
// has a return/throw at end
2016-06-20 22:18:31 +02:00
$has_ending_statments = ScopeChecker::doesReturnOrThrow($elseif->stmts);
if (!$has_ending_statments) {
$vars = array_diff_key($elseif_context->vars_possibly_in_scope, $context->vars_possibly_in_scope);
2016-05-16 22:12:02 +02:00
// if we're leaving this block, add vars to outer for loop scope
if ($has_leaving_statements) {
$for_vars_possibly_in_scope = array_merge($vars, $for_vars_possibly_in_scope);
}
else {
$new_vars_possibly_in_scope = array_merge($vars, $new_vars_possibly_in_scope);
}
}
}
}
if ($stmt->else) {
$else_context = clone $original_context;
if ($negated_types) {
$else_vars_reconciled = TypeChecker::reconcileKeyedTypes($negated_types, $else_context->vars_in_scope, $this->_file_name, $stmt->getLine());
if ($else_vars_reconciled === false) {
return false;
}
$else_context->vars_in_scope = $else_vars_reconciled;
}
$old_else_context = clone $else_context;
2016-04-04 06:17:19 +02:00
if ($this->check($stmt->else->stmts, $else_context, $for_vars_possibly_in_scope) === false) {
return false;
}
if (count($stmt->else->stmts)) {
$has_leaving_statements = ScopeChecker::doesLeaveBlock($stmt->else->stmts, true, true);
2016-04-04 06:17:19 +02:00
// if it doesn't end in a return
if (!$has_leaving_statements) {
2016-07-25 21:05:58 +02:00
/** @var Context $original_context */
$else_redefined_vars = Context::getRedefinedVars($original_context, $else_context);
2016-04-04 06:17:19 +02:00
if ($redefined_vars === null) {
$redefined_vars = $else_redefined_vars;
2016-04-30 20:14:22 +02:00
$possibly_redefined_vars = $redefined_vars;
2016-04-04 06:17:19 +02:00
}
else {
foreach ($redefined_vars as $redefined_var => $type) {
if (!isset($else_redefined_vars[$redefined_var])) {
unset($redefined_vars[$redefined_var]);
}
else {
2016-06-17 22:05:28 +02:00
$redefined_vars[$redefined_var] = Type::combineUnionTypes($else_redefined_vars[$redefined_var], $type);
}
2016-04-04 06:17:19 +02:00
}
2016-04-30 20:14:22 +02:00
foreach ($else_redefined_vars as $var => $type) {
2016-06-16 02:16:40 +02:00
if ($type->isMixed()) {
$possibly_redefined_vars[$var] = $type;
2016-04-30 20:14:22 +02:00
}
else if (isset($possibly_redefined_vars[$var])) {
2016-06-16 02:16:40 +02:00
$possibly_redefined_vars[$var] = Type::combineUnionTypes($type, $possibly_redefined_vars[$var]);
2016-04-30 20:14:22 +02:00
}
else {
$possibly_redefined_vars[$var] = $type;
}
}
2016-04-04 06:17:19 +02:00
}
if ($new_vars === null) {
$new_vars = array_diff_key($else_context->vars_in_scope, $context->vars_in_scope);
2016-04-04 06:17:19 +02:00
}
else {
foreach ($new_vars as $new_var => $type) {
if (!isset($else_context->vars_in_scope[$new_var])) {
unset($new_vars[$new_var]);
}
2016-06-16 07:19:52 +02:00
else {
$new_vars[$new_var] = Type::combineUnionTypes($type, $else_context->vars_in_scope[$new_var]);
2016-06-16 07:19:52 +02:00
}
}
}
}
// update the parent context as necessary
2016-06-28 21:28:05 +02:00
if ($negatable_if_types) {
$context->update($old_else_context, $else_context, $has_leaving_statments, $updated_vars);
}
// has a return/throw at end
2016-06-20 22:18:31 +02:00
$has_ending_statments = ScopeChecker::doesReturnOrThrow($stmt->else->stmts);
if (!$has_ending_statments) {
$vars = array_diff_key($else_context->vars_possibly_in_scope, $context->vars_possibly_in_scope);
if ($has_leaving_statements) {
$for_vars_possibly_in_scope = array_merge($vars, $for_vars_possibly_in_scope);
}
else {
$new_vars_possibly_in_scope = array_merge($vars, $new_vars_possibly_in_scope);
}
2016-04-04 06:17:19 +02:00
}
}
}
if ($new_vars) {
$context->vars_in_scope = array_merge($context->vars_in_scope, $new_vars);
}
$context->vars_possibly_in_scope = array_merge($context->vars_possibly_in_scope, $new_vars_possibly_in_scope);
// vars can only be redefined if there was an else (defined in every block)
if ($stmt->else && $redefined_vars) {
foreach ($redefined_vars as $var => $type) {
$context->vars_in_scope[$var] = $type;
$updated_vars[$var] = true;
}
}
2016-04-30 20:14:22 +02:00
if ($possibly_redefined_vars) {
foreach ($possibly_redefined_vars as $var => $type) {
if (isset($context->vars_in_scope[$var]) && !isset($updated_vars[$var])) {
$context->vars_in_scope[$var] = Type::combineUnionTypes($context->vars_in_scope[$var], $type);
2016-04-27 00:17:47 +02:00
}
}
}
}
protected function _checkCondition(PhpParser\Node\Expr $stmt, Context $context)
{
return $this->_checkExpression($stmt, $context);
}
protected function _checkStatic(PhpParser\Node\Stmt\Static_ $stmt, Context $context)
{
foreach ($stmt->vars as $var) {
if ($var instanceof PhpParser\Node\Stmt\StaticVar) {
if (is_string($var->name)) {
if ($this->_check_variables) {
$context->vars_in_scope[$var->name] = Type::getMixed();
$context->vars_possibly_in_scope[$var->name] = true;
$this->registerVariable($var->name, $var->getLine());
}
} else {
if ($this->_checkExpression($var->name, $context) === false) {
return false;
}
}
if ($var->default) {
if ($this->_checkExpression($var->default, $context) === false) {
return false;
}
}
} else {
if ($this->_checkExpression($var, $context) === false) {
return false;
}
}
}
}
2016-04-27 00:42:48 +02:00
/**
* @return false|null
2016-04-27 00:42:48 +02:00
*/
protected function _checkExpression(PhpParser\Node\Expr $stmt, Context $context, $array_assignment = false)
{
2016-06-18 20:45:55 +02:00
foreach (Config::getInstance()->getPlugins() as $plugin) {
if ($plugin->checkExpression($stmt, $context, $this->_file_name) === false) {
2016-06-18 20:45:55 +02:00
return false;
}
}
if ($stmt instanceof PhpParser\Node\Expr\Variable) {
return $this->_checkVariable($stmt, $context, null, -1, $array_assignment);
} elseif ($stmt instanceof PhpParser\Node\Expr\Assign) {
return $this->_checkAssignment($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\AssignOp) {
return $this->_checkAssignmentOperation($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\MethodCall) {
return $this->_checkMethodCall($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\StaticCall) {
return $this->_checkStaticCall($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\ConstFetch) {
return $this->_checkConstFetch($stmt);
} elseif ($stmt instanceof PhpParser\Node\Scalar\String_) {
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getString();
} elseif ($stmt instanceof PhpParser\Node\Scalar\EncapsedStringPart) {
// do nothing
} elseif ($stmt instanceof PhpParser\Node\Scalar\MagicConst) {
// do nothing
} elseif ($stmt instanceof PhpParser\Node\Scalar\LNumber) {
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getInt();
} elseif ($stmt instanceof PhpParser\Node\Scalar\DNumber) {
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getFloat();
} elseif ($stmt instanceof PhpParser\Node\Expr\UnaryMinus) {
return $this->_checkExpression($stmt->expr, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\UnaryPlus) {
return $this->_checkExpression($stmt->expr, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\Isset_) {
foreach ($stmt->vars as $isset_var) {
if ($isset_var instanceof PhpParser\Node\Expr\PropertyFetch &&
$isset_var->var instanceof PhpParser\Node\Expr\Variable &&
$isset_var->var->name === 'this' &&
is_string($isset_var->name)
) {
2016-06-16 02:16:40 +02:00
$var_id = 'this->' . $isset_var->name;
$context->vars_in_scope[$var_id] = Type::getMixed();
$context->vars_possibly_in_scope[$var_id] = true;
}
}
} elseif ($stmt instanceof PhpParser\Node\Expr\ClassConstFetch) {
return $this->_checkClassConstFetch($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\PropertyFetch) {
return $this->_checkPropertyFetch($stmt, $context, $array_assignment);
} elseif ($stmt instanceof PhpParser\Node\Expr\StaticPropertyFetch) {
return $this->_checkStaticPropertyFetch($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\BitwiseNot) {
return $this->_checkExpression($stmt->expr, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\BinaryOp) {
return $this->_checkBinaryOp($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\PostInc) {
return $this->_checkExpression($stmt->var, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\PostDec) {
return $this->_checkExpression($stmt->var, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\PreInc) {
return $this->_checkExpression($stmt->var, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\PreDec) {
return $this->_checkExpression($stmt->var, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\New_) {
return $this->_checkNew($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\Array_) {
return $this->_checkArray($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Scalar\Encapsed) {
return $this->_checkEncapsulatedString($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\FuncCall) {
return $this->_checkFunctionCall($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\Ternary) {
return $this->_checkTernary($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\BooleanNot) {
return $this->_checkBooleanNot($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\Empty_) {
return $this->_checkEmpty($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\Closure) {
$closure_checker = new ClosureChecker($stmt, $this->_source);
if ($this->_checkClosureUses($stmt, $context) === false) {
return false;
}
2016-01-26 20:11:56 +01:00
$use_context = new Context();
if (!$this->_is_static) {
$this_class = ClassChecker::getThisClass() && ClassChecker::classExtends(ClassChecker::getThisClass(), $this->_absolute_class) ?
2016-05-20 06:24:26 +02:00
ClassChecker::getThisClass() :
$this->_absolute_class;
2016-06-16 02:16:40 +02:00
2016-06-20 18:38:31 +02:00
if ($this_class) {
$use_context->vars_in_scope['this'] = new Type\Union([new Type\Atomic($this_class)]);
}
}
foreach ($context->vars_in_scope as $var => $type) {
if (strpos($var, 'this->') === 0) {
$use_context->vars_in_scope[$var] = $type;
}
}
foreach ($context->vars_possibly_in_scope as $var => $type) {
if (strpos($var, 'this->') === 0) {
$use_context->var_possibly_in_scope[$var] = true;
}
}
foreach ($stmt->uses as $use) {
$use_context->vars_in_scope[$use->var] = isset($context->vars_in_scope[$use->var]) ? $context->vars_in_scope[$use->var] : Type::getMixed();
$use_context->vars_possibly_in_scope[$use->var] = true;
}
$closure_checker->check($use_context, $this->_check_methods);
} elseif ($stmt instanceof PhpParser\Node\Expr\ArrayDimFetch) {
return $this->_checkArrayAccess($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\Cast\Int_) {
if ($this->_checkExpression($stmt->expr, $context) === false) {
return false;
}
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getInt();
} elseif ($stmt instanceof PhpParser\Node\Expr\Cast\Double) {
if ($this->_checkExpression($stmt->expr, $context) === false) {
return false;
}
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getDouble();
} elseif ($stmt instanceof PhpParser\Node\Expr\Cast\Bool_) {
if ($this->_checkExpression($stmt->expr, $context) === false) {
return false;
}
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getBool();
} elseif ($stmt instanceof PhpParser\Node\Expr\Cast\String_) {
if ($this->_checkExpression($stmt->expr, $context) === false) {
return false;
}
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getString();
} elseif ($stmt instanceof PhpParser\Node\Expr\Cast\Object_) {
if ($this->_checkExpression($stmt->expr, $context) === false) {
return false;
}
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getObject();
} elseif ($stmt instanceof PhpParser\Node\Expr\Cast\Array_) {
if ($this->_checkExpression($stmt->expr, $context) === false) {
return false;
}
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getArray();
} elseif ($stmt instanceof PhpParser\Node\Expr\Clone_) {
if ($this->_checkExpression($stmt->expr, $context) === false) {
return false;
}
2016-06-16 18:04:55 +02:00
if (property_exists($stmt->expr, 'inferredType')) {
$stmt->inferredType = $stmt->expr->inferredType;
2016-05-06 03:20:15 +02:00
}
} elseif ($stmt instanceof PhpParser\Node\Expr\Instanceof_) {
if ($this->_checkExpression($stmt->expr, $context) === false) {
return false;
}
if ($stmt->class instanceof PhpParser\Node\Name && !in_array($stmt->class->parts[0], ['self', 'static', 'parent'])) {
if ($this->_check_classes) {
if (ClassChecker::checkClassName($stmt->class, $this->_namespace, $this->_aliased_classes, $this->_file_name, $this->_suppressed_issues) === false) {
return false;
}
}
}
} elseif ($stmt instanceof PhpParser\Node\Expr\Exit_) {
// do nothing
} elseif ($stmt instanceof PhpParser\Node\Expr\Include_) {
2016-07-25 21:05:58 +02:00
$this->_checkInclude($stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Expr\Eval_) {
$this->_check_classes = false;
$this->_check_variables = false;
if ($this->_checkExpression($stmt->expr, $context) === false) {
return false;
}
} elseif ($stmt instanceof PhpParser\Node\Expr\AssignRef) {
if ($stmt->var instanceof PhpParser\Node\Expr\Variable) {
$context->vars_in_scope[$stmt->var->name] = Type::getMixed();
$context->vars_possibly_in_scope[$stmt->var->name] = true;
$this->registerVariable($stmt->var->name, $stmt->var->getLine());
} else {
if ($this->_checkExpression($stmt->var, $context) === false) {
return false;
}
}
if ($this->_checkExpression($stmt->expr, $context) === false) {
return false;
}
} elseif ($stmt instanceof PhpParser\Node\Expr\ErrorSuppress) {
// do nothing
} elseif ($stmt instanceof PhpParser\Node\Expr\ShellExec) {
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new ForbiddenCode('Use of shell_exec', $this->_file_name, $stmt->getLine()),
$this->_suppressed_issues
)) {
return false;
}
} elseif ($stmt instanceof PhpParser\Node\Expr\Print_) {
if ($this->_checkExpression($stmt->expr, $context) === false) {
return false;
}
} else {
var_dump('Unrecognised expression in ' . $this->_file_name);
var_dump($stmt);
}
}
2016-04-27 00:42:48 +02:00
/**
* @return false|null
2016-04-27 00:42:48 +02:00
*/
protected function _checkVariable(PhpParser\Node\Expr\Variable $stmt, Context $context, $method_id = null, $argument_offset = -1, $array_assignment = false)
{
if ($this->_is_static && $stmt->name === 'this') {
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new InvalidStaticVariable('Invalid reference to $this in a static context', $this->_file_name, $stmt->getLine()),
$this->_suppressed_issues
)) {
return false;
}
}
if (!$this->_check_variables) {
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getMixed();
2016-06-27 20:30:33 +02:00
if (is_string($stmt->name) && !isset($context->vars_in_scope[$stmt->name])) {
$context->vars_in_scope[$stmt->name] = Type::getMixed();
$context->vars_possibly_in_scope[$stmt->name] = true;
}
return;
}
if (in_array($stmt->name, ['_SERVER', '_GET', '_POST', '_COOKIE', '_REQUEST', '_FILES', '_ENV', 'GLOBALS', 'argv'])) {
return;
}
if (!is_string($stmt->name)) {
return $this->_checkExpression($stmt->name, $context);
}
if ($method_id && isset($context->vars_in_scope[$stmt->name]) && !$context->vars_in_scope[$stmt->name]->isMixed()) {
if ($this->_checkFunctionArgumentType($context->vars_in_scope[$stmt->name], $method_id, $argument_offset, $this->_file_name, $stmt->getLine()) === false) {
return false;
}
}
if ($stmt->name === 'this') {
return;
}
if ($method_id && $this->_isPassedByReference($method_id, $argument_offset)) {
$this->_assignByRefParam($stmt, $method_id, $context);
return;
2016-05-10 17:46:36 +02:00
}
$var_name = $stmt->name;
2016-05-10 17:46:36 +02:00
if (!isset($context->vars_in_scope[$var_name])) {
if (!isset($context->vars_possibly_in_scope[$var_name]) || !isset($this->_all_vars[$var_name])) {
2016-06-15 01:22:29 +02:00
if ($array_assignment) {
// if we're in an array assignment, let's assign the variable
// because PHP allows it
$context->vars_in_scope[$var_name] = Type::getArray();
$context->vars_possibly_in_scope[$var_name] = true;
2016-06-15 01:22:29 +02:00
$this->registerVariable($var_name, $stmt->getLine());
}
else {
IssueBuffer::add(
2016-06-15 01:22:29 +02:00
new UndefinedVariable('Cannot find referenced variable $' . $var_name, $this->_file_name, $stmt->getLine())
);
return false;
2016-05-10 17:46:36 +02:00
}
}
if (isset($this->_all_vars[$var_name]) && !isset($this->_warn_vars[$var_name])) {
$this->_warn_vars[$var_name] = true;
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new PossiblyUndefinedVariable(
'Possibly undefined variable $' . $var_name .', first seen on line ' . $this->_all_vars[$var_name],
$this->_file_name,
$stmt->getLine()
),
$this->_suppressed_issues
)) {
return false;
}
}
2016-01-26 20:11:56 +01:00
} else {
$stmt->inferredType = $context->vars_in_scope[$var_name];
2016-04-30 20:14:22 +02:00
}
}
protected function _assignByRefParam(PhpParser\Node\Expr $stmt, $method_id, Context $context)
{
2016-05-10 17:46:36 +02:00
if ($stmt instanceof PhpParser\Node\Expr\Variable) {
$property_id = $stmt->name;
}
else if ($stmt instanceof PhpParser\Node\Expr\PropertyFetch && $stmt->var->name === 'this') {
$property_id = $stmt->var->name . '->' . $stmt->name;
}
else {
throw new \InvalidArgumentException('Bad property passed to _checkMethodParam');
}
2016-04-30 20:14:22 +02:00
if (!isset($context->vars_in_scope[$property_id])) {
$context->vars_possibly_in_scope[$property_id] = true;
$this->registerVariable($property_id, $stmt->getLine());
2016-05-10 17:46:36 +02:00
if ($stmt instanceof PhpParser\Node\Expr\PropertyFetch && $this->_source->getMethodId()) {
$this_method_id = $this->_source->getMethodId();
if (!isset(self::$_this_assignments[$this_method_id])) {
self::$_this_assignments[$this_method_id] = [];
}
2016-01-26 20:11:56 +01:00
2016-06-16 02:16:40 +02:00
self::$_this_assignments[$this_method_id][$stmt->name] = Type::getMixed();
}
}
$context->vars_in_scope[$property_id] = Type::getMixed();
}
protected function _checkPropertyFetch(PhpParser\Node\Expr\PropertyFetch $stmt, Context $context, $array_assignment = false)
{
if (!is_string($stmt->name)) {
if ($this->_checkExpression($stmt->name, $context) === false) {
return false;
}
}
if ($stmt->var instanceof PhpParser\Node\Expr\Variable) {
if ($this->_checkVariable($stmt->var, $context) === false) {
return false;
}
2016-08-07 02:27:13 +02:00
$var_name = is_string($stmt->name) ? $stmt->name : null;
$var_id = self::getVarId($stmt);
$stmt_var_type = null;
if (isset($context->vars_in_scope[$var_id])) {
// we don't need to check anything
$stmt->inferredType = $context->vars_in_scope[$var_id];
return;
}
if (isset($context->vars_in_scope[$stmt->var->name])) {
$stmt_var_type = $context->vars_in_scope[$stmt->var->name];
}
elseif (isset($stmt->var->inferredType)) {
$stmt_var_type = $stmt->var->inferredType;
}
if ($stmt_var_type) {
if (!$stmt_var_type->isMixed()) {
if ($stmt_var_type->isNull()) {
if (IssueBuffer::accepts(
new NullReference(
2016-08-07 02:27:13 +02:00
'Cannot get property on null variable $' . $var_id,
$this->_file_name,
$stmt->getLine()
),
$this->_suppressed_issues
)) {
return false;
}
return;
}
if ($stmt_var_type->isNullable()) {
if (IssueBuffer::accepts(
new NullPropertyFetch(
'Cannot get property on possibly null variable $' . $var_id,
$this->_file_name,
$stmt->getLine()
),
$this->_suppressed_issues
)) {
return false;
}
2016-08-07 02:27:13 +02:00
$stmt->inferredType = Type::getNull();
}
2016-08-07 02:27:13 +02:00
if ($stmt_var_type->isObjectType() && is_string($stmt->name)) {
foreach ($stmt_var_type->types as $lhs_type_part) {
if ($lhs_type_part->isNull()) {
continue;
}
2016-08-07 19:58:46 +02:00
// stdClass and SimpleXMLElement are special cases where we cannot infer the return types
// but we don't want to throw an error
// Hack has a similar issue: https://github.com/facebook/hhvm/issues/5164
if ($lhs_type_part->isObject() || $lhs_type_part->value === 'stdClass' || $lhs_type_part->value === 'SimpleXMLElement') {
2016-08-07 02:27:13 +02:00
$stmt->inferredType = Type::getMixed();
continue;
}
2016-08-07 02:27:13 +02:00
if (!$lhs_type_part->isObjectType()) {
// @todo InvalidPropertyFetch
continue;
}
2016-08-07 02:27:13 +02:00
if (method_exists((string) $lhs_type_part, '__get')) {
continue;
}
2016-08-07 17:35:27 +02:00
if (!ClassChecker::classExists($lhs_type_part->value)) {
if (ClassChecker::interfaceExists($lhs_type_part->value)) {
if (IssueBuffer::accepts(
new NoInterfaceProperties(
'Interfaces cannot have properties',
$this->_file_name,
$stmt->getLine()
),
$this->_suppressed_issues
)) {
return false;
}
return;
}
if (IssueBuffer::accepts(
new UndefinedClass(
'Cannot get properties of undefined class ' . $lhs_type_part->value,
$this->_file_name,
$stmt->getLine()
),
$this->_suppressed_issues
)) {
return false;
}
return;
}
2016-08-07 18:23:29 +02:00
if ($var_name === 'this' || $lhs_type_part->value === $this->_absolute_class) {
$class_visibility = \ReflectionProperty::IS_PRIVATE;
}
elseif (ClassChecker::classExtends($lhs_type_part->value, $this->_absolute_class)) {
$class_visibility = \ReflectionProperty::IS_PROTECTED;
}
else {
$class_visibility = \ReflectionProperty::IS_PUBLIC;
}
2016-08-07 02:27:13 +02:00
$class_properties = ClassChecker::getInstancePropertiesForClass(
2016-08-07 17:35:27 +02:00
$lhs_type_part->value,
2016-08-07 02:27:13 +02:00
$class_visibility
);
if (!$class_properties || !isset($class_properties[$stmt->name])) {
if (IssueBuffer::accepts(
new UndefinedProperty('$' . $var_id . ' is not defined', $this->_file_name, $stmt->getLine()),
$this->_suppressed_issues
)) {
return false;
}
return;
}
if (isset($stmt->inferredType)) {
$stmt->inferredType = Type::combineUnionTypes($class_properties[$stmt->name], $stmt->inferredType);
}
else {
$stmt->inferredType = $class_properties[$stmt->name];
}
}
2016-08-07 02:27:13 +02:00
return;
}
else {
// @todo ScalarPropertyFetch issue
}
}
else {
// @todo MixedPropertyFetch issue
}
}
return;
}
return $this->_checkExpression($stmt->var, $context);
}
protected function _checkThisPropertyFetch(PhpParser\Node\Expr\PropertyFetch $stmt, Context $context, $array_assignment = false)
{
$class_checker = $this->_source->getClassChecker();
if (!$class_checker) {
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new InvalidScope('Cannot use $this when not inside class', $this->_file_name, $stmt->getLine()),
$this->_suppressed_issues
)) {
return false;
}
}
2016-08-07 02:27:13 +02:00
}
/**
* @param PhpParser\Node\Expr\PropertyFetch|PhpParser\Node\Stmt\PropertyProperty $stmt
* @param string $prop_name
* @param Type\Union $assignment_type
* @param Context $context
* @param int $line_number
* @return false|null
*/
protected function _checkPropertyAssignment($stmt, $prop_name, Type\Union $assignment_type, Context $context)
{
$class_property_types = [];
2016-08-07 02:27:13 +02:00
if ($stmt instanceof PhpParser\Node\Stmt\PropertyProperty) {
$class_properties = ClassChecker::getInstancePropertiesForClass($this->_absolute_class, \ReflectionProperty::IS_PRIVATE);
2016-08-07 02:27:13 +02:00
if (!isset($class_properties[$prop_name])) {
// @todo UndefinedProperty
return;
}
2016-06-15 01:22:29 +02:00
2016-08-07 02:27:13 +02:00
$class_property_types[] = $class_properties[$prop_name];
2016-06-15 01:22:29 +02:00
2016-08-07 02:27:13 +02:00
$var_id = 'this->' . $prop_name;
}
2016-08-07 02:27:13 +02:00
else {
2016-08-07 18:23:29 +02:00
if (!isset($context->vars_in_scope[$stmt->var->name])) {
if ($this->_checkVariable($stmt->var, $context) === false) {
return false;
}
return;
}
2016-08-07 02:27:13 +02:00
$lhs_type = $context->vars_in_scope[$stmt->var->name];
2016-08-07 02:27:13 +02:00
if (!$lhs_type) {
2016-08-07 17:35:27 +02:00
var_dump('no class property types');
2016-08-07 02:27:13 +02:00
// @todo This shouldn't happen
return;
}
2016-06-24 00:45:46 +02:00
2016-08-07 02:27:13 +02:00
$var_id = self::getVarId($stmt);
2016-06-24 00:45:46 +02:00
2016-08-07 02:27:13 +02:00
if ($lhs_type->isMixed()) {
// @todo MixedAssignment
return;
}
2016-06-24 00:45:46 +02:00
2016-08-07 02:27:13 +02:00
if ($lhs_type->isNull()) {
// @todo NullPropertyAssignment
return;
}
2016-06-24 00:45:46 +02:00
2016-08-07 02:27:13 +02:00
if ($lhs_type->isNullable()) {
// @todo NullablePropertyAssignment
}
2016-08-07 17:35:27 +02:00
$has_regular_setter = false;
2016-08-07 02:27:13 +02:00
foreach ($lhs_type->types as $lhs_type_part) {
if ($lhs_type_part->isNull()) {
continue;
2016-06-24 00:45:46 +02:00
}
2016-08-07 17:35:27 +02:00
if (method_exists((string) $lhs_type_part, '__set')) {
continue;
}
$has_regular_setter = true;
2016-08-07 02:27:13 +02:00
if (!$lhs_type_part->isObjectType()) {
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
2016-06-24 00:45:46 +02:00
new InvalidPropertyAssignment(
2016-08-07 02:27:13 +02:00
'$' . $var_id . ' with possible non-object type \'' . $lhs_type_part . '\' cannot be assigned to',
2016-06-24 00:45:46 +02:00
$this->_file_name,
2016-08-07 02:27:13 +02:00
$stmt->getLine()
),
$this->_suppressed_issues
2016-06-24 00:45:46 +02:00
)) {
return false;
}
2016-08-07 02:27:13 +02:00
continue;
}
2016-08-07 17:35:27 +02:00
if ($lhs_type_part->isObject()) {
continue;
}
2016-08-07 18:23:29 +02:00
if ($lhs_type_part->value === 'stdClass') {
2016-08-07 17:35:27 +02:00
$class_property_types[] = new Type\Union([$lhs_type_part]);
2016-08-07 02:27:13 +02:00
continue;
}
2016-08-07 18:23:29 +02:00
if (self::isMock($lhs_type_part->value)) {
return;
}
if ($stmt->var->name === 'this' || $lhs_type_part->value === $this->_absolute_class) {
$class_visibility = \ReflectionProperty::IS_PRIVATE;
}
elseif (ClassChecker::classExtends($lhs_type_part->value, $this->_absolute_class)) {
$class_visibility = \ReflectionProperty::IS_PROTECTED;
}
else {
$class_visibility = \ReflectionProperty::IS_PUBLIC;
}
2016-08-07 02:27:13 +02:00
$class_properties = ClassChecker::getInstancePropertiesForClass(
(string) $lhs_type_part,
$class_visibility
);
if (!isset($class_properties[$prop_name])) {
// @todo UndefinedProperty
continue;
}
$class_property_types[] = $class_properties[$prop_name];
}
2016-08-07 17:35:27 +02:00
if (!$has_regular_setter) {
return;
}
}
if (count($class_property_types) === 1 && (string) $class_property_types[0] === 'stdClass') {
return;
2016-08-07 02:27:13 +02:00
}
if (!$class_property_types) {
2016-08-07 17:35:27 +02:00
if (IssueBuffer::accepts(
new MissingPropertyDeclaration(
'Missing property declaration for $' . $var_id,
$this->_file_name,
$stmt->getLine()
),
$this->_suppressed_issues
)) {
return false;
}
return;
}
if ($assignment_type->isMixed()) {
2016-08-07 02:27:13 +02:00
return;
}
foreach ($class_property_types as $class_property_type) {
if ($class_property_type->isMixed()) {
continue;
}
if (!$assignment_type->isIn($class_property_type)) {
if (IssueBuffer::accepts(
new InvalidPropertyAssignment(
'$' . $var_id . ' with declared type \'' . $class_property_type . '\' cannot be assigned type \'' . $assignment_type . '\'',
2016-08-07 02:27:13 +02:00
$this->_file_name,
$stmt->getLine()
),
$this->_suppressed_issues
)) {
return false;
2016-06-24 00:45:46 +02:00
}
}
}
}
protected function _checkNew(PhpParser\Node\Expr\New_ $stmt, Context $context)
{
$absolute_class = null;
if ($stmt->class instanceof PhpParser\Node\Name && !in_array($stmt->class->parts[0], ['self', 'static', 'parent'])) {
if ($this->_check_classes) {
if (ClassChecker::checkClassName($stmt->class, $this->_namespace, $this->_aliased_classes, $this->_file_name, $this->_suppressed_issues) === false) {
return false;
}
$absolute_class = ClassChecker::getAbsoluteClassFromName($stmt->class, $this->_namespace, $this->_aliased_classes);
2016-06-16 18:04:55 +02:00
$stmt->inferredType = new Type\Union([new Type\Atomic($absolute_class)]);
}
}
if ($absolute_class) {
if (method_exists($absolute_class, '__construct')) {
$method_id = $absolute_class . '::__construct';
if ($this->_checkMethodParams($stmt->args, $method_id, $context, $stmt->getLine()) === false) {
return false;
}
}
}
}
protected function _checkArray(PhpParser\Node\Expr\Array_ $stmt, Context $context)
{
// if the array is empty, this special type allows us to match any other array type against it
if (empty($stmt->items)) {
$stmt->inferredType = new Type\Union([new Type\Generic('array', [new Type\Union([new Type\Atomic('empty')])], true)]);
return;
}
foreach ($stmt->items as $item) {
if ($item->key) {
if ($this->_checkExpression($item->key, $context) === false) {
return false;
}
}
if ($this->_checkExpression($item->value, $context) === false) {
return false;
}
}
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getArray();
}
protected function _checkTryCatch(PhpParser\Node\Stmt\TryCatch $stmt, Context $context)
{
$this->check($stmt->stmts, $context);
2016-06-20 22:18:31 +02:00
// clone context for catches after running the try block, as
// we optimistically assume it only failed at the very end
$original_context = clone $context;
foreach ($stmt->catches as $catch) {
$catch_context = clone $original_context;
if ($catch->type) {
$catch_context->vars_in_scope[$catch->var] = new Type\Union([
new Type\Atomic(ClassChecker::getAbsoluteClassFromName($catch->type, $this->_namespace, $this->_aliased_classes))
]);
}
else {
$catch_context->vars_in_scope[$catch->var] = Type::getMixed();
}
$catch_context->vars_possibly_in_scope[$catch->var] = true;
$this->registerVariable($catch->var, $catch->getLine());
if ($this->_check_classes) {
if (ClassChecker::checkClassName($catch->type, $this->_namespace, $this->_aliased_classes, $this->_file_name, $this->_suppressed_issues) === false) {
return;
}
}
$this->check($catch->stmts, $catch_context);
if (!ScopeChecker::doesReturnOrThrow($catch->stmts)) {
2016-06-20 22:18:31 +02:00
foreach ($catch_context->vars_in_scope as $catch_var => $type) {
if ($catch->var !== $catch_var && isset($context->vars_in_scope[$catch_var]) && (string) $context->vars_in_scope[$catch_var] !== (string) $type) {
$context->vars_in_scope[$catch_var] = Type::combineUnionTypes($context->vars_in_scope[$catch_var], $type);
}
}
2016-06-20 22:18:31 +02:00
$context->vars_possibly_in_scope = array_merge($catch_context->vars_possibly_in_scope, $context->vars_possibly_in_scope);
}
}
if ($stmt->finallyStmts) {
$this->check($stmt->finallyStmts, $context);
}
}
protected function _checkFor(PhpParser\Node\Stmt\For_ $stmt, Context $context)
{
2016-06-20 07:05:44 +02:00
$for_context = clone $context;
$for_context->in_loop = true;
foreach ($stmt->init as $init) {
2016-06-20 07:05:44 +02:00
if ($this->_checkExpression($init, $for_context) === false) {
return false;
}
}
foreach ($stmt->cond as $condition) {
2016-06-20 07:05:44 +02:00
if ($this->_checkCondition($condition, $for_context) === false) {
return false;
}
}
foreach ($stmt->loop as $expr) {
2016-06-20 07:05:44 +02:00
if ($this->_checkExpression($expr, $for_context) === false) {
return false;
}
}
$this->check($stmt->stmts, $for_context, $for_context->vars_possibly_in_scope);
foreach ($context->vars_in_scope as $var => $type) {
2016-06-16 02:16:40 +02:00
if ($type->isMixed()) {
continue;
}
2016-06-20 07:05:44 +02:00
if ($for_context->vars_in_scope[$var]->isMixed()) {
$context->vars_in_scope[$var] = $for_context->vars_in_scope[$var];
2016-06-16 02:16:40 +02:00
}
2016-06-20 07:05:44 +02:00
if ((string) $for_context->vars_in_scope[$var] !== (string) $type) {
$context->vars_in_scope[$var] = Type::combineUnionTypes($context->vars_in_scope[$var], $for_context->vars_in_scope[$var]);
2016-05-06 03:20:15 +02:00
}
}
2016-06-20 18:38:31 +02:00
$context->vars_possibly_in_scope = array_merge($for_context->vars_possibly_in_scope, $context->vars_possibly_in_scope);
}
protected function _checkForeach(PhpParser\Node\Stmt\Foreach_ $stmt, Context $context)
{
if ($this->_checkExpression($stmt->expr, $context) === false) {
return false;
}
2016-06-20 18:38:31 +02:00
$foreach_context = clone $context;
$foreach_context->in_loop = true;
if ($stmt->keyVar) {
2016-06-20 18:38:31 +02:00
$foreach_context->vars_in_scope[$stmt->keyVar->name] = Type::getMixed();
$foreach_context->vars_possibly_in_scope[$stmt->keyVar->name] = true;
$this->registerVariable($stmt->keyVar->name, $stmt->getLine());
}
if ($stmt->valueVar) {
2016-04-12 01:13:50 +02:00
$value_type = null;
2016-06-17 22:05:28 +02:00
$var_id = self::getVarId($stmt->expr);
2016-06-15 01:22:29 +02:00
2016-07-10 22:09:09 +02:00
if (isset($stmt->expr->inferredType)) {
$iterator_type = $stmt->expr->inferredType;
}
elseif (isset($foreach_context->vars_in_scope[$var_id])) {
$iterator_type = $foreach_context->vars_in_scope[$var_id];
}
else {
$iterator_type = null;
}
if ($iterator_type) {
2016-06-15 01:22:29 +02:00
foreach ($iterator_type->types as $return_type) {
// if it's an empty array, we cannot iterate over it
if ((string) $return_type === 'array<empty>') {
continue;
}
2016-07-10 22:09:09 +02:00
if ($return_type instanceof Type\Generic) {
$value_type = $return_type->type_params[0];
}
2016-06-15 01:22:29 +02:00
switch ($return_type->value) {
case 'mixed':
case 'empty':
2016-07-10 22:09:09 +02:00
break;
case 'array':
break;
case 'null':
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new NullReference('Cannot iterate over ' . $return_type->value, $this->_file_name, $stmt->getLine()),
$this->_suppressed_issues
)) {
return false;
}
break;
case 'string':
case 'void':
case 'int':
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new InvalidIterator('Cannot iterate over ' . $return_type->value, $this->_file_name, $stmt->getLine()),
$this->_suppressed_issues
)) {
return false;
}
break;
2016-04-12 01:13:50 +02:00
default:
2016-07-10 22:09:09 +02:00
if (ClassChecker::classImplements($return_type->value, 'Iterator')) {
2016-07-19 01:04:51 +02:00
$iterator_method = $return_type->value . '::current';
$iterator_class_type = ClassMethodChecker::getMethodReturnTypes($iterator_method);
2016-07-10 22:09:09 +02:00
if ($iterator_class_type) {
2016-07-19 01:04:51 +02:00
$value_type = self::fleshOutReturnTypes($iterator_class_type, [], $iterator_method);
2016-07-10 22:09:09 +02:00
}
}
2016-06-15 01:22:29 +02:00
if ($return_type->value !== 'array' && $return_type->value !== 'Traversable' && $return_type->value !== $this->_class_name) {
if (ClassChecker::checkAbsoluteClassOrInterface($return_type->value, $this->_file_name, $stmt->getLine(), $this->_suppressed_issues) === false) {
return false;
}
}
2016-04-12 01:13:50 +02:00
}
}
}
2016-07-10 22:09:09 +02:00
if ($value_type && $value_type instanceof Type\Atomic) {
$value_type = new Type\Union([$value_type]);
}
2016-06-20 18:38:31 +02:00
$foreach_context->vars_in_scope[$stmt->valueVar->name] = $value_type ? $value_type : Type::getMixed();
$foreach_context->vars_possibly_in_scope[$stmt->valueVar->name] = true;
$this->registerVariable($stmt->valueVar->name, $stmt->getLine());
}
2016-07-25 21:05:58 +02:00
CommentChecker::getTypeFromComment((string) $stmt->getDocComment(), $foreach_context, $this->_source, null);
$this->check($stmt->stmts, $foreach_context, $foreach_context->vars_possibly_in_scope);
foreach ($context->vars_in_scope as $var => $type) {
2016-06-16 02:16:40 +02:00
if ($type->isMixed()) {
continue;
}
if ($foreach_context->vars_in_scope[$var]->isMixed()) {
2016-06-20 18:38:31 +02:00
$context->vars_in_scope[$var] = $foreach_context->vars_in_scope[$var];
2016-06-16 02:16:40 +02:00
}
if ((string) $foreach_context->vars_in_scope[$var] !== (string) $type) {
$context->vars_in_scope[$var] = Type::combineUnionTypes($context->vars_in_scope[$var], $foreach_context->vars_in_scope[$var]);
2016-05-06 03:20:15 +02:00
}
}
2016-06-20 18:38:31 +02:00
$context->vars_possibly_in_scope = array_merge($foreach_context->vars_possibly_in_scope, $context->vars_possibly_in_scope);
}
protected function _checkWhile(PhpParser\Node\Stmt\While_ $stmt, Context $context)
{
$while_context = clone $context;
2016-06-17 22:05:28 +02:00
if ($this->_checkCondition($stmt->cond, $while_context) === false) {
return false;
}
2016-05-06 03:20:15 +02:00
$while_types = $this->_type_checker->getTypeAssertions($stmt->cond, true);
// if the while has an or as the main component, we cannot safely reason about it
if ($stmt->cond instanceof PhpParser\Node\Expr\BinaryOp && self::_containsBooleanOr($stmt->cond)) {
2016-06-17 22:05:28 +02:00
// do nothing
2016-05-06 03:20:15 +02:00
}
else {
$while_vars_in_scope_reconciled = TypeChecker::reconcileKeyedTypes($while_types, $while_context->vars_in_scope, $this->_file_name, $stmt->getLine());
if ($while_vars_in_scope_reconciled === false) {
return false;
}
$while_context->vars_in_scope = $while_vars_in_scope_reconciled;
2016-05-06 03:20:15 +02:00
}
if ($this->check($stmt->stmts, $while_context) === false) {
return false;
}
2016-05-06 03:20:15 +02:00
foreach ($context->vars_in_scope as $var => $type) {
2016-06-16 02:16:40 +02:00
if ($type->isMixed()) {
continue;
}
if ($while_context->vars_in_scope[$var]->isMixed()) {
$context->vars_in_scope[$var] = $while_context->vars_in_scope[$var];
2016-06-16 02:16:40 +02:00
}
2016-06-20 22:18:31 +02:00
if ((string) $while_context->vars_in_scope[$var] !== (string) $type) {
$context->vars_in_scope[$var] = Type::combineUnionTypes($while_context->vars_in_scope[$var], $type);
2016-05-06 03:20:15 +02:00
}
}
2016-06-20 22:18:31 +02:00
$context->vars_possibly_in_scope = array_merge($context->vars_possibly_in_scope, $while_context->vars_possibly_in_scope);
}
protected function _checkDo(PhpParser\Node\Stmt\Do_ $stmt, Context $context)
{
2016-06-20 22:18:31 +02:00
// do not clone context for do, because it executes in current scope always
if ($this->check($stmt->stmts, $context) === false) {
return false;
}
2016-06-20 22:18:31 +02:00
return $this->_checkCondition($stmt->cond, $context);
}
protected function _checkBinaryOp(PhpParser\Node\Expr\BinaryOp $stmt, Context $context, $nesting = 0)
{
if ($stmt instanceof PhpParser\Node\Expr\BinaryOp\Concat && $nesting > 20) {
// ignore deeply-nested string concatenation
}
else if ($stmt instanceof PhpParser\Node\Expr\BinaryOp\BooleanAnd) {
$left_type_assertions = $this->_type_checker->getReconcilableTypeAssertions($stmt->left);
if ($this->_checkExpression($stmt->left, $context) === false) {
return false;
}
// while in an and, we allow scope to boil over to support
// statements of the form if ($x && $x->foo())
$op_vars_in_scope = TypeChecker::reconcileKeyedTypes($left_type_assertions, $context->vars_in_scope, $this->_file_name, $stmt->getLine());
if ($op_vars_in_scope === false) {
return false;
}
2016-06-20 22:18:31 +02:00
$op_context = clone $context;
$op_context->vars_in_scope = $op_vars_in_scope;
2016-06-20 22:18:31 +02:00
if ($this->_checkExpression($stmt->right, $op_context) === false) {
return false;
}
2016-06-20 22:18:31 +02:00
foreach ($op_context->vars_in_scope as $var => $type) {
if (!isset($context->vars_in_scope[$var])) {
$context->vars_in_scope[$var] = $type;
continue;
}
}
$context->vars_possibly_in_scope = array_merge($op_context->vars_possibly_in_scope, $context->vars_possibly_in_scope);
}
else if ($stmt instanceof PhpParser\Node\Expr\BinaryOp\BooleanOr) {
$left_type_assertions = $this->_type_checker->getNegatableTypeAssertions($stmt->left);
$negated_type_assertions = TypeChecker::negateTypes($left_type_assertions);
if ($this->_checkExpression($stmt->left, $context) === false) {
return false;
}
// while in an or, we allow scope to boil over to support
// statements of the form if ($x === null || $x->foo())
$op_vars_in_scope = TypeChecker::reconcileKeyedTypes($negated_type_assertions, $context->vars_in_scope, $this->_file_name, $stmt->getLine());
if ($op_vars_in_scope === false) {
return false;
}
2016-06-20 22:18:31 +02:00
$op_context = clone $context;
$op_context->vars_in_scope = $op_vars_in_scope;
2016-06-20 22:18:31 +02:00
if ($this->_checkExpression($stmt->right, $op_context) === false) {
return false;
}
2016-06-20 22:18:31 +02:00
$context->vars_possibly_in_scope = array_merge($op_context->vars_possibly_in_scope, $context->vars_possibly_in_scope);
}
else {
2016-04-27 00:17:47 +02:00
if ($stmt instanceof PhpParser\Node\Expr\BinaryOp\Concat) {
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getString();
2016-04-27 00:17:47 +02:00
}
if ($stmt->left instanceof PhpParser\Node\Expr\BinaryOp) {
if ($this->_checkBinaryOp($stmt->left, $context, ++$nesting) === false) {
return false;
}
}
else {
if ($this->_checkExpression($stmt->left, $context) === false) {
return false;
}
}
if ($stmt->right instanceof PhpParser\Node\Expr\BinaryOp) {
if ($this->_checkBinaryOp($stmt->right, $context, ++$nesting) === false) {
return false;
}
}
else {
if ($this->_checkExpression($stmt->right, $context) === false) {
return false;
}
}
}
2016-04-27 00:17:47 +02:00
if ($stmt instanceof PhpParser\Node\Expr\BinaryOp\BooleanAnd ||
$stmt instanceof PhpParser\Node\Expr\BinaryOp\BooleanOr ||
$stmt instanceof PhpParser\Node\Expr\BinaryOp\Equal ||
$stmt instanceof PhpParser\Node\Expr\BinaryOp\NotEqual ||
$stmt instanceof PhpParser\Node\Expr\BinaryOp\Identical ||
$stmt instanceof PhpParser\Node\Expr\BinaryOp\NotIdentical ||
$stmt instanceof PhpParser\Node\Expr\BinaryOp\Greater ||
$stmt instanceof PhpParser\Node\Expr\BinaryOp\GreaterOrEqual ||
$stmt instanceof PhpParser\Node\Expr\BinaryOp\Smaller ||
$stmt instanceof PhpParser\Node\Expr\BinaryOp\SmallerOrEqual
) {
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getBool();
2016-04-27 00:17:47 +02:00
}
}
protected function _checkAssignment(PhpParser\Node\Expr\Assign $stmt, Context $context)
{
$var_id = self::getVarId($stmt->var);
if ($this->_checkExpression($stmt->expr, $context) === false) {
// if we're not exiting immediately, make everything mixed
$context->vars_in_scope[$var_id] = Type::getMixed();
return false;
}
2016-07-25 21:05:58 +02:00
$type_in_comments = CommentChecker::getTypeFromComment((string) $stmt->getDocComment(), $context, $this->_source, $var_id);
if ($type_in_comments) {
2016-06-16 02:16:40 +02:00
$return_type = Type::parseString($type_in_comments);
}
2016-06-16 18:04:55 +02:00
elseif (isset($stmt->expr->inferredType)) {
$return_type = $stmt->expr->inferredType;
}
else {
2016-06-15 01:22:29 +02:00
$return_type = Type::getMixed();
}
2016-04-30 20:14:22 +02:00
$stmt->inferredType = $return_type;
if ($stmt->var instanceof PhpParser\Node\Expr\Variable && is_string($stmt->var->name)) {
$context->vars_in_scope[$var_id] = $return_type;
$context->vars_possibly_in_scope[$var_id] = true;
$this->registerVariable($var_id, $stmt->var->getLine());
} elseif ($stmt->var instanceof PhpParser\Node\Expr\List_) {
foreach ($stmt->var->vars as $var) {
if ($var) {
$context->vars_in_scope[$var->name] = Type::getMixed();
$context->vars_possibly_in_scope[$var->name] = true;
$this->registerVariable($var->name, $var->getLine());
}
}
} else if ($stmt->var instanceof PhpParser\Node\Expr\ArrayDimFetch) {
if ($this->_checkArrayAssignment($stmt->var, $context, $return_type) === false) {
return false;
}
2016-03-23 18:05:25 +01:00
} else if ($stmt->var instanceof PhpParser\Node\Expr\PropertyFetch &&
$stmt->var->var instanceof PhpParser\Node\Expr\Variable &&
is_string($stmt->var->name)) {
$method_id = $this->_source->getMethodId();
2016-08-07 02:27:13 +02:00
$this->_checkPropertyAssignment($stmt->var, $stmt->var->name, $return_type, $context);
$context->vars_in_scope[$var_id] = $return_type;
$context->vars_possibly_in_scope[$var_id] = true;
2016-03-03 23:24:44 +01:00
}
if ($var_id && isset($context->vars_in_scope[$var_id]) && $context->vars_in_scope[$var_id]->isVoid()) {
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new FailedTypeResolution('Cannot assign $' . $var_id . ' to type void', $this->_file_name, $stmt->getLine()),
$this->_suppressed_issues
)) {
return false;
}
}
}
2016-06-17 22:05:28 +02:00
public static function getVarId(PhpParser\Node\Expr $stmt)
{
if ($stmt instanceof PhpParser\Node\Expr\Variable && is_string($stmt->name)) {
return $stmt->name;
}
else if ($stmt instanceof PhpParser\Node\Expr\PropertyFetch &&
$stmt->var instanceof PhpParser\Node\Expr\Variable &&
2016-06-15 01:22:29 +02:00
is_string($stmt->name)) {
2016-06-17 22:05:28 +02:00
$object_id = self::getVarId($stmt->var);
if (!$object_id) {
return null;
}
2016-06-15 01:22:29 +02:00
return $object_id . '->' . $stmt->name;
}
return null;
}
protected function _checkArrayAssignment(PhpParser\Node\Expr\ArrayDimFetch $stmt, Context $context, Type\Union $assignment_type)
{
if ($this->_checkExpression($stmt->var, $context, true) === false) {
return false;
}
2016-06-17 22:05:28 +02:00
$var_id = self::getVarId($stmt->var);
2016-06-16 18:04:55 +02:00
if (isset($stmt->var->inferredType)) {
$return_type = $stmt->var->inferredType;
2016-06-16 02:16:40 +02:00
if (!$return_type->isMixed()) {
2016-06-16 02:16:40 +02:00
foreach ($return_type->types as &$type) {
2016-07-13 17:18:07 +02:00
if ($type->isScalarType()) {
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new InvalidArrayAssignment(
'Cannot assign value on variable $' . $var_id . ' of scalar type ' . $type->value,
$this->_file_name,
$stmt->getLine()
),
$this->_suppressed_issues
2016-06-16 07:19:52 +02:00
)) {
return false;
}
continue;
}
2016-06-16 02:16:40 +02:00
$refined_type = $this->_refineArrayType($type, $assignment_type, $var_id, $stmt->getLine());
2016-06-16 02:16:40 +02:00
if ($refined_type === false) {
return false;
}
2016-06-16 02:16:40 +02:00
$type = $refined_type;
}
$context->vars_in_scope[$var_id] = $return_type;
2016-06-15 01:22:29 +02:00
}
}
}
2016-06-15 01:22:29 +02:00
/**
*
* @param Type\Atomic $type
* @param string $var_id
* @param int $line_number
* @return Type\Atomic|false
2016-06-15 01:22:29 +02:00
*/
2016-06-16 02:16:40 +02:00
protected function _refineArrayType(Type\Atomic $type, Type\Union $assignment_type, $var_id, $line_number)
2016-06-15 01:22:29 +02:00
{
if ($type->value === 'null') {
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new NullReference(
'Cannot assign value on possibly null array ' . $var_id,
$this->_file_name,
$line_number
),
$this->_suppressed_issues
2016-06-15 01:22:29 +02:00
)) {
return false;
}
2016-06-15 01:22:29 +02:00
return $type;
}
foreach ($assignment_type->types as $at) {
if ($type->value === 'string' && $at->isString()) {
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new InvalidArrayAssignment(
'Cannot assign value on variable ' . $var_id . ' using string offset',
$this->_file_name,
$line_number
),
$this->_suppressed_issues
)) {
return false;
}
}
}
2016-06-15 01:22:29 +02:00
if ($type->value !== 'array' && !ClassChecker::classImplements($type->value, 'ArrayAccess')) {
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new InvalidArrayAssignment(
'Cannot assign value on variable ' . $var_id . ' that does not implement ArrayAccess',
$this->_file_name,
$line_number
),
$this->_suppressed_issues
2016-06-15 01:22:29 +02:00
)) {
return false;
}
return $type;
}
if ($type instanceof Type\Generic) {
if ($type->is_empty) {
// boil this down to a regular array
2016-06-16 02:16:40 +02:00
if ($assignment_type->isMixed()) {
2016-06-15 01:22:29 +02:00
return new Type\Atomic($type->value);
}
2016-06-15 01:22:29 +02:00
2016-07-25 00:02:03 +02:00
$type->type_params[0] = $assignment_type;
2016-06-16 02:16:40 +02:00
$type->is_empty = false;
2016-06-15 01:22:29 +02:00
return $type;
}
2016-06-16 02:16:40 +02:00
$array_type = $type->type_params[0] instanceof Type\Union ? $type->type_params[0] : new Type\Union([$type->type_params[0]]);
2016-06-15 01:22:29 +02:00
2016-06-16 02:16:40 +02:00
if ((string) $array_type !== (string) $assignment_type) {
$type->type_params[0] = Type::combineUnionTypes($array_type, $assignment_type);
2016-06-15 01:22:29 +02:00
return $type;
}
}
2016-06-15 01:22:29 +02:00
2016-06-16 02:16:40 +02:00
2016-06-15 01:22:29 +02:00
return $type;
}
protected function _checkAssignmentOperation(PhpParser\Node\Expr\AssignOp $stmt, Context $context)
{
if ($this->_checkExpression($stmt->var, $context) === false) {
return false;
}
return $this->_checkExpression($stmt->expr, $context);
}
protected function _checkMethodCall(PhpParser\Node\Expr\MethodCall $stmt, Context $context)
{
if ($this->_checkExpression($stmt->var, $context) === false) {
return false;
}
$class_type = null;
$method_id = null;
if ($stmt->var instanceof PhpParser\Node\Expr\Variable) {
if (is_string($stmt->var->name) && $stmt->var->name === 'this' && !$this->_class_name) {
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new InvalidScope('Use of $this in non-class context', $this->_file_name, $stmt->getLine()),
$this->_suppressed_issues
)) {
return false;
}
}
}
2016-06-17 22:05:28 +02:00
$var_id = self::getVarId($stmt->var);
2016-06-15 01:22:29 +02:00
$class_type = isset($context->vars_in_scope[$var_id]) ? $context->vars_in_scope[$var_id] : null;
2016-06-30 06:27:47 +02:00
if (isset($stmt->var->inferredType)) {
$class_type = $stmt->var->inferredType;
}
elseif (!$class_type) {
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getMixed();
}
if ($stmt->var instanceof PhpParser\Node\Expr\Variable && $stmt->var->name === 'this' && is_string($stmt->name)) {
$this_method_id = $this->_source->getMethodId();
if (!isset(self::$_this_calls[$this_method_id])) {
self::$_this_calls[$this_method_id] = [];
}
self::$_this_calls[$this_method_id][] = $stmt->name;
2016-05-20 06:24:26 +02:00
if (ClassChecker::getThisClass() &&
(
ClassChecker::getThisClass() === $this->_absolute_class ||
ClassChecker::classExtends(ClassChecker::getThisClass(), $this->_absolute_class) ||
2016-05-20 06:24:26 +02:00
trait_exists($this->_absolute_class)
)) {
2016-05-20 06:24:26 +02:00
$method_id = $this->_absolute_class . '::' . $stmt->name;
if ($this->_checkInsideMethod($method_id, $context) === false) {
return false;
}
}
}
if (!$this->_check_methods) {
return;
}
2016-06-16 02:16:40 +02:00
if ($class_type && is_string($stmt->name)) {
foreach ($class_type->types as $type) {
$absolute_class = $type->value;
2016-04-12 01:13:50 +02:00
switch ($absolute_class) {
case 'null':
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new NullReference(
'Cannot call method ' . $stmt->name . ' on possibly null variable ' . $class_type,
$this->_file_name,
$stmt->getLine()
),
$this->_suppressed_issues
)) {
return false;
}
break;
case 'int':
case 'bool':
case 'array':
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new InvalidArgument(
'Cannot call method ' . $stmt->name . ' on ' . $class_type . ' variable',
$this->_file_name,
$stmt->getLine()
),
$this->_suppressed_issues
)) {
return false;
}
break;
2016-04-04 02:14:19 +02:00
case 'mixed':
2016-07-08 01:37:39 +02:00
if (IssueBuffer::accepts(
new MixedMethodCall(
'Cannot call method ' . $stmt->name . ' on a mixed variable',
$this->_file_name,
$stmt->getLine()
),
$this->_suppressed_issues
2016-07-08 01:37:39 +02:00
)) {
return false;
}
break;
default:
if ($absolute_class[0] === strtoupper($absolute_class[0]) && !method_exists($absolute_class, '__call') && !self::isMock($absolute_class)) {
$does_class_exist = ClassChecker::checkAbsoluteClassOrInterface($absolute_class, $this->_file_name, $stmt->getLine(), $this->_suppressed_issues);
if (!$does_class_exist) {
return $does_class_exist;
}
$method_id = $absolute_class . '::' . $stmt->name;
if (!isset(self::$_method_call_index[$method_id])) {
self::$_method_call_index[$method_id] = [];
}
if ($this->_source instanceof ClassMethodChecker) {
self::$_method_call_index[$method_id][] = $this->_source->getMethodId();
}
else {
self::$_method_call_index[$method_id][] = $this->_source->getFileName();
}
$does_method_exist = ClassMethodChecker::checkMethodExists($method_id, $this->_file_name, $stmt->getLine(), $this->_suppressed_issues);
if (!$does_method_exist) {
return $does_method_exist;
}
if (!($this->_source->getSource() instanceof TraitChecker)) {
$calling_context = $this->_absolute_class;
2016-05-21 01:06:42 +02:00
if (ClassChecker::getThisClass() && ClassChecker::classExtends(ClassChecker::getThisClass(), $this->_absolute_class)) {
$calling_context = $this->_absolute_class;
}
2016-05-21 01:06:42 +02:00
if (ClassMethodChecker::checkMethodVisibility($method_id, $calling_context, $this->_file_name, $stmt->getLine(), $this->_suppressed_issues) === false) {
return false;
}
}
if (ClassMethodChecker::checkMethodNotDeprecated($method_id, $this->_file_name, $stmt->getLine(), $this->_suppressed_issues) === false) {
return false;
}
$return_types = ClassMethodChecker::getMethodReturnTypes($method_id);
if ($return_types) {
2016-07-19 01:04:51 +02:00
$return_types = self::fleshOutReturnTypes($return_types, $stmt->args, $method_id);
2016-06-16 18:04:55 +02:00
$stmt->inferredType = $return_types;
}
}
}
}
}
if ($this->_checkMethodParams($stmt->args, $method_id, $context, $stmt->getLine()) === false) {
return false;
}
}
protected function _checkInsideMethod($method_id, Context $context)
2016-06-03 01:21:48 +02:00
{
$method_checker = ClassChecker::getMethodChecker($method_id);
if ($method_checker && $method_checker->getMethodId() !== $this->_source->getMethodId()) {
$this_context = new Context();
2016-06-03 01:21:48 +02:00
foreach ($context->vars_possibly_in_scope as $var => $type) {
2016-06-03 01:21:48 +02:00
if (strpos($var, 'this->') === 0) {
$this_context->vars_possibly_in_scope[$var] = true;
2016-06-03 01:21:48 +02:00
}
}
foreach ($context->vars_in_scope as $var => $type) {
2016-06-03 01:21:48 +02:00
if (strpos($var, 'this->') === 0) {
$this_context->vars_in_scope[$var] = $type;
2016-06-03 01:21:48 +02:00
}
}
2016-06-20 07:29:30 +02:00
$this_context->vars_in_scope['this'] = $context->vars_in_scope['this'];
$method_checker->check($this_context);
2016-06-03 01:21:48 +02:00
foreach ($this_context->vars_in_scope as $var => $type) {
$context->vars_possibly_in_scope[$var] = true;
2016-06-03 01:21:48 +02:00
}
foreach ($this_context->vars_in_scope as $var => $type) {
$context->vars_in_scope[$var] = $type;
2016-06-03 01:21:48 +02:00
}
}
}
protected function _checkClosureUses(PhpParser\Node\Expr\Closure $stmt, Context $context)
{
foreach ($stmt->uses as $use) {
if (!isset($context->vars_in_scope[$use->var])) {
if ($use->byRef) {
$context->vars_in_scope[$use->var] = Type::getMixed();
$context->vars_possibly_in_scope[$use->var] = true;
$this->registerVariable($use->var, $use->getLine());
return;
}
if (!isset($context->vars_possibly_in_scope[$use->var])) {
if ($this->_check_variables) {
IssueBuffer::add(
new UndefinedVariable('Cannot find referenced variable $' . $use->var, $this->_file_name, $use->getLine())
);
return false;
}
}
if (isset($this->_all_vars[$use->var])) {
if (!isset($this->_warn_vars[$use->var])) {
$this->_warn_vars[$use->var] = true;
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new PossiblyUndefinedVariable(
'Possibly undefined variable $' . $use->var . ', first seen on line ' . $this->_all_vars[$use->var],
$this->_file_name,
$use->getLine()
),
$this->_suppressed_issues
)) {
return false;
}
}
return;
}
if ($this->_check_variables) {
IssueBuffer::add(
new UndefinedVariable('Cannot find referenced variable $' . $use->var, $this->_file_name, $use->getLine())
);
return false;
}
}
}
}
2016-04-27 00:42:48 +02:00
/**
* @return void
*/
protected function _checkStaticCall(PhpParser\Node\Expr\StaticCall $stmt, Context $context)
{
if ($stmt->class instanceof PhpParser\Node\Expr\Variable || $stmt->class instanceof PhpParser\Node\Expr\ArrayDimFetch) {
// this is when calling $some_class::staticMethod() - which is a shitty way of doing things
// because it can't be statically type-checked
return;
}
$method_id = null;
$absolute_class = null;
if (count($stmt->class->parts) === 1 && in_array($stmt->class->parts[0], ['self', 'static', 'parent'])) {
if ($stmt->class->parts[0] === 'parent') {
2016-04-17 16:25:43 +02:00
if ($this->_class_extends === null) {
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new ParentNotFound('Cannot call method on parent as this class does not extend another', $this->_file_name, $stmt->getLine()),
$this->_suppressed_issues
)) {
return false;
}
2016-04-17 16:25:43 +02:00
}
$absolute_class = $this->_class_extends;
} else {
$absolute_class = ($this->_namespace ? $this->_namespace . '\\' : '') . $this->_class_name;
}
} elseif ($this->_check_classes) {
$does_class_exist = ClassChecker::checkClassName($stmt->class, $this->_namespace, $this->_aliased_classes, $this->_file_name, $this->_suppressed_issues);
if (!$does_class_exist) {
return $does_class_exist;
}
$absolute_class = ClassChecker::getAbsoluteClassFromName($stmt->class, $this->_namespace, $this->_aliased_classes);
}
2016-07-25 00:02:03 +02:00
if (!$this->_check_methods) {
return;
}
2016-06-03 01:21:48 +02:00
if ($stmt->class->parts === ['parent'] && is_string($stmt->name)) {
if (ClassChecker::getThisClass()) {
$method_id = $absolute_class . '::' . $stmt->name;
if ($this->_checkInsideMethod($method_id, $context) === false) {
return false;
}
2016-06-03 01:21:48 +02:00
}
}
if ($absolute_class && is_string($stmt->name) && !method_exists($absolute_class, '__callStatic') && !self::isMock($absolute_class)) {
$method_id = $absolute_class . '::' . $stmt->name;
if (!isset(self::$_method_call_index[$method_id])) {
self::$_method_call_index[$method_id] = [];
}
if ($this->_source instanceof ClassMethodChecker) {
self::$_method_call_index[$method_id][] = $this->_source->getMethodId();
}
else {
self::$_method_call_index[$method_id][] = $this->_source->getFileName();
}
$does_method_exist = ClassMethodChecker::checkMethodExists($method_id, $this->_file_name, $stmt->getLine(), $this->_suppressed_issues);
if (!$does_method_exist) {
return $does_method_exist;
}
if (ClassMethodChecker::checkMethodVisibility($method_id, $this->_absolute_class, $this->_file_name, $stmt->getLine(), $this->_suppressed_issues) === false) {
return false;
}
if ($this->_is_static) {
if (ClassMethodChecker::checkMethodStatic($method_id, $this->_file_name, $stmt->getLine(), $this->_suppressed_issues) === false) {
return false;
}
}
else {
if ($stmt->class->parts[0] === 'self' && $stmt->name !== '__construct') {
if (ClassMethodChecker::checkMethodStatic($method_id, $this->_file_name, $stmt->getLine(), $this->_suppressed_issues) === false) {
return false;
}
}
}
if (ClassMethodChecker::checkMethodNotDeprecated($method_id, $this->_file_name, $stmt->getLine(), $this->_suppressed_issues) === false) {
return false;
}
$return_types = ClassMethodChecker::getMethodReturnTypes($method_id);
if ($return_types) {
2016-07-19 01:04:51 +02:00
$return_types = self::fleshOutReturnTypes($return_types, $stmt->args, $method_id);
2016-06-16 18:04:55 +02:00
$stmt->inferredType = $return_types;
}
}
return $this->_checkMethodParams($stmt->args, $method_id, $context, $stmt->getLine());
}
2016-07-19 01:04:51 +02:00
public static function fleshOutReturnTypes(Type\Union $return_type, array $args, $method_id)
{
2016-07-19 01:04:51 +02:00
foreach ($return_type->types as $key => $return_type_part) {
self::_fleshOutAtomicReturnType($return_type_part, $args, $method_id);
2016-07-19 01:04:51 +02:00
if ($return_type_part->value !== $key) {
unset($return_type->types[$key]);
$return_type->types[$return_type_part->value] = $return_type_part;
}
2016-06-15 01:22:29 +02:00
}
2016-03-10 21:43:23 +01:00
2016-06-15 01:22:29 +02:00
return $return_type;
}
2016-04-20 19:36:46 +02:00
protected static function _fleshOutAtomicReturnType(Type\Atomic &$return_type, array $args, $method_id)
2016-06-15 01:22:29 +02:00
{
if ($return_type->value === '$this' || $return_type->value === 'static') {
$absolute_class = explode('::', $method_id)[0];
2016-06-15 01:22:29 +02:00
$return_type->value = $absolute_class;
}
else if ($return_type->value[0] === '$') {
$method_params = ClassMethodChecker::getMethodParams($method_id);
2016-06-15 01:22:29 +02:00
foreach ($args as $i => $arg) {
$method_param = $method_params[$i];
2016-06-15 01:22:29 +02:00
if ($return_type->value === '$' . $method_param['name']) {
if ($arg->value instanceof PhpParser\Node\Scalar\String_) {
$return_type->value = preg_replace('/^\\\/', '', $arg->value->value);
2016-04-20 19:36:46 +02:00
}
}
}
2016-04-20 19:36:46 +02:00
2016-06-15 01:22:29 +02:00
if ($return_type->value[0] === '$') {
$return_type = Type::getMixed(false);
2016-06-15 01:22:29 +02:00
}
}
if ($return_type instanceof Type\Generic) {
2016-06-15 01:22:29 +02:00
foreach ($return_type->type_params as $type_param) {
if ($type_param instanceof Type\Union) {
2016-07-19 01:04:51 +02:00
$type_param = self::fleshOutReturnTypes($type_param, $args, $method_id);
2016-06-15 01:22:29 +02:00
}
else {
$type_param = self::_fleshOutAtomicReturnType($type_param, $args, $method_id);
}
}
}
}
2016-03-10 21:43:23 +01:00
protected static function _getMethodFromCallBlock($call, array $args, $method_id)
{
$absolute_class = explode('::', $method_id)[0];
$original_call = $call;
$call = preg_replace('/^\$this(->|::)/', $absolute_class . '::', $call);
$call = preg_replace('/\(\)$/', '', $call);
if (strpos($call, '$') !== false) {
$method_params = ClassMethodChecker::getMethodParams($method_id);
2016-03-10 21:43:23 +01:00
foreach ($args as $i => $arg) {
$method_param = $method_params[$i];
2016-03-10 21:43:23 +01:00
$preg_var_name = preg_quote('$' . $method_param['name']);
if (preg_match('/::' . $preg_var_name . '$/', $call)) {
if ($arg->value instanceof PhpParser\Node\Scalar\String_) {
$call = preg_replace('/' . $preg_var_name . '$/', $arg->value->value, $call);
break;
}
}
}
}
return $original_call === $call || strpos($call, '$') !== false ? null : $call;
}
protected function _checkMethodParams(array $args, $method_id, Context $context, $line_number)
{
foreach ($args as $i => $arg) {
2016-05-10 17:46:36 +02:00
if ($arg->value instanceof PhpParser\Node\Expr\PropertyFetch &&
$arg->value->var instanceof PhpParser\Node\Expr\Variable &&
$arg->value->var->name === 'this' &&
is_string($arg->value->name)
) {
$property_id = 'this' . '->' . $arg->value->name;
2016-05-10 17:46:36 +02:00
if ($method_id) {
if (isset($context->vars_in_scope[$property_id]) && !$context->vars_in_scope[$property_id]->isMixed()) {
if ($this->_checkFunctionArgumentType($context->vars_in_scope[$property_id], $method_id, $i, $this->_file_name, $arg->getLine()) === false) {
return false;
}
}
if ($this->_isPassedByReference($method_id, $i)) {
$this->_assignByRefParam($arg->value, $method_id, $context);
}
else {
if ($this->_checkPropertyFetch($arg->value, $context) === false) {
return false;
}
}
2016-05-10 17:46:36 +02:00
} else {
if (false || !isset($context->vars_in_scope[$property_id]) || $context->vars_in_scope[$property_id]->isNull()) {
// we don't know if it exists, assume it's passed by reference
$context->vars_in_scope[$property_id] = Type::getMixed();
$context->vars_possibly_in_scope[$property_id] = true;
$this->registerVariable($property_id, $arg->value->getLine());
}
2016-05-10 17:46:36 +02:00
}
}
elseif ($arg->value instanceof PhpParser\Node\Expr\Variable) {
if ($method_id) {
if ($this->_checkVariable($arg->value, $context, $method_id, $i) === false) {
return false;
}
} elseif (is_string($arg->value->name)) {
if (false || !isset($context->vars_in_scope[$arg->value->name]) || $context->vars_in_scope[$arg->value->name]->isNull()) {
// we don't know if it exists, assume it's passed by reference
$context->vars_in_scope[$arg->value->name] = Type::getMixed();
$context->vars_possibly_in_scope[$arg->value->name] = true;
$this->registerVariable($arg->value->name, $arg->value->getLine());
}
}
} else {
if ($this->_checkExpression($arg->value, $context) === false) {
return false;
}
}
2016-06-16 18:04:55 +02:00
if ($method_id && isset($arg->value->inferredType)) {
if ($this->_checkFunctionArgumentType($arg->value->inferredType, $method_id, $i, $this->_file_name, $arg->value->getLine()) === false) {
2016-06-16 02:16:40 +02:00
return false;
}
}
}
if ($method_id) {
$method_params = ClassMethodChecker::getMethodParams($method_id);
if (count($args) > count($method_params)) {
if (IssueBuffer::accepts(
new TooManyArguments('Too many arguments for method ' . $method_id, $this->_file_name, $line_number),
$this->_suppressed_issues
)) {
return false;
}
return;
}
if (count($args) < count($method_params)) {
for ($i = count($args); $i < count($method_params); $i++) {
$param = $method_params[$i];
if (!$param['is_optional']) {
if (IssueBuffer::accepts(
new TooFewArguments('Too few arguments for method ' . $method_id, $this->_file_name, $line_number),
$this->_suppressed_issues
)) {
return false;
}
break;
}
}
}
}
}
protected function _checkConstFetch(PhpParser\Node\Expr\ConstFetch $stmt)
{
if ($stmt->name instanceof PhpParser\Node\Name) {
2016-04-27 00:17:47 +02:00
switch ($stmt->name->parts) {
case ['null']:
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getNull();
2016-04-27 00:17:47 +02:00
break;
case ['false']:
2016-04-30 20:14:22 +02:00
// false is a subtype of bool
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getFalse();
2016-04-30 20:14:22 +02:00
break;
case ['true']:
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getBool();
2016-04-27 00:17:47 +02:00
break;
}
}
}
protected function _checkClassConstFetch(PhpParser\Node\Expr\ClassConstFetch $stmt, Context $context)
{
if ($this->_check_consts && $stmt->class instanceof PhpParser\Node\Name && $stmt->class->parts !== ['static']) {
if ($stmt->class->parts === ['self']) {
$absolute_class = $this->_absolute_class;
} else {
$absolute_class = ClassChecker::getAbsoluteClassFromName($stmt->class, $this->_namespace, $this->_aliased_classes);
if (ClassChecker::checkAbsoluteClassOrInterface($absolute_class, $this->_file_name, $stmt->getLine(), $this->_suppressed_issues) === false) {
return false;
}
}
$const_id = $absolute_class . '::' . $stmt->name;
2016-07-23 16:58:53 +02:00
if (!isset(self::$_class_consts[$const_id])) {
if (!defined($const_id)) {
if (IssueBuffer::accepts(
new UndefinedConstant('Const ' . $const_id . ' is not defined', $this->_file_name, $stmt->getLine()),
$this->_suppressed_issues
)) {
return false;
}
}
2016-07-23 16:58:53 +02:00
self::$_class_consts[$const_id] = true;
}
return;
}
if ($stmt->class instanceof PhpParser\Node\Expr) {
if ($this->_checkExpression($stmt->class, $context) === false) {
return false;
}
}
}
2016-04-27 00:42:48 +02:00
/**
* @return null|false
2016-04-27 00:42:48 +02:00
*/
protected function _checkStaticPropertyFetch(PhpParser\Node\Expr\StaticPropertyFetch $stmt, Context $context)
{
if ($stmt->class instanceof PhpParser\Node\Expr\Variable || $stmt->class instanceof PhpParser\Node\Expr\ArrayDimFetch) {
// this is when calling $some_class::staticMethod() - which is a shitty way of doing things
// because it can't be statically type-checked
return;
}
$method_id = null;
$absolute_class = null;
if (count($stmt->class->parts) === 1 && in_array($stmt->class->parts[0], ['self', 'static', 'parent'])) {
if ($stmt->class->parts[0] === 'parent') {
$absolute_class = $this->_class_extends;
} else {
2016-03-23 18:05:25 +01:00
$absolute_class = ($this->_namespace ? $this->_namespace . '\\' : '') . $this->_class_name;
}
2016-08-07 02:27:13 +02:00
}
elseif ($this->_check_classes) {
if (ClassChecker::checkClassName($stmt->class, $this->_namespace, $this->_aliased_classes, $this->_file_name, $this->_suppressed_issues) === false) {
return false;
}
$absolute_class = ClassChecker::getAbsoluteClassFromName($stmt->class, $this->_namespace, $this->_aliased_classes);
}
if ($absolute_class && $this->_check_variables && is_string($stmt->name) && !self::isMock($absolute_class)) {
2016-08-07 18:23:29 +02:00
if ($absolute_class === $this->_absolute_class) {
$class_visibility = \ReflectionProperty::IS_PRIVATE;
}
elseif (ClassChecker::classExtends($this->_absolute_class, $absolute_class)) {
$class_visibility = \ReflectionProperty::IS_PROTECTED;
}
else {
$class_visibility = \ReflectionProperty::IS_PUBLIC;
}
2016-08-07 02:27:13 +02:00
$visible_class_properties = ClassChecker::getStaticPropertiesForClass(
$absolute_class,
2016-08-07 18:23:29 +02:00
$class_visibility
2016-08-07 02:27:13 +02:00
);
2016-08-07 02:27:13 +02:00
if (!isset($visible_class_properties[$stmt->name])) {
$var_id = $absolute_class . '::$' . $stmt->name;
$all_class_properties = [];
if ($absolute_class !== $this->_absolute_class) {
$all_class_properties = ClassChecker::getStaticPropertiesForClass(
$absolute_class,
2016-08-07 18:23:29 +02:00
\ReflectionProperty::IS_PRIVATE
);
2016-08-07 02:27:13 +02:00
}
2016-08-07 02:27:13 +02:00
if ($all_class_properties && isset($all_class_properties[$stmt->name])) {
// @todo change issue type
IssueBuffer::add(
new UndefinedProperty('Static property ' . $var_id . ' is not visible in this context', $this->_file_name, $stmt->getLine())
);
}
else {
IssueBuffer::add(
new UndefinedProperty('Static property ' . $var_id . ' does not exist', $this->_file_name, $stmt->getLine())
);
}
2016-08-07 02:27:13 +02:00
return false;
}
}
}
protected function _checkReturn(PhpParser\Node\Stmt\Return_ $stmt, Context $context)
{
2016-07-25 21:05:58 +02:00
$type_in_comments = CommentChecker::getTypeFromComment((string) $stmt->getDocComment(), $context, $this->_source);
if ($stmt->expr) {
if ($this->_checkExpression($stmt->expr, $context) === false) {
return false;
}
2016-04-27 00:17:47 +02:00
2016-05-06 03:20:15 +02:00
if ($type_in_comments) {
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::parseString($type_in_comments);
2016-05-06 03:20:15 +02:00
}
2016-06-16 18:04:55 +02:00
elseif (isset($stmt->expr->inferredType)) {
$stmt->inferredType = $stmt->expr->inferredType;
2016-04-27 00:17:47 +02:00
}
else {
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getMixed();
2016-04-27 00:17:47 +02:00
}
}
else {
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getVoid();
}
2016-05-16 22:12:02 +02:00
if ($this->_source instanceof FunctionChecker) {
$this->_source->addReturnTypes($stmt->expr ? (string) $stmt->inferredType : '', $context);
2016-05-16 22:12:02 +02:00
}
}
protected function _checkTernary(PhpParser\Node\Expr\Ternary $stmt, Context $context)
{
if ($this->_checkCondition($stmt->cond, $context) === false) {
return false;
}
$t_if_context = clone $context;
2016-06-28 21:28:05 +02:00
if ($stmt->cond instanceof PhpParser\Node\Expr\BinaryOp) {
$reconcilable_if_types = $this->_type_checker->getReconcilableTypeAssertions($stmt->cond, true);
$negatable_if_types = $this->_type_checker->getNegatableTypeAssertions($stmt->cond, true);
}
else {
$reconcilable_if_types = $negatable_if_types = $this->_type_checker->getTypeAssertions($stmt->cond, true);
}
$if_return_type = null;
2016-06-28 21:28:05 +02:00
$t_if_vars_in_scope_reconciled =
TypeChecker::reconcileKeyedTypes(
$reconcilable_if_types,
$t_if_context->vars_in_scope,
$this->_file_name,
$stmt->getLine()
);
if ($t_if_vars_in_scope_reconciled === false) {
return false;
}
$t_if_context->vars_in_scope = $t_if_vars_in_scope_reconciled;
if ($stmt->if) {
if ($this->_checkExpression($stmt->if, $t_if_context) === false) {
return false;
}
}
$t_else_context = clone $context;
2016-06-28 21:28:05 +02:00
if ($negatable_if_types) {
$negated_if_types = TypeChecker::negateTypes($negatable_if_types);
$t_else_vars_in_scope_reconciled = TypeChecker::reconcileKeyedTypes($negated_if_types, $t_else_context->vars_in_scope, $this->_file_name, $stmt->getLine());
if ($t_else_vars_in_scope_reconciled === false) {
return false;
}
$t_else_context->vars_in_scope = $t_else_vars_in_scope_reconciled;
}
2016-04-04 02:14:19 +02:00
if ($this->_checkExpression($stmt->else, $t_else_context) === false) {
return false;
}
$lhs_type = null;
if ($stmt->if) {
2016-06-16 18:04:55 +02:00
if (isset($stmt->if->inferredType)) {
$lhs_type = $stmt->if->inferredType;
}
}
elseif ($stmt->cond) {
2016-06-16 18:04:55 +02:00
if (isset($stmt->cond->inferredType)) {
2016-07-25 21:05:58 +02:00
$if_return_type_reconciled = TypeChecker::reconcileTypes('!empty', $stmt->cond->inferredType, '', $this->_file_name, $stmt->getLine());
2016-06-24 00:45:46 +02:00
if ($if_return_type_reconciled === false) {
return false;
}
$lhs_type = $if_return_type_reconciled;
}
}
2016-06-16 18:04:55 +02:00
if (!$lhs_type || !isset($stmt->else->inferredType)) {
$stmt->inferredType = Type::getMixed();
}
else {
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::combineUnionTypes($lhs_type, $stmt->else->inferredType);
}
}
protected function _checkBooleanNot(PhpParser\Node\Expr\BooleanNot $stmt, Context $context)
{
return $this->_checkExpression($stmt->expr, $context);
}
protected function _checkEmpty(PhpParser\Node\Expr\Empty_ $stmt, Context $context)
{
return $this->_checkExpression($stmt->expr, $context);
}
protected function _checkThrow(PhpParser\Node\Stmt\Throw_ $stmt, Context $context)
{
return $this->_checkExpression($stmt->expr, $context);
}
protected function _checkSwitch(PhpParser\Node\Stmt\Switch_ $stmt, Context $context, array &$for_vars_possibly_in_scope)
{
$type_candidate_var = null;
if ($stmt->cond instanceof PhpParser\Node\Expr\FuncCall &&
$stmt->cond->name instanceof PhpParser\Node\Name &&
$stmt->cond->name->parts === ['get_class']) {
$var = $stmt->cond->args[0]->value;
if ($var instanceof PhpParser\Node\Expr\Variable && is_string($var->name)) {
$type_candidate_var = $var->name;
}
}
if ($this->_checkCondition($stmt->cond, $context) === false) {
return false;
}
$original_context = clone $context;
$case_types = [];
$new_vars_in_scope = null;
$new_vars_possibly_in_scope = [];
$redefined_vars = null;
2016-06-28 19:56:44 +02:00
// the last statement always breaks, by default
$last_case_exit_type = 'break';
$case_exit_types = new \SplFixedArray(count($stmt->cases));
$has_default = false;
2016-06-28 19:56:44 +02:00
// create a map of case statement -> ultimate exit type
for ($i = count($stmt->cases) - 1; $i >= 0; $i--) {
$case = $stmt->cases[$i];
if (ScopeChecker::doesReturnOrThrow($case->stmts)) {
$last_case_exit_type = 'return_throw';
}
elseif (ScopeChecker::doesEverBreakOrContinue($case->stmts, true)) {
$last_case_exit_type = 'continue';
}
elseif (ScopeChecker::doesEverBreakOrContinue($case->stmts)) {
$last_case_exit_type = 'break';
}
$case_exit_types[$i] = $last_case_exit_type;
}
for ($i = 0, $l = count($stmt->cases); $i < $l; $i++) {
$case = $stmt->cases[$i];
$case_exit_type = $case_exit_types[$i];
if ($case->cond) {
if ($this->_checkCondition($case->cond, $context) === false) {
return false;
}
if ($type_candidate_var && $case->cond instanceof PhpParser\Node\Scalar\String_) {
$case_types[] = $case->cond->value;
}
}
$last_stmt = null;
if ($case->stmts) {
$switch_vars = $type_candidate_var && !empty($case_types)
2016-06-16 02:22:57 +02:00
? [$type_candidate_var => Type::parseString(implode('|', $case_types))]
: [];
$case_context = clone $original_context;
$case_context->vars_in_scope = array_merge($case_context->vars_in_scope, $switch_vars);
$case_context->vars_possibly_in_scope = array_merge($case_context->vars_possibly_in_scope, $switch_vars);
$old_case_context = clone $case_context;
$this->check($case->stmts, $case_context);
$last_stmt = $case->stmts[count($case->stmts) - 1];
// has a return/throw at end
2016-06-20 22:18:31 +02:00
$has_ending_statments = ScopeChecker::doesReturnOrThrow($case->stmts);
if ($case_exit_type !== 'return_throw') {
$vars = array_diff_key($case_context->vars_possibly_in_scope, $original_context->vars_possibly_in_scope);
// if we're leaving this block, add vars to outer for loop scope
2016-06-28 19:56:44 +02:00
if ($case_exit_type === 'continue') {
$for_vars_possibly_in_scope = array_merge($vars, $for_vars_possibly_in_scope);
}
else {
$case_redefined_vars = Context::getRedefinedVars($original_context, $case_context);
Type::redefineGenericUnionTypes($case_redefined_vars, $context);
if ($redefined_vars === null) {
$redefined_vars = $case_redefined_vars;
}
else {
foreach ($redefined_vars as $redefined_var => $type) {
if (!isset($case_redefined_vars[$redefined_var])) {
unset($redefined_vars[$redefined_var]);
}
}
}
if ($new_vars_in_scope === null) {
$new_vars_in_scope = array_diff_key($case_context->vars_in_scope, $context->vars_in_scope);
$new_vars_possibly_in_scope = array_diff_key($case_context->vars_possibly_in_scope, $context->vars_possibly_in_scope);
}
else {
foreach ($new_vars_in_scope as $new_var => $type) {
if (!isset($case_context->vars_in_scope[$new_var])) {
unset($new_vars_in_scope[$new_var]);
}
}
$new_vars_possibly_in_scope = array_merge(
array_diff_key(
$case_context->vars_possibly_in_scope,
$context->vars_possibly_in_scope
),
$new_vars_possibly_in_scope
);
}
}
}
}
if ($type_candidate_var && ($last_stmt instanceof PhpParser\Node\Stmt\Break_ || $last_stmt instanceof PhpParser\Node\Stmt\Return_)) {
$case_types = [];
}
if (!$case->cond) {
$has_default = true;
}
}
// only update vars if there is a default
// if that default has a throw/return/continue, that should be handled above
if ($has_default) {
if ($new_vars_in_scope) {
$context->vars_in_scope = array_merge($context->vars_in_scope, $new_vars_in_scope);
}
if ($redefined_vars) {
$context->vars_in_scope = array_merge($context->vars_in_scope, $redefined_vars);
}
}
$context->vars_possibly_in_scope = array_merge($context->vars_possibly_in_scope, $new_vars_possibly_in_scope);
}
2016-06-16 02:16:40 +02:00
protected function _checkFunctionArgumentType(Type\Union $input_type, $method_id, $argument_offset, $file_name, $line_number)
{
2016-06-29 16:57:15 +02:00
if (strpos($method_id, '::') === false) {
return;
}
2016-06-29 16:57:15 +02:00
$method_params = ClassMethodChecker::getMethodParams($method_id);
2016-06-29 16:57:15 +02:00
if (!isset($method_params[$argument_offset])) {
return;
}
2016-06-29 16:57:15 +02:00
$param_type = $method_params[$argument_offset]['type'];
if ($param_type->isMixed()) {
return;
}
if ($input_type->isMixed()) {
// @todo make this a config
return;
}
if ($input_type->isNullable() && !$param_type->isNullable()) {
2016-06-29 16:57:15 +02:00
if (IssueBuffer::accepts(
new NullReference(
'Argument ' . ($argument_offset + 1) . ' of ' . $method_id . ' cannot be null, possibly null value provided',
$file_name,
$line_number
),
$this->_suppressed_issues
2016-06-29 16:57:15 +02:00
)) {
return false;
}
}
foreach ($input_type->types as $input_type_part) {
if ($input_type_part->isNull()) {
continue;
}
2016-07-10 22:09:09 +02:00
$type_match_found = false;
$scalar_type_match_found = false;
2016-07-10 22:09:09 +02:00
2016-06-29 16:57:15 +02:00
foreach ($param_type->types as $param_type_part) {
if ($param_type_part->isNull()) {
continue;
2016-06-16 02:16:40 +02:00
}
2016-07-10 22:09:09 +02:00
if ($input_type_part->value === $param_type_part->value ||
ClassChecker::classExtendsOrImplements($input_type_part->value, $param_type_part->value) ||
2016-07-10 22:09:09 +02:00
self::isMock($input_type_part->value)
) {
$type_match_found = true;
break;
}
2016-06-29 16:57:15 +02:00
2016-07-10 22:09:09 +02:00
if ($input_type_part->value === 'false' && $param_type_part->value === 'bool') {
$type_match_found = true;
}
if ($input_type_part->value === 'int' && $param_type_part->value === 'float') {
$type_match_found = true;
}
2016-07-13 17:18:07 +02:00
if ($param_type_part->isNumeric() && $input_type_part->isNumericType()) {
$type_match_found = true;
}
if ($param_type_part->isCallable() && ($input_type_part->value === 'string' || $input_type_part->value === 'array')) {
// @todo add value checks if possible here
$type_match_found = true;
}
2016-07-13 17:18:07 +02:00
if ($input_type_part->isScalarType()) {
if ($param_type_part->isScalarType()) {
2016-07-12 02:11:00 +02:00
$scalar_type_match_found = true;
}
}
else if ($param_type_part->isObject()) {
$type_match_found = true;
}
if (ClassChecker::classExtendsOrImplements($param_type_part->value, $input_type_part->value)) {
2016-07-10 22:09:09 +02:00
// @todo handle coercion
$type_match_found = true;
break;
}
2016-07-10 22:09:09 +02:00
}
if (!$type_match_found) {
if ($scalar_type_match_found) {
if (IssueBuffer::accepts(
new InvalidScalarArgument(
'Argument ' . ($argument_offset + 1) . ' of ' . $method_id . ' expects ' . $param_type . ', ' . $input_type . ' provided',
$file_name,
$line_number
),
$this->_suppressed_issues
)) {
return false;
}
}
else if (IssueBuffer::accepts(
2016-07-10 22:09:09 +02:00
new InvalidArgument(
'Argument ' . ($argument_offset + 1) . ' of ' . $method_id . ' expects ' . $param_type . ', ' . $input_type . ' provided',
$file_name,
$line_number
),
$this->_suppressed_issues
2016-07-10 22:09:09 +02:00
)) {
return false;
2016-06-16 02:16:40 +02:00
}
}
}
}
protected function _checkFunctionCall(PhpParser\Node\Expr\FuncCall $stmt, Context $context)
{
$method = $stmt->name;
if ($method instanceof PhpParser\Node\Name) {
if ($method->parts === ['method_exists']) {
$this->_check_methods = false;
2016-03-23 18:05:25 +01:00
} elseif ($method->parts === ['function_exists']) {
$this->_check_functions = false;
} elseif ($method->parts === ['defined']) {
$this->_check_consts = false;
} elseif ($method->parts === ['extract']) {
$this->_check_variables = false;
} elseif ($method->parts === ['var_dump'] || $method->parts === ['die'] || $method->parts === ['exit']) {
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new ForbiddenCode('Unsafe ' . implode('', $method->parts), $this->_file_name, $stmt->getLine()),
$this->_suppressed_issues
)) {
return false;
}
}
}
2016-03-23 18:05:25 +01:00
$method_id = null;
if ($stmt->name instanceof PhpParser\Node\Name && $this->_check_functions) {
$method_id = implode('', $stmt->name->parts);
if ($this->_absolute_class) {
//$method_id = $this->_absolute_class . '::' . $method_id;
2016-03-23 18:05:25 +01:00
}
if ($this->_checkFunctionExists($method_id, $stmt) === false) {
return false;
}
2016-06-16 18:04:55 +02:00
$stmt->inferredType = Type::getMixed();
2016-03-23 18:05:25 +01:00
}
foreach ($stmt->args as $i => $arg) {
if ($arg->value instanceof PhpParser\Node\Expr\Variable) {
2016-03-23 18:05:25 +01:00
if ($method_id) {
if ($this->_checkVariable($arg->value, $context, $method_id, $i) === false) {
return false;
}
} else {
if ($this->_checkVariable($arg->value, $context) === false) {
return false;
}
}
} else {
if ($this->_checkExpression($arg->value, $context) === false) {
return false;
}
}
}
}
/**
* @param PhpParser\Node\Expr\ArrayDimFetch $stmt
* @param array &$context->vars_in_scope
* @param array &$context->vars_possibly_in_scope
* @return false|null
*/
protected function _checkArrayAccess(PhpParser\Node\Expr\ArrayDimFetch $stmt, Context $context)
{
if ($this->_checkExpression($stmt->var, $context) === false) {
return false;
}
$var_type = null;
if (isset($stmt->var->inferredType)) {
$var_type = $stmt->var->inferredType;
if ($var_type instanceof Type\Generic) {
// create a union type to pass back to the statement
$array_type = $var_type->type_params[0] instanceof Type\Union ? $var_type->type_params[0] : new Type\Union([$var_type->type_params[0]]);
$stmt->inferredType = $array_type;
}
}
if ($stmt->dim) {
if ($this->_checkExpression($stmt->dim, $context) === false) {
return false;
}
if (isset($stmt->dim->inferredType) && $var_type && $var_type->isString()) {
foreach ($stmt->dim->inferredType->types as $at) {
if ($at->isString()) {
$var_id = self::getVarId($stmt->var);
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new InvalidArrayAccess(
'Cannot access value on string variable ' . $var_id . ' using string offset',
$this->_file_name,
$stmt->getLine()
),
$this->_suppressed_issues
)) {
return false;
}
}
}
}
}
}
protected function _checkEncapsulatedString(PhpParser\Node\Scalar\Encapsed $stmt, Context $context)
{
foreach ($stmt->parts as $part) {
if ($this->_checkExpression($part, $context) === false) {
return false;
}
}
}
public function registerVariable($var_name, $line_number)
{
if (!isset($this->_all_vars[$var_name])) {
$this->_all_vars[$var_name] = $line_number;
}
}
2016-04-27 00:42:48 +02:00
/**
* @return false|null
2016-04-27 00:42:48 +02:00
*/
2016-03-23 18:05:25 +01:00
public function _checkFunctionExists($method_id, $stmt)
{
if (isset(self::$_existing_functions[$method_id])) {
return;
}
$file_checker = FileChecker::getFileCheckerFromFileName($this->_file_name);
if ($file_checker->hasFunction($method_id)) {
return;
}
if (strpos($method_id, '::') !== false) {
$method_id = preg_replace('/^[^:]+::/', '', $method_id);
}
try {
(new \ReflectionFunction($method_id));
}
catch (\ReflectionException $e) {
2016-06-26 21:18:40 +02:00
if (IssueBuffer::accepts(
new UndefinedFunction('Function ' . $method_id . ' does not exist', $this->_file_name, $stmt->getLine()),
$this->_suppressed_issues
)) {
return false;
}
2016-03-23 18:05:25 +01:00
}
self::$_existing_functions[$method_id] = 1;
}
2016-07-25 21:05:58 +02:00
protected function _checkInclude(PhpParser\Node\Expr\Include_ $stmt, Context $context)
{
if ($this->_checkExpression($stmt->expr, $context) === false) {
return false;
}
$path_to_file = null;
if ($stmt->expr instanceof PhpParser\Node\Scalar\String_) {
$path_to_file = $stmt->expr->value;
// attempts to resolve using get_include_path dirs
$include_path = self::_resolveIncludePath($path_to_file, dirname($this->_file_name));
$path_to_file = $include_path ? $include_path : $path_to_file;
if ($path_to_file[0] !== '/') {
$path_to_file = getcwd() . '/' . $path_to_file;
}
}
else {
$path_to_file = self::_getPathTo($stmt->expr, $this->_file_name);
}
if ($path_to_file) {
$reduce_pattern = '/\/[^\/]+\/\.\.\//';
while (preg_match($reduce_pattern, $path_to_file)) {
$path_to_file = preg_replace($reduce_pattern, '/', $path_to_file);
}
// if the file is already included, we can't check much more
if (in_array($path_to_file, get_included_files())) {
return;
}
if (in_array($path_to_file, FileChecker::getIncludesToIgnore())) {
$this->_check_classes = false;
$this->_check_variables = false;
2016-07-25 21:05:58 +02:00
return;
}
if (file_exists($path_to_file)) {
if ($this->_source instanceof FileChecker) {
$file_checker = new FileChecker($path_to_file, []);
$file_checker->check(true, true, $context);
}
else {
$include_stmts = FileChecker::getStatementsForFile($path_to_file);
$this->check($include_stmts, $context);
}
2016-07-25 21:05:58 +02:00
return;
}
$this->_check_classes = false;
$this->_check_variables = false;
}
}
/**
* Parse a docblock comment into its parts.
*
* Taken from advanced api docmaker
* Which was taken from https://github.com/facebook/libphutil/blob/master/src/parser/docblock/PhutilDocblockParser.php
*
* @return array Array of the main comment and specials
*/
public static function parseDocComment($docblock)
{
// Strip off comments.
$docblock = trim($docblock);
$docblock = preg_replace('@^/\*\*@', '', $docblock);
$docblock = preg_replace('@\*/$@', '', $docblock);
$docblock = preg_replace('@^\s*\*@m', '', $docblock);
// Normalize multi-line @specials.
$lines = explode("\n", $docblock);
$last = false;
foreach ($lines as $k => $line) {
if (preg_match('/^\s?@\w/i', $line)) {
$last = $k;
} elseif (preg_match('/^\s*$/', $line)) {
$last = false;
} elseif ($last !== false) {
$lines[$last] = rtrim($lines[$last]).' '.trim($line);
unset($lines[$k]);
}
}
$docblock = implode("\n", $lines);
$special = array();
// Parse @specials.
$matches = null;
$have_specials = preg_match_all('/^\s?@(\w+)\s*([^\n]*)/m', $docblock, $matches, PREG_SET_ORDER);
if ($have_specials) {
$docblock = preg_replace('/^\s?@(\w+)\s*([^\n]*)/m', '', $docblock);
foreach ($matches as $match) {
list($_, $type, $data) = $match;
if (empty($special[$type])) {
$special[$type] = array();
}
$special[$type][] = $data;
}
}
$docblock = str_replace("\t", ' ', $docblock);
// Smush the whole docblock to the left edge.
$min_indent = 80;
$indent = 0;
foreach (array_filter(explode("\n", $docblock)) as $line) {
for ($ii = 0; $ii < strlen($line); $ii++) {
if ($line[$ii] != ' ') {
break;
}
$indent++;
}
$min_indent = min($indent, $min_indent);
}
$docblock = preg_replace('/^' . str_repeat(' ', $min_indent) . '/m', '', $docblock);
$docblock = rtrim($docblock);
// Trim any empty lines off the front, but leave the indent level if there
// is one.
$docblock = preg_replace('/^\s*\n/', '', $docblock);
return array('description' => $docblock, 'specials' => $special);
}
2016-04-27 00:42:48 +02:00
/**
* @return string
*/
2016-04-27 00:17:47 +02:00
public static function renderDocComment(array $parsed_doc_comment)
{
$doc_comment_text = '/**' . PHP_EOL;
2016-04-30 20:14:22 +02:00
$description_lines = null;
2016-04-30 21:43:06 +02:00
$trimmed_description = trim($parsed_doc_comment['description']);
if (!empty($trimmed_description)) {
2016-04-30 20:14:22 +02:00
$description_lines = explode(PHP_EOL, $parsed_doc_comment['description']);
2016-04-27 00:17:47 +02:00
2016-04-30 20:14:22 +02:00
foreach ($description_lines as $line) {
$doc_comment_text .= ' * ' . $line . PHP_EOL;
}
2016-04-27 00:17:47 +02:00
}
if ($description_lines && $parsed_doc_comment['specials']) {
$doc_comment_text .= ' *' . PHP_EOL;
}
if ($parsed_doc_comment['specials']) {
$type_lengths = array_map('strlen', array_keys($parsed_doc_comment['specials']));
$type_width = max($type_lengths) + 1;
foreach ($parsed_doc_comment['specials'] as $type => $lines) {
foreach ($lines as $line) {
$doc_comment_text .= ' * @' . str_pad($type, $type_width) . $line . PHP_EOL;
}
}
}
$doc_comment_text .= ' */';
return $doc_comment_text;
}
protected function _isPassedByReference($method_id, $argument_offset)
{
if (strpos($method_id, '::') !== false) {
2016-03-23 18:05:25 +01:00
try {
$method_params = ClassMethodChecker::getMethodParams($method_id);
return $argument_offset < count($method_params) && $method_params[$argument_offset]['by_ref'];
2016-03-23 18:05:25 +01:00
}
catch (\ReflectionException $e) {
// we fall through to the functions below
}
}
$file_checker = FileChecker::getFileCheckerFromFileName($this->_file_name);
if ($file_checker->hasFunction($method_id)) {
return $file_checker->isPassedByReference($method_id, $argument_offset);
}
2016-03-23 18:05:25 +01:00
if (strpos($method_id, '::') !== false) {
$method_id = preg_replace('/^[^:]+::/', '', $method_id);
}
try {
$reflection_parameters = (new \ReflectionFunction($method_id))->getParameters();
// if value is passed by reference
return $argument_offset < count($reflection_parameters) && $reflection_parameters[$argument_offset]->isPassedByReference();
}
catch (\ReflectionException $e) {
return false;
}
}
2016-04-27 00:42:48 +02:00
/**
* @return string
*/
public static function findEntryPoints($method_id)
{
$output = 'Entry points for ' . $method_id;
if (empty(self::$_method_call_index[$method_id])) {
2016-03-03 23:24:44 +01:00
list($absolute_class, $method_name) = explode('::', $method_id);
$reflection_class = new \ReflectionClass($absolute_class);
$parent_class = $reflection_class->getParentClass();
if ($parent_class) {
try {
$parent_class->getMethod($method_name);
$method_id = $parent_class->getName() . '::' . $method_name;
return $output . ' - NONE - it extends ' . $method_id . ' though';
}
catch (\ReflectionException $e) {
// do nothing
}
}
return $output . ' - NONE';
}
$parents = self::$_method_call_index[$method_id];
$ignore = [$method_id];
$entry_points = [];
while (!empty($parents)) {
$parent_method_id = array_shift($parents);
$ignore[] = $parent_method_id;
$new_parents = self::_findParents($parent_method_id, $ignore);
if ($new_parents === null) {
$entry_points[] = $parent_method_id;
}
else {
$parents = array_merge($parents, $new_parents);
}
}
$entry_points = array_unique($entry_points);
if (count($entry_points) > 20) {
return $output . PHP_EOL . ' - ' . implode(PHP_EOL . ' - ', array_slice($entry_points, 0, 20)) . ' and more...';
}
return $output . PHP_EOL . ' - ' . implode(PHP_EOL . ' - ', $entry_points);
}
protected static function _findParents($method_id, array $ignore)
{
if (empty(self::$_method_call_index[$method_id])) {
return null;
}
return array_diff(array_unique(self::$_method_call_index[$method_id]), $ignore);
}
2016-03-23 18:05:25 +01:00
protected static function _getPathTo(PhpParser\Node\Expr $stmt, $file_name)
{
if ($file_name[0] !== '/') {
$file_name = getcwd() . '/' . $file_name;
}
if ($stmt instanceof PhpParser\Node\Scalar\String_) {
return $stmt->value;
} elseif ($stmt instanceof PhpParser\Node\Expr\BinaryOp\Concat) {
$left_string = self::_getPathTo($stmt->left, $file_name);
$right_string = self::_getPathTo($stmt->right, $file_name);
if ($left_string && $right_string) {
return $left_string . $right_string;
}
} elseif ($stmt instanceof PhpParser\Node\Expr\FuncCall &&
$stmt->name instanceof PhpParser\Node\Name &&
$stmt->name->parts === ['dirname']) {
if ($stmt->args) {
$evaled_path = self::_getPathTo($stmt->args[0]->value, $file_name);
if (!$evaled_path) {
return;
}
return dirname($evaled_path);
}
} elseif ($stmt instanceof PhpParser\Node\Expr\ConstFetch && $stmt->name instanceof PhpParser\Node\Name) {
$const_name = implode('', $stmt->name->parts);
if (defined($const_name)) {
return constant($const_name);
}
} elseif ($stmt instanceof PhpParser\Node\Scalar\MagicConst\Dir) {
return dirname($file_name);
} elseif ($stmt instanceof PhpParser\Node\Scalar\MagicConst\File) {
return $file_name;
}
return null;
}
2016-04-27 00:42:48 +02:00
/**
2016-06-20 07:05:44 +02:00
* @return string|null
2016-04-27 00:42:48 +02:00
*/
2016-03-23 18:05:25 +01:00
protected static function _resolveIncludePath($file_name, $current_directory)
{
$paths = PATH_SEPARATOR == ':' ?
preg_split('#(?<!phar):#', get_include_path()) :
explode(PATH_SEPARATOR, get_include_path());
foreach ($paths as $prefix) {
$ds = substr($prefix, -1) == DIRECTORY_SEPARATOR ? '' : DIRECTORY_SEPARATOR;
if ($prefix === '.') {
$prefix = $current_directory;
}
$file = $prefix . $ds . $file_name;
if (file_exists($file)) {
return $file;
}
}
}
public static function setMockInterfaces(array $classes)
{
self::$_mock_interfaces = $classes;
}
public static function isMock($absolute_class)
{
return in_array($absolute_class, Config::getInstance()->getMockClasses());
}
2016-04-27 00:42:48 +02:00
/**
* @return bool
*/
protected static function _containsBooleanOr(PhpParser\Node\Expr\BinaryOp $stmt)
{
2016-04-04 07:21:28 +02:00
// we only want to discount expressions where either the whole thing is an or
if ($stmt instanceof PhpParser\Node\Expr\BinaryOp\BooleanOr) {
return true;
}
return false;
}
public function getAliasedClasses()
{
return $this->_aliased_classes;
}
public static function getThisAssignments($method_id, $include_constructor = false)
{
$absolute_class = explode('::', $method_id)[0];
$this_assignments = [];
if ($include_constructor && isset(self::$_this_assignments[$absolute_class . '::__construct'])) {
$this_assignments = self::$_this_assignments[$absolute_class . '::__construct'];
}
if (isset(self::$_this_assignments[$method_id])) {
$this_assignments = TypeChecker::combineKeyedTypes($this_assignments, self::$_this_assignments[$method_id]);
}
if (isset(self::$_this_calls[$method_id])) {
foreach (self::$_this_calls[$method_id] as $call) {
$call_assingments = self::getThisAssignments($absolute_class . '::' . $call);
$this_assignments = TypeChecker::combineKeyedTypes($this_assignments, $call_assingments);
}
}
return $this_assignments;
}
}