1
0
mirror of https://github.com/danog/psalm.git synced 2024-12-03 10:07:52 +01:00
psalm/tests/PropertyTypeTest.php

110 lines
2.5 KiB
PHP
Raw Normal View History

2016-07-12 06:53:36 +02:00
<?php
2016-07-26 00:37:44 +02:00
namespace Psalm\Tests;
2016-07-12 06:53:36 +02:00
use PhpParser\ParserFactory;
use PHPUnit_Framework_TestCase;
2016-11-02 07:29:00 +01:00
use Psalm\Checker\FileChecker;
use Psalm\Config;
use Psalm\Context;
2016-07-12 06:53:36 +02:00
class PropertyTypeTest extends PHPUnit_Framework_TestCase
{
2016-11-02 07:29:00 +01:00
protected static $parser;
protected static $file_filter;
2016-07-12 06:53:36 +02:00
public static function setUpBeforeClass()
{
2016-11-02 07:29:00 +01:00
self::$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
2016-07-12 06:53:36 +02:00
2016-11-02 07:29:00 +01:00
$config = Config::getInstance();
2016-07-12 06:53:36 +02:00
$config->throw_exception = true;
}
public function setUp()
{
2016-11-02 07:29:00 +01:00
FileChecker::clearCache();
2016-07-12 06:53:36 +02:00
}
public function testNewVarInIf()
{
2016-11-02 07:29:00 +01:00
$stmts = self::$parser->parse('<?php
2016-07-12 06:53:36 +02:00
class A {
/**
* @var mixed
*/
public $foo;
2016-11-11 23:13:24 +01:00
/** @return void */
2016-07-12 06:53:36 +02:00
public function bar()
{
if (rand(0,10) === 5) {
$this->foo = [];
}
if (!is_array($this->foo)) {
// do something
}
}
}
');
2016-11-02 07:29:00 +01:00
$file_checker = new FileChecker('somefile.php', $stmts);
2016-07-12 06:53:36 +02:00
$file_checker->check();
}
2016-10-03 17:40:42 +02:00
public function testSharedPropertyInIf()
{
2016-11-02 07:29:00 +01:00
$stmts = self::$parser->parse('<?php
2016-10-03 17:40:42 +02:00
class A {
/** @var int */
public $foo;
}
class B {
/** @var string */
public $foo;
}
$a = null;
$b = null;
if ($a instanceof A || $a instanceof B) {
$b = $a->foo;
}
');
2016-11-02 07:29:00 +01:00
$file_checker = new FileChecker('somefile.php', $stmts);
2016-10-03 17:40:42 +02:00
$context = new Context('somefile.php');
$file_checker->check(true, true, $context);
2016-10-15 19:10:05 +02:00
$this->assertEquals('null|string|int', (string) $context->vars_in_scope['$b']);
2016-10-03 17:40:42 +02:00
}
public function testSharedPropertyInElseIf()
{
2016-11-02 07:29:00 +01:00
$stmts = self::$parser->parse('<?php
2016-10-03 17:40:42 +02:00
class A {
/** @var int */
public $foo;
}
class B {
/** @var string */
public $foo;
}
$a = null;
$b = null;
if (rand(0, 10) === 4) {
// do nothing
}
elseif ($a instanceof A || $a instanceof B) {
$b = $a->foo;
}
');
2016-11-02 07:29:00 +01:00
$file_checker = new FileChecker('somefile.php', $stmts);
2016-10-03 17:40:42 +02:00
$context = new Context('somefile.php');
$file_checker->check(true, true, $context);
2016-10-15 19:10:05 +02:00
$this->assertEquals('null|string|int', (string) $context->vars_in_scope['$b']);
2016-10-03 17:40:42 +02:00
}
2016-07-12 06:53:36 +02:00
}