diff --git a/src/PhpGenerator/ClassLike.php b/src/PhpGenerator/ClassLike.php index ce49782d..15c2d30c 100644 --- a/src/PhpGenerator/ClassLike.php +++ b/src/PhpGenerator/ClassLike.php @@ -40,15 +40,28 @@ abstract class ClassLike public static function from(string|object $class, bool $withBodies = false): self { - return (new Factory) + $instance = (new Factory) ->fromClassReflection(new \ReflectionClass($class), $withBodies); + + if (!$instance instanceof static) { + $class = is_object($class) ? $class::class : $class; + trigger_error("$class cannot be represented with " . static::class . '. Call ' . $instance::class . '::' . __FUNCTION__ . '() or ' . __METHOD__ . '() instead.', E_USER_WARNING); + } + + return $instance; } public static function fromCode(string $code): self { - return (new Factory) + $instance = (new Factory) ->fromClassCode($code); + + if (!$instance instanceof static) { + trigger_error('Provided code cannot be represented with ' . static::class . '. Call ' . $instance::class . '::' . __FUNCTION__ . '() or ' . __METHOD__ . '() instead.', E_USER_WARNING); + } + + return $instance; } diff --git a/tests/PhpGenerator/ClassLike.typecheck.phpt b/tests/PhpGenerator/ClassLike.typecheck.phpt new file mode 100644 index 00000000..9b681c80 --- /dev/null +++ b/tests/PhpGenerator/ClassLike.typecheck.phpt @@ -0,0 +1,36 @@ + ClassType::from(Abc\Interface1::class), + E_USER_WARNING, + 'Abc\Interface1 cannot be represented with Nette\PhpGenerator\ClassType. Call Nette\PhpGenerator\InterfaceType::from() or Nette\PhpGenerator\ClassLike::from() instead.', +); + +Assert::error( + fn() => TraitType::from(Abc\Class1::class), + E_USER_WARNING, + 'Abc\Class1 cannot be represented with Nette\PhpGenerator\TraitType. Call Nette\PhpGenerator\ClassType::from() or Nette\PhpGenerator\ClassLike::from() instead.', +); + +Assert::error( + fn() => ClassType::fromCode(' InterfaceType::fromCode(' ClassType::from($class), $classes); +$res = array_map(fn($class) => ClassLike::from($class), $classes); sameFile(__DIR__ . '/expected/ClassType.from.trait-use.expect', implode("\n", $res)); -$res = array_map(fn($class) => ClassType::from($class, withBodies: true), $classes); +$res = array_map(fn($class) => ClassLike::from($class, withBodies: true), $classes); sameFile(__DIR__ . '/expected/ClassType.from.trait-use.bodies.expect', implode("\n", $res));