Skip to content

Commit

Permalink
Fix psalm after release of new major versions of ORM and DBAL
Browse files Browse the repository at this point in the history
  • Loading branch information
ostrolucky committed Feb 10, 2024
1 parent fb22c93 commit fb9543f
Show file tree
Hide file tree
Showing 18 changed files with 53 additions and 64 deletions.
9 changes: 3 additions & 6 deletions Command/CreateDatabaseDoctrineCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
use Throwable;

use function in_array;
use function method_exists;
use function sprintf;

/**
Expand Down Expand Up @@ -62,13 +61,11 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}

// Need to get rid of _every_ occurrence of dbname from connection configuration and we have already extracted all relevant info from url
/** @psalm-suppress InvalidArrayOffset Need to be compatible with DBAL < 4, which still has `$params['url']` */
unset($params['dbname'], $params['path'], $params['url']);

$tmpConnection = DriverManager::getConnection($params, $connection->getConfiguration());

$schemaManager = method_exists($tmpConnection, 'createSchemaManager')
? $tmpConnection->createSchemaManager()
: $tmpConnection->getSchemaManager();
$tmpConnection = DriverManager::getConnection($params, $connection->getConfiguration());
$schemaManager = $tmpConnection->createSchemaManager();
$shouldNotCreateDatabase = $ifNotExists && in_array($name, $schemaManager->listDatabases());

// Only quote if we don't have a path
Expand Down
2 changes: 2 additions & 0 deletions Command/DoctrineCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ public function __construct(ManagerRegistry $doctrine)
* get a doctrine entity generator
*
* @return EntityGenerator
*
* @psalm-suppress UndefinedDocblockClass ORM < 3 specific
*/
protected function getEntityGenerator()
{
Expand Down
11 changes: 5 additions & 6 deletions Command/DropDatabaseDoctrineCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace Doctrine\Bundle\DoctrineBundle\Command;

use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Schema\SqliteSchemaManager;
use Doctrine\DBAL\Schema\SQLiteSchemaManager;
use InvalidArgumentException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
Expand All @@ -12,7 +12,6 @@

use function file_exists;
use function in_array;
use function method_exists;
use function sprintf;
use function unlink;

Expand Down Expand Up @@ -73,6 +72,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
throw new InvalidArgumentException("Connection does not contain a 'path' or 'dbname' parameter and cannot be dropped.");
}

/** @psalm-suppress InvalidArrayOffset Need to be compatible with DBAL < 4, which still has `$params['url']` */
unset($params['dbname'], $params['url']);

if (! $input->getOption('force')) {
Expand All @@ -89,9 +89,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
// as some vendors do not allow dropping the database connected to.
$connection->close();
$connection = DriverManager::getConnection($params, $connection->getConfiguration());
$schemaManager = method_exists($connection, 'createSchemaManager')
? $connection->createSchemaManager()
: $connection->getSchemaManager();
$schemaManager = $connection->createSchemaManager();
$shouldDropDatabase = ! $ifExists || in_array($name, $schemaManager->listDatabases());

// Only quote if we don't have a path
Expand All @@ -101,7 +99,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int

try {
if ($shouldDropDatabase) {
if ($schemaManager instanceof SqliteSchemaManager) {
/** @psalm-suppress TypeDoesNotContainType Bogus error, Doctrine\DBAL\Schema\AbstractSchemaManager<Doctrine\DBAL\Platforms\AbstractPlatform> does contain Doctrine\DBAL\Schema\SQLiteSchemaManager */
if ($schemaManager instanceof SQLiteSchemaManager) {
// dropDatabase() is deprecated for Sqlite
$connection->close();
if (file_exists($name)) {
Expand Down
2 changes: 2 additions & 0 deletions Command/Proxy/ConvertMappingDoctrineCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
* formats.
*
* @deprecated use Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand instead
*
* @psalm-suppress UndefinedClass ORM < 3
*/
class ConvertMappingDoctrineCommand extends ConvertMappingCommand
{
Expand Down
1 change: 1 addition & 0 deletions Command/Proxy/DoctrineCommandHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public static function setApplicationEntityManager(Application $application, $em
$em = $application->getKernel()->getContainer()->get('doctrine')->getManager($emName);
assert($em instanceof EntityManagerInterface);
$helperSet = $application->getHelperSet();
/** @psalm-suppress InvalidArgument ORM < 3 specific */
$helperSet->set(new EntityManagerHelper($em), 'em');

trigger_deprecation(
Expand Down
2 changes: 2 additions & 0 deletions Command/Proxy/EnsureProductionSettingsDoctrineCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
* Ensure the Doctrine ORM is configured properly for a production environment.
*
* @deprecated use Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand instead
*
* @psalm-suppress UndefinedClass ORM < 3 specific
*/
class EnsureProductionSettingsDoctrineCommand extends EnsureProductionSettingsCommand
{
Expand Down
4 changes: 3 additions & 1 deletion ConnectionFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,8 @@ public function createConnection(array $params, ?Configuration $config = null, ?
$connection = DriverManager::getConnection(...array_merge([$params, $config], $eventManager ? [$eventManager] : []));
$params = $this->addDatabaseSuffix(array_merge($connection->getParams(), $overriddenOptions));
$driver = $connection->getDriver();
$platform = $driver->getDatabasePlatform(
/** @psalm-suppress InvalidScalarArgument Bogus error, StaticServerVersionProvider implements Doctrine\DBAL\ServerVersionProvider */
$platform = $driver->getDatabasePlatform(
...(class_exists(StaticServerVersionProvider::class) ? [new StaticServerVersionProvider($params['serverVersion'] ?? '')] : []),
);

Expand Down Expand Up @@ -250,6 +251,7 @@ private function addDatabaseSuffix(array $params): array
*/
private function parseDatabaseUrl(array $params): array
{
/** @psalm-suppress InvalidArrayOffset Need to be compatible with DBAL < 4, which still has `$params['url']` */
if (! isset($params['url'])) {
return $params;
}
Expand Down
4 changes: 2 additions & 2 deletions Controller/ProfilerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use Doctrine\Bundle\DoctrineBundle\Registry;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Platforms\OraclePlatform;
use Doctrine\DBAL\Platforms\SqlitePlatform;
use Doctrine\DBAL\Platforms\SQLitePlatform;
use Doctrine\DBAL\Platforms\SQLServerPlatform;
use Exception;
use Symfony\Bridge\Doctrine\DataCollector\DoctrineDataCollector;
Expand Down Expand Up @@ -64,7 +64,7 @@ public function explainAction($token, $connectionName, $query)
assert($connection instanceof Connection);
try {
$platform = $connection->getDatabasePlatform();
if ($platform instanceof SqlitePlatform) {
if ($platform instanceof SQLitePlatform) {
$results = $this->explainSQLitePlatform($connection, $query);
} elseif ($platform instanceof SQLServerPlatform) {
throw new Exception('Explain for SQLServerPlatform is currently not supported. Contributions are welcome.');
Expand Down
4 changes: 1 addition & 3 deletions DataCollector/DoctrineDataCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
use Doctrine\ORM\Cache\CacheConfiguration;
use Doctrine\ORM\Cache\Logging\CacheLoggerChain;
use Doctrine\ORM\Cache\Logging\StatisticsCacheLogger;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Tools\SchemaValidator;
Expand Down Expand Up @@ -122,8 +121,7 @@ public function collect(Request $request, Response $response, ?Throwable $except
}
}

$emConfig = $em->getConfiguration();
assert($emConfig instanceof Configuration);
$emConfig = $em->getConfiguration();
$slcEnabled = $emConfig->isSecondLevelCacheEnabled();

if (! $slcEnabled) {
Expand Down
3 changes: 3 additions & 0 deletions DependencyInjection/DoctrineExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -849,10 +849,13 @@ protected function loadOrmEntityManagerMappingInformation(array $entityManager,
$mappingService = $this->getObjectManagerElementName($entityManager['name'] . '_' . $driverType . '_metadata_driver');
$mappingDriverDef = $container->getDefinition($mappingService);
$args = $mappingDriverDef->getArguments();
/** @psalm-suppress TypeDoesNotContainType Psalm doesn't know that $this->drivers is set by $this->loadMappingInformation() call */
if ($driverType === 'annotation') {
$args[2] = $entityManager['report_fields_where_declared'];
/** @psalm-suppress TypeDoesNotContainType Psalm doesn't know that $this->drivers is set by $this->loadMappingInformation() call */
} elseif ($driverType === 'attribute') {
$args[1] = $entityManager['report_fields_where_declared'];
/** @psalm-suppress TypeDoesNotContainType Psalm doesn't know that $this->drivers is set by $this->loadMappingInformation() call */
} elseif ($driverType === 'xml') {
$args[1] ??= SimplifiedXmlDriver::DEFAULT_FILE_EXTENSION;
$args[2] = $entityManager['validate_xml_mapping'];
Expand Down
7 changes: 1 addition & 6 deletions ManagerConfigurator.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,7 @@ private function enableFilters(EntityManagerInterface $entityManager): void

$filterCollection = $entityManager->getFilters();
foreach ($this->enabledFilters as $filter) {
$filterObject = $filterCollection->enable($filter);
if ($filterObject === null) {
continue;
}

$this->setFilterParameters($filter, $filterObject);
$this->setFilterParameters($filter, $filterCollection->enable($filter));
}
}

Expand Down
23 changes: 3 additions & 20 deletions Mapping/DisconnectedMetadataFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,7 @@
use RuntimeException;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;

use function array_pop;
use function class_exists;
use function dirname;
use function explode;
use function implode;
use function sprintf;
use function str_replace;
use function strpos;
Expand Down Expand Up @@ -110,22 +106,9 @@ public function getNamespaceMetadata($namespace, $path = null)
*/
public function findNamespaceAndPathForMetadata(ClassMetadataCollection $metadata, $path = null)
{
$all = $metadata->getMetadata();
if (class_exists($all[0]->name)) {
$r = new ReflectionClass($all[0]->name);
$path = $this->getBasePathForClass($r->getName(), $r->getNamespaceName(), dirname($r->getFilename()));
$ns = $r->getNamespaceName();
} elseif ($path) {
// Get namespace by removing the last component of the FQCN
$nsParts = explode('\\', $all[0]->name);
array_pop($nsParts);
$ns = implode('\\', $nsParts);
} else {
throw new RuntimeException(sprintf('Unable to determine where to save the "%s" class (use the --path option).', $all[0]->name));
}

$metadata->setPath($path);
$metadata->setNamespace($ns);
$r = new ReflectionClass($metadata->getMetadata()[0]->name);
$metadata->setPath($this->getBasePathForClass($r->getName(), $r->getNamespaceName(), dirname($r->getFilename())));
$metadata->setNamespace($r->getNamespaceName());
}

/**
Expand Down
1 change: 1 addition & 0 deletions Registry.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ public function getAliasNamespace($alias)
}

try {
/** @psalm-suppress UndefinedMethod ORM < 3 specific */
return $objectManager->getConfiguration()->getEntityNamespace($alias);
} catch (ORMException $e) {
}
Expand Down
1 change: 1 addition & 0 deletions Tests/Command/DropDatabaseDoctrineTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public function testExecute(array $options): void
'driver' => 'pdo_sqlite',
];

/** @psalm-suppress InvalidArgument Need to be compatible with DBAL < 4, which still has `$params['url']` */
$container = $this->getMockContainer($connectionName, $params);

$application = new Application();
Expand Down
6 changes: 3 additions & 3 deletions Tests/ConnectionFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace Doctrine\Bundle\DoctrineBundle\Tests;

use Doctrine\Bundle\DoctrineBundle\ConnectionFactory;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver;
Expand Down Expand Up @@ -110,6 +109,7 @@ public function testConnectionOverrideOptions(): void

public function testConnectionCharsetFromUrl()
{
/** @psalm-suppress InvalidArgument Need to be compatible with DBAL < 4, which still has `$params['url']` */
$connection = (new ConnectionFactory([]))->createConnection(
['url' => 'mysql://root:password@database:3306/main?charset=utf8mb4_unicode_ci'],
$this->configuration,
Expand Down Expand Up @@ -169,10 +169,10 @@ class FakeConnection extends Connection
/**
* {@inheritDoc}
*/
public function __construct(array $params, Driver $driver, ?Configuration $config = null, ?EventManager $eventManager = null)
public function __construct(array $params, Driver $driver, ?Configuration $config = null)
{
++self::$creationCount;

parent::__construct($params, $driver, $config, $eventManager);
parent::__construct($params, $driver, $config);
}
}
13 changes: 10 additions & 3 deletions Tests/DataCollector/DoctrineDataCollectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,14 +137,21 @@ public function testGetGroupedQueriesWithDeprecatedDebugStackLogger(): void
$this->markTestSkipped('This test requires symfony < 7.0');
}

$logger = $this->getMockBuilder(DebugStack::class)->getMock();
$logger->queries = [];
/** @psalm-suppress UndefinedClass Symfony < 7 specific */
$logger = $this->getMockBuilder(DebugStack::class)->getMock();
/** @psalm-suppress NoInterfaceProperties */
$logger->queries = [];
/**
* @psalm-suppress NoInterfaceProperties
* @psalm-suppress UndefinedDocblockClass
*/
$logger->queries[] = [
'sql' => 'SELECT * FROM foo WHERE bar = :bar',
'params' => [':bar' => 1],
'types' => null,
'executionMS' => 32,
];
/** @psalm-suppress NoInterfaceProperties */
$logger->queries[] = [
'sql' => 'SELECT * FROM foo WHERE bar = :bar',
'params' => [':bar' => 2],
Expand All @@ -158,7 +165,7 @@ public function testGetGroupedQueriesWithDeprecatedDebugStackLogger(): void
$this->assertCount(1, $groupedQueries['default']);
$this->assertSame('SELECT * FROM foo WHERE bar = :bar', $groupedQueries['default'][0]['sql']);
$this->assertSame(2, $groupedQueries['default'][0]['count']);

/** @psalm-suppress NoInterfaceProperties */
$logger->queries[] = [
'sql' => 'SELECT * FROM bar',
'params' => [],
Expand Down
14 changes: 0 additions & 14 deletions Tests/Mapping/DisconnectedMetadataFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,4 @@ public function testCannotFindNamespaceAndPathForMetadata(): void
EXCEPTION);
$factory->findNamespaceAndPathForMetadata($collection);
}

public function testFindNamespaceAndPathForMetadata(): void
{
/** @psalm-suppress UndefinedClass */
$class = new ClassMetadata('\Vendor\Package\Class');
$collection = new ClassMetadataCollection([$class]);

$registry = $this->getMockBuilder(ManagerRegistry::class)->getMock();
$factory = new DisconnectedMetadataFactory($registry);

$factory->findNamespaceAndPathForMetadata($collection, '/path/to/code');

$this->assertEquals('\Vendor\Package', $collection->getNamespace());
}
}
10 changes: 10 additions & 0 deletions psalm.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,16 @@
<errorLevel type="suppress">
<!-- We use the "Foo" namespace in unit tests. We are aware that those classes don't exist. -->
<referencedClass name="Foo\*"/>
<!-- Dropped in ORM 3 -->
<referencedClass name="Doctrine\ORM\Tools\EntityGenerator"/>
<referencedClass name="Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper"/>
<referencedClass name="Doctrine\ORM\Tools\DisconnectedClassMetadataFactory"/>
<referencedClass name="Doctrine\ORM\Mapping\Driver\YamlDriver"/>
<referencedClass name="Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver"/>
<referencedClass name="Doctrine\ORM\Mapping\Driver\AnnotationDriver"/>
<referencedClass name="Doctrine\ORM\ORMException"/>
<!-- Dropped in DBAL 4 -->
<referencedClass name="Doctrine\DBAL\Exception"/>
</errorLevel>
</UndefinedClass>
<DuplicateClass>
Expand Down

0 comments on commit fb9543f

Please sign in to comment.