1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
|
<?php
declare(strict_types=1);
namespace Doctrine\Tests\Common\DataFixtures\Purger;
use Doctrine\Common\DataFixtures\Purger\MongoDBPurger;
use Doctrine\ODM\MongoDB\Configuration;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Mapping\Driver\AttributeDriver;
use Doctrine\Tests\Common\DataFixtures\BaseTestCase;
use Doctrine\Tests\Common\DataFixtures\TestDocument\Role;
use MongoCollection;
use MongoDB\Collection;
use MongoDB\Driver\Exception\ConnectionTimeoutException;
use function class_exists;
use function dirname;
use function method_exists;
class MongoDBPurgerTest extends BaseTestCase
{
public const TEST_DOCUMENT_ROLE = Role::class;
private function getDocumentManager(): DocumentManager
{
if (! class_exists(DocumentManager::class)) {
$this->markTestSkipped('Missing doctrine/mongodb-odm');
}
$root = dirname(__DIR__, 5);
$config = new Configuration();
$config->setProxyDir($root . '/generate/proxies');
$config->setProxyNamespace('Proxies');
$config->setHydratorDir($root . '/generate/hydrators');
$config->setHydratorNamespace('Hydrators');
$config->setMetadataDriverImpl(AttributeDriver::create(dirname(__DIR__) . '/TestDocument'));
$dm = DocumentManager::create(null, $config);
$this->skipIfMongoDBUnavailable($dm);
return $dm;
}
private function getPurger(): MongoDBPurger
{
return new MongoDBPurger($this->getDocumentManager());
}
public function testPurgeKeepsIndices(): void
{
$purger = $this->getPurger();
$dm = $purger->getObjectManager();
$collection = $dm->getDocumentCollection(self::TEST_DOCUMENT_ROLE);
$collection->drop();
$this->assertIndexCount(0, $collection);
$role = new Role();
$role->setName('role');
$dm->persist($role);
$dm->flush();
$dm->getSchemaManager()->ensureDocumentIndexes(self::TEST_DOCUMENT_ROLE);
$this->assertIndexCount(2, $collection);
$purger->purge();
$this->assertIndexCount(2, $collection);
}
private function assertIndexCount(int $expectedCount, Collection|MongoCollection $collection): void
{
if ($collection instanceof Collection) {
$indexes = $collection->listIndexes();
} else {
$indexes = $collection->getIndexInfo();
}
$this->assertCount($expectedCount, $indexes);
}
private function skipIfMongoDBUnavailable(DocumentManager $documentManager): void
{
if (method_exists($documentManager, 'getClient')) {
try {
$documentManager->getClient()->selectDatabase('admin')->command(['ping' => 1]);
} catch (ConnectionTimeoutException) {
$this->markTestSkipped('Unable to connect to MongoDB');
}
return;
}
if ($documentManager->getConnection()->connect()) {
return;
}
$this->markTestSkipped('Unable to connect to MongoDB');
}
}
|