Skip to content

Support for PDO subclasses returned by PDO::connect #12359

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
xPaw opened this issue Jan 2, 2025 · 2 comments · May be fixed by phpstan/phpstan-src#4015
Open

Support for PDO subclasses returned by PDO::connect #12359

xPaw opened this issue Jan 2, 2025 · 2 comments · May be fixed by phpstan/phpstan-src#4015

Comments

@xPaw
Copy link

xPaw commented Jan 2, 2025

Feature request

Repro: https://phpstan.org/r/a737df77-1a70-4ef6-af8d-c3a605bf84cc

PHP 8.4 added PDO::connect static function which returns a PDO subclass for a specific driver
https://www.php.net/manual/en/pdo.connect.php

However the issue here, even if you added support for parsing the DSN string to get the correct subclass, I suspect most of them will be coming from configs/env, so it may not be available at analysis time.

Unsure what a good solution for this would be, for now I can manually narrow the type with a comment:

	/** @var \Pdo\Mysql $db */
	$db = PDO::connect();
	return $db;

Did PHPStan help you today? Did it make you happy in any way?

No response

@ondrejmirtes
Copy link
Member

We'd have to detect the driver from the DSN connection string.

@phpstan-bot
Copy link
Contributor

@xPaw After the latest push in 2.1.x, PHPStan now reports different result with your code snippet:

@@ @@
-PHP 8.4 (2 errors)
+PHP 8.4 (1 error)
 ==========
 
  9: Property HelloWorld::$db (Pdo\Mysql) does not accept PDO.
-10: Method HelloWorld::db() should return Pdo\Mysql but returns PDO.
 
-PHP 7.2 – 8.3 (5 errors)
+PHP 7.2 – 8.3 (4 errors)
 ==========
 
  5: Property HelloWorld::$db has unknown class Pdo\Mysql as its type.
  7: Method HelloWorld::db() has invalid return type Pdo\Mysql.
  9: Call to an undefined static method PDO::connect().
- 9: Property HelloWorld::$db (Pdo\Mysql) does not accept mixed.
-10: Method HelloWorld::db() should return Pdo\Mysql but returns mixed.
+ 9: Property HelloWorld::$db (Pdo\Mysql) does not accept mixed.
Full report

PHP 8.4 (1 error)

Line Error
9 Property HelloWorld::$db (Pdo\Mysql) does not accept PDO.

PHP 7.2 – 8.3 (4 errors)

Line Error
5 Property HelloWorld::$db has unknown class Pdo\Mysql as its type.
7 Method HelloWorld::db() has invalid return type Pdo\Mysql.
9 Call to an undefined static method PDO::connect().
9 Property HelloWorld::$db (Pdo\Mysql) does not accept mixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants