*/
29 | use ServiceRepositoryTrait;
30 | }
31 |
--------------------------------------------------------------------------------
/src/Repository/ServiceRepositoryTrait.php:
--------------------------------------------------------------------------------
1 | $documentClass
21 | */
22 | public function __construct(ManagerRegistry $registry, string $documentClass)
23 | {
24 | $manager = $registry->getManagerForClass($documentClass);
25 | assert($manager instanceof DocumentManager || $manager === null);
26 |
27 | if ($manager === null) {
28 | throw new LogicException(sprintf(
29 | 'Could not find the document manager for class "%s". Check your Doctrine configuration to make sure it is configured to load this document’s metadata.',
30 | $documentClass,
31 | ));
32 | }
33 |
34 | parent::__construct($manager, $manager->getUnitOfWork(), $manager->getClassMetadata($documentClass));
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/Validator/Constraints/Unique.php:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
--------------------------------------------------------------------------------
/templates/Collector/mongodb.html.twig:
--------------------------------------------------------------------------------
1 | {% extends '@WebProfiler/Profiler/layout.html.twig' %}
2 |
3 | {% block toolbar %}
4 | {% if collector.commandCount > 0 %}
5 | {% set icon %}
6 | {{ include('@DoctrineMongoDB/Collector/icon.svg') }}
7 | {{ collector.commandCount }}
8 |
9 | in
10 | {{ '%0.2f'|format(collector.time / 1000) }}
11 | ms
12 |
13 | {% endset %}
14 | {% set text %}
15 |
16 | Database commands
17 | {{ collector.commandCount }}
18 |
19 |
20 | Command time
21 | {{ '%0.2f'|format(collector.time / 1000) }} ms
22 |
23 | {% endset %}
24 | {% include '@WebProfiler/Profiler/toolbar_item.html.twig' with { 'link': profiler_url } %}
25 | {% endif %}
26 | {% endblock %}
27 |
28 | {% block menu %}
29 |
30 |
31 | Doctrine MongoDB
32 |
33 | {{ collector.commandCount }}
34 |
35 |
36 | {% endblock %}
37 |
38 | {% block panel %}
39 | Command metrics
40 |
41 |
42 | {{ collector.commandCount }}
43 | Database commands
44 |
45 |
46 |
47 | {{ '%0.3f'|format(collector.time / 1000) }} ms
48 | Command time
49 |
50 |
51 |
52 | Commands
53 | {% if collector.commands is empty %}
54 |
55 | No commands were performed.
56 |
57 | {% endif %}
58 |
59 |
60 |
61 | # |
62 | Time |
63 | Database |
64 | Info |
65 |
66 |
67 |
68 | {% for command in collector.commands %}
69 |
70 | {{ loop.index }} |
71 | {{ '%0.3f'|format(command.durationMicros / 1000) }} ms |
72 | {{ command.database }} |
73 |
74 | {{ command.command|json_encode() }}
75 |
78 |
81 | |
82 |
83 | {% endfor %}
84 |
85 |
86 | {% endblock %}
87 |
--------------------------------------------------------------------------------
/tests/APM/StopwatchCommandLoggerTest.php:
--------------------------------------------------------------------------------
1 | dm = TestCase::createTestDocumentManager();
22 |
23 | $this->stopwatch = new Stopwatch(true);
24 | $this->commandLogger = new StopwatchCommandLogger($this->stopwatch);
25 | $this->commandLogger->register();
26 |
27 | parent::setUp();
28 | }
29 |
30 | protected function tearDown(): void
31 | {
32 | $this->commandLogger->unregister();
33 |
34 | $this->dm->getDocumentCollection(Category::class)->drop();
35 |
36 | parent::tearDown();
37 | }
38 |
39 | public function testItLogsStopwatchEvents(): void
40 | {
41 | $category = new Category('one');
42 |
43 | $this->dm->persist($category);
44 | $this->dm->flush();
45 |
46 | $this->dm->remove($category);
47 | $this->dm->flush();
48 |
49 | $this->dm->getRepository(Category::class)->findAll();
50 | $events = $this->stopwatch->getSectionEvents('__root__');
51 |
52 | self::assertCount(3, $events);
53 |
54 | foreach ($events as $eventName => $stopwatchEvent) {
55 | self::assertMatchesRegularExpression('/mongodb_\d+/', $eventName);
56 | self::assertGreaterThan(0, $stopwatchEvent->getDuration());
57 | self::assertSame('doctrine_mongodb', $stopwatchEvent->getCategory());
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/tests/CacheWarmer/HydratorCacheWarmerTest.php:
--------------------------------------------------------------------------------
1 | container = new Container();
28 | $this->container->setParameter('doctrine_mongodb.odm.hydrator_dir', sys_get_temp_dir());
29 | $this->container->setParameter('doctrine_mongodb.odm.auto_generate_hydrator_classes', Configuration::AUTOGENERATE_NEVER);
30 |
31 | $dm = $this->createTestDocumentManager([__DIR__ . '/../Fixtures/Validator']);
32 |
33 | $registryStub = $this->getMockBuilder(ManagerRegistry::class)->disableOriginalConstructor()->getMock();
34 | $registryStub->method('getManagers')->willReturn([$dm]);
35 | $this->container->set('doctrine_mongodb', $registryStub);
36 |
37 | $this->warmer = new HydratorCacheWarmer($this->container);
38 | }
39 |
40 | public function testWarmerNotOptional(): void
41 | {
42 | $this->assertFalse($this->warmer->isOptional());
43 | }
44 |
45 | public function testWarmerExecuted(): void
46 | {
47 | $hydratorFilename = $this->getHydratorFilename();
48 |
49 | try {
50 | $this->warmer->warmUp('meh');
51 | $this->assertFileExists($hydratorFilename);
52 | } finally {
53 | @unlink($hydratorFilename);
54 | }
55 | }
56 |
57 | /** @dataProvider provideWarmerNotExecuted */
58 | public function testWarmerNotExecuted(int $autoGenerate): void
59 | {
60 | $this->container->setParameter('doctrine_mongodb.odm.auto_generate_hydrator_classes', $autoGenerate);
61 | $hydratorFilename = $this->getHydratorFilename();
62 |
63 | try {
64 | $this->warmer->warmUp('meh');
65 | $this->assertFileDoesNotExist($hydratorFilename);
66 | } finally {
67 | @unlink($hydratorFilename);
68 | }
69 | }
70 |
71 | /** @return array */
72 | public static function provideWarmerNotExecuted(): array
73 | {
74 | return [
75 | [ Configuration::AUTOGENERATE_ALWAYS ],
76 | [ Configuration::AUTOGENERATE_EVAL ],
77 | [ Configuration::AUTOGENERATE_FILE_NOT_EXISTS ],
78 | ];
79 | }
80 |
81 | private function getHydratorFilename(): string
82 | {
83 | return sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'DoctrineBundleMongoDBBundleTestsFixturesValidatorDocumentHydrator.php';
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/tests/CacheWarmer/PersistentCollectionCacheWarmerTest.php:
--------------------------------------------------------------------------------
1 | container = new Container();
30 | $this->container->setParameter('doctrine_mongodb.odm.persistent_collection_dir', sys_get_temp_dir());
31 | $this->container->setParameter('doctrine_mongodb.odm.auto_generate_persistent_collection_classes', Configuration::AUTOGENERATE_NEVER);
32 |
33 | $this->generatorMock = $this->getMockBuilder(PersistentCollectionGenerator::class)->getMock();
34 |
35 | $dm = $this->createTestDocumentManager([__DIR__ . '/../Fixtures/Cache']);
36 | $dm->getConfiguration()->setPersistentCollectionGenerator($this->generatorMock);
37 |
38 | $registryStub = $this->getMockBuilder(ManagerRegistry::class)->getMock();
39 | $registryStub->method('getManagers')->willReturn([$dm]);
40 | $this->container->set('doctrine_mongodb', $registryStub);
41 |
42 | $this->warmer = new PersistentCollectionCacheWarmer($this->container);
43 | }
44 |
45 | public function testWarmerNotOptional(): void
46 | {
47 | $this->assertFalse($this->warmer->isOptional());
48 | }
49 |
50 | public function testWarmerExecuted(): void
51 | {
52 | $this->generatorMock->expects($this->exactly(2))->method('generateClass');
53 | $this->warmer->warmUp('meh');
54 | }
55 |
56 | /** @dataProvider provideWarmerNotExecuted */
57 | public function testWarmerNotExecuted(int $autoGenerate): void
58 | {
59 | $this->container->setParameter('doctrine_mongodb.odm.auto_generate_persistent_collection_classes', $autoGenerate);
60 | $this->generatorMock->expects($this->exactly(0))->method('generateClass');
61 | $this->warmer->warmUp('meh');
62 | }
63 |
64 | public static function provideWarmerNotExecuted(): array
65 | {
66 | return [
67 | [ Configuration::AUTOGENERATE_ALWAYS ],
68 | [ Configuration::AUTOGENERATE_EVAL ],
69 | [ Configuration::AUTOGENERATE_FILE_NOT_EXISTS ],
70 | ];
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/tests/CacheWarmer/ProxyCacheWarmerTest.php:
--------------------------------------------------------------------------------
1 | container = new Container();
31 | $this->container->setParameter('doctrine_mongodb.odm.proxy_dir', sys_get_temp_dir());
32 | $this->container->setParameter('doctrine_mongodb.odm.auto_generate_proxy_classes', Configuration::AUTOGENERATE_EVAL);
33 |
34 | $this->proxyMock = $this->getMockBuilder(ProxyFactory::class)->disableOriginalConstructor()->getMock();
35 |
36 | $dm = $this->createTestDocumentManager([__DIR__ . '/../Fixtures/Validator']);
37 | $r = new ReflectionObject($dm);
38 | $p = $r->getProperty('proxyFactory');
39 | $p->setAccessible(true);
40 | $p->setValue($dm, $this->proxyMock);
41 |
42 | $registryStub = $this->getMockBuilder(ManagerRegistry::class)->disableOriginalConstructor()->getMock();
43 | $registryStub->method('getManagers')->willReturn([$dm]);
44 | $this->container->set('doctrine_mongodb', $registryStub);
45 |
46 | $this->warmer = new ProxyCacheWarmer($this->container);
47 | }
48 |
49 | public function testWarmerNotOptional(): void
50 | {
51 | $this->assertFalse($this->warmer->isOptional());
52 | }
53 |
54 | public function testWarmerExecuted(): void
55 | {
56 | $this->container->setParameter('doctrine_mongodb.odm.auto_generate_proxy_classes', Configuration::AUTOGENERATE_FILE_NOT_EXISTS);
57 |
58 | $this->proxyMock
59 | ->expects($this->once())
60 | ->method('generateProxyClasses')
61 | ->with($this->countOf(1));
62 | $this->warmer->warmUp('meh');
63 | }
64 |
65 | public function testWarmerNotExecuted(): void
66 | {
67 | $this->container->setParameter('doctrine_mongodb.odm.auto_generate_proxy_classes', Configuration::AUTOGENERATE_EVAL);
68 | $this->proxyMock->expects($this->exactly(0))->method('generateProxyClasses');
69 | $this->warmer->warmUp('meh');
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/tests/Command/CommandTestKernel.php:
--------------------------------------------------------------------------------
1 | loadFromExtension('framework', [
41 | 'secret' => 'foo',
42 | 'router' => ['utf8' => false],
43 | 'http_method_override' => false,
44 | ]);
45 |
46 | $container->loadFromExtension('doctrine_mongodb', [
47 | 'connections' => ['default' => []],
48 | 'document_managers' => [
49 | 'command_test' => [
50 | 'connection' => 'default',
51 | 'mappings' => ['CommandBundle' => null],
52 | ],
53 | 'command_test_without_documents' => ['connection' => 'default'],
54 | ],
55 | ]);
56 |
57 | $container
58 | ->autowire(UserFixtures::class)
59 | ->addTag(FixturesCompilerPass::FIXTURE_TAG, ['group' => 'test_group']);
60 |
61 | $container
62 | ->autowire(OtherFixtures::class)
63 | ->addTag(FixturesCompilerPass::FIXTURE_TAG);
64 | }
65 |
66 | public function getCacheDir(): string
67 | {
68 | return sys_get_temp_dir() . '/doctrine_mongodb_odm_bundle';
69 | }
70 |
71 | public function getLogDir(): string
72 | {
73 | return sys_get_temp_dir();
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/tests/Command/DoctrineODMCommandTest.php:
--------------------------------------------------------------------------------
1 | boot();
19 | $application = new Application($kernel);
20 |
21 | DoctrineODMCommand::setApplicationDocumentManager($application, $dmName);
22 |
23 | $this->assertInstanceOf(DocumentManagerHelper::class, $application->getHelperSet()->get('dm'));
24 | }
25 |
26 | public static function provideDmName(): iterable
27 | {
28 | yield ['command_test'];
29 | yield [null];
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/tests/Command/InfoDoctrineODMCommandTest.php:
--------------------------------------------------------------------------------
1 | find('doctrine:mongodb:mapping:info');
21 | $commandTester = new CommandTester($command);
22 | $commandTester->execute(['--dm' => 'command_test']);
23 |
24 | $output = $commandTester->getDisplay();
25 | $this->assertStringContainsString('Found 1 documents mapped in document manager command_test', $output);
26 | $this->assertStringContainsString(User::class, $output);
27 | }
28 |
29 | public function testExecuteWithDocumentManagerWithoutDocuments(): void
30 | {
31 | $kernel = new CommandTestKernel('test', false);
32 | $application = new Application($kernel);
33 |
34 | $command = $application->find('doctrine:mongodb:mapping:info');
35 | $commandTester = new CommandTester($command);
36 |
37 | $this->expectException(Throwable::class);
38 | $this->expectExceptionMessage('You do not have any mapped Doctrine MongoDB ODM documents for any of your bundles. Create a class inside the Document namespace of any of your bundles and provide mapping information for it with Attributes directly in the classes doc blocks or with XML in your bundles Resources/config/doctrine/metadata/mongodb directory');
39 |
40 | $commandTester->execute(['--dm' => 'command_test_without_documents']);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/tests/Command/LoadDataFixturesDoctrineODMCommandTest.php:
--------------------------------------------------------------------------------
1 | command = $application->find('doctrine:mongodb:fixtures:load');
22 | }
23 |
24 | public function testIsInteractiveByDefault(): void
25 | {
26 | $commandTester = new CommandTester($this->command);
27 | $commandTester->execute([]);
28 |
29 | $output = $commandTester->getDisplay();
30 | $this->assertStringContainsString('Careful, database will be purged. Do you want to continue (y/N) ?', $output);
31 | }
32 |
33 | public function testGroup(): void
34 | {
35 | $commandTester = new CommandTester($this->command);
36 | $commandTester->execute([
37 | '--group' => ['test_group'],
38 | ], ['interactive' => false]);
39 |
40 | $output = $commandTester->getDisplay();
41 | $this->assertStringContainsString('loading Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\CommandBundle\DataFixtures\UserFixtures', $output);
42 | $this->assertStringNotContainsString('loading Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\CommandBundle\DataFixtures\OtherFixtures', $output);
43 | }
44 |
45 | public function testNonExistingGroup(): void
46 | {
47 | $commandTester = new CommandTester($this->command);
48 | $commandTester->execute([
49 | '--group' => ['non_existing_group'],
50 | ], ['interactive' => false]);
51 |
52 | $output = $commandTester->getDisplay();
53 | $this->assertStringContainsString('Could not find any fixture services to load in the groups', $output);
54 | $this->assertStringContainsString('(non_existing_group)', $output);
55 | }
56 |
57 | public function testExecute(): void
58 | {
59 | $commandTester = new CommandTester($this->command);
60 | $commandTester->execute([], ['interactive' => false]);
61 |
62 | $output = $commandTester->getDisplay();
63 | $this->assertStringContainsString('loading Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\CommandBundle\DataFixtures\UserFixtures', $output);
64 | $this->assertStringContainsString('loading Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\CommandBundle\DataFixtures\OtherFixtures', $output);
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/tests/DataCollector/CommandDataCollectorTest.php:
--------------------------------------------------------------------------------
1 | dm = TestCase::createTestDocumentManager();
23 |
24 | $this->commandLogger = new CommandLogger();
25 | $this->commandLogger->register();
26 |
27 | parent::setUp();
28 | }
29 |
30 | protected function tearDown(): void
31 | {
32 | $this->commandLogger->unregister();
33 |
34 | $this->dm->getDocumentCollection(Category::class)->drop();
35 |
36 | parent::tearDown();
37 | }
38 |
39 | public function testCollector(): void
40 | {
41 | $category = new Category('one');
42 |
43 | $this->dm->persist($category);
44 | $this->dm->flush();
45 |
46 | $this->dm->remove($category);
47 | $this->dm->flush();
48 |
49 | $this->dm->getRepository(Category::class)->findAll();
50 |
51 | $collector = new CommandDataCollector($this->commandLogger);
52 | $collector->collect(new Request(), new Response());
53 |
54 | self::assertSame(3, $collector->getCommandCount());
55 | self::assertGreaterThan(0, $collector->getTime());
56 | self::assertSame('Category', $collector->getCommands()[0]['command']->insert);
57 | self::assertGreaterThan(0, $collector->getCommands()[0]['durationMicros']);
58 | self::assertSame('Category', $collector->getCommands()[1]['command']->delete);
59 | self::assertGreaterThan(0, $collector->getCommands()[1]['durationMicros']);
60 | self::assertSame('Category', $collector->getCommands()[2]['command']->find);
61 | self::assertGreaterThan(0, $collector->getCommands()[2]['durationMicros']);
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/Bundles/AttributesBundle/AttributesBundle.php:
--------------------------------------------------------------------------------
1 | */
10 | class TestCustomClassRepoRepository extends DocumentRepository
11 | {
12 | }
13 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/Bundles/RepositoryServiceBundle/Repository/TestCustomServiceRepoDocumentRepository.php:
--------------------------------------------------------------------------------
1 | */
12 | class TestCustomServiceRepoDocumentRepository extends ServiceDocumentRepository
13 | {
14 | public function __construct(ManagerRegistry $registry)
15 | {
16 | parent::__construct($registry, TestCustomServiceRepoDocument::class);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/Bundles/RepositoryServiceBundle/Repository/TestCustomServiceRepoGridFSRepository.php:
--------------------------------------------------------------------------------
1 | */
12 | class TestCustomServiceRepoGridFSRepository extends ServiceDocumentRepository
13 | {
14 | public function __construct(ManagerRegistry $registry)
15 | {
16 | parent::__construct($registry, TestCustomServiceRepoFile::class);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/Bundles/RepositoryServiceBundle/Repository/TestUnmappedDocumentRepository.php:
--------------------------------------------------------------------------------
1 | */
12 | class TestUnmappedDocumentRepository extends ServiceDocumentRepository
13 | {
14 | public function __construct(ManagerRegistry $registry)
15 | {
16 | parent::__construct($registry, TestUnmappedDocument::class);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/Bundles/RepositoryServiceBundle/RepositoryServiceBundle.php:
--------------------------------------------------------------------------------
1 | */
29 | public function registerBundles(): iterable
30 | {
31 | return [
32 | new FrameworkBundle(),
33 | new DoctrineMongoDBBundle(),
34 | ];
35 | }
36 |
37 | public function registerContainerConfiguration(LoaderInterface $loader): void
38 | {
39 | $loader->load(static function (ContainerBuilder $container): void {
40 | $container->loadFromExtension('framework', ['secret' => 'F00']);
41 |
42 | $container->loadFromExtension('doctrine_mongodb', [
43 | 'connections' => ['default' => []],
44 | 'document_managers' => [
45 | 'default' => [
46 | 'mappings' => [
47 | 'RepositoryServiceBundle' => [
48 | 'type' => 'attribute',
49 | 'dir' => __DIR__ . '/Bundles/RepositoryServiceBundle/Document',
50 | 'prefix' => 'Fixtures\Bundles\RepositoryServiceBundle\Document',
51 | ],
52 | ],
53 | ],
54 | ],
55 | ]);
56 |
57 | // Register a NullLogger to avoid getting the stderr default logger of FrameworkBundle
58 | $container->register('logger', NullLogger::class);
59 | });
60 | }
61 |
62 | public function getProjectDir(): string
63 | {
64 | if ($this->projectDir === null) {
65 | $this->projectDir = sys_get_temp_dir() . '/sf_kernel_' . md5((string) mt_rand());
66 | }
67 |
68 | return $this->projectDir;
69 | }
70 |
71 | public function getRootDir(): string
72 | {
73 | return $this->getProjectDir();
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/config/xml/mongodb_service_multiple_connections.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
9 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/config/xml/mongodb_service_simple_single_connection.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
9 |
10 |
11 |
12 |
13 |
14 | Symfony\Component\Cache\Adapter\MemcachedAdapter
15 | localhost
16 | 11211
17 | Memcached
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/config/xml/mongodb_service_single_connection.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
9 |
10 |
11 |
12 |
13 |
14 | Doctrine\Common\Cache\MemcacheCache
15 | localhost
16 | 11211
17 | Memcached
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/config/xml/odm_filters.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | 1
17 | foo
18 | {"key":"value"}
19 | [1,2,3]
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/config/xml/odm_imports.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/config/xml/odm_imports_import.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/config/xml/odm_resolve_target_document.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
9 |
10 | MyUserClass
11 |
12 |
13 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/config/xml/odm_types.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/config/yml/full.yml:
--------------------------------------------------------------------------------
1 | doctrine_mongodb:
2 | auto_generate_proxy_classes: 2
3 | auto_generate_hydrator_classes: true
4 | auto_generate_persistent_collection_classes: 3
5 | default_connection: conn1
6 | default_database: default_db_name
7 | default_document_manager: default_dm_name
8 | hydrator_dir: "%kernel.cache_dir%/doctrine/odm/mongodb/Test_Hydrators"
9 | hydrator_namespace: Test_Hydrators
10 | proxy_dir: "%kernel.cache_dir%/doctrine/odm/mongodb/Test_Proxies"
11 | proxy_namespace: Test_Proxies
12 | persistent_collection_dir: "%kernel.cache_dir%/doctrine/odm/mongodb/Test_Pcolls"
13 | persistent_collection_namespace: Test_Pcolls
14 |
15 | resolve_target_documents:
16 | Foo\BarInterface: Bar\FooClass
17 |
18 | default_commit_options:
19 | j: false
20 | timeout: 10
21 | w: majority
22 | wtimeout: 10
23 |
24 | connections:
25 | conn1:
26 | server: mongodb://localhost
27 | options:
28 | connectTimeoutMS: 500
29 | authSource: some_db
30 | db: database_val
31 | journal: true
32 | password: password_val
33 | readPreference: secondaryPreferred
34 | readPreferenceTags:
35 | - { dc: east, use: reporting }
36 | - { dc: west }
37 | - { }
38 | replicaSet: foo
39 | socketTimeoutMS: 1000
40 | ssl: true
41 | tls: true
42 | tlsAllowInvalidCertificates: false
43 | tlsAllowInvalidHostnames: false
44 | tlsCAFile: '/path/to/cert.pem'
45 | tlsCertificateKeyFile: '/path/to/key.crt'
46 | tlsCertificateKeyFilePassword: 'secret'
47 | tlsDisableCertificateRevocationCheck: false
48 | tlsDisableOCSPEndpointCheck: false
49 | tlsInsecure: false
50 | authMechanism: MONGODB-X509
51 | username: username_val
52 | retryReads: false
53 | retryWrites: false
54 | w: majority
55 | wTimeoutMS: 1000
56 | driver_options:
57 | context: conn1_context_service
58 | conn2:
59 | server: mongodb://otherhost
60 |
61 | document_managers:
62 | dm1:
63 | repository_factory: doctrine_mongodb.odm.container_repository_factory
64 | persistent_collection_factory: ~
65 | mappings:
66 | FooBundle: attribute
67 | metadata_cache_driver:
68 | type: memcached
69 | class: fooClass
70 | host: host_val
71 | port: 1234
72 | instance_class: instance_val
73 | profiler:
74 | enabled: true
75 | pretty: false
76 | filters:
77 | disabled_filter:
78 | class: Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\Filter\DisabledFilter
79 | enabled: false
80 | basic_filter:
81 | class: Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\Filter\BasicFilter
82 | enabled: true
83 | complex_filter:
84 | class: Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\Filter\ComplexFilter
85 | enabled: true
86 | parameters:
87 | integer: 1
88 | string: foo
89 | object: { key: value }
90 | array: [ 1, 2, 3 ]
91 | dm2:
92 | connection: dm2_connection
93 | database: db1
94 | default_document_repository_class: Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\Repository\CustomRepository
95 | default_gridfs_repository_class: Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\Repository\CustomGridFSRepository
96 | repository_factory: doctrine_mongodb.odm.container_repository_factory
97 | persistent_collection_factory: ~
98 | mappings:
99 | BarBundle:
100 | type: xml
101 | dir: "%kernel.cache_dir%"
102 | prefix: prefix_val
103 | alias: alias_val
104 | is_bundle: false
105 | metadata_cache_driver: apcu
106 | logging: true
107 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/config/yml/mongodb_service_multiple_connections.yml:
--------------------------------------------------------------------------------
1 | doctrine_mongodb:
2 | default_document_manager: dm2
3 | default_connection: conn2
4 | connections:
5 | conn1:
6 | server: mongodb://localhost:27017
7 | conn2:
8 | server: mongodb://localhost:27017
9 | document_managers:
10 | dm1:
11 | connection: conn1
12 | metadata_cache_driver: array
13 | dm2:
14 | connection: conn2
15 | metadata_cache_driver: apcu
16 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/config/yml/mongodb_service_simple_single_connection.yml:
--------------------------------------------------------------------------------
1 | doctrine_mongodb:
2 | connections:
3 | default:
4 | server: mongodb://localhost:27017
5 | default_database: mydb
6 | document_managers:
7 | default:
8 | metadata_cache_driver:
9 | type: memcached
10 | class: Symfony\Component\Cache\Adapter\MemcachedAdapter
11 | host: localhost
12 | port: 11211
13 | instance_class: Memcached
14 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/config/yml/mongodb_service_single_connection.yml:
--------------------------------------------------------------------------------
1 | doctrine_mongodb:
2 | connections:
3 | default:
4 | server: mongodb://localhost:27017
5 | document_managers:
6 | default:
7 | connection: default
8 | metadata_cache_driver:
9 | type: memcached
10 | class: Symfony\Component\Cache\Adapter\MemcachedAdapter
11 | host: localhost
12 | port: 11211
13 | instance_class: Memcached
14 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/config/yml/odm_filters.yml:
--------------------------------------------------------------------------------
1 | doctrine_mongodb:
2 | connections:
3 | default:
4 | server: mongodb://localhost:27017
5 | document_managers:
6 | default:
7 | filters:
8 | disabled_filter:
9 | class: Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\Filter\DisabledFilter
10 | enabled: false
11 | basic_filter:
12 | class: Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\Filter\BasicFilter
13 | enabled: true
14 | complex_filter:
15 | class: Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\Filter\ComplexFilter
16 | enabled: true
17 | parameters:
18 | integer: 1
19 | string: foo
20 | object: { key: value }
21 | array: [ 1, 2, 3 ]
22 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/config/yml/odm_imports.yml:
--------------------------------------------------------------------------------
1 | imports:
2 | - { resource: odm_imports_import.yml }
3 |
4 | doctrine_mongodb:
5 | auto_generate_proxy_classes: true
6 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/config/yml/odm_imports_import.yml:
--------------------------------------------------------------------------------
1 | doctrine_mongodb:
2 | auto_generate_proxy_classes: false
3 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/config/yml/odm_resolve_target_document.yml:
--------------------------------------------------------------------------------
1 | doctrine_mongodb:
2 | resolve_target_documents:
3 | Symfony\Component\Security\Core\User\UserInterface: MyUserClass
4 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/Fixtures/config/yml/odm_types.yml:
--------------------------------------------------------------------------------
1 | doctrine_mongodb:
2 | connections:
3 | default:
4 | server: mongodb://localhost:27017
5 | types:
6 | custom_type_shortcut: Vendor\Type\CustomTypeShortcut
7 | custom_type:
8 | class: Vendor\Type\CustomType
9 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/XmlMongoDBExtensionTest.php:
--------------------------------------------------------------------------------
1 | load($file . '.xml');
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/tests/DependencyInjection/YamlMongoDBExtensionTest.php:
--------------------------------------------------------------------------------
1 | load($file . '.yml');
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/tests/DocumentValueResolverFunctionalTest.php:
--------------------------------------------------------------------------------
1 | get(DocumentManager::class);
31 | $user = new User('user-identifier');
32 |
33 | $dm->persist($user);
34 | $dm->flush();
35 |
36 | $client->request('GET', '/user/user-identifier');
37 |
38 | $this->assertResponseIsSuccessful();
39 | $this->assertSame('user-identifier', $client->getResponse()->getContent());
40 |
41 | $dm->remove($user);
42 | }
43 |
44 | public function testWithConfiguration(): void
45 | {
46 | $client = static::createClient();
47 |
48 | $dm = static::getContainer()->get(DocumentManager::class);
49 | $user = new User('user-identifier');
50 |
51 | $dm->persist($user);
52 | $dm->flush();
53 |
54 | $client->request('GET', '/user_with_mapping/user-identifier');
55 |
56 | $this->assertResponseIsSuccessful();
57 | $this->assertSame('user-identifier', $client->getResponse()->getContent());
58 |
59 | $dm->remove($user);
60 | }
61 |
62 | protected static function getKernelClass(): string
63 | {
64 | return FooTestKernel::class;
65 | }
66 | }
67 |
68 | class FooTestKernel extends Kernel
69 | {
70 | use MicroKernelTrait;
71 |
72 | private string $randomKey;
73 |
74 | public function __construct()
75 | {
76 | $this->randomKey = uniqid('');
77 |
78 | parent::__construct('test', false);
79 | }
80 |
81 | protected function getContainerClass(): string
82 | {
83 | return 'test' . $this->randomKey . parent::getContainerClass();
84 | }
85 |
86 | public function registerBundles(): array
87 | {
88 | return [
89 | new FrameworkBundle(),
90 | new DoctrineMongoDBBundle(),
91 | new FooBundle(),
92 | ];
93 | }
94 |
95 | protected function configureRoutes(RoutingConfigurator $routes): void
96 | {
97 | $routes->add('tv_user_show', '/user/{id}')
98 | ->controller([DocumentValueResolverController::class, 'showUserByDefault']);
99 |
100 | $routes->add('user_with_mapping', '/user_with_mapping/{identifier}')
101 | ->controller([DocumentValueResolverController::class, 'showUserWithMapping']);
102 | }
103 |
104 | protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader): void
105 | {
106 | $c->loadFromExtension('framework', [
107 | 'secret' => 'foo',
108 | 'router' => ['utf8' => false],
109 | 'http_method_override' => false,
110 | 'test' => true,
111 | ]);
112 |
113 | $c->loadFromExtension('doctrine_mongodb', [
114 | 'connections' => ['default' => []],
115 | 'document_managers' => [
116 | 'default' => [
117 | 'mappings' => [
118 | 'App' => [
119 | 'is_bundle' => false,
120 | 'type' => 'attribute',
121 | 'dir' => '%kernel.project_dir%/Document',
122 | 'prefix' => 'Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\FooBundle',
123 | 'alias' => 'Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\FooBundle',
124 | ],
125 | ],
126 | ],
127 | ],
128 | ]);
129 |
130 | $loader->load(__DIR__ . '/Fixtures/FooBundle/config/services.php');
131 | }
132 |
133 | public function getProjectDir(): string
134 | {
135 | return __DIR__ . '/Fixtures/FooBundle/';
136 | }
137 |
138 | public function getCacheDir(): string
139 | {
140 | return sys_get_temp_dir() . '/doctrine_mongodb_odm_bundle' . $this->randomKey;
141 | }
142 |
143 | public function getLogDir(): string
144 | {
145 | return sys_get_temp_dir();
146 | }
147 | }
148 |
--------------------------------------------------------------------------------
/tests/Fixtures/Cache/Collections.php:
--------------------------------------------------------------------------------
1 | */
28 | class SomeCollection extends ArrayCollection
29 | {
30 | }
31 |
32 | /** @template-extends ArrayCollection */
33 | class AnotherCollection extends ArrayCollection
34 | {
35 | }
36 |
--------------------------------------------------------------------------------
/tests/Fixtures/CommandBundle/CommandBundle.php:
--------------------------------------------------------------------------------
1 | name = $name;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/tests/Fixtures/Filter/BasicFilter.php:
--------------------------------------------------------------------------------
1 | getId());
21 | }
22 |
23 | #[Route(path: '/user_with_identifier/{identifier}', name: 'tv_user_show_with_identifier')]
24 | public function showUserWithMapping(
25 | #[MapDocument(mapping: ['identifier' => 'id'])]
26 | User $user,
27 | ): Response {
28 | return new Response($user->getId());
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/tests/Fixtures/FooBundle/DataFixtures/DependentOnRequiredConstructorArgsFixtures.php:
--------------------------------------------------------------------------------
1 | id;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/tests/Fixtures/FooBundle/FooBundle.php:
--------------------------------------------------------------------------------
1 | services()
9 | ->defaults()
10 | ->autowire()
11 | ->autoconfigure();
12 |
13 | $services->load('Doctrine\\Bundle\\MongoDBBundle\\Tests\\Fixtures\\FooBundle\\', '..')
14 | ->exclude('../{config,DataFixtures,Document}');
15 | };
16 |
--------------------------------------------------------------------------------
/tests/Fixtures/Form/Category.php:
--------------------------------------------------------------------------------
1 | */
23 | #[ODM\ReferenceMany(
24 | targetDocument: Document::class,
25 | mappedBy: 'categories',
26 | )]
27 | public Collection $documents;
28 |
29 | public function __construct(string $name)
30 | {
31 | $this->name = $name;
32 | $this->documents = new ArrayCollection();
33 | }
34 |
35 | public function __toString(): string
36 | {
37 | return $this->name;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/tests/Fixtures/Form/Document.php:
--------------------------------------------------------------------------------
1 | */
24 | #[ODM\ReferenceMany(
25 | targetDocument: Category::class,
26 | inversedBy: 'documents',
27 | strategy: ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET_ARRAY,
28 | )]
29 | public Collection $categories;
30 |
31 | public function __construct(ObjectId $id, string $name)
32 | {
33 | $this->id = $id;
34 | $this->name = $name;
35 | $this->categories = new ArrayCollection();
36 | }
37 |
38 | public function __toString(): string
39 | {
40 | return $this->name;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/tests/Fixtures/Form/Guesser.php:
--------------------------------------------------------------------------------
1 | */
30 | #[ODM\ReferenceMany(
31 | targetDocument: Category::class,
32 | inversedBy: 'documents',
33 | strategy: ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET_ARRAY,
34 | )]
35 | public Collection $categories;
36 |
37 | #[ODM\Field(type: Type::BOOL)]
38 | public ?bool $boolField = null;
39 |
40 | #[ODM\Field(type: Type::FLOAT)]
41 | public ?float $floatField = null;
42 |
43 | #[ODM\Field(type: Type::INT)]
44 | public ?int $intField = null;
45 |
46 | #[ODM\Field(type: Type::COLLECTION)]
47 | public array $collectionField;
48 |
49 | public mixed $nonMappedField;
50 | }
51 |
--------------------------------------------------------------------------------
/tests/Fixtures/Repository/CustomGridFSRepository.php:
--------------------------------------------------------------------------------
1 | */
10 | final class CustomGridFSRepository extends DocumentRepository
11 | {
12 | }
13 |
--------------------------------------------------------------------------------
/tests/Fixtures/Repository/CustomRepository.php:
--------------------------------------------------------------------------------
1 | */
10 | final class CustomRepository extends DocumentRepository
11 | {
12 | }
13 |
--------------------------------------------------------------------------------
/tests/Fixtures/Security/User.php:
--------------------------------------------------------------------------------
1 | id = $id;
24 | $this->name = $name;
25 | }
26 |
27 | public function getRoles(): array
28 | {
29 | return [];
30 | }
31 |
32 | public function getPassword(): void
33 | {
34 | }
35 |
36 | public function getSalt(): void
37 | {
38 | }
39 |
40 | public function getUserIdentifier(): string
41 | {
42 | return $this->name;
43 | }
44 |
45 | public function getUsername(): string
46 | {
47 | return $this->getUserIdentifier();
48 | }
49 |
50 | public function eraseCredentials(): void
51 | {
52 | }
53 |
54 | public function equals(UserInterface $user): void
55 | {
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/tests/Fixtures/Validator/Document.php:
--------------------------------------------------------------------------------
1 | id = $id;
39 | }
40 | }
41 |
42 | #[ODM\EmbeddedDocument]
43 | class EmbeddedDocument
44 | {
45 | #[ODM\Field(type: Type::STRING)]
46 | public string $name;
47 | }
48 |
--------------------------------------------------------------------------------
/tests/Form/Type/DocumentTypeTest.php:
--------------------------------------------------------------------------------
1 | dm = TestCase::createTestDocumentManager([
34 | __DIR__ . '/../../Fixtures/Form/Document',
35 | ]);
36 | $this->dmRegistry = $this->createRegistryMock('default', $this->dm);
37 |
38 | parent::setUp();
39 | }
40 |
41 | protected function tearDown(): void
42 | {
43 | $documentClasses = [
44 | Document::class,
45 | Category::class,
46 | ];
47 |
48 | foreach ($documentClasses as $class) {
49 | $this->dm->getDocumentCollection($class)->drop();
50 | }
51 |
52 | parent::tearDown();
53 | }
54 |
55 | public function testDocumentManagerOptionSetsEmOption(): void
56 | {
57 | $field = $this->factory->createNamed('name', DocumentType::class, null, [
58 | 'class' => Document::class,
59 | 'document_manager' => 'default',
60 | ]);
61 |
62 | $this->assertSame($this->dm, $field->getConfig()->getOption('em'));
63 | }
64 |
65 | public function testDocumentManagerInstancePassedAsOption(): void
66 | {
67 | $field = $this->factory->createNamed('name', DocumentType::class, null, [
68 | 'class' => Document::class,
69 | 'document_manager' => $this->dm,
70 | ]);
71 |
72 | $this->assertSame($this->dm, $field->getConfig()->getOption('em'));
73 | }
74 |
75 | public function testSettingDocumentManagerAndEmOptionShouldThrowException(): void
76 | {
77 | $this->expectException(InvalidArgumentException::class);
78 | $this->factory->createNamed('name', DocumentType::class, null, [
79 | 'document_manager' => 'default',
80 | 'em' => 'default',
81 | ]);
82 | }
83 |
84 | public function testManyToManyReferences(): void
85 | {
86 | $categoryOne = new Category('one');
87 | $this->dm->persist($categoryOne);
88 | $categoryTwo = new Category('two');
89 | $this->dm->persist($categoryTwo);
90 |
91 | $document = new Document(new ObjectId(), 'document');
92 | $document->categories[] = $categoryOne;
93 | $this->dm->persist($document);
94 |
95 | $this->dm->flush();
96 |
97 | $form = $this->factory->create(FormType::class, $document)
98 | ->add(
99 | 'categories',
100 | DocumentType::class,
101 | [
102 | 'class' => Category::class,
103 | 'multiple' => true,
104 | 'expanded' => true,
105 | 'document_manager' => 'default',
106 | ],
107 | );
108 |
109 | $view = $form->createView();
110 | $categoryView = $view['categories'];
111 | $this->assertInstanceOf(FormView::class, $categoryView);
112 |
113 | $this->assertCount(2, $categoryView->children);
114 | $this->assertTrue($form->get('categories')->get('0')->createView()->vars['checked']);
115 | $this->assertFalse($form->get('categories')->get('1')->createView()->vars['checked']);
116 | }
117 |
118 | /** @return MockObject&ManagerRegistry */
119 | protected function createRegistryMock(string $name, DocumentManager $dm): MockObject
120 | {
121 | $registry = $this->createMock(ManagerRegistry::class);
122 | $registry
123 | ->method('getManager')
124 | ->with($this->equalTo($name))
125 | ->willReturn($dm);
126 |
127 | return $registry;
128 | }
129 |
130 | /** @return FormExtensionInterface[] */
131 | protected function getExtensions(): array
132 | {
133 | return array_merge(parent::getExtensions(), [
134 | new DoctrineMongoDBExtension($this->dmRegistry),
135 | ]);
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/tests/Form/Type/GuesserTestType.php:
--------------------------------------------------------------------------------
1 | add('name')
18 | // Not setting "date_widget" is deprecated in Symfony 6.4
19 | ->add('date', null, ['date_widget' => 'single_text'])
20 | ->add('ts', null, ['date_widget' => 'single_text'])
21 | ->add('categories', null, ['document_manager' => $options['dm']])
22 | ->add('boolField')
23 | ->add('floatField')
24 | ->add('intField')
25 | ->add('collectionField')
26 | ->add('nonMappedField');
27 | }
28 |
29 | public function configureOptions(OptionsResolver $resolver): void
30 | {
31 | $resolver->setDefaults([
32 | 'data_class' => Guesser::class,
33 | ])->setRequired('dm');
34 | }
35 |
36 | public function getBlockPrefix(): string
37 | {
38 | return 'guesser_test';
39 | }
40 |
41 | public function getName(): string
42 | {
43 | return $this->getBlockPrefix();
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/tests/Form/Type/TypeGuesserTest.php:
--------------------------------------------------------------------------------
1 | dm = TestCase::createTestDocumentManager([
31 | __DIR__ . '/../../Fixtures/Form/Guesser',
32 | ]);
33 | $this->dmRegistry = $this->createRegistryMock('default', $this->dm);
34 |
35 | parent::setUp();
36 | }
37 |
38 | protected function tearDown(): void
39 | {
40 | $documentClasses = [
41 | Document::class,
42 | Category::class,
43 | Guesser::class,
44 | ];
45 |
46 | foreach ($documentClasses as $class) {
47 | $this->dm->getDocumentCollection($class)->drop();
48 | }
49 |
50 | parent::tearDown();
51 | }
52 |
53 | public function testTypesShouldBeGuessedCorrectly(): void
54 | {
55 | $form = $this->factory->create(GuesserTestType::class, null, ['dm' => $this->dm]);
56 | $this->assertType('text', $form->get('name'));
57 | $this->assertType('document', $form->get('categories'));
58 | $this->assertType('datetime', $form->get('date'));
59 | $this->assertType('datetime', $form->get('ts'));
60 | $this->assertType('checkbox', $form->get('boolField'));
61 | $this->assertType('number', $form->get('floatField'));
62 | $this->assertType('integer', $form->get('intField'));
63 | $this->assertType('collection', $form->get('collectionField'));
64 | $this->assertType('text', $form->get('nonMappedField'));
65 | }
66 |
67 | protected function assertType(string $type, FormInterface $form): void
68 | {
69 | $this->assertEquals($type, $form->getConfig()->getType()->getBlockPrefix());
70 | }
71 |
72 | /** @return MockObject&ManagerRegistry */
73 | protected function createRegistryMock(string $name, DocumentManager $dm): MockObject
74 | {
75 | $registry = $this->createMock(ManagerRegistry::class);
76 | $registry
77 | ->method('getManager')
78 | ->with($this->equalTo($name))
79 | ->willReturn($dm);
80 | $registry
81 | ->method('getManagers')
82 | ->willReturn(['default' => $dm]);
83 |
84 | return $registry;
85 | }
86 |
87 | /** @return FormExtensionInterface[] */
88 | protected function getExtensions(): array
89 | {
90 | return array_merge(parent::getExtensions(), [
91 | new DoctrineMongoDBExtension($this->dmRegistry),
92 | ]);
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/tests/ManagerRegistryTest.php:
--------------------------------------------------------------------------------
1 | register('manager.default', DocumentManagerStub::class)
20 | ->setPublic(true);
21 | $container->register('manager.lazy', DocumentManagerStub::class)
22 | ->setPublic(true)
23 | ->setLazy(true)
24 | ->addTag('proxy', ['interface' => ObjectManager::class]);
25 | $container->compile();
26 |
27 | /** @var class-string $containerClass */
28 | $containerClass = 'MongoDBManagerRepositoryTestResetContainer';
29 | $dumper = new PhpDumper($container);
30 | eval('?' . '>' . $dumper->dump(['class' => $containerClass]));
31 |
32 | $container = new $containerClass();
33 | $repository = new ManagerRegistry('MongoDB', [], [
34 | 'default' => 'manager.default',
35 | 'lazy' => 'manager.lazy',
36 | ], '', '', '', $container);
37 |
38 | DocumentManagerStub::$clearCount = 0;
39 |
40 | $repository->reset();
41 |
42 | // Service was not initialized, so reset should not be called
43 | $this->assertSame(0, DocumentManagerStub::$clearCount);
44 |
45 | // The lazy service is reinitialized instead of being cleared
46 | $container->get('manager.lazy')->flush();
47 | $repository->reset();
48 | $this->assertSame(0, DocumentManagerStub::$clearCount);
49 |
50 | // The default service is cleared when initialized
51 | $container->get('manager.default')->flush();
52 | $repository->reset();
53 | $this->assertSame(1, DocumentManagerStub::$clearCount);
54 | }
55 | }
56 |
57 | class DocumentManagerStub extends DocumentManager
58 | {
59 | public static int $clearCount;
60 |
61 | public function __construct()
62 | {
63 | }
64 |
65 | /** {@inheritDoc} */
66 | public function clear($objectName = null): void
67 | {
68 | self::$clearCount++;
69 | }
70 |
71 | public function flush(array $options = []): void
72 | {
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/tests/Mapping/Driver/AbstractDriverTestCase.php:
--------------------------------------------------------------------------------
1 | getDriver([
18 | 'foo' => 'MyNamespace\MyBundle\DocumentFoo',
19 | $this->getFixtureDir() => 'MyNamespace\MyBundle\Document',
20 | ]);
21 |
22 | $locator = $this->getDriverLocator($driver);
23 |
24 | $this->assertEquals(
25 | $this->getFixtureDir() . '/Foo' . $this->getFileExtension(),
26 | $locator->findMappingFile('MyNamespace\MyBundle\Document\Foo'),
27 | );
28 | }
29 |
30 | public function testFindMappingFileInSubnamespace(): void
31 | {
32 | $driver = $this->getDriver([$this->getFixtureDir() => 'MyNamespace\MyBundle\Document']);
33 |
34 | $locator = $this->getDriverLocator($driver);
35 |
36 | $this->assertEquals(
37 | $this->getFixtureDir() . '/Foo.Bar' . $this->getFileExtension(),
38 | $locator->findMappingFile('MyNamespace\MyBundle\Document\Foo\Bar'),
39 | );
40 | }
41 |
42 | public function testFindMappingFileNamespacedFoundFileNotFound(): void
43 | {
44 | $driver = $this->getDriver([$this->getFixtureDir() => 'MyNamespace\MyBundle\Document']);
45 |
46 | $locator = $this->getDriverLocator($driver);
47 |
48 | $this->expectException(MappingException::class);
49 |
50 | $locator->findMappingFile('MyNamespace\MyBundle\Document\Missing');
51 | }
52 |
53 | public function testFindMappingNamespaceNotFound(): void
54 | {
55 | $driver = $this->getDriver([$this->getFixtureDir() => 'MyNamespace\MyBundle\Document']);
56 |
57 | $locator = $this->getDriverLocator($driver);
58 |
59 | $this->expectException(MappingException::class);
60 |
61 | $locator->findMappingFile('MyOtherNamespace\MyBundle\Document\Foo');
62 | }
63 |
64 | abstract protected function getFileExtension(): string;
65 |
66 | abstract protected function getFixtureDir(): string;
67 |
68 | abstract protected function getDriver(array $paths = []): FileDriver;
69 |
70 | private function getDriverLocator(FileDriver $driver): FileLocator
71 | {
72 | $ref = new ReflectionProperty($driver, 'locator');
73 | $ref->setAccessible(true);
74 |
75 | return $ref->getValue($driver);
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/tests/Mapping/Driver/Fixtures/xml/Foo.Bar.mongodb.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/tests/Mapping/Driver/Fixtures/xml/Foo.mongodb.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/tests/Mapping/Driver/XmlDriverTest.php:
--------------------------------------------------------------------------------
1 | getFileExtension());
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/tests/TestCase.php:
--------------------------------------------------------------------------------
1 | setAutoGenerateProxyClasses(Configuration::AUTOGENERATE_FILE_NOT_EXISTS);
22 | $config->setProxyDir(sys_get_temp_dir());
23 | $config->setHydratorDir(sys_get_temp_dir());
24 | $config->setProxyNamespace('SymfonyTests\Doctrine');
25 | $config->setHydratorNamespace('SymfonyTests\Doctrine');
26 | $config->setMetadataDriverImpl(new AttributeDriver($paths));
27 | $config->setMetadataCache(new ArrayAdapter());
28 |
29 | return DocumentManager::create(null, $config);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/tests/Validator/Constraints/UniqueTest.php:
--------------------------------------------------------------------------------
1 | loadClassMetadata($metadata));
21 |
22 | [$constraint] = $metadata->getConstraints();
23 | self::assertInstanceOf(Unique::class, $constraint);
24 | self::assertSame(['email'], $constraint->fields);
25 | self::assertSame('doctrine_odm.mongodb.unique', $constraint->validatedBy());
26 | }
27 | }
28 |
29 | #[Unique(['email'])]
30 | class UniqueDocumentDummyOne
31 | {
32 | private string $email;
33 | }
34 |
--------------------------------------------------------------------------------
/tests/bootstrap.php:
--------------------------------------------------------------------------------
1 |