1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-30 04:39:00 +01:00
psalm/tests/ClassLikeStringTest.php

1020 lines
34 KiB
PHP
Raw Permalink Normal View History

<?php
namespace Psalm\Tests;
use Psalm\Config;
use Psalm\Context;
2021-12-03 20:29:06 +01:00
use Psalm\Exception\CodeException;
2021-12-04 21:55:53 +01:00
use Psalm\Tests\Traits\InvalidCodeAnalysisTestTrait;
use Psalm\Tests\Traits\ValidCodeAnalysisTestTrait;
class ClassLikeStringTest extends TestCase
{
2021-12-04 21:55:53 +01:00
use InvalidCodeAnalysisTestTrait;
use ValidCodeAnalysisTestTrait;
public function testDontAllowStringStandInForNewClass(): void
{
2019-05-17 00:36:36 +02:00
$this->expectExceptionMessage('InvalidStringClass');
2021-12-03 20:29:06 +01:00
$this->expectException(CodeException::class);
Config::getInstance()->allow_string_standin_for_class = false;
$this->addFile(
'somefile.php',
'<?php
class A {}
$a = "A";
2022-12-18 17:15:15 +01:00
new $a();',
);
$this->analyzeFile('somefile.php', new Context());
}
public function testDontAllowStringStandInForStaticMethodCall(): void
{
2019-05-17 00:36:36 +02:00
$this->expectExceptionMessage('InvalidStringClass');
2021-12-03 20:29:06 +01:00
$this->expectException(CodeException::class);
Config::getInstance()->allow_string_standin_for_class = false;
$this->addFile(
'somefile.php',
'<?php
class A {
public static function foo() : void {}
}
$a = "A";
2022-12-18 17:15:15 +01:00
$a::foo();',
);
$this->analyzeFile('somefile.php', new Context());
}
public function providerValidCodeParse(): iterable
{
return [
'arrayOfClassConstants' => [
'code' => '<?php
/**
* @param array<class-string> $arr
*/
function takesClassConstants(array $arr) : void {}
class A {}
class B {}
takesClassConstants([A::class, B::class]);',
],
'arrayOfStringClasses' => [
'code' => '<?php
/**
* @param array<class-string> $arr
*/
function takesClassConstants(array $arr) : void {}
class A {}
class B {}
takesClassConstants(["A", "B"]);',
Add support for strict arrays, fix type alias intersection, fix array_is_list assertion on non-lists (#8395) * Immutable CodeLocation * Remove excess clones * Remove external clones * Remove leftover clones * Fix final clone issue * Immutable storages * Refactoring * Fixes * Fixes * Fix * Fix * Fixes * Simplify * Fixes * Fix * Fixes * Update * Fix * Cache global types * Fix * Update * Update * Fixes * Fixes * Refactor * Fixes * Fix * Fix * More caching * Fix * Fix * Update * Update * Fix * Fixes * Update * Refactor * Update * Fixes * Break one more test * Fix * FIx * Fix * Fix * Fix * Fix * Improve performance and readability * Equivalent logic * Fixes * Revert * Revert "Revert" This reverts commit f9175100c8452c80559234200663fd4c4f4dd889. * Fix * Fix reference bug * Make default TypeVisitor immutable * Bugfix * Remove clones * Partial refactoring * Refactoring * Fixes * Fix * Fixes * Fixes * cs-fix * Fix final bugs * Add test * Misc fixes * Update * Fixes * Experiment with removing different property * revert "Experiment with removing different property" This reverts commit ac1156e077fc4ea633530d51096d27b6e88bfdf9. * Uniform naming * Uniform naming * Hack hotfix * Clean up $_FILES ref #8621 * Undo hack, try fixing properly * Helper method * Remove redundant call * Partially fix bugs * Cleanup * Change defaults * Fix bug * Fix (?, hope this doesn't break anything else) * cs-fix * Review fixes * Bugfix * Bugfix * Improve logic * Add support for list{} and callable-list{} types, properly implement array_is_list assertions (fixes #8389) * Default to sealed arrays * Fix array_merge bug * Fixes * Fix * Sealed type checks * Properly infer properties-of and get_object_vars on final classes * Fix array_map zipping * Fix tests * Fixes * Fixes * Fix more stuff * Recursively resolve type aliases * Fix typo * Fixes * Fix array_is_list assertion on keyed array * Add BC docs * Fixes * fix * Update * Update * Update * Update * Seal arrays with count assertions * Fix #8528 * Fix * Update * Improve sealed array foreach logic * get_object_vars on template properties * Fix sealed array assertion reconciler logic * Improved reconciler * Add tests * Single source of truth for test types * Fix tests * Fixup tests * Fixup tests * Fixup tests * Update * Fix tests * Fix tests * Final fixes * Fixes * Use list syntax only when needed * Fix tests * Cs-fix * Update docs * Update docs * Update docs * Update docs * Update docs * Document missing types * Update docs * Improve class-string-map docs * Update * Update * I love working on psalm :) * Keep arrays unsealed by default * Fixup tests * Fix syntax mistake * cs-fix * Fix typo * Re-import missing types * Keep strict types only in return types * argc/argv fixes * argc/argv fixes * Fix test * Comment-out valinor code, pinging @romm pls merge https://github.com/CuyZ/Valinor/pull/246 so we can add valinor to the psalm docs :)
2022-11-05 22:34:42 +01:00
'assertions' => [],
'ignored_issues' => ['ArgumentTypeCoercion'],
],
'singleClassConstantAsConstant' => [
'code' => '<?php
/**
* @param class-string $s
*/
function takesClassConstants(string $s) : void {}
class A {}
takesClassConstants(A::class);',
],
'singleClassConstantWithString' => [
'code' => '<?php
/**
* @param class-string $s
*/
function takesClassConstants(string $s) : void {}
class A {}
/** @psalm-suppress ArgumentTypeCoercion */
takesClassConstants("A");',
Add support for strict arrays, fix type alias intersection, fix array_is_list assertion on non-lists (#8395) * Immutable CodeLocation * Remove excess clones * Remove external clones * Remove leftover clones * Fix final clone issue * Immutable storages * Refactoring * Fixes * Fixes * Fix * Fix * Fixes * Simplify * Fixes * Fix * Fixes * Update * Fix * Cache global types * Fix * Update * Update * Fixes * Fixes * Refactor * Fixes * Fix * Fix * More caching * Fix * Fix * Update * Update * Fix * Fixes * Update * Refactor * Update * Fixes * Break one more test * Fix * FIx * Fix * Fix * Fix * Fix * Improve performance and readability * Equivalent logic * Fixes * Revert * Revert "Revert" This reverts commit f9175100c8452c80559234200663fd4c4f4dd889. * Fix * Fix reference bug * Make default TypeVisitor immutable * Bugfix * Remove clones * Partial refactoring * Refactoring * Fixes * Fix * Fixes * Fixes * cs-fix * Fix final bugs * Add test * Misc fixes * Update * Fixes * Experiment with removing different property * revert "Experiment with removing different property" This reverts commit ac1156e077fc4ea633530d51096d27b6e88bfdf9. * Uniform naming * Uniform naming * Hack hotfix * Clean up $_FILES ref #8621 * Undo hack, try fixing properly * Helper method * Remove redundant call * Partially fix bugs * Cleanup * Change defaults * Fix bug * Fix (?, hope this doesn't break anything else) * cs-fix * Review fixes * Bugfix * Bugfix * Improve logic * Add support for list{} and callable-list{} types, properly implement array_is_list assertions (fixes #8389) * Default to sealed arrays * Fix array_merge bug * Fixes * Fix * Sealed type checks * Properly infer properties-of and get_object_vars on final classes * Fix array_map zipping * Fix tests * Fixes * Fixes * Fix more stuff * Recursively resolve type aliases * Fix typo * Fixes * Fix array_is_list assertion on keyed array * Add BC docs * Fixes * fix * Update * Update * Update * Update * Seal arrays with count assertions * Fix #8528 * Fix * Update * Improve sealed array foreach logic * get_object_vars on template properties * Fix sealed array assertion reconciler logic * Improved reconciler * Add tests * Single source of truth for test types * Fix tests * Fixup tests * Fixup tests * Fixup tests * Update * Fix tests * Fix tests * Final fixes * Fixes * Use list syntax only when needed * Fix tests * Cs-fix * Update docs * Update docs * Update docs * Update docs * Update docs * Document missing types * Update docs * Improve class-string-map docs * Update * Update * I love working on psalm :) * Keep arrays unsealed by default * Fixup tests * Fix syntax mistake * cs-fix * Fix typo * Re-import missing types * Keep strict types only in return types * argc/argv fixes * argc/argv fixes * Fix test * Comment-out valinor code, pinging @romm pls merge https://github.com/CuyZ/Valinor/pull/246 so we can add valinor to the psalm docs :)
2022-11-05 22:34:42 +01:00
'assertions' => [],
],
'returnClassConstant' => [
'code' => '<?php
class A {}
/**
* @return class-string
*/
function takesClassConstants() : string {
return A::class;
}',
],
'returnClassConstantAllowCoercion' => [
'code' => '<?php
class A {}
/**
* @return class-string
*/
function takesClassConstants() : string {
return "A";
}',
Add support for strict arrays, fix type alias intersection, fix array_is_list assertion on non-lists (#8395) * Immutable CodeLocation * Remove excess clones * Remove external clones * Remove leftover clones * Fix final clone issue * Immutable storages * Refactoring * Fixes * Fixes * Fix * Fix * Fixes * Simplify * Fixes * Fix * Fixes * Update * Fix * Cache global types * Fix * Update * Update * Fixes * Fixes * Refactor * Fixes * Fix * Fix * More caching * Fix * Fix * Update * Update * Fix * Fixes * Update * Refactor * Update * Fixes * Break one more test * Fix * FIx * Fix * Fix * Fix * Fix * Improve performance and readability * Equivalent logic * Fixes * Revert * Revert "Revert" This reverts commit f9175100c8452c80559234200663fd4c4f4dd889. * Fix * Fix reference bug * Make default TypeVisitor immutable * Bugfix * Remove clones * Partial refactoring * Refactoring * Fixes * Fix * Fixes * Fixes * cs-fix * Fix final bugs * Add test * Misc fixes * Update * Fixes * Experiment with removing different property * revert "Experiment with removing different property" This reverts commit ac1156e077fc4ea633530d51096d27b6e88bfdf9. * Uniform naming * Uniform naming * Hack hotfix * Clean up $_FILES ref #8621 * Undo hack, try fixing properly * Helper method * Remove redundant call * Partially fix bugs * Cleanup * Change defaults * Fix bug * Fix (?, hope this doesn't break anything else) * cs-fix * Review fixes * Bugfix * Bugfix * Improve logic * Add support for list{} and callable-list{} types, properly implement array_is_list assertions (fixes #8389) * Default to sealed arrays * Fix array_merge bug * Fixes * Fix * Sealed type checks * Properly infer properties-of and get_object_vars on final classes * Fix array_map zipping * Fix tests * Fixes * Fixes * Fix more stuff * Recursively resolve type aliases * Fix typo * Fixes * Fix array_is_list assertion on keyed array * Add BC docs * Fixes * fix * Update * Update * Update * Update * Seal arrays with count assertions * Fix #8528 * Fix * Update * Improve sealed array foreach logic * get_object_vars on template properties * Fix sealed array assertion reconciler logic * Improved reconciler * Add tests * Single source of truth for test types * Fix tests * Fixup tests * Fixup tests * Fixup tests * Update * Fix tests * Fix tests * Final fixes * Fixes * Use list syntax only when needed * Fix tests * Cs-fix * Update docs * Update docs * Update docs * Update docs * Update docs * Document missing types * Update docs * Improve class-string-map docs * Update * Update * I love working on psalm :) * Keep arrays unsealed by default * Fixup tests * Fix syntax mistake * cs-fix * Fix typo * Re-import missing types * Keep strict types only in return types * argc/argv fixes * argc/argv fixes * Fix test * Comment-out valinor code, pinging @romm pls merge https://github.com/CuyZ/Valinor/pull/246 so we can add valinor to the psalm docs :)
2022-11-05 22:34:42 +01:00
'assertions' => [],
'ignored_issues' => ['LessSpecificReturnStatement', 'MoreSpecificReturnType'],
],
'returnClassConstantArray' => [
'code' => '<?php
class A {}
class B {}
/**
* @return array<class-string>
*/
function takesClassConstants() : array {
return [A::class, B::class];
}',
],
'returnClassConstantArrayAllowCoercion' => [
'code' => '<?php
class A {}
class B {}
/**
* @return array<class-string>
*/
function takesClassConstants() : array {
return ["A", "B"];
}',
Add support for strict arrays, fix type alias intersection, fix array_is_list assertion on non-lists (#8395) * Immutable CodeLocation * Remove excess clones * Remove external clones * Remove leftover clones * Fix final clone issue * Immutable storages * Refactoring * Fixes * Fixes * Fix * Fix * Fixes * Simplify * Fixes * Fix * Fixes * Update * Fix * Cache global types * Fix * Update * Update * Fixes * Fixes * Refactor * Fixes * Fix * Fix * More caching * Fix * Fix * Update * Update * Fix * Fixes * Update * Refactor * Update * Fixes * Break one more test * Fix * FIx * Fix * Fix * Fix * Fix * Improve performance and readability * Equivalent logic * Fixes * Revert * Revert "Revert" This reverts commit f9175100c8452c80559234200663fd4c4f4dd889. * Fix * Fix reference bug * Make default TypeVisitor immutable * Bugfix * Remove clones * Partial refactoring * Refactoring * Fixes * Fix * Fixes * Fixes * cs-fix * Fix final bugs * Add test * Misc fixes * Update * Fixes * Experiment with removing different property * revert "Experiment with removing different property" This reverts commit ac1156e077fc4ea633530d51096d27b6e88bfdf9. * Uniform naming * Uniform naming * Hack hotfix * Clean up $_FILES ref #8621 * Undo hack, try fixing properly * Helper method * Remove redundant call * Partially fix bugs * Cleanup * Change defaults * Fix bug * Fix (?, hope this doesn't break anything else) * cs-fix * Review fixes * Bugfix * Bugfix * Improve logic * Add support for list{} and callable-list{} types, properly implement array_is_list assertions (fixes #8389) * Default to sealed arrays * Fix array_merge bug * Fixes * Fix * Sealed type checks * Properly infer properties-of and get_object_vars on final classes * Fix array_map zipping * Fix tests * Fixes * Fixes * Fix more stuff * Recursively resolve type aliases * Fix typo * Fixes * Fix array_is_list assertion on keyed array * Add BC docs * Fixes * fix * Update * Update * Update * Update * Seal arrays with count assertions * Fix #8528 * Fix * Update * Improve sealed array foreach logic * get_object_vars on template properties * Fix sealed array assertion reconciler logic * Improved reconciler * Add tests * Single source of truth for test types * Fix tests * Fixup tests * Fixup tests * Fixup tests * Update * Fix tests * Fix tests * Final fixes * Fixes * Use list syntax only when needed * Fix tests * Cs-fix * Update docs * Update docs * Update docs * Update docs * Update docs * Document missing types * Update docs * Improve class-string-map docs * Update * Update * I love working on psalm :) * Keep arrays unsealed by default * Fixup tests * Fix syntax mistake * cs-fix * Fix typo * Re-import missing types * Keep strict types only in return types * argc/argv fixes * argc/argv fixes * Fix test * Comment-out valinor code, pinging @romm pls merge https://github.com/CuyZ/Valinor/pull/246 so we can add valinor to the psalm docs :)
2022-11-05 22:34:42 +01:00
'assertions' => [],
'ignored_issues' => ['LessSpecificReturnStatement', 'MoreSpecificReturnType'],
],
'ifClassStringEquals' => [
'code' => '<?php
class A {}
class B {}
/** @param class-string $class */
function foo(string $class) : void {
if ($class === A::class) {}
if ($class === A::class || $class === B::class) {}
}',
],
'classStringCombination' => [
'code' => '<?php
class A {}
/** @return class-string */
function foo() : string {
return A::class;
}
/** @param class-string $a */
function bar(string $a) : void {}
bar(rand(0, 1) ? foo() : A::class);
bar(rand(0, 1) ? A::class : foo());',
],
2018-08-21 23:59:06 +02:00
'assertionToClassString' => [
'code' => '<?php
2018-08-21 23:59:06 +02:00
class A {}
function foo(string $s) : void {
if ($s === A::class) {
bar($s);
}
}
/** @param class-string $s */
function bar(string $s) : void {
new $s();
}',
'assertions' => [],
'ignored_issues' => ['MixedMethodCall'],
2018-08-21 23:59:06 +02:00
],
'constantArrayOffset' => [
'code' => '<?php
2018-08-21 23:59:06 +02:00
class A {
const FOO = [
B::class => "bar",
];
}
class B {}
/** @param class-string $s */
function bar(string $s) : void {}
foreach (A::FOO as $class => $_) {
bar($class);
}',
],
2018-08-23 17:43:53 +02:00
'arrayEquivalence' => [
'code' => '<?php
2018-08-23 17:43:53 +02:00
class A {}
class B {}
$foo = [
A::class,
B::class
];
foreach ($foo as $class) {
if ($class === A::class) {}
}',
],
'switchMixedVar' => [
'code' => '<?php
class A {}
class B {}
class C {}
/** @param mixed $a */
function foo($a) : void {
switch ($a) {
case A::class:
return;
2018-11-02 22:03:49 +01:00
case B::class:
case C::class:
return;
}
}',
],
2018-11-02 22:03:49 +01:00
'reconcileToFalsy' => [
'code' => '<?php
/** @psalm-param ?class-string $s */
function bar(?string $s) : void {}
2018-11-02 22:03:49 +01:00
class A {}
/** @psalm-return ?class-string */
function bat() {
if (rand(0, 1)) return null;
return A::class;
2018-11-02 22:03:49 +01:00
}
$a = bat();
$a ? 1 : 0;
bar($a);',
2018-11-02 22:03:49 +01:00
],
'allowTraitClassComparison' => [
'code' => '<?php
trait T {
public function foo() : void {
if (self::class === A::class) {}
if (self::class !== A::class) {}
}
}
class A {
use T;
}
class B {
use T;
2019-03-23 19:27:54 +01:00
}',
],
2019-01-02 17:18:22 +01:00
'refineStringToClassString' => [
'code' => '<?php
2019-01-02 17:18:22 +01:00
class A {}
function foo(string $s) : ?A {
2019-01-02 17:18:22 +01:00
if ($s !== A::class) {
return null;
2019-01-02 17:18:22 +01:00
}
return new $s();
2019-01-02 17:18:22 +01:00
}',
],
2019-01-02 20:24:31 +01:00
'takesChildOfClass' => [
'code' => '<?php
2019-01-02 20:24:31 +01:00
class A {}
class AChild extends A {}
/**
* @param class-string<A> $s
*/
function foo(string $s) : void {}
foo(AChild::class);',
],
2019-01-05 21:12:42 +01:00
'returnClassConstantClassStringParameterized' => [
'code' => '<?php
2019-01-05 21:12:42 +01:00
class A {}
/**
* @return class-string<A> $s
*/
function foo(A $a) : string {
return $a::class;
}',
],
'returnGetCalledClassClassStringParameterized' => [
'code' => '<?php
class A {
/**
* @return class-string<A> $s
*/
function foo() : string {
return get_called_class();
}
}',
],
2019-01-05 21:12:42 +01:00
'returnGetClassClassStringParameterized' => [
'code' => '<?php
2019-01-05 21:12:42 +01:00
class A {}
/**
* @return class-string<A> $s
*/
function foo(A $a) : string {
return get_class($a);
}',
],
'returnGetParentClassClassStringParameterizedNoArg' => [
'code' => '<?php
class A {}
class B extends A {
/**
* @return class-string<A> $s
*/
function foo() : string {
return get_parent_class();
}
}',
],
2019-01-05 21:12:42 +01:00
'createClassOfTypeFromString' => [
'code' => '<?php
2019-01-05 21:12:42 +01:00
class A {}
/**
* @return class-string<A> $s
*/
function foo(string $s) : string {
if (!class_exists($s)) {
throw new \UnexpectedValueException("bad");
}
if (!is_a($s, A::class, true)) {
throw new \UnexpectedValueException("bad");
}
return $s;
}',
],
'createClassOfTypeFromStringUsingIsSubclassOf' => [
'code' => '<?php
class A {}
/**
* @return class-string<A> $s
*/
function foo(string $s) : string {
if (!class_exists($s)) {
throw new \UnexpectedValueException("bad");
}
if (!is_subclass_of($s, A::class)) {
throw new \UnexpectedValueException("bad");
}
return $s;
}',
],
'checkSubclassOfAbstract' => [
'code' => '<?php
interface Foo {
public static function Bar() : bool;
};
class FooClass implements Foo {
public static function Bar() : bool {
return true;
}
}
function foo(string $className) : bool {
if (is_subclass_of($className, Foo::class, true)) {
return $className::Bar();
}
return false;
}',
],
'explicitIntersectionClassString' => [
'code' => '<?php
interface Foo {
public static function one() : void;
};
interface Bar {
public static function two() : void;
}
/**
* @param interface-string<Foo&Bar> $className
*/
function foo($className) : void {
$className::one();
$className::two();
2019-03-23 19:27:54 +01:00
}',
],
'implicitIntersectionClassString' => [
'code' => '<?php
interface Foo {
public static function one() : bool;
};
interface Bar {
public static function two() : bool;
}
/**
* @param interface-string<Bar> $className
*/
function foo(string $className) : void {
$className::two();
if (is_subclass_of($className, Foo::class, true)) {
$className::one();
$className::two();
}
2019-03-23 19:27:54 +01:00
}',
],
'instanceofClassString' => [
'code' => '<?php
function f(Exception $e): ?InvalidArgumentException {
$type = InvalidArgumentException::class;
if ($e instanceof $type) {
return $e;
} else {
return null;
}
2019-03-23 19:27:54 +01:00
}',
],
2021-09-17 19:52:11 +02:00
'instanceofClassStringNotLiteral' => [
'code' => '<?php
2021-09-17 19:52:11 +02:00
final class Z {
/**
* @psalm-var class-string<stdClass> $class
*/
private string $class = stdClass::class;
public function go(object $object): ?stdClass {
$a = $this->class;
if ($object instanceof $a) {
return $object;
}
return null;
}
2022-12-18 17:15:15 +01:00
}',
2021-09-17 19:52:11 +02:00
],
2019-02-01 03:06:21 +01:00
'returnTemplatedClassString' => [
'code' => '<?php
2019-02-01 03:06:21 +01:00
/**
* @template T
*
* @param class-string<T> $shouldBe
* @return class-string<T>
*/
function identity(string $shouldBe) : string { return $shouldBe; }
identity(DateTimeImmutable::class)::createFromMutable(new DateTime());',
],
'filterIsObject' => [
'code' => '<?php
/**
* @param interface-string<DateTimeInterface>|DateTimeInterface $maybe
*
* @return interface-string<DateTimeInterface>
*/
function Foo($maybe) : string {
if (is_object($maybe)) {
return get_class($maybe);
}
return $maybe;
}',
],
'filterIsString' => [
'code' => '<?php
/**
* @param interface-string<DateTimeInterface>|DateTimeInterface $maybe
*
* @return interface-string<DateTimeInterface>
*/
function Bar($maybe) : string {
if (is_string($maybe)) {
return $maybe;
}
return get_class($maybe);
}',
],
2019-03-08 23:35:09 +01:00
'mergeLiteralClassStringsWithGeneric' => [
'code' => '<?php
2019-03-08 23:35:09 +01:00
class Base {}
class A extends Base {}
class B extends Base {}
/**
* @param array<A::class|B::class> $literal_classes
* @param array<class-string<Base>> $generic_classes
* @return array<class-string<Base>>
*/
function foo(array $literal_classes, array $generic_classes) {
return array_merge($literal_classes, $generic_classes);
2019-03-23 19:27:54 +01:00
}',
2019-03-08 23:35:09 +01:00
],
'mergeGenericClassStringsWithLiteral' => [
'code' => '<?php
2019-03-08 23:35:09 +01:00
class Base {}
class A extends Base {}
class B extends Base {}
/**
* @param array<A::class|B::class> $literal_classes
* @param array<class-string<Base>> $generic_classes
* @return array<class-string<Base>>
*/
function bar(array $literal_classes, array $generic_classes) {
return array_merge($generic_classes, $literal_classes);
2019-03-23 19:27:54 +01:00
}',
2019-03-08 23:35:09 +01:00
],
'noCrashWithIsSubclassOfNonExistentVariable' => [
'code' => '<?php
class A {}
function foo() : void {
/**
* @psalm-suppress UndefinedVariable
* @psalm-suppress MixedArgument
*/
if (!is_subclass_of($s, A::class)) {}
}',
],
'allowClassExistsCheckOnClassString' => [
'code' => '<?php
class C
{
public function __construct() {
if (class_exists(\Doesnt\Really::class)) {
\Doesnt\Really::something();
}
}
2019-07-05 22:24:00 +02:00
}',
],
'allowClassExistsCheckOnString' => [
'code' => '<?php
class C
{
public function __construct() {
if (class_exists("Doesnt\\Really")) {
\Doesnt\Really::something();
}
}
2019-07-05 22:24:00 +02:00
}',
],
'allowComparisonToStaticClassString' => [
'code' => '<?php
class A {
const CLASSES = ["foobar" => B::class];
function foo(): bool {
return self::CLASSES["foobar"] === static::class;
}
}
2019-07-05 22:24:00 +02:00
class B extends A {}',
],
'noCrashWhenClassExists' => [
'code' => '<?php
class A {}
if (class_exists(A::class)) {
new \RuntimeException();
2019-07-05 22:24:00 +02:00
}',
],
'noCrashWhenClassExistsNegated' => [
'code' => '<?php
class A {}
if (!class_exists(A::class)) {
new \RuntimeException();
2019-07-05 22:24:00 +02:00
}',
],
'createNewObjectFromGetClass' => [
'code' => '<?php
/**
* @psalm-consistent-constructor
*/
class Example {
static function staticMethod(): string {
return "";
}
public function instanceMethod(): string {
$className = get_class();
return $className::staticMethod();
}
}
/**
* @param class-string<Example> $className
*/
function example(string $className, Example $object): string {
$objectClassName = get_class($object);
takesExampleClassString($className);
takesExampleClassString($objectClassName);
if (rand(0, 1)) {
return (new $className)->instanceMethod();
}
if (rand(0, 1)) {
return (new $objectClassName)->instanceMethod();
}
if (rand(0, 1)) {
return $className::staticMethod();
}
return $objectClassName::staticMethod();
}
/** @param class-string<Example> $className */
2022-12-18 17:15:15 +01:00
function takesExampleClassString(string $className): void {}',
],
'noCrashOnPolyfill' => [
'code' => '<?php
if (class_exists(My_Parent::class) && !class_exists(My_Extend::class)) {
/**
* Extended class
*/
class My_Extend extends My_Parent {
/**
* Construct
*
* @return void
*/
public function __construct() {
echo "foo";
}
}
}',
],
'selfResolvedOnStaticProperty' => [
'code' => '<?php
namespace Bar;
class Foo {
/** @var class-string<self> */
private static $c;
/**
* @return class-string<self>
*/
public static function r() : string
{
return self::$c;
}
2022-12-18 17:15:15 +01:00
}',
],
2020-03-09 23:59:56 +01:00
'traitClassStringClone' => [
'code' => '<?php
2020-03-09 23:59:56 +01:00
trait Factory
{
/** @return class-string<static> */
public static function getFactoryClass()
{
return static::class;
}
}
/**
* @psalm-consistent-constructor
*/
2020-03-09 23:59:56 +01:00
class A
{
use Factory;
public static function factory(): self
{
$class = static::getFactoryClass();
return new $class;
}
}
/**
* @psalm-consistent-constructor
*/
2020-03-09 23:59:56 +01:00
class B
{
use Factory;
public static function factory(): self
{
$class = static::getFactoryClass();
return new $class;
}
2022-12-18 17:15:15 +01:00
}',
2020-03-09 23:59:56 +01:00
],
'staticClassReturn' => [
'code' => '<?php
/**
* @psalm-consistent-constructor
*/
class A {
/** @return static */
public static function getInstance() {
$class = static::class;
return new $class();
}
2022-12-18 17:15:15 +01:00
}',
],
2020-03-27 14:51:53 +01:00
'getCalledClassIsStaticClass' => [
'code' => '<?php
/**
* @psalm-consistent-constructor
*/
2020-03-27 14:51:53 +01:00
class A {
/** @return static */
public function getStatic() {
$c = get_called_class();
return new $c();
}
2022-12-18 17:15:15 +01:00
}',
2020-03-27 14:51:53 +01:00
],
'accessConstantOnClassStringVariable' => [
'code' => '<?php
class Beep {
/** @var string */
public static $boop = "boop";
}
$beep = rand(0, 1) ? new Beep() : Beep::class;
echo $beep::$boop;
',
],
2021-03-27 02:21:38 +01:00
'ClassConstFetchWithTemplate' => [
'code' => '<?php
2021-03-27 02:21:38 +01:00
/**
* @template T of object
* @psalm-param T $obj
* @return class-string<T>
*/
function a($obj) {
$class = $obj::class;
return $class;
}',
],
'classStringAllowsClasses' => [
'code' => '<?php
/**
* @param class-string $s
*/
function takesOpen(string $s): void {}
/**
* @param class-string<Exception> $s
*/
function takesException(string $s): void {}
/**
* @param class-string<Exception> $s
*/
function takesThrowable(string $s): void {}
takesOpen(InvalidArgumentException::class);
takesException(InvalidArgumentException::class);
takesThrowable(InvalidArgumentException::class);',
],
'reflectionClassCoercion' => [
'code' => '<?php
/** @return ReflectionClass<object> */
function takesString(string $s) {
/** @psalm-suppress ArgumentTypeCoercion */
return new ReflectionClass($s);
}',
2021-03-27 02:21:38 +01:00
],
'checkDifferentSubclass' => [
'code' => '<?php
class A {}
class B {}
Add support for strict arrays, fix type alias intersection, fix array_is_list assertion on non-lists (#8395) * Immutable CodeLocation * Remove excess clones * Remove external clones * Remove leftover clones * Fix final clone issue * Immutable storages * Refactoring * Fixes * Fixes * Fix * Fix * Fixes * Simplify * Fixes * Fix * Fixes * Update * Fix * Cache global types * Fix * Update * Update * Fixes * Fixes * Refactor * Fixes * Fix * Fix * More caching * Fix * Fix * Update * Update * Fix * Fixes * Update * Refactor * Update * Fixes * Break one more test * Fix * FIx * Fix * Fix * Fix * Fix * Improve performance and readability * Equivalent logic * Fixes * Revert * Revert "Revert" This reverts commit f9175100c8452c80559234200663fd4c4f4dd889. * Fix * Fix reference bug * Make default TypeVisitor immutable * Bugfix * Remove clones * Partial refactoring * Refactoring * Fixes * Fix * Fixes * Fixes * cs-fix * Fix final bugs * Add test * Misc fixes * Update * Fixes * Experiment with removing different property * revert "Experiment with removing different property" This reverts commit ac1156e077fc4ea633530d51096d27b6e88bfdf9. * Uniform naming * Uniform naming * Hack hotfix * Clean up $_FILES ref #8621 * Undo hack, try fixing properly * Helper method * Remove redundant call * Partially fix bugs * Cleanup * Change defaults * Fix bug * Fix (?, hope this doesn't break anything else) * cs-fix * Review fixes * Bugfix * Bugfix * Improve logic * Add support for list{} and callable-list{} types, properly implement array_is_list assertions (fixes #8389) * Default to sealed arrays * Fix array_merge bug * Fixes * Fix * Sealed type checks * Properly infer properties-of and get_object_vars on final classes * Fix array_map zipping * Fix tests * Fixes * Fixes * Fix more stuff * Recursively resolve type aliases * Fix typo * Fixes * Fix array_is_list assertion on keyed array * Add BC docs * Fixes * fix * Update * Update * Update * Update * Seal arrays with count assertions * Fix #8528 * Fix * Update * Improve sealed array foreach logic * get_object_vars on template properties * Fix sealed array assertion reconciler logic * Improved reconciler * Add tests * Single source of truth for test types * Fix tests * Fixup tests * Fixup tests * Fixup tests * Update * Fix tests * Fix tests * Final fixes * Fixes * Use list syntax only when needed * Fix tests * Cs-fix * Update docs * Update docs * Update docs * Update docs * Update docs * Document missing types * Update docs * Improve class-string-map docs * Update * Update * I love working on psalm :) * Keep arrays unsealed by default * Fixup tests * Fix syntax mistake * cs-fix * Fix typo * Re-import missing types * Keep strict types only in return types * argc/argv fixes * argc/argv fixes * Fix test * Comment-out valinor code, pinging @romm pls merge https://github.com/CuyZ/Valinor/pull/246 so we can add valinor to the psalm docs :)
2022-11-05 22:34:42 +01:00
/** @param class-string<A> $s */
function takesAString(string $a): void {}
/** @param class-string<B> $s */
function takesBString(string $a): void {}
Add support for strict arrays, fix type alias intersection, fix array_is_list assertion on non-lists (#8395) * Immutable CodeLocation * Remove excess clones * Remove external clones * Remove leftover clones * Fix final clone issue * Immutable storages * Refactoring * Fixes * Fixes * Fix * Fix * Fixes * Simplify * Fixes * Fix * Fixes * Update * Fix * Cache global types * Fix * Update * Update * Fixes * Fixes * Refactor * Fixes * Fix * Fix * More caching * Fix * Fix * Update * Update * Fix * Fixes * Update * Refactor * Update * Fixes * Break one more test * Fix * FIx * Fix * Fix * Fix * Fix * Improve performance and readability * Equivalent logic * Fixes * Revert * Revert "Revert" This reverts commit f9175100c8452c80559234200663fd4c4f4dd889. * Fix * Fix reference bug * Make default TypeVisitor immutable * Bugfix * Remove clones * Partial refactoring * Refactoring * Fixes * Fix * Fixes * Fixes * cs-fix * Fix final bugs * Add test * Misc fixes * Update * Fixes * Experiment with removing different property * revert "Experiment with removing different property" This reverts commit ac1156e077fc4ea633530d51096d27b6e88bfdf9. * Uniform naming * Uniform naming * Hack hotfix * Clean up $_FILES ref #8621 * Undo hack, try fixing properly * Helper method * Remove redundant call * Partially fix bugs * Cleanup * Change defaults * Fix bug * Fix (?, hope this doesn't break anything else) * cs-fix * Review fixes * Bugfix * Bugfix * Improve logic * Add support for list{} and callable-list{} types, properly implement array_is_list assertions (fixes #8389) * Default to sealed arrays * Fix array_merge bug * Fixes * Fix * Sealed type checks * Properly infer properties-of and get_object_vars on final classes * Fix array_map zipping * Fix tests * Fixes * Fixes * Fix more stuff * Recursively resolve type aliases * Fix typo * Fixes * Fix array_is_list assertion on keyed array * Add BC docs * Fixes * fix * Update * Update * Update * Update * Seal arrays with count assertions * Fix #8528 * Fix * Update * Improve sealed array foreach logic * get_object_vars on template properties * Fix sealed array assertion reconciler logic * Improved reconciler * Add tests * Single source of truth for test types * Fix tests * Fixup tests * Fixup tests * Fixup tests * Update * Fix tests * Fix tests * Final fixes * Fixes * Use list syntax only when needed * Fix tests * Cs-fix * Update docs * Update docs * Update docs * Update docs * Update docs * Document missing types * Update docs * Improve class-string-map docs * Update * Update * I love working on psalm :) * Keep arrays unsealed by default * Fixup tests * Fix syntax mistake * cs-fix * Fix typo * Re-import missing types * Keep strict types only in return types * argc/argv fixes * argc/argv fixes * Fix test * Comment-out valinor code, pinging @romm pls merge https://github.com/CuyZ/Valinor/pull/246 so we can add valinor to the psalm docs :)
2022-11-05 22:34:42 +01:00
/** @param class-string $s */
function foo(string $s): void {
if (is_subclass_of($s, A::class)) {
takesAString($s);
}
if (is_subclass_of($s, B::class)) {
takesBString($s);
}
}',
],
'checkDifferentSubclassAfterNotClassExists' => [
'code' => '<?php
class A {}
class B {}
/** @param class-string<A> $s */
function takesAString(string $a): void {}
/** @param class-string<B> $s */
function takesBString(string $a): void {}
Add support for strict arrays, fix type alias intersection, fix array_is_list assertion on non-lists (#8395) * Immutable CodeLocation * Remove excess clones * Remove external clones * Remove leftover clones * Fix final clone issue * Immutable storages * Refactoring * Fixes * Fixes * Fix * Fix * Fixes * Simplify * Fixes * Fix * Fixes * Update * Fix * Cache global types * Fix * Update * Update * Fixes * Fixes * Refactor * Fixes * Fix * Fix * More caching * Fix * Fix * Update * Update * Fix * Fixes * Update * Refactor * Update * Fixes * Break one more test * Fix * FIx * Fix * Fix * Fix * Fix * Improve performance and readability * Equivalent logic * Fixes * Revert * Revert "Revert" This reverts commit f9175100c8452c80559234200663fd4c4f4dd889. * Fix * Fix reference bug * Make default TypeVisitor immutable * Bugfix * Remove clones * Partial refactoring * Refactoring * Fixes * Fix * Fixes * Fixes * cs-fix * Fix final bugs * Add test * Misc fixes * Update * Fixes * Experiment with removing different property * revert "Experiment with removing different property" This reverts commit ac1156e077fc4ea633530d51096d27b6e88bfdf9. * Uniform naming * Uniform naming * Hack hotfix * Clean up $_FILES ref #8621 * Undo hack, try fixing properly * Helper method * Remove redundant call * Partially fix bugs * Cleanup * Change defaults * Fix bug * Fix (?, hope this doesn't break anything else) * cs-fix * Review fixes * Bugfix * Bugfix * Improve logic * Add support for list{} and callable-list{} types, properly implement array_is_list assertions (fixes #8389) * Default to sealed arrays * Fix array_merge bug * Fixes * Fix * Sealed type checks * Properly infer properties-of and get_object_vars on final classes * Fix array_map zipping * Fix tests * Fixes * Fixes * Fix more stuff * Recursively resolve type aliases * Fix typo * Fixes * Fix array_is_list assertion on keyed array * Add BC docs * Fixes * fix * Update * Update * Update * Update * Seal arrays with count assertions * Fix #8528 * Fix * Update * Improve sealed array foreach logic * get_object_vars on template properties * Fix sealed array assertion reconciler logic * Improved reconciler * Add tests * Single source of truth for test types * Fix tests * Fixup tests * Fixup tests * Fixup tests * Update * Fix tests * Fix tests * Final fixes * Fixes * Use list syntax only when needed * Fix tests * Cs-fix * Update docs * Update docs * Update docs * Update docs * Update docs * Document missing types * Update docs * Improve class-string-map docs * Update * Update * I love working on psalm :) * Keep arrays unsealed by default * Fixup tests * Fix syntax mistake * cs-fix * Fix typo * Re-import missing types * Keep strict types only in return types * argc/argv fixes * argc/argv fixes * Fix test * Comment-out valinor code, pinging @romm pls merge https://github.com/CuyZ/Valinor/pull/246 so we can add valinor to the psalm docs :)
2022-11-05 22:34:42 +01:00
function foo(string $s): void {
if (!class_exists($s, false)) {
return;
}
if (is_subclass_of($s, A::class)) {
takesAString($s);
}
if (is_subclass_of($s, B::class)) {
takesBString($s);
}
}',
],
'compareGetClassToLiteralClass' => [
'code' => '<?php
class A {}
class B extends A {}
function foo(A $a): void {
if (get_class($a) === A::class) {}
}',
],
2022-12-04 20:28:53 +01:00
'classStringUnion' => [
'code' => '<?php
class Foo
{
/** @var class-string<TypeOne>|class-string<TypeTwo> */
public ?string $bar = null;
/** @var class-string<TypeOne|TypeTwo> */
public ?string $baz = null;
}
class TypeOne {}
class TypeTwo {}
$foo = new Foo;
$foo->bar = TypeOne::class;
$foo->bar = TypeOne::class;
$foo->baz = TypeTwo::class;
2022-12-18 17:15:15 +01:00
$foo->baz = TypeTwo::class;',
],
];
}
public function providerInvalidCodeParse(): iterable
{
return [
'arrayOfStringClasses' => [
'code' => '<?php
/**
* @param array<class-string> $arr
*/
function takesClassConstants(array $arr) : void {}
class A {}
class B {}
takesClassConstants(["A", "B"]);',
'error_message' => 'ArgumentTypeCoercion',
],
'arrayOfNonExistentStringClasses' => [
'code' => '<?php
/**
* @param array<class-string> $arr
*/
function takesClassConstants(array $arr) : void {}
/** @psalm-suppress ArgumentTypeCoercion */
takesClassConstants(["A", "B"]);',
'error_message' => 'UndefinedClass',
],
'singleClassConstantWithInvalidDocblock' => [
'code' => '<?php
/**
* @param clas-string $s
*/
function takesClassConstants(string $s) : void {}',
'error_message' => 'InvalidDocblock',
],
'returnClassConstantDisallowCoercion' => [
'code' => '<?php
class A {}
/**
* @return class-string
*/
function takesClassConstants() : string {
return "A";
}',
'error_message' => 'LessSpecificReturnStatement',
],
'returnClassConstantArrayDisallowCoercion' => [
'code' => '<?php
class A {}
/**
* @return array<class-string>
*/
function takesClassConstants() : array {
return ["A", "B"];
}',
'error_message' => 'LessSpecificReturnStatement',
],
'returnClassConstantArrayAllowCoercionWithUndefinedClass' => [
'code' => '<?php
class A {}
/**
* @return array<class-string>
*/
function takesClassConstants() : array {
return ["A", "B"];
}',
'error_message' => 'UndefinedClass',
'ignored_issues' => ['LessSpecificReturnStatement', 'MoreSpecificReturnType'],
],
'badClassStringConstructor' => [
'code' => '<?php
class Foo
{
public function __construct(int $_)
{
}
}
/**
* @return Foo
*/
function makeFoo()
{
$fooClass = Foo::class;
return new $fooClass;
}',
'error_message' => 'TooFewArguments',
],
'unknownConstructorCall' => [
'code' => '<?php
/** @param class-string $s */
function bar(string $s) : void {
new $s();
}',
'error_message' => 'MixedMethodCall',
],
2019-01-02 20:24:31 +01:00
'doesNotTakeChildOfClass' => [
'code' => '<?php
2019-01-02 20:24:31 +01:00
class A {}
class AChild extends A {}
/**
* @param A::class $s
*/
function foo(string $s) : void {}
foo(AChild::class);',
'error_message' => 'InvalidArgument',
],
2019-01-05 21:12:42 +01:00
'createClassOfWrongTypeFromString' => [
'code' => '<?php
2019-01-05 21:12:42 +01:00
class A {}
class B {}
/**
* @return class-string<A> $s
*/
function foo(string $s) : string {
if (!class_exists($s)) {
throw new \UnexpectedValueException("bad");
}
if (!is_a($s, B::class, true)) {
throw new \UnexpectedValueException("bad");
}
return $s;
}',
'error_message' => 'InvalidReturnStatement',
],
];
}
}