Search code examples
databasedockerdoctrinephpstan

Phpstan doctrine database connection error


I'm using doctrine in a project (not symfony). In this project I also use phpstan, i installed both phpstan/phpstan-doctrine and phpstan/extension-installer. My phpstan.neon is like this:

parameters:
    level: 8
    paths:
        - src/
    doctrine:
        objectManagerLoader: tests/object-manager.php

Inside tests/object-manager.php it return the result of a call to a function that return the entity manager.

Here is the code that create the entity manager

$database_url = $_ENV['DATABASE_URL'];
$isDevMode = $this->isDevMode();
$proxyDir = null;
$cache = null;
$useSimpleAnnotationReader = false;

$config = Setup::createAnnotationMetadataConfiguration(
    [$this->getProjectDirectory() . '/src'],
    $isDevMode,
    $proxyDir,
    $cache,
    $useSimpleAnnotationReader
);


// database configuration parameters
$conn = [
    'url' => $database_url,
];

// obtaining the entity manager
$entityManager = EntityManager::create($conn, $config);

When i run vendor/bin/phpstan analyze i get this error:

Internal error: An exception occurred in the driver: SQLSTATE[08006] [7] could not translate host name "postgres_db" to address: nodename nor servname provided, or not known

This appear because i'm using docker and my database url is postgres://user:password@postgres_db/database postgres_db is the name of my database container so the hostname is known inside the docker container.

When i run phpstan inside the container i do not have the error.

So is there a way to run phpstan outside docker ? Because i'm pretty sure that when i'll push my code the github workflow will fail because of this

Do phpstan need to try to reach the database ?


Solution

  • I opened an issue on the github of phpstan-doctrine and i had an answer by @jlherren that explained :

    The problem is that Doctrine needs to know what version of the DB server it is working with in order to instantiate the correct AbstractPlatform implementation, of which there are several available for the same DB vendor (e.g. PostgreSQL94Platform or PostgreSQL100Platform for postgres, and similarly for other DB drivers). To auto-detect this information, it will simply connect to the DB and query the version.

    I just changed my database url from:

    DATABASE_URL=postgres://user:password@database_ip/database
    

    To:

    DATABASE_URL=postgres://user:password@database_ip/database?serverVersion=14.2