moved DoctrineMongoDBBundle to its own repository

The repo is now here: https://github.com/symfony/DoctrineMongoDBBundle

It has been done as the bundle depends on Doctrine Common 2.1, but everything
else in Symfony relies on Doctrine Common 2.0.
This commit is contained in:
Fabien Potencier 2011-04-21 23:14:15 +02:00
parent fc23f39335
commit e6d86eb9f7
60 changed files with 1 additions and 4000 deletions

View File

@ -1,76 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
/**
* The hydrator generator cache warmer generates all document hydrators.
*
* In the process of generating hydrators the cache for all the metadata is primed also,
* since this information is necessary to build the hydrators in the first place.
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class HydratorCacheWarmer implements CacheWarmerInterface
{
/**
* @var Container
*/
private $container;
/**
* @param Container $container
*/
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* This cache warmer is not optional, without hydrators fatal error occurs!
*
* @return false
*/
public function isOptional()
{
return false;
}
public function warmUp($cacheDir)
{
// we need the directory no matter the hydrator cache generation strategy.
$hydratorCacheDir = $this->container->getParameter('doctrine.odm.mongodb.hydrator_dir');
if (!file_exists($hydratorCacheDir)) {
if (false === @mkdir($hydratorCacheDir, 0777, true)) {
throw new \RuntimeException(sprintf('Unable to create the Doctrine Hydrator directory (%s)', dirname($hydratorCacheDir)));
}
} else if (!is_writable($hydratorCacheDir)) {
throw new \RuntimeException(sprintf('Doctrine Hydrator directory (%s) is not writeable for the current system user.', $hydratorCacheDir));
}
// if hydrators are autogenerated we don't need to generate them in the cache warmer.
if ($this->container->getParameter('doctrine.odm.mongodb.auto_generate_hydrator_classes') === true) {
return;
}
$documentManagers = $this->container->getParameter('doctrine.odm.mongodb.document_managers');
foreach ($documentManagers as $documentManagerName) {
$dm = $this->container->get(sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManagerName));
/* @var $dm Doctrine\ODM\MongoDB\DocumentManager */
$classes = $dm->getMetadataFactory()->getAllMetadata();
$dm->getHydratorFactory()->generateHydratorClasses($classes);
}
}
}

View File

@ -1,76 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
/**
* The proxy generator cache warmer generates all document proxies.
*
* In the process of generating proxies the cache for all the metadata is primed also,
* since this information is necessary to build the proxies in the first place.
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class ProxyCacheWarmer implements CacheWarmerInterface
{
/**
* @var Container
*/
private $container;
/**
* @param Container $container
*/
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* This cache warmer is not optional, without proxies fatal error occurs!
*
* @return false
*/
public function isOptional()
{
return false;
}
public function warmUp($cacheDir)
{
// we need the directory no matter the proxy cache generation strategy.
$proxyCacheDir = $this->container->getParameter('doctrine.odm.mongodb.proxy_dir');
if (!file_exists($proxyCacheDir)) {
if (false === @mkdir($proxyCacheDir, 0777, true)) {
throw new \RuntimeException(sprintf('Unable to create the Doctrine Proxy directory (%s)', dirname($proxyCacheDir)));
}
} else if (!is_writable($proxyCacheDir)) {
throw new \RuntimeException(sprintf('Doctrine Proxy directory (%s) is not writeable for the current system user.', $proxyCacheDir));
}
// if proxies are autogenerated we don't need to generate them in the cache warmer.
if ($this->container->getParameter('doctrine.odm.mongodb.auto_generate_proxy_classes') === true) {
return;
}
$documentManagers = $this->container->getParameter('doctrine.odm.mongodb.document_managers');
foreach ($documentManagers as $documentManagerName) {
$dm = $this->container->get(sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManagerName));
/* @var $dm Doctrine\ODM\MongoDB\DocumentManager */
$classes = $dm->getMetadataFactory()->getAllMetadata();
$dm->getProxyFactory()->generateProxyClasses($classes);
}
}
}

View File

@ -1,54 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Doctrine\ODM\MongoDB\Tools\Console\Command\ClearCache\MetadataCommand;
/**
* Command to clear the metadata cache of the various cache drivers.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jonathan H. Wage <jonwage@gmail.com>
* @author Henrik Westphal <henrik.westphal@gmail.com>
*/
class ClearMetadataCacheDoctrineODMCommand extends MetadataCommand
{
protected function configure()
{
parent::configure();
$this
->setName('doctrine:mongodb:cache:clear-metadata')
->setDescription('Clear all metadata cache for a document manager.')
->addOption('dm', null, InputOption::VALUE_OPTIONAL, 'The document manager to use for this command.')
->setHelp(<<<EOT
The <info>doctrine:mongodb:cache:clear-metadata</info> command clears all metadata cache for the default document manager:
<info>./app/console doctrine:mongodb:cache:clear-metadata</info>
You can also optionally specify the <comment>--dm</comment> option to specify which document manager to clear the cache for:
<info>./app/console doctrine:mongodb:cache:clear-metadata --dm=default</info>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm'));
return parent::execute($input, $output);
}
}

View File

@ -1,53 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\Output;
use Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\CreateCommand;
/**
* Command to create the database schema for a set of classes based on their mappings.
*
* @author Justin Hileman <justin@shopopensky.com>
*/
class CreateSchemaDoctrineODMCommand extends CreateCommand
{
protected function configure()
{
parent::configure();
$this
->setName('doctrine:mongodb:schema:create')
->addOption('dm', null, InputOption::VALUE_REQUIRED, 'The document manager to use for this command.')
->setHelp(<<<EOT
The <info>doctrine:mongodb:schema:create</info> command creates the default document manager's schema:
<info>./app/console doctrine:mongodb:schema:create</info>
You can also optionally specify the name of a document manager to create the schema for:
<info>./app/console doctrine:mongodb:schema:create --dm=default</info>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm'));
parent::execute($input, $output);
}
}

View File

@ -1,121 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\Command;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Doctrine\ODM\MongoDB\Tools\Console\Helper\DocumentManagerHelper;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Doctrine\ODM\MongoDB\Tools\DisconnectedClassMetadataFactory;
use Doctrine\ODM\MongoDB\Tools\DocumentGenerator;
/**
* Base class for Doctrine ODM console commands to extend.
*
* @author Justin Hileman <justin@shopopensky.com>
*/
abstract class DoctrineODMCommand extends Command
{
public static function setApplicationDocumentManager(Application $application, $dmName)
{
$container = $application->getKernel()->getContainer();
$dmName = $dmName ? $dmName : 'default';
$dmServiceName = sprintf('doctrine.odm.mongodb.%s_document_manager', $dmName);
if (!$container->has($dmServiceName)) {
throw new \InvalidArgumentException(sprintf('Could not find Doctrine ODM DocumentManager named "%s"', $dmName));
}
$dm = $container->get($dmServiceName);
$helperSet = $application->getHelperSet();
$helperSet->set(new DocumentManagerHelper($dm), 'dm');
}
protected function getDocumentGenerator()
{
$documentGenerator = new DocumentGenerator();
$documentGenerator->setAnnotationPrefix('mongodb:');
$documentGenerator->setGenerateAnnotations(false);
$documentGenerator->setGenerateStubMethods(true);
$documentGenerator->setRegenerateDocumentIfExists(false);
$documentGenerator->setUpdateDocumentIfExists(true);
$documentGenerator->setNumSpaces(4);
return $documentGenerator;
}
protected function getDoctrineDocumentManagers()
{
$documentManagerNames = $this->container->getParameter('doctrine.odm.mongodb.document_managers');
$documentManagers = array();
foreach ($documentManagerNames as $documentManagerName) {
$dm = $this->container->get(sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManagerName));
$documentManagers[] = $dm;
}
return $documentManagers;
}
protected function getBundleMetadatas(Bundle $bundle)
{
$namespace = $bundle->getNamespace();
$bundleMetadatas = array();
$documentManagers = $this->getDoctrineDocumentManagers();
foreach ($documentManagers as $key => $dm) {
$cmf = new DisconnectedClassMetadataFactory();
$cmf->setDocumentManager($dm);
$cmf->setConfiguration($dm->getConfiguration());
$metadatas = $cmf->getAllMetadata();
foreach ($metadatas as $metadata) {
if (strpos($metadata->name, $namespace) === 0) {
$bundleMetadatas[$metadata->name] = $metadata;
}
}
}
return $bundleMetadatas;
}
protected function findBundle($bundleName)
{
$foundBundle = false;
foreach ($this->getApplication()->getKernel()->getBundles() as $bundle) {
/* @var $bundle Bundle */
if (strtolower($bundleName) == strtolower($bundle->getName())) {
$foundBundle = $bundle;
break;
}
}
if (!$foundBundle) {
throw new \InvalidArgumentException("No bundle " . $bundleName . " was found.");
}
return $foundBundle;
}
/**
* Transform classname to a path $foundBundle substract it to get the destination
*
* @param Bundle $bundle
* @return string
*/
protected function findBasePathForBundle($bundle)
{
$path = str_replace('\\', '/', $bundle->getNamespace());
$search = str_replace('\\', '/', $bundle->getPath());
$destination = str_replace('/'.$path, '', $search, $c);
if ($c != 1) {
throw new \RuntimeException(sprintf('Can\'t find base path for bundle (path: "%s", destination: "%s").', $path, $destination));
}
return $destination;
}
}

View File

@ -1,53 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\Output;
use Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\DropCommand;
/**
* Command to create the database schema for a set of classes based on their mappings.
*
* @author Justin Hileman <justin@shopopensky.com>
*/
class DropSchemaDoctrineODMCommand extends DropCommand
{
protected function configure()
{
parent::configure();
$this
->setName('doctrine:mongodb:schema:drop')
->addOption('dm', null, InputOption::VALUE_REQUIRED, 'The document manager to use for this command.')
->setHelp(<<<EOT
The <info>doctrine:mongodb:schema:drop</info> command drops the default document manager's schema:
<info>./app/console doctrine:mongodb:schema:drop</info>
You can also optionally specify the name of a document manager to drop the schema for:
<info>./app/console doctrine:mongodb:schema:drop --dm=default</info>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm'));
parent::execute($input, $output);
}
}

View File

@ -1,80 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\Output;
/**
* Generate document classes from mapping information
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class GenerateDocumentsDoctrineODMCommand extends DoctrineODMCommand
{
protected function configure()
{
$this
->setName('doctrine:mongodb:generate:documents')
->setDescription('Generate document classes and method stubs from your mapping information.')
->addArgument('bundle', InputArgument::REQUIRED, 'The bundle to initialize the document or documents in.')
->addOption('document', null, InputOption::VALUE_OPTIONAL, 'The document class to initialize (shortname without namespace).')
->setHelp(<<<EOT
The <info>doctrine:mongodb:generate:documents</info> command generates document classes and method stubs from your mapping information:
You have to limit generation of documents to an individual bundle:
<info>./app/console doctrine:mongodb:generate:documents MyCustomBundle</info>
Alternatively, you can limit generation to a single document within a bundle:
<info>./app/console doctrine:mongodb:generate:documents "MyCustomBundle" --document="User"</info>
You have to specify the shortname (without namespace) of the document you want to filter for.
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$bundleName = $input->getArgument('bundle');
$filterDocument = $input->getOption('document');
$foundBundle = $this->findBundle($bundleName);
if ($metadatas = $this->getBundleMetadatas($foundBundle)) {
$output->writeln(sprintf('Generating documents for "<info>%s</info>"', $foundBundle->getName()));
$documentGenerator = $this->getDocumentGenerator();
foreach ($metadatas as $metadata) {
if ($filterDocument && $metadata->reflClass->getShortName() == $filterDocument) {
continue;
}
if (strpos($metadata->name, $foundBundle->getNamespace()) === false) {
throw new \RuntimeException(
"Document " . $metadata->name . " and bundle don't have a common namespace, ".
"generation failed because the target directory cannot be detected.");
}
$output->writeln(sprintf(' > generating <comment>%s</comment>', $metadata->name));
$documentGenerator->generate(array($metadata), $this->findBasePathForBundle($foundBundle));
}
} else {
throw new \RuntimeException("Bundle " . $bundleName . " does not contain any mapped documents.");
}
}
}

View File

@ -1,54 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\Output;
use Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateHydratorsCommand;
/**
* Generate the Doctrine ORM document hydrators to your cache directory.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class GenerateHydratorsDoctrineODMCommand extends GenerateHydratorsCommand
{
protected function configure()
{
parent::configure();
$this
->setName('doctrine:mongodb:generate:hydrators')
->addOption('dm', null, InputOption::VALUE_OPTIONAL, 'The document manager to use for this command.')
->setHelp(<<<EOT
The <info>doctrine:mongodb:generate:hydrators</info> command generates hydrator classes for your documents:
<info>./app/console doctrine:mongodb:generate:hydrators</info>
You can specify the document manager you want to generate the hydrators for:
<info>./app/console doctrine:mongodb:generate:hydrators --dm=name</info>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm'));
return parent::execute($input, $output);
}
}

View File

@ -1,54 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\Output;
use Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateProxiesCommand;
/**
* Generate the Doctrine ORM document proxies to your cache directory.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class GenerateProxiesDoctrineODMCommand extends GenerateProxiesCommand
{
protected function configure()
{
parent::configure();
$this
->setName('doctrine:mongodb:generate:proxies')
->addOption('dm', null, InputOption::VALUE_OPTIONAL, 'The document manager to use for this command.')
->setHelp(<<<EOT
The <info>doctrine:mongodb:generate:proxies</info> command generates proxy classes for your default document manager:
<info>./app/console doctrine:mongodb:generate:proxies</info>
You can specify the document manager you want to generate the proxies for:
<info>./app/console doctrine:mongodb:generate:proxies --dm=name</info>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm'));
return parent::execute($input, $output);
}
}

View File

@ -1,77 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\Output;
use Doctrine\ODM\MongoDB\Tools\DocumentRepositoryGenerator;
/**
* Command to generate repository classes for mapping information.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class GenerateRepositoriesDoctrineODMCommand extends DoctrineODMCommand
{
protected function configure()
{
$this
->setName('doctrine:mongodb:generate:repositories')
->setDescription('Generate repository classes from your mapping information.')
->addArgument('bundle', InputArgument::REQUIRED, 'The bundle to initialize the repositories in.')
->addOption('document', null, InputOption::VALUE_OPTIONAL, 'The document class to generate the repository for (shortname without namespace).')
->setHelp(<<<EOT
The <info>doctrine:mongodb:generate:repositories</info> command generates the configured document repository classes from your mapping information:
<info>./app/console doctrine:mongodb:generate:repositories</info>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$bundleName = $input->getArgument('bundle');
$filterDocument = $input->getOption('document');
$foundBundle = $this->findBundle($bundleName);
if ($metadatas = $this->getBundleMetadatas($foundBundle)) {
$output->writeln(sprintf('Generating document repositories for "<info>%s</info>"', $foundBundle->getName()));
$generator = new DocumentRepositoryGenerator();
foreach ($metadatas as $metadata) {
if ($filterDocument && $filterDocument !== $metadata->reflClass->getShortname()) {
continue;
}
if ($metadata->customRepositoryClassName) {
if (strpos($metadata->customRepositoryClassName, $foundBundle->getNamespace()) === false) {
throw new \RuntimeException(
"Repository " . $metadata->customRepositoryClassName . " and bundle don't have a common namespace, ".
"generation failed because the target directory cannot be detected.");
}
$output->writeln(sprintf(' > <info>OK</info> generating <comment>%s</comment>', $metadata->customRepositoryClassName));
$generator->writeDocumentRepositoryClass($metadata->customRepositoryClassName, $this->findBasePathForBundle($foundBundle));
} else {
$output->writeln(sprintf(' > <error>SKIP</error> no custom repository for <comment>%s</comment>', $metadata->name));
}
}
} else {
throw new \RuntimeException("Bundle " . $bundleName . " does not contain any mapped documents.");
}
}
}

View File

@ -1,84 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Show information about mapped documents
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class InfoDoctrineODMCommand extends DoctrineODMCommand
{
protected function configure()
{
$this
->setName('doctrine:mongodb:mapping:info')
->addOption('dm', null, InputOption::VALUE_OPTIONAL, 'The document manager to use for this command.')
->setDescription('Show basic information about all mapped documents.')
->setHelp(<<<EOT
The <info>doctrine:mongodb:mapping:info</info> shows basic information about which
documents exist and possibly if their mapping information contains errors or not.
<info>./app/console doctrine:mongodb:mapping:info</info>
If you are using multiple document managers you can pick your choice with the <info>--dm</info> option:
<info>./app/console doctrine:mongodb:mapping:info --dm=default</info>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$documentManagerName = $input->getOption('dm') ?
$input->getOption('dm') :
$this->container->getParameter('doctrine.odm.mongodb.default_document_manager');
$documentManagerService = sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManagerName);
/* @var $documentManager Doctrine\ODM\MongoDB\DocumentManager */
$documentManager = $this->container->get($documentManagerService);
$documentClassNames = $documentManager->getConfiguration()
->getMetadataDriverImpl()
->getAllClassNames();
if (!$documentClassNames) {
throw new \Exception(
'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 Annotations directly in the classes doc blocks '.
'or with XML/YAML in your bundles Resources/config/doctrine/metadata/mongodb directory.'
);
}
$output->write(sprintf("Found <info>%d</info> documents mapped in document manager <info>%s</info>:\n",
count($documentClassNames), $documentManagerName), true);
foreach ($documentClassNames AS $documentClassName) {
try {
$cm = $documentManager->getClassMetadata($documentClassName);
$output->write("<info>[OK]</info> " . $documentClassName, true);
} catch(\Exception $e) {
$output->write("<error>[FAIL]</error> " . $documentClassName, true);
$output->write("<comment>" . $e->getMessage()."</comment>", true);
$output->write("", true);
}
}
}
}

View File

@ -1,108 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\Output;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpKernel\Util\Filesystem;
use Symfony\Bundle\DoctrineAbstractBundle\Common\DataFixtures\Loader as DataFixturesLoader;
use Doctrine\Common\DataFixtures\Executor\MongoDBExecutor;
use Doctrine\Common\DataFixtures\Purger\MongoDBPurger;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Internal\CommitOrderCalculator;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
use InvalidArgumentException;
/**
* Load data fixtures from bundles.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class LoadDataFixturesDoctrineODMCommand extends DoctrineODMCommand
{
protected function configure()
{
$this
->setName('doctrine:mongodb:data:load')
->setDescription('Load data fixtures to your database.')
->addOption('fixtures', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'The directory or file to load data fixtures from.')
->addOption('append', null, InputOption::VALUE_NONE, 'Append the data fixtures instead of flushing the database first.')
->addOption('dm', null, InputOption::VALUE_REQUIRED, 'The document manager to use for this command.')
->setHelp(<<<EOT
The <info>doctrine:mongodb:data:load</info> command loads data fixtures from your bundles:
<info>./app/console doctrine:mongodb:data:load</info>
You can also optionally specify the path to fixtures with the <info>--fixtures</info> option:
<info>./app/console doctrine:mongodb:data:load --fixtures=/path/to/fixtures1 --fixtures=/path/to/fixtures2</info>
If you want to append the fixtures instead of flushing the database first you can use the <info>--append</info> option:
<info>./app/console doctrine:mongodb:data:load --append</info>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$dmName = $input->getOption('dm');
$dmName = $dmName ? $dmName : 'default';
$dmServiceName = sprintf('doctrine.odm.mongodb.%s_document_manager', $dmName);
if (!$this->container->has($dmServiceName)) {
throw new InvalidArgumentException(
sprintf(
'Could not find a document manager configured with the name "%s". Check your '.
'application configuration to configure your Doctrine document managers.', $dmName
)
);
}
$dm = $this->container->get($dmServiceName);
$dirOrFile = $input->getOption('fixtures');
if ($dirOrFile) {
$paths = is_array($dirOrFile) ? $dirOrFile : array($dirOrFile);
} else {
$paths = array();
foreach ($this->container->get('kernel')->getBundles() as $bundle) {
$paths[] = $bundle->getPath().'/DataFixtures/MongoDB';
}
}
$loader = new DataFixturesLoader($this->container);
foreach ($paths as $path) {
if (is_dir($path)) {
$loader->loadFromDirectory($path);
}
}
$fixtures = $loader->getFixtures();
if (!$fixtures) {
throw new InvalidArgumentException(
sprintf('Could not find any fixtures to load in: %s', "\n\n- ".implode("\n- ", $paths))
);
}
$purger = new MongoDBPurger($dm);
$executor = new MongoDBExecutor($dm, $purger);
$executor->setLogger(function($message) use ($output) {
$output->writeln(sprintf(' <comment>></comment> <info>%s</info>', $message));
});
$executor->execute($fixtures, $input->getOption('append'));
}
}

View File

@ -1,44 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\Output;
use Doctrine\ODM\MongoDB\Tools\Console\Command\QueryCommand;
/**
* Execute a Doctrine MongoDB ODM query and output the results.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class QueryDoctrineODMCommand extends QueryCommand
{
protected function configure()
{
parent::configure();
$this
->setName('doctrine:mongodb:query')
->addOption('dm', null, InputOption::VALUE_OPTIONAL, 'The document manager to use for this command.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm'));
return parent::execute($input, $output);
}
}

View File

@ -1,59 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\DataCollector;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
use Symfony\Bundle\DoctrineMongoDBBundle\Logger\DoctrineMongoDBLogger;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Data collector for the Doctrine MongoDB ODM.
*
* @author Kris Wallsmith <kris.wallsmith@symfony.com>
*/
class DoctrineMongoDBDataCollector extends DataCollector
{
protected $logger;
public function __construct(DoctrineMongoDBLogger $logger)
{
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Exception $exception = null)
{
$this->data['nb_queries'] = $this->logger->getNbQueries();
$this->data['queries'] = $this->logger->getQueries();
}
public function getQueryCount()
{
return $this->data['nb_queries'];
}
public function getQueries()
{
return $this->data['queries'];
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'mongodb';
}
}

View File

@ -1,22 +0,0 @@
<?php
namespace Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
class AddValidatorNamespaceAliasPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('validator.mapping.loader.annotation_loader')) {
return;
}
$loader = $container->getDefinition('validator.mapping.loader.annotation_loader');
$args = $loader->getArguments();
$args[0]['assertMongoDB'] = 'Symfony\\Bundle\\DoctrineMongoDBBundle\\Validator\\Constraints\\';
$loader->replaceArgument(0, $args[0]);
}
}

View File

@ -1,30 +0,0 @@
<?php
namespace Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
class CreateHydratorDirectoryPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
if (!$container->hasParameter('doctrine.odm.mongodb.hydrator_dir')) {
return;
}
// Don't do anything if auto_generate_hydrator_classes is false
if (!$container->getParameter('doctrine.odm.mongodb.auto_generate_hydrator_classes')) {
return;
}
// Create document proxy directory
$hydratorCacheDir = $container->getParameter('doctrine.odm.mongodb.hydrator_dir');
if (!is_dir($hydratorCacheDir)) {
if (false === @mkdir($hydratorCacheDir, 0777, true)) {
exit(sprintf('Unable to create the Doctrine Hydrator directory (%s)', dirname($hydratorCacheDir)));
}
} elseif (!is_writable($hydratorCacheDir)) {
exit(sprintf('Unable to write in the Doctrine Hydrator directory (%s)', $hydratorCacheDir));
}
}
}

View File

@ -1,30 +0,0 @@
<?php
namespace Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
class CreateProxyDirectoryPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
if (!$container->hasParameter('doctrine.odm.mongodb.proxy_dir')) {
return;
}
// Don't do anything if auto_generate_proxy_classes is false
if (!$container->getParameter('doctrine.odm.mongodb.auto_generate_proxy_classes')) {
return;
}
// Create document proxy directory
$proxyCacheDir = $container->getParameter('doctrine.odm.mongodb.proxy_dir');
if (!is_dir($proxyCacheDir)) {
if (false === @mkdir($proxyCacheDir, 0777, true)) {
exit(sprintf('Unable to create the Doctrine Proxy directory (%s)', dirname($proxyCacheDir)));
}
} elseif (!is_writable($proxyCacheDir)) {
exit(sprintf('Unable to write in the Doctrine Proxy directory (%s)', $proxyCacheDir));
}
}
}

View File

@ -1,59 +0,0 @@
<?php
namespace Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
class RegisterEventListenersAndSubscribersPass implements CompilerPassInterface
{
protected $container;
public function process(ContainerBuilder $container)
{
$this->container = $container;
foreach ($container->findTaggedServiceIds('doctrine.odm.mongodb.event_manager') as $id => $tag) {
$definition = $container->getDefinition($id);
$prefix = substr($id, 0, -1 * strlen('_event_manager'));
$this->registerListeners($prefix, $definition);
$this->registerSubscribers($prefix, $definition);
}
}
protected function registerSubscribers($prefix, $definition)
{
$subscribers = array_merge(
$this->container->findTaggedServiceIds('doctrine.common.event_subscriber'),
$this->container->findTaggedServiceIds($prefix.'_event_subscriber')
);
foreach ($subscribers as $id => $instances) {
$definition->addMethodCall('addEventSubscriber', array(new Reference($id)));
}
}
protected function registerListeners($prefix, $definition)
{
$listeners = array_merge(
$this->container->findTaggedServiceIds('doctrine.common.event_listener'),
$this->container->findTaggedServiceIds($prefix.'_event_listener')
);
foreach ($listeners as $listenerId => $instances) {
$events = array();
foreach ($instances as $attributes) {
if (isset($attributes['event'])) {
$events[] = $attributes['event'];
}
}
if (0 < count($events)) {
$definition->addMethodCall('addEventListener', array(
$events,
new Reference($listenerId),
));
}
}
}
}

View File

@ -1,193 +0,0 @@
<?php
namespace Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* FrameworkExtension configuration structure.
*
* @author Ryan Weaver <ryan@thatsquality.com>
*/
class Configuration implements ConfigurationInterface
{
private $debug;
/**
* Constructor.
*
* @param Boolean $debug The kernel.debug value
*/
public function __construct($debug)
{
$this->debug = (Boolean) $debug;
}
/**
* Generates the configuration tree builder.
*
* @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('doctrine_mongo_db');
$this->addDocumentManagersSection($rootNode);
$this->addConnectionsSection($rootNode);
$rootNode
->children()
->scalarNode('proxy_namespace')->defaultValue('Proxies')->end()
->scalarNode('proxy_dir')->defaultValue('%kernel.cache_dir%/doctrine/odm/mongodb/Proxies')->end()
->scalarNode('auto_generate_proxy_classes')->defaultValue(false)->end()
->scalarNode('hydrator_namespace')->defaultValue('Hydrators')->end()
->scalarNode('hydrator_dir')->defaultValue('%kernel.cache_dir%/doctrine/odm/mongodb/Hydrators')->end()
->scalarNode('auto_generate_hydrator_classes')->defaultValue(false)->end()
->scalarNode('default_document_manager')->end()
->scalarNode('default_connection')->end()
->scalarNode('default_database')->defaultValue('default')->end()
->end()
;
return $treeBuilder;
}
/**
* Configures the "document_managers" section
*/
private function addDocumentManagersSection(ArrayNodeDefinition $rootNode)
{
$rootNode
->fixXmlConfig('document_manager')
->children()
->arrayNode('document_managers')
->useAttributeAsKey('id')
->prototype('array')
//->performNoDeepMerging()
->treatNullLike(array())
->append($this->getMetadataCacheDriverNode())
->children()
->scalarNode('connection')->end()
->scalarNode('database')->end()
->booleanNode('logging')->defaultValue($this->debug)->end()
->end()
->fixXmlConfig('mapping')
->append($this->getMappingsNode())
->end()
->end()
->end()
;
}
/**
* Adds the configuration for the "connections" key
*/
private function addConnectionsSection(ArrayNodeDefinition $rootNode)
{
$rootNode
->fixXmlConfig('connection')
->children()
->arrayNode('connections')
->useAttributeAsKey('id')
->prototype('array')
->performNoDeepMerging()
->children()
->scalarNode('server')->defaultNull()->end()
->end()
->append($this->addConnectionOptionsNode())
->end()
->end()
->end()
;
}
/**
* Returns the array node used for "mappings".
*
* This is used in two different parts of the tree.
*
* @param NodeBuilder $rootNode The parent node
* @return NodeBuilder
*/
protected function getMappingsNode()
{
$builder = new TreeBuilder();
$node = $builder->root('mappings');
$node
->useAttributeAsKey('name')
->prototype('array')
->beforeNormalization()
// if it's not an array, then the scalar is the type key
->ifString()
->then(function($v) { return array ('type' => $v); })
->end()
// I believe that "null" should *not* set the type
// it's guessed in AbstractDoctrineExtension::detectMetadataDriver
->treatNullLike(array())
->children()
->scalarNode('type')->end()
->scalarNode('dir')->end()
->scalarNode('prefix')->end()
->scalarNode('alias')->end()
->booleanNode('is_bundle')->end()
->end()
->performNoDeepMerging()
->end()
;
return $node;
}
/**
* Adds the NodeBuilder for the "options" key of a connection.
*/
private function addConnectionOptionsNode()
{
$builder = new TreeBuilder();
$node = $builder->root('options');
$node
->performNoDeepMerging()
->addDefaultsIfNotSet() // adds an empty array of omitted
// options go into the Mongo constructor
// http://www.php.net/manual/en/mongo.construct.php
->children()
->booleanNode('connect')->end()
->scalarNode('persist')->end()
->scalarNode('timeout')->end()
->booleanNode('replicaSet')->end()
->scalarNode('username')->end()
->scalarNode('password')->end()
->end()
->end();
return $node;
}
private function getMetadataCacheDriverNode()
{
$builder = new TreeBuilder();
$node = $builder->root('metadata_cache_driver');
$node
->beforeNormalization()
// if scalar
->ifTrue(function($v) { return !is_array($v); })
->then(function($v) { return array('type' => $v); })
->end()
->children()
->scalarNode('type')->end()
->scalarNode('class')->end()
->scalarNode('host')->end()
->scalarNode('port')->end()
->scalarNode('instance_class')->end()
->end()
->end();
return $node;
}
}

View File

@ -1,344 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Bundle\DoctrineAbstractBundle\DependencyInjection\AbstractDoctrineExtension;
/**
* Doctrine MongoDB ODM extension.
*
* @author Bulat Shakirzyanov <bulat@theopenskyproject.com>
* @author Kris Wallsmith <kris.wallsmith@symfony.com>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class DoctrineMongoDBExtension extends AbstractDoctrineExtension
{
/**
* Responds to the doctrine_mongo_db configuration parameter.
*/
public function load(array $configs, ContainerBuilder $container)
{
// Load DoctrineMongoDBBundle/Resources/config/mongodb.xml
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('mongodb.xml');
$processor = new Processor();
$configuration = new Configuration($container->getParameter('kernel.debug'));
$config = $processor->processConfiguration($configuration, $configs);
// can't currently default this correctly in Configuration
if (!isset($config['metadata_cache_driver'])) {
$config['metadata_cache_driver'] = array('type' => 'array');
}
if (empty ($config['default_connection'])) {
$keys = array_keys($config['connections']);
$config['default_connection'] = reset($keys);
}
if (empty ($config['default_document_manager'])) {
$keys = array_keys($config['document_managers']);
$config['default_document_manager'] = reset($keys);
}
// set some options as parameters and unset them
$config = $this->overrideParameters($config, $container);
// load the connections
$this->loadConnections($config['connections'], $container);
// load the document managers
$this->loadDocumentManagers(
$config['document_managers'],
$config['default_document_manager'],
$config['default_database'],
$config['metadata_cache_driver'],
$container
);
}
/**
* Uses some of the extension options to override DI extension parameters.
*
* @param array $options The available configuration options
* @param ContainerBuilder $container A ContainerBuilder instance
*/
protected function overrideParameters($options, ContainerBuilder $container)
{
$overrides = array(
'proxy_namespace',
'proxy_dir',
'auto_generate_proxy_classes',
'hydrator_namespace',
'hydrator_dir',
'auto_generate_hydrator_classes',
);
foreach ($overrides as $key) {
if (isset($options[$key])) {
$container->setParameter('doctrine.odm.mongodb.'.$key, $options[$key]);
// the option should not be used, the parameter should be referenced
unset($options[$key]);
}
}
return $options;
}
/**
* Loads the document managers configuration.
*
* @param array $dmConfigs An array of document manager configs
* @param string $defaultDM The default document manager name
* @param string $defaultDB The default db name
* @param string $defaultMetadataCache The default metadata cache configuration
* @param ContainerBuilder $container A ContainerBuilder instance
*/
protected function loadDocumentManagers(array $dmConfigs, $defaultDM, $defaultDB, $defaultMetadataCache, ContainerBuilder $container)
{
foreach ($dmConfigs as $name => $documentManager) {
$documentManager['name'] = $name;
$this->loadDocumentManager(
$documentManager,
$defaultDM,
$defaultDB,
$defaultMetadataCache,
$container
);
}
$container->setParameter('doctrine.odm.mongodb.document_managers', array_keys($dmConfigs));
}
/**
* Loads a document manager configuration.
*
* @param array $documentManager A document manager configuration array
* @param string $defaultDM The default document manager name
* @param string $defaultDB The default db name
* @param string $defaultMetadataCache The default metadata cache configuration
* @param ContainerBuilder $container A ContainerBuilder instance
*/
protected function loadDocumentManager(array $documentManager, $defaultDM, $defaultDB, $defaultMetadataCache, ContainerBuilder $container)
{
$defaultDatabase = isset($documentManager['default_database']) ? $documentManager['default_database'] : $defaultDB;
$configServiceName = sprintf('doctrine.odm.mongodb.%s_configuration', $documentManager['name']);
if ($container->hasDefinition($configServiceName)) {
$odmConfigDef = $container->getDefinition($configServiceName);
} else {
$odmConfigDef = new Definition('%doctrine.odm.mongodb.configuration_class%');
$container->setDefinition($configServiceName, $odmConfigDef);
}
$this->loadDocumentManagerBundlesMappingInformation($documentManager, $odmConfigDef, $container);
$this->loadDocumentManagerMetadataCacheDriver($documentManager, $container, $defaultMetadataCache);
$methods = array(
'setMetadataCacheImpl' => new Reference(sprintf('doctrine.odm.mongodb.%s_metadata_cache', $documentManager['name'])),
'setMetadataDriverImpl' => new Reference(sprintf('doctrine.odm.mongodb.%s_metadata_driver', $documentManager['name'])),
'setProxyDir' => '%doctrine.odm.mongodb.proxy_dir%',
'setProxyNamespace' => '%doctrine.odm.mongodb.proxy_namespace%',
'setAutoGenerateProxyClasses' => '%doctrine.odm.mongodb.auto_generate_proxy_classes%',
'setHydratorDir' => '%doctrine.odm.mongodb.hydrator_dir%',
'setHydratorNamespace' => '%doctrine.odm.mongodb.hydrator_namespace%',
'setAutoGenerateHydratorClasses' => '%doctrine.odm.mongodb.auto_generate_hydrator_classes%',
'setDefaultDB' => $defaultDatabase,
);
if ($documentManager['logging']) {
$methods['setLoggerCallable'] = array(new Reference('doctrine.odm.mongodb.logger'), 'logQuery');
}
foreach ($methods as $method => $arg) {
if ($odmConfigDef->hasMethodCall($method)) {
$odmConfigDef->removeMethodCall($method);
}
$odmConfigDef->addMethodCall($method, array($arg));
}
// event manager
$eventManagerName = isset($documentManager['event_manager']) ? $documentManager['event_manager'] : $documentManager['name'];
$eventManagerId = sprintf('doctrine.odm.mongodb.%s_event_manager', $eventManagerName);
if (!$container->hasDefinition($eventManagerId)) {
$eventManagerDef = new Definition('%doctrine.odm.mongodb.event_manager_class%');
$eventManagerDef->addTag('doctrine.odm.mongodb.event_manager');
$eventManagerDef->setPublic(false);
$container->setDefinition($eventManagerId, $eventManagerDef);
}
$odmDmArgs = array(
new Reference(sprintf('doctrine.odm.mongodb.%s_connection', isset($documentManager['connection']) ? $documentManager['connection'] : $documentManager['name'])),
new Reference(sprintf('doctrine.odm.mongodb.%s_configuration', $documentManager['name'])),
new Reference($eventManagerId),
);
$odmDmDef = new Definition('%doctrine.odm.mongodb.document_manager_class%', $odmDmArgs);
$odmDmDef->setFactoryClass('%doctrine.odm.mongodb.document_manager_class%');
$odmDmDef->setFactoryMethod('create');
$odmDmDef->addTag('doctrine.odm.mongodb.document_manager');
$container->setDefinition(sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManager['name']), $odmDmDef);
if ($documentManager['name'] == $defaultDM) {
$container->setAlias(
'doctrine.odm.mongodb.document_manager',
new Alias(sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManager['name']))
);
$container->setAlias(
'doctrine.odm.mongodb.event_manager',
new Alias(sprintf('doctrine.odm.mongodb.%s_event_manager', $documentManager['name']))
);
}
}
/**
* Loads the configured document manager metadata cache driver.
*
* @param array $config A configured document manager array
* @param ContainerBuilder $container A ContainerBuilder instance
* @param array $defaultMetadataCache The default metadata cache configuration array
*/
protected function loadDocumentManagerMetadataCacheDriver(array $documentManager, ContainerBuilder $container, $defaultMetadataCache)
{
$dmMetadataCacheDriver = isset($documentManager['metadata_cache_driver']) ? $documentManager['metadata_cache_driver'] : $defaultMetadataCache;
$type = $dmMetadataCacheDriver['type'];
if ('memcache' === $type) {
$memcacheClass = isset($dmMetadataCacheDriver['class']) ? $dmMetadataCacheDriver['class'] : sprintf('%%doctrine.odm.mongodb.cache.%s_class%%', $type);
$cacheDef = new Definition($memcacheClass);
$memcacheHost = isset($dmMetadataCacheDriver['host']) ? $dmMetadataCacheDriver['host'] : '%doctrine.odm.mongodb.cache.memcache_host%';
$memcachePort = isset($dmMetadataCacheDriver['port']) ? $dmMetadataCacheDriver['port'] : '%doctrine.odm.mongodb.cache.memcache_port%';
$memcacheInstanceClass = isset($dmMetadataCacheDriver['instance-class']) ? $dmMetadataCacheDriver['instance-class'] : (isset($dmMetadataCacheDriver['instance_class']) ? $dmMetadataCacheDriver['instance_class'] : '%doctrine.odm.mongodb.cache.memcache_instance_class%');
$memcacheInstance = new Definition($memcacheInstanceClass);
$memcacheInstance->addMethodCall('connect', array($memcacheHost, $memcachePort));
$container->setDefinition(sprintf('doctrine.odm.mongodb.%s_memcache_instance', $documentManager['name']), $memcacheInstance);
$cacheDef->addMethodCall('setMemcache', array(new Reference(sprintf('doctrine.odm.mongodb.%s_memcache_instance', $documentManager['name']))));
} else {
$cacheDef = new Definition(sprintf('%%doctrine.odm.mongodb.cache.%s_class%%', $type));
}
$container->setDefinition(sprintf('doctrine.odm.mongodb.%s_metadata_cache', $documentManager['name']), $cacheDef);
}
/**
* Loads the configured connections.
*
* @param array $config An array of connections configurations
* @param ContainerBuilder $container A ContainerBuilder instance
*/
protected function loadConnections(array $connections, ContainerBuilder $container)
{
foreach ($connections as $name => $connection) {
$odmConnArgs = array(
isset($connection['server']) ? $connection['server'] : null,
isset($connection['options']) ? $connection['options'] : array(),
new Reference(sprintf('doctrine.odm.mongodb.%s_configuration', $name))
);
$odmConnDef = new Definition('%doctrine.odm.mongodb.connection_class%', $odmConnArgs);
$container->setDefinition(sprintf('doctrine.odm.mongodb.%s_connection', $name), $odmConnDef);
}
}
/**
* Loads an ODM document managers bundle mapping information.
*
* There are two distinct configuration possibilities for mapping information:
*
* 1. Specify a bundle and optionally details where the entity and mapping information reside.
* 2. Specify an arbitrary mapping location.
*
* @example
*
* doctrine.orm:
* mappings:
* MyBundle1: ~
* MyBundle2: yml
* MyBundle3: { type: annotation, dir: Documents/ }
* MyBundle4: { type: xml, dir: Resources/config/doctrine/mapping }
* MyBundle5:
* type: yml
* dir: [bundle-mappings1/, bundle-mappings2/]
* alias: BundleAlias
* arbitrary_key:
* type: xml
* dir: %kernel.dir%/../src/vendor/DoctrineExtensions/lib/DoctrineExtensions/Documents
* prefix: DoctrineExtensions\Documents\
* alias: DExt
*
* In the case of bundles everything is really optional (which leads to autodetection for this bundle) but
* in the mappings key everything except alias is a required argument.
*
* @param array $documentManager A configured ODM entity manager.
* @param Definition A Definition instance
* @param ContainerBuilder $container A ContainerBuilder instance
*/
protected function loadDocumentManagerBundlesMappingInformation(array $documentManager, Definition $odmConfigDef, ContainerBuilder $container)
{
// reset state of drivers and alias map. They are only used by this methods and children.
$this->drivers = array();
$this->aliasMap = array();
$this->loadMappingInformation($documentManager, $container);
$this->registerMappingDrivers($documentManager, $container);
if ($odmConfigDef->hasMethodCall('setDocumentNamespaces')) {
// TODO: Can we make a method out of it on Definition? replaceMethodArguments() or something.
$calls = $odmConfigDef->getMethodCalls();
foreach ($calls as $call) {
if ($call[0] == 'setDocumentNamespaces') {
$this->aliasMap = array_merge($call[1][0], $this->aliasMap);
}
}
$method = $odmConfigDef->removeMethodCall('setDocumentNamespaces');
}
$odmConfigDef->addMethodCall('setDocumentNamespaces', array($this->aliasMap));
}
protected function getObjectManagerElementName($name)
{
return 'doctrine.odm.mongodb.' . $name;
}
protected function getMappingObjectDefaultName()
{
return 'Document';
}
protected function getMappingResourceConfigDirectory()
{
return 'Resources/config/doctrine/metadata/mongodb';
}
/**
* Returns the namespace to be used for this extension (XML namespace).
*
* @return string The XML namespace
*/
public function getNamespace()
{
return 'http://symfony.com/schema/dic/doctrine/odm/mongodb';
}
/**
* @return string
*/
public function getXsdValidationBasePath()
{
return __DIR__.'/../Resources/config/schema';
}
}

View File

@ -1,40 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\AddValidatorNamespaceAliasPass;
use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\CreateHydratorDirectoryPass;
use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\CreateProxyDirectoryPass;
use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\RegisterEventListenersAndSubscribersPass;
/**
* Doctrine MongoDB ODM bundle.
*
* @author Bulat Shakirzyanov <bulat@theopenskyproject.com>
* @author Kris Wallsmith <kris.wallsmith@symfony.com>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class DoctrineMongoDBBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new AddValidatorNamespaceAliasPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION);
$container->addCompilerPass(new RegisterEventListenersAndSubscribersPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION);
$container->addCompilerPass(new CreateProxyDirectoryPass(), PassConfig::TYPE_BEFORE_REMOVING);
$container->addCompilerPass(new CreateHydratorDirectoryPass(), PassConfig::TYPE_BEFORE_REMOVING);
}
}

View File

@ -1,301 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Logger;
use Doctrine\MongoDB\GridFSFile;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
/**
* Logger for the Doctrine MongoDB ODM.
*
* The {@link logQuery()} method is configured as the logger callable in the
* service container.
*
* @author Kris Wallsmith <kris.wallsmith@symfony.com>
*/
class DoctrineMongoDBLogger
{
protected $logger;
protected $prefix;
protected $queries;
protected $processed;
protected $formattedQueries;
protected $nbRealQueries;
/**
* Constructor.
*
* @param LoggerInterface $logger The Symfony logger
* @param string $prefix A prefix for messages sent to the Symfony logger
*/
public function __construct(LoggerInterface $logger = null, $prefix = 'MongoDB query: ')
{
$this->logger = $logger;
$this->prefix = $prefix;
$this->queries = array();
$this->processed = false;
}
/**
* Logs a query.
*
* This method is configured as the logger callable in the service
* container.
*
* @param array $query A query log array from Doctrine
*/
public function logQuery(array $query)
{
$this->queries[] = $query;
$this->processed = false;
if (null !== $this->logger) {
$this->logger->info($this->prefix.static::bsonEncode($query));
}
}
/**
* Returns the number of queries that have been logged.
*
* @return integer The number of queries logged
*/
public function getNbQueries()
{
if (!$this->processed) {
$this->processQueries();
}
return $this->nbRealQueries;
}
/**
* Returns a human-readable array of queries logged.
*
* @return array An array of queries
*/
public function getQueries()
{
if (!$this->processed) {
$this->processQueries();
}
return $this->formattedQueries;
}
/**
* Groups and formats query arrays.
*
* @param array $queries An array of query arrays
*
* @return array An array of human-readable queries
*/
protected function processQueries()
{
$this->formattedQueries = array();
$this->nbRealQueries = 0;
$grouped = array();
$ordered = array();
foreach ($this->queries as $query) {
if (!isset($query['query']) || !isset($query['fields'])) {
// no grouping necessary
$ordered[] = array($query);
continue;
}
$cursor = serialize($query['query']).serialize($query['fields']);
// append if issued from cursor (currently just "sort")
if (isset($query['sort'])) {
unset($query['query'], $query['fields']);
$grouped[$cursor][count($grouped[$cursor]) - 1][] = $query;
} else {
$grouped[$cursor][] = array($query);
$ordered[] =& $grouped[$cursor][count($grouped[$cursor]) - 1];
}
}
$i = 0;
$db = '';
$query = '';
foreach ($ordered as $logs) {
foreach ($logs as $log) {
if (isset($log['db']) && $db != $log['db']) {
// for readability
$this->formattedQueries[$i++] = 'use '.$log['db'].';';
$db = $log['db'];
}
if (isset($log['collection'])) {
// flush the previous and start a new query
if (!empty($query)) {
if ('.' == $query[0]) {
$query = 'db'.$query;
}
$this->formattedQueries[$i++] = $query.';';
++$this->nbRealQueries;
}
$query = 'db.'.$log['collection'];
}
// format the method call
if (isset($log['authenticate'])) {
$query .= '.authenticate()';
} elseif (isset($log['batchInsert'])) {
$query .= '.batchInsert(**'.$log['num'].' item(s)**)';
} elseif (isset($log['command'])) {
$query .= '.command()';
} elseif (isset($log['count'])) {
$query .= '.count(';
if ($log['query'] || $log['limit'] || $log['skip']) {
$query .= static::bsonEncode($log['query']);
if ($log['limit'] || $log['skip']) {
$query .= ', '.static::bsonEncode($log['limit']);
if ($log['skip']) {
$query .= ', '.static::bsonEncode($log['skip']);
}
}
}
$query .= ')';
} elseif (isset($log['createCollection'])) {
$query .= '.createCollection()';
} elseif (isset($log['createDBRef'])) {
$query .= '.createDBRef()';
} elseif (isset($log['deleteIndex'])) {
$query .= '.dropIndex('.static::bsonEncode($log['keys']).')';
} elseif (isset($log['deleteIndexes'])) {
$query .= '.dropIndexes()';
} elseif (isset($log['drop'])) {
$query .= '.drop()';
} elseif (isset($log['dropDatabase'])) {
$query .= '.dropDatabase()';
} elseif (isset($log['ensureIndex'])) {
$query .= '.ensureIndex('.static::bsonEncode($log['keys']).', '.static::bsonEncode($log['options']).')';
} elseif (isset($log['execute'])) {
$query .= '.execute()';
} elseif (isset($log['find'])) {
$query .= '.find(';
if ($log['query'] || $log['fields']) {
$query .= static::bsonEncode($log['query']);
if ($log['fields']) {
$query .= ', '.static::bsonEncode($log['fields']);
}
}
$query .= ')';
} elseif (isset($log['findOne'])) {
$query .= '.findOne(';
if ($log['query'] || $log['fields']) {
$query .= static::bsonEncode($log['query']);
if ($log['fields']) {
$query .= ', '.static::bsonEncode($log['fields']);
}
}
$query .= ')';
} elseif (isset($log['getDBRef'])) {
$query .= '.getDBRef()';
} elseif (isset($log['group'])) {
$query .= '.group('.static::bsonEncode(array(
'keys' => $log['keys'],
'initial' => $log['initial'],
'reduce' => $log['reduce'],
)).')';
} elseif (isset($log['insert'])) {
$query .= '.insert('.static::bsonEncode($log['document']).')';
} elseif (isset($log['remove'])) {
$query .= '.remove('.static::bsonEncode($log['query']).')';
} elseif (isset($log['save'])) {
$query .= '.save('.static::bsonEncode($log['document']).')';
} elseif (isset($log['sort'])) {
$query .= '.sort('.static::bsonEncode($log['sortFields']).')';
} elseif (isset($log['update'])) {
// todo: include $log['options']
$query .= '.update('.static::bsonEncode($log['query']).', '.static::bsonEncode($log['newObj']).')';
} elseif (isset($log['validate'])) {
$query .= '.validate()';
}
}
}
if (!empty($query)) {
if ('.' == $query[0]) {
$query = 'db'.$query;
}
$this->formattedQueries[$i++] = $query.';';
++$this->nbRealQueries;
}
}
static protected function bsonEncode($query, $array = true)
{
$parts = array();
foreach ($query as $key => $value) {
if (!is_numeric($key)) {
$array = false;
}
if (null === $value) {
$formatted = 'null';
} elseif (is_bool($value)) {
$formatted = $value ? 'true' : 'false';
} elseif (is_numeric($value)) {
$formatted = $value;
} elseif (is_scalar($value)) {
$formatted = '"'.$value.'"';
} elseif (is_array($value)) {
$formatted = static::bsonEncode($value);
} elseif ($value instanceof \MongoId) {
$formatted = 'ObjectId("'.$value.'")';
} elseif ($value instanceof \MongoDate) {
$formatted = 'new Date("'.date('r', $value->sec).'")';
} elseif ($value instanceof \DateTime) {
$formatted = 'new Date("'.date('r', $value->getTimestamp()).'")';
} elseif ($value instanceof \MongoRegex) {
$formatted = 'new RegExp("'.$value->regex.'", "'.$value->flags.'")';
} elseif ($value instanceof \MongoMinKey) {
$formatted = 'new MinKey()';
} elseif ($value instanceof \MongoMaxKey) {
$formatted = 'new MaxKey()';
} elseif ($value instanceof \MongoBinData) {
$formatted = 'new BinData("'.$value->bin.'", "'.$value->type.'")';
} elseif ($value instanceof \MongoGridFSFile || $value instanceof GridFSFile) {
$formatted = 'new MongoGridFSFile("'.$value->getFilename().'")';
} elseif ($value instanceof \stdClass) {
$formatted = static::bsonEncode((array) $value);
} else {
$formatted = (string) $value;
}
$parts['"'.$key.'"'] = $formatted;
}
if (0 == count($parts)) {
return $array ? '[ ]' : '{ }';
}
if ($array) {
return '[ '.implode(', ', $parts).' ]';
} else {
$mapper = function($key, $value)
{
return $key.': '.$value;
};
return '{ '.implode(', ', array_map($mapper, array_keys($parts), array_values($parts))).' }';
}
}
}

View File

@ -1,119 +0,0 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<parameters>
<parameter key="doctrine.odm.mongodb.connection_class">Doctrine\MongoDB\Connection</parameter>
<parameter key="doctrine.odm.mongodb.configuration_class">Doctrine\ODM\MongoDB\Configuration</parameter>
<parameter key="doctrine.odm.mongodb.document_manager_class">Doctrine\ODM\MongoDB\DocumentManager</parameter>
<parameter key="doctrine.odm.mongodb.logger_class">Symfony\Bundle\DoctrineMongoDBBundle\Logger\DoctrineMongoDBLogger</parameter>
<parameter key="doctrine.odm.mongodb.data_collector_class">Symfony\Bundle\DoctrineMongoDBBundle\DataCollector\DoctrineMongoDBDataCollector</parameter>
<parameter key="doctrine.odm.mongodb.event_manager_class">Doctrine\Common\EventManager</parameter>
<!-- proxies -->
<parameter key="doctrine.odm.mongodb.proxy_namespace">Proxies</parameter>
<parameter key="doctrine.odm.mongodb.proxy_dir">%kernel.cache_dir%/doctrine/odm/mongodb/Proxies</parameter>
<parameter key="doctrine.odm.mongodb.auto_generate_proxy_classes">false</parameter>
<!-- hydrators -->
<parameter key="doctrine.odm.mongodb.hydrator_namespace">Hydrators</parameter>
<parameter key="doctrine.odm.mongodb.hydrator_dir">%kernel.cache_dir%/doctrine/odm/mongodb/Hydrators</parameter>
<parameter key="doctrine.odm.mongodb.auto_generate_hydrator_classes">false</parameter>
<!-- cache -->
<parameter key="doctrine.odm.mongodb.cache.array_class">Doctrine\Common\Cache\ArrayCache</parameter>
<parameter key="doctrine.odm.mongodb.cache.apc_class">Doctrine\Common\Cache\ApcCache</parameter>
<parameter key="doctrine.odm.mongodb.cache.memcache_class">Doctrine\Common\Cache\MemcacheCache</parameter>
<parameter key="doctrine.odm.mongodb.cache.memcache_host">localhost</parameter>
<parameter key="doctrine.odm.mongodb.cache.memcache_port">11211</parameter>
<parameter key="doctrine.odm.mongodb.cache.memcache_instance_class">Memcache</parameter>
<parameter key="doctrine.odm.mongodb.cache.xcache_class">Doctrine\Common\Cache\XcacheCache</parameter>
<!-- metadata -->
<parameter key="doctrine.odm.mongodb.metadata.driver_chain_class">Doctrine\ODM\MongoDB\Mapping\Driver\DriverChain</parameter>
<parameter key="doctrine.odm.mongodb.metadata.annotation_class">Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver</parameter>
<parameter key="doctrine.odm.mongodb.metadata.annotation_reader_class">Doctrine\Common\Annotations\AnnotationReader</parameter>
<parameter key="doctrine.odm.mongodb.metadata.xml_class">Doctrine\ODM\MongoDB\Mapping\Driver\XmlDriver</parameter>
<parameter key="doctrine.odm.mongodb.metadata.yml_class">Doctrine\ODM\MongoDB\Mapping\Driver\YamlDriver</parameter>
<!-- directories -->
<parameter key="doctrine.odm.mongodb.mapping_dirs" type="collection"></parameter>
<parameter key="doctrine.odm.mongodb.xml_mapping_dirs">%doctrine.odm.mongodb.mapping_dirs%</parameter>
<parameter key="doctrine.odm.mongodb.yml_mapping_dirs">%doctrine.odm.mongodb.mapping_dirs%</parameter>
<parameter key="doctrine.odm.mongodb.document_dirs" type="collection"></parameter>
<!-- security/user -->
<parameter key="doctrine.odm.mongodb.security.user.provider.class">Symfony\Bundle\DoctrineMongoDBBundle\Security\DocumentUserProvider</parameter>
<!-- proxy cache warmer -->
<parameter key="doctrine.odm.mongodb.proxy_cache_warmer.class">Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer\ProxyCacheWarmer</parameter>
<!-- hydrator cache warmer -->
<parameter key="doctrine.odm.mongodb.hydrator_cache_warmer.class">Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer\HydratorCacheWarmer</parameter>
<!-- validator -->
<parameter key="doctrine_odm.mongodb.validator.unique.class">Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints\UniqueValidator</parameter>
</parameters>
<services>
<!-- defaults -->
<service id="doctrine.odm.mongodb.cache" alias="doctrine.odm.mongodb.cache.array" />
<!-- metadata -->
<service id="doctrine.odm.mongodb.metadata.chain" class="%doctrine.odm.mongodb.metadata.driver_chain_class%" />
<service id="doctrine.odm.mongodb.metadata.annotation" class="%doctrine.odm.mongodb.metadata.annotation_class%">
<argument type="service" id="doctrine.odm.mongodb.metadata.annotation_reader" />
<argument>%doctrine.odm.mongodb.document_dirs%</argument>
</service>
<service id="doctrine.odm.mongodb.metadata.annotation_reader" class="%doctrine.odm.mongodb.metadata.annotation_reader_class%">
<argument type="service" id="doctrine.odm.mongodb.cache" />
<call method="setAnnotationNamespaceAlias">
<argument>Doctrine\ODM\MongoDB\Mapping\</argument>
<argument>mongodb</argument>
</call>
</service>
<service id="doctrine.odm.mongodb.metadata.xml" class="%doctrine.odm.mongodb.metadata.xml_class%">
<argument>%doctrine.odm.mongodb.xml_mapping_dirs%</argument>
</service>
<service id="doctrine.odm.mongodb.metadata.yml" class="%doctrine.odm.mongodb.metadata.yml_class%">
<argument>%doctrine.odm.mongodb.yml_mapping_dirs%</argument>
</service>
<!-- cache -->
<service id="doctrine.odm.mongodb.cache.array" class="%doctrine.odm.mongodb.cache.array_class%" />
<!-- logger -->
<service id="doctrine.odm.mongodb.logger" class="%doctrine.odm.mongodb.logger_class%">
<argument type="service" id="logger" on-invalid="null" />
<tag name="monolog.logger" channel="doctrine" />
</service>
<service id="doctrine.odm.mongodb.data_collector" class="%doctrine.odm.mongodb.data_collector_class%" public="false">
<tag name="data_collector" template="DoctrineMongoDBBundle:Collector:mongodb" id="mongodb" />
<argument type="service" id="doctrine.odm.mongodb.logger" />
</service>
<!-- Cache Warmers -->
<service id="doctrine.odm.mongodb.proxy_cache_warmer" class="%doctrine.odm.mongodb.proxy_cache_warmer.class%" public="false">
<tag name="kernel.cache_warmer" />
<argument type="service" id="service_container" />
</service>
<service id="doctrine.odm.mongodb.hydrator_cache_warmer" class="%doctrine.odm.mongodb.hydrator_cache_warmer.class%" public="false">
<tag name="kernel.cache_warmer" />
<argument type="service" id="service_container" />
</service>
<!-- validator -->
<service id="doctrine_odm.mongodb.validator.unique" class="%doctrine_odm.mongodb.validator.unique.class%">
<tag name="validator.constraint_validator" alias="doctrine_odm.mongodb.unique" />
<argument type="service" id="service_container" />
</service>
<!-- Security -->
<service id="doctrine.odm.mongodb.security.user.provider" class="%doctrine.odm.mongodb.security.user.provider.class%" public="false" abstract="true">
<argument type="service" id="doctrine.odm.mongodb.security.user.document_manager" />
</service>
<service id="doctrine.odm.mongodb.security.user.document_manager" alias="doctrine.odm.mongodb.default_document_manager" public="false" />
</services>
</container>

View File

@ -1,36 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<xsd:schema xmlns="http://symfony.com/schema/dic/doctrine/odm/mongodb"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://symfony.com/schema/dic/doctrine/odm/mongodb"
elementFormDefault="qualified">
<xsd:element name="config" type="config" />
<xsd:complexType name="config">
<xsd:attribute name="host" type="xsd:string" />
<xsd:attribute name="port" type="xsd:integer" />
<xsd:attribute name="database" type="xsd:string" />
<xsd:attribute name="proxy-dir" type="xsd:string" />
<xsd:attribute name="auto-generate-proxy-classes" type="xsd:boolean" />
<xsd:attribute name="cache" type="cache" />
<xsd:attribute name="metadata" type="metadata" />
</xsd:complexType>
<xsd:simpleType name="cache">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="array" />
<xsd:enumeration value="apc" />
<xsd:enumeration value="memcache" />
<xsd:enumeration value="xcache" />
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="metadata">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="annotation" />
<xsd:enumeration value="xml" />
<xsd:enumeration value="yml" />
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>

View File

@ -1,45 +0,0 @@
{% extends 'WebProfilerBundle:Profiler:layout.html.twig' %}
{% block toolbar %}
{% set icon %}
<img width="20" height="28" alt="Mongo" style="border-width: 0; vertical-align: middle; margin-right: 5px;" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAcCAYAAABh2p9gAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQRJREFUeNpi/P//PwM1ARMDlcGogZQDlpMnT7pxc3NbA9nhQKxOpL5rQLwJiPeBsI6Ozl+YBOOOHTv+AOllQNwtLS39F2owKYZ/gRq8G4i3ggxEToggWzvc3d2Pk+1lNL4fFAs6ODi8JzdS7mMRVyDVoAMHDsANdAPiOCC+jCQvQKqBQB/BDbwBxK5AHA3E/kB8nKJkA8TMQBwLxaBIKQbi70AvTADSBiSadwFXpCikpKQU8PDwkGTaly9fHFigkaKIJid4584dkiMFFI6jkTJII0WVmpHCAixZQEXWYhDeuXMnyLsVlEQKI45qFBQZ8eRECi4DBaAlDqle/8A48ip6gAADANdQY88Uc0oGAAAAAElFTkSuQmCC"/>
{% endset %}
{% set text %}
<span>{{ collector.querycount }}</span>
{% endset %}
{% include 'WebProfilerBundle:Profiler:toolbar_item.html.twig' with { 'link': profiler_url } %}
{% endblock %}
{% block menu %}
<span class="label">
<span class="icon"><img src="{{ asset('bundles/webprofiler/images/profiler/db.png') }}" alt="" /></span>
<strong>Doctrine MongoDB</strong>
<span class="count">
<span>{{ collector.querycount }}</span>
</span>
</span>
{% endblock %}
{% block panel %}
<h2>Queries</h2>
{% if not collector.queries %}
<p>
<em>Query logging is disabled.</em>
<p>
{% elseif not collector.querycount %}
<p>
<em>No queries.</em>
</p>
{% else %}
<ul class="alt">
{% for query in collector.queries %}
<li class="{{ cycle(['odd', 'even'], loop.index) }}">
<div>
<code>{{ query }}</code>
</div>
</li>
{% endfor %}
</ul>
{% endif %}
{% endblock %}

View File

@ -1,78 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
class DocumentUserProvider implements UserProviderInterface
{
protected $class;
protected $repository;
protected $property;
public function __construct($em, $class, $property = null)
{
$this->class = $class;
if (false !== strpos($this->class, ':')) {
$this->class = $em->getClassMetadata($class)->getName();
}
$this->repository = $em->getRepository($class);
$this->property = $property;
}
/**
* {@inheritdoc}
*/
public function loadUserByUsername($username)
{
if (null !== $this->property) {
$user = $this->repository->findOneBy(array($this->property => $username));
} else {
if (!$this->repository instanceof UserProviderInterface) {
throw new \InvalidArgumentException(sprintf('The Doctrine repository "%s" must implement UserProviderInterface.', get_class($this->repository)));
}
$user = $this->repository->loadUserByUsername($username);
}
if (null === $user) {
throw new UsernameNotFoundException(sprintf('User "%s" not found.', $username));
}
return $user;
}
/**
* {@inheritDoc}
*/
public function loadUser(UserInterface $user)
{
if (!$user instanceof $this->class) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
}
return $this->loadUserByUsername($user->getUsername());
}
/**
* {@inheritDoc}
*/
public function supportsClass($class)
{
return $class === $this->class;
}
}

View File

@ -1,97 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\CacheWarmer;
use Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer\HydratorCacheWarmer;
class HydratorCacheWarmerTest extends \Symfony\Bundle\DoctrineMongoDBBundle\Tests\TestCase
{
/**
* This is not necessarily a good test, it doesn't generate any hydrators
* because there are none in the AnnotationsBundle. However that is
* rather a task of doctrine to test. We touch the lines here and
* verify that the container is called correctly for the relevant information.
*
* @group DoctrineODMMongoDBHydrator
*/
public function testWarmCache()
{
$testManager = $this->createTestDocumentManager(array(
__DIR__ . "/../DependencyInjection/Fixtures/Bundles/AnnotationsBundle/Document")
);
$container = $this->getMock('Symfony\Component\DependencyInjection\Container');
$container->expects($this->at(0))
->method('getParameter')
->with($this->equalTo('doctrine.odm.mongodb.hydrator_dir'))
->will($this->returnValue(sys_get_temp_dir()));
$container->expects($this->at(1))
->method('getParameter')
->with($this->equalTo('doctrine.odm.mongodb.auto_generate_hydrator_classes'))
->will($this->returnValue(false));
$container->expects($this->at(2))
->method('getParameter')
->with($this->equalTo('doctrine.odm.mongodb.document_managers'))
->will($this->returnValue(array('default', 'foo')));
$container->expects($this->at(3))
->method('get')
->with($this->equalTo('doctrine.odm.mongodb.default_document_manager'))
->will($this->returnValue($testManager));
$container->expects($this->at(4))
->method('get')
->with($this->equalTo('doctrine.odm.mongodb.foo_document_manager'))
->will($this->returnValue($testManager));
$cacheWarmer = new HydratorCacheWarmer($container);
$cacheWarmer->warmUp(sys_get_temp_dir());
}
/**
* @group DoctrineODMMongoDBHydrator
*/
public function testSkipWhenHydratorsAreAutoGenerated()
{
$testManager = $this->createTestDocumentManager(array(
__DIR__ . "/../DependencyInjection/Fixtures/Bundles/AnnotationsBundle/Document")
);
$container = $this->getMock('Symfony\Component\DependencyInjection\Container');
$container->expects($this->at(0))
->method('getParameter')
->with($this->equalTo('doctrine.odm.mongodb.hydrator_dir'))
->will($this->returnValue(sys_get_temp_dir()));
$container->expects($this->at(1))
->method('getParameter')
->with($this->equalTo('doctrine.odm.mongodb.auto_generate_hydrator_classes'))
->will($this->returnValue(true));
$container->expects($this->at(2))
->method('getParameter')
->with($this->equalTo('assertion'))
->will($this->returnValue(true));
$cacheWarmer = new HydratorCacheWarmer($container);
$cacheWarmer->warmUp(sys_get_temp_dir());
$container->getParameter('assertion'); // check that the assertion is really the third call.
}
/**
* @group DoctrineODMMongoDBHydrator
*/
public function testHydratorCacheWarmingIsNotOptional()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\Container');
$cacheWarmer = new HydratorCacheWarmer($container);
$this->assertFalse($cacheWarmer->isOptional());
}
}

View File

@ -1,97 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\CacheWarmer;
use Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer\ProxyCacheWarmer;
class ProxyCacheWarmerTest extends \Symfony\Bundle\DoctrineMongoDBBundle\Tests\TestCase
{
/**
* This is not necessarily a good test, it doesn't generate any proxies
* because there are none in the AnnotationsBundle. However that is
* rather a task of doctrine to test. We touch the lines here and
* verify that the container is called correctly for the relevant information.
*
* @group DoctrineODMMongoDBProxy
*/
public function testWarmCache()
{
$testManager = $this->createTestDocumentManager(array(
__DIR__ . "/../DependencyInjection/Fixtures/Bundles/AnnotationsBundle/Document")
);
$container = $this->getMock('Symfony\Component\DependencyInjection\Container');
$container->expects($this->at(0))
->method('getParameter')
->with($this->equalTo('doctrine.odm.mongodb.proxy_dir'))
->will($this->returnValue(sys_get_temp_dir()));
$container->expects($this->at(1))
->method('getParameter')
->with($this->equalTo('doctrine.odm.mongodb.auto_generate_proxy_classes'))
->will($this->returnValue(false));
$container->expects($this->at(2))
->method('getParameter')
->with($this->equalTo('doctrine.odm.mongodb.document_managers'))
->will($this->returnValue(array('default', 'foo')));
$container->expects($this->at(3))
->method('get')
->with($this->equalTo('doctrine.odm.mongodb.default_document_manager'))
->will($this->returnValue($testManager));
$container->expects($this->at(4))
->method('get')
->with($this->equalTo('doctrine.odm.mongodb.foo_document_manager'))
->will($this->returnValue($testManager));
$cacheWarmer = new ProxyCacheWarmer($container);
$cacheWarmer->warmUp(sys_get_temp_dir());
}
/**
* @group DoctrineODMMongoDBProxy
*/
public function testSkipWhenProxiesAreAutoGenerated()
{
$testManager = $this->createTestDocumentManager(array(
__DIR__ . "/../DependencyInjection/Fixtures/Bundles/AnnotationsBundle/Document")
);
$container = $this->getMock('Symfony\Component\DependencyInjection\Container');
$container->expects($this->at(0))
->method('getParameter')
->with($this->equalTo('doctrine.odm.mongodb.proxy_dir'))
->will($this->returnValue(sys_get_temp_dir()));
$container->expects($this->at(1))
->method('getParameter')
->with($this->equalTo('doctrine.odm.mongodb.auto_generate_proxy_classes'))
->will($this->returnValue(true));
$container->expects($this->at(2))
->method('getParameter')
->with($this->equalTo('assertion'))
->will($this->returnValue(true));
$cacheWarmer = new ProxyCacheWarmer($container);
$cacheWarmer->warmUp(sys_get_temp_dir());
$container->getParameter('assertion'); // check that the assertion is really the third call.
}
/**
* @group DoctrineODMMongoDBProxy
*/
public function testProxyCacheWarmingIsNotOptional()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\Container');
$cacheWarmer = new ProxyCacheWarmer($container);
$this->assertFalse($cacheWarmer->isOptional());
}
}

View File

@ -1,60 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\DoctrineMongoDBExtension;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
class ContainerTest extends TestCase
{
public function getContainer()
{
require_once __DIR__.'/DependencyInjection/Fixtures/Bundles/YamlBundle/YamlBundle.php';
$container = new ContainerBuilder(new ParameterBag(array(
'kernel.bundles' => array('YamlBundle' => 'DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\YamlBundle\YamlBundle'),
'kernel.cache_dir' => sys_get_temp_dir(),
'kernel.debug' => false,
)));
$loader = new DoctrineMongoDBExtension();
$container->registerExtension($loader);
$configs = array();
$configs[] = array('connections' => array('default' => array()), 'document_managers' => array('default' => array('mappings' => array('YamlBundle' => array()))));
$loader->load($configs, $container);
return $container;
}
public function testContainer()
{
$container = $this->getContainer();
$this->assertInstanceOf('Doctrine\ODM\MongoDB\Mapping\Driver\DriverChain', $container->get('doctrine.odm.mongodb.metadata.chain'));
$this->assertInstanceOf('Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver', $container->get('doctrine.odm.mongodb.metadata.annotation'));
$this->assertInstanceOf('Doctrine\Common\Annotations\AnnotationReader', $container->get('doctrine.odm.mongodb.metadata.annotation_reader'));
$this->assertInstanceOf('Doctrine\ODM\MongoDB\Mapping\Driver\XmlDriver', $container->get('doctrine.odm.mongodb.metadata.xml'));
$this->assertInstanceOf('Doctrine\ODM\MongoDB\Mapping\Driver\YamlDriver', $container->get('doctrine.odm.mongodb.metadata.yml'));
$this->assertInstanceOf('Doctrine\Common\Cache\ArrayCache', $container->get('doctrine.odm.mongodb.cache.array'));
$this->assertInstanceOf('Symfony\Bundle\DoctrineMongoDBBundle\Logger\DoctrineMongoDBLogger', $container->get('doctrine.odm.mongodb.logger'));
$this->assertInstanceOf('Symfony\Bundle\DoctrineMongoDBBundle\DataCollector\DoctrineMongoDBDataCollector', $container->get('doctrine.odm.mongodb.data_collector'));
$this->assertInstanceOf('Doctrine\MongoDB\Connection', $container->get('doctrine.odm.mongodb.default_connection'));
$this->assertInstanceOf('Doctrine\ODM\MongoDB\Configuration', $container->get('doctrine.odm.mongodb.default_configuration'));
$this->assertInstanceOf('Doctrine\ODM\MongoDB\Mapping\Driver\DriverChain', $container->get('doctrine.odm.mongodb.default_metadata_driver'));
$this->assertInstanceOf('Doctrine\Common\Cache\ArrayCache', $container->get('doctrine.odm.mongodb.default_metadata_cache'));
$this->assertInstanceOf('Doctrine\ODM\MongoDB\DocumentManager', $container->get('doctrine.odm.mongodb.default_document_manager'));
$this->assertInstanceOf('Doctrine\Common\Cache\ArrayCache', $container->get('doctrine.odm.mongodb.cache'));
$this->assertInstanceOf('Doctrine\ODM\MongoDB\DocumentManager', $container->get('doctrine.odm.mongodb.document_manager'));
$this->assertInstanceof('Doctrine\Common\EventManager', $container->get('doctrine.odm.mongodb.event_manager'));
}
}

View File

@ -1,364 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\DependencyInjection;
use Symfony\Bundle\DoctrineMongoDBBundle\Tests\TestCase;
use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\AddValidatorNamespaceAliasPass;
use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\DoctrineMongoDBExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Reference;
abstract class AbstractMongoDBExtensionTest extends TestCase
{
abstract protected function loadFromFile(ContainerBuilder $container, $file);
public function testDependencyInjectionConfigurationDefaults()
{
$container = $this->getContainer();
$loader = new DoctrineMongoDBExtension();
$loader->load(array(array()), $container);
$this->assertEquals('Doctrine\MongoDB\Connection', $container->getParameter('doctrine.odm.mongodb.connection_class'));
$this->assertEquals('Doctrine\ODM\MongoDB\Configuration', $container->getParameter('doctrine.odm.mongodb.configuration_class'));
$this->assertEquals('Doctrine\ODM\MongoDB\DocumentManager', $container->getParameter('doctrine.odm.mongodb.document_manager_class'));
$this->assertEquals('Proxies', $container->getParameter('doctrine.odm.mongodb.proxy_namespace'));
$this->assertEquals(false, $container->getParameter('doctrine.odm.mongodb.auto_generate_proxy_classes'));
$this->assertEquals('Doctrine\Common\Cache\ArrayCache', $container->getParameter('doctrine.odm.mongodb.cache.array_class'));
$this->assertEquals('Doctrine\Common\Cache\ApcCache', $container->getParameter('doctrine.odm.mongodb.cache.apc_class'));
$this->assertEquals('Doctrine\Common\Cache\MemcacheCache', $container->getParameter('doctrine.odm.mongodb.cache.memcache_class'));
$this->assertEquals('localhost', $container->getParameter('doctrine.odm.mongodb.cache.memcache_host'));
$this->assertEquals('11211', $container->getParameter('doctrine.odm.mongodb.cache.memcache_port'));
$this->assertEquals('Memcache', $container->getParameter('doctrine.odm.mongodb.cache.memcache_instance_class'));
$this->assertEquals('Doctrine\Common\Cache\XcacheCache', $container->getParameter('doctrine.odm.mongodb.cache.xcache_class'));
$this->assertEquals('Doctrine\ODM\MongoDB\Mapping\Driver\DriverChain', $container->getParameter('doctrine.odm.mongodb.metadata.driver_chain_class'));
$this->assertEquals('Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver', $container->getParameter('doctrine.odm.mongodb.metadata.annotation_class'));
$this->assertEquals('Doctrine\Common\Annotations\AnnotationReader', $container->getParameter('doctrine.odm.mongodb.metadata.annotation_reader_class'));
$this->assertEquals('Doctrine\ODM\MongoDB\Mapping\Driver\XmlDriver', $container->getParameter('doctrine.odm.mongodb.metadata.xml_class'));
$this->assertEquals('Doctrine\ODM\MongoDB\Mapping\Driver\YamlDriver', $container->getParameter('doctrine.odm.mongodb.metadata.yml_class'));
$this->assertEquals('Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints\UniqueValidator', $container->getParameter('doctrine_odm.mongodb.validator.unique.class'));
$config = array(
'proxy_namespace' => 'MyProxies',
'auto_generate_proxy_classes' => true,
'connections' => array('default' => array()),
'document_managers' => array('default' => array())
);
$loader->load(array($config), $container);
$this->assertEquals('MyProxies', $container->getParameter('doctrine.odm.mongodb.proxy_namespace'));
$this->assertEquals(true, $container->getParameter('doctrine.odm.mongodb.auto_generate_proxy_classes'));
$definition = $container->getDefinition('doctrine.odm.mongodb.default_connection');
$this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass());
$this->assertEquals(array(null, array(), new Reference('doctrine.odm.mongodb.default_configuration')), $definition->getArguments());
$definition = $container->getDefinition('doctrine.odm.mongodb.default_document_manager');
$this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass());
$this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass());
$this->assertEquals('create', $definition->getFactoryMethod());
$this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags());
$arguments = $definition->getArguments();
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
$this->assertEquals('doctrine.odm.mongodb.default_connection', (string) $arguments[0]);
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
$this->assertEquals('doctrine.odm.mongodb.default_configuration', (string) $arguments[1]);
}
public function testSingleDocumentManagerConfiguration()
{
$container = $this->getContainer();
$loader = new DoctrineMongoDBExtension();
$config = array(
'connections' => array(
'default' => array(
'server' => 'mongodb://localhost:27017',
'options' => array('connect' => true)
)
),
'document_managers' => array('default' => array())
);
$loader->load(array($config), $container);
$definition = $container->getDefinition('doctrine.odm.mongodb.default_connection');
$this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass());
$this->assertEquals(array('mongodb://localhost:27017', array('connect' => true), new Reference('doctrine.odm.mongodb.default_configuration')), $definition->getArguments());
$definition = $container->getDefinition('doctrine.odm.mongodb.default_document_manager');
$this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass());
$this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass());
$this->assertEquals('create', $definition->getFactoryMethod());
$this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags());
$arguments = $definition->getArguments();
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
$this->assertEquals('doctrine.odm.mongodb.default_connection', (string) $arguments[0]);
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
$this->assertEquals('doctrine.odm.mongodb.default_configuration', (string) $arguments[1]);
}
public function testLoadSimpleSingleConnection()
{
$container = $this->getContainer();
$loader = new DoctrineMongoDBExtension();
$container->registerExtension($loader);
$this->loadFromFile($container, 'mongodb_service_simple_single_connection');
$container->getCompilerPassConfig()->setOptimizationPasses(array());
$container->getCompilerPassConfig()->setRemovingPasses(array());
$container->compile();
$definition = $container->getDefinition('doctrine.odm.mongodb.default_connection');
$this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass());
$this->assertEquals(array('mongodb://localhost:27017', array('connect' => true), new Reference('doctrine.odm.mongodb.default_configuration')), $definition->getArguments());
$definition = $container->getDefinition('doctrine.odm.mongodb.default_configuration');
$methodCalls = $definition->getMethodCalls();
$methodNames = array_map(function($call) { return $call[0]; }, $methodCalls);
$this->assertInternalType('integer', $pos = array_search('setDefaultDB', $methodNames));
$this->assertEquals('mydb', $methodCalls[$pos][1][0]);
$definition = $container->getDefinition('doctrine.odm.mongodb.default_document_manager');
$this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass());
$this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass());
$this->assertEquals('create', $definition->getFactoryMethod());
$this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags());
$arguments = $definition->getArguments();
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
$this->assertEquals('doctrine.odm.mongodb.default_connection', (string) $arguments[0]);
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
$this->assertEquals('doctrine.odm.mongodb.default_configuration', (string) $arguments[1]);
}
public function testLoadSingleConnection()
{
$container = $this->getContainer();
$loader = new DoctrineMongoDBExtension();
$container->registerExtension($loader);
$this->loadFromFile($container, 'mongodb_service_single_connection');
$container->getCompilerPassConfig()->setOptimizationPasses(array());
$container->getCompilerPassConfig()->setRemovingPasses(array());
$container->compile();
$definition = $container->getDefinition('doctrine.odm.mongodb.default_connection');
$this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass());
$this->assertEquals(array('mongodb://localhost:27017', array('connect' => true), new Reference('doctrine.odm.mongodb.default_configuration')), $definition->getArguments());
$definition = $container->getDefinition('doctrine.odm.mongodb.default_document_manager');
$this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass());
$this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass());
$this->assertEquals('create', $definition->getFactoryMethod());
$this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags());
$arguments = $definition->getArguments();
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
$this->assertEquals('doctrine.odm.mongodb.default_connection', (string) $arguments[0]);
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
$this->assertEquals('doctrine.odm.mongodb.default_configuration', (string) $arguments[1]);
}
public function testLoadMultipleConnections()
{
$container = $this->getContainer();
$loader = new DoctrineMongoDBExtension();
$container->registerExtension($loader);
$this->loadFromFile($container, 'mongodb_service_multiple_connections');
$container->getCompilerPassConfig()->setOptimizationPasses(array());
$container->getCompilerPassConfig()->setRemovingPasses(array());
$container->compile();
$definition = $container->getDefinition('doctrine.odm.mongodb.conn1_connection');
$this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass());
$this->assertEquals(array('mongodb://localhost:27017', array('connect' => true), new Reference('doctrine.odm.mongodb.conn1_configuration')), $definition->getArguments());
$this->assertEquals('doctrine.odm.mongodb.dm2_document_manager', (string) $container->getAlias('doctrine.odm.mongodb.document_manager'));
$definition = $container->getDefinition('doctrine.odm.mongodb.dm1_document_manager');
$this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass());
$this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass());
$this->assertEquals('create', $definition->getFactoryMethod());
$this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags());
$arguments = $definition->getArguments();
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
$this->assertEquals('doctrine.odm.mongodb.conn1_connection', (string) $arguments[0]);
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
$this->assertEquals('doctrine.odm.mongodb.dm1_configuration', (string) $arguments[1]);
$definition = $container->getDefinition('doctrine.odm.mongodb.conn2_connection');
$this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass());
$this->assertEquals(array('mongodb://localhost:27017', array('connect' => true), new Reference('doctrine.odm.mongodb.conn2_configuration')), $definition->getArguments());
$definition = $container->getDefinition('doctrine.odm.mongodb.dm2_document_manager');
$this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass());
$this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass());
$this->assertEquals('create', $definition->getFactoryMethod());
$this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags());
$arguments = $definition->getArguments();
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
$this->assertEquals('doctrine.odm.mongodb.conn2_connection', (string) $arguments[0]);
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
$this->assertEquals('doctrine.odm.mongodb.dm2_configuration', (string) $arguments[1]);
}
public function testBundleDocumentAliases()
{
$container = $this->getContainer();
$loader = new DoctrineMongoDBExtension();
$loader->load(array(array('document_managers' => array('default' => array('mappings' => array('YamlBundle' => array()))))), $container);
$definition = $container->getDefinition('doctrine.odm.mongodb.default_configuration');
$calls = $definition->getMethodCalls();
$this->assertTrue(isset($calls[0][1][0]['YamlBundle']));
$this->assertEquals('DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\YamlBundle\Document', $calls[0][1][0]['YamlBundle']);
}
public function testYamlBundleMappingDetection()
{
$container = $this->getContainer();
$loader = new DoctrineMongoDBExtension('YamlBundle');
$loader->load(array(array('document_managers' => array('default' => array('mappings' => array('YamlBundle' => array()))))), $container);
$calls = $container->getDefinition('doctrine.odm.mongodb.default_metadata_driver')->getMethodCalls();
$this->assertEquals('doctrine.odm.mongodb.default_yml_metadata_driver', (string) $calls[0][1][0]);
$this->assertEquals('DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\YamlBundle\Document', $calls[0][1][1]);
}
public function testXmlBundleMappingDetection()
{
$container = $this->getContainer('XmlBundle');
$loader = new DoctrineMongoDBExtension();
$loader->load(array(array('document_managers' => array('default' => array('mappings' => array('XmlBundle' => array()))))), $container);
$calls = $container->getDefinition('doctrine.odm.mongodb.default_metadata_driver')->getMethodCalls();
$this->assertEquals('doctrine.odm.mongodb.default_xml_metadata_driver', (string) $calls[0][1][0]);
$this->assertEquals('DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\XmlBundle\Document', $calls[0][1][1]);
}
public function testAnnotationsBundleMappingDetection()
{
$container = $this->getContainer('AnnotationsBundle');
$loader = new DoctrineMongoDBExtension();
$loader->load(array(array('document_managers' => array('default' => array('mappings' => array('AnnotationsBundle' => array()))))), $container);
$calls = $container->getDefinition('doctrine.odm.mongodb.default_metadata_driver')->getMethodCalls();
$this->assertEquals('doctrine.odm.mongodb.default_annotation_metadata_driver', (string) $calls[0][1][0]);
$this->assertEquals('DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\AnnotationsBundle\Document', $calls[0][1][1]);
}
public function testDocumentManagerMetadataCacheDriverConfiguration()
{
$container = $this->getContainer();
$loader = new DoctrineMongoDBExtension();
$container->registerExtension($loader);
$this->loadFromFile($container, 'mongodb_service_multiple_connections');
$container->getCompilerPassConfig()->setOptimizationPasses(array());
$container->getCompilerPassConfig()->setRemovingPasses(array());
$container->compile();
$definition = $container->getDefinition('doctrine.odm.mongodb.dm1_metadata_cache');
$this->assertEquals('%doctrine.odm.mongodb.cache.xcache_class%', $definition->getClass());
$definition = $container->getDefinition('doctrine.odm.mongodb.dm2_metadata_cache');
$this->assertEquals('%doctrine.odm.mongodb.cache.apc_class%', $definition->getClass());
}
public function testDocumentManagerMemcacheMetadataCacheDriverConfiguration()
{
$container = $this->getContainer();
$loader = new DoctrineMongoDBExtension();
$container->registerExtension($loader);
$this->loadFromFile($container, 'mongodb_service_simple_single_connection');
$container->getCompilerPassConfig()->setOptimizationPasses(array());
$container->getCompilerPassConfig()->setRemovingPasses(array());
$container->compile();
$definition = $container->getDefinition('doctrine.odm.mongodb.default_metadata_cache');
$this->assertEquals('Doctrine\Common\Cache\MemcacheCache', $definition->getClass());
$calls = $definition->getMethodCalls();
$this->assertEquals('setMemcache', $calls[0][0]);
$this->assertEquals('doctrine.odm.mongodb.default_memcache_instance', (string) $calls[0][1][0]);
$definition = $container->getDefinition('doctrine.odm.mongodb.default_memcache_instance');
$this->assertEquals('Memcache', $definition->getClass());
$calls = $definition->getMethodCalls();
$this->assertEquals('connect', $calls[0][0]);
$this->assertEquals('localhost', $calls[0][1][0]);
$this->assertEquals(11211, $calls[0][1][1]);
}
public function testDependencyInjectionImportsOverrideDefaults()
{
$container = $this->getContainer();
$loader = new DoctrineMongoDBExtension();
$container->registerExtension($loader);
$this->loadFromFile($container, 'odm_imports');
$container->getCompilerPassConfig()->setOptimizationPasses(array());
$container->getCompilerPassConfig()->setRemovingPasses(array());
$container->compile();
$this->assertTrue($container->getParameter('doctrine.odm.mongodb.auto_generate_proxy_classes'));
}
public function testRegistersValidatorNamespace()
{
$container = $this->getContainer();
$container->register('validator.mapping.loader.annotation_loader')
->setClass('stdClass')
->addArgument(array('foo' => 'Foo\\'));
$container->getCompilerPassConfig()->setOptimizationPasses(array());
$container->getCompilerPassConfig()->setRemovingPasses(array());
$container->addCompilerPass(new AddValidatorNamespaceAliasPass());
$container->compile();
$definition = $container->getDefinition('validator.mapping.loader.annotation_loader');
$arguments = $definition->getArguments();
$this->assertEquals(array(
'assertMongoDB' => 'Symfony\\Bundle\\DoctrineMongoDBBundle\\Validator\\Constraints\\',
'foo' => 'Foo\\',
), $arguments[0], 'compiler adds constraint alias to validator');
}
protected function getContainer($bundle = 'YamlBundle')
{
require_once __DIR__.'/Fixtures/Bundles/'.$bundle.'/'.$bundle.'.php';
return new ContainerBuilder(new ParameterBag(array(
'kernel.bundles' => array($bundle => 'DoctrineMongoDBBundle\\Tests\\DependencyInjection\\Fixtures\\Bundles\\'.$bundle.'\\'.$bundle),
'kernel.cache_dir' => sys_get_temp_dir(),
'kernel.debug' => false,
)));
}
}

View File

@ -1,283 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Configuration;
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Config\Definition\Processor;
class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
public function testDefaults()
{
$processor = new Processor();
$configuration = new Configuration(false);
$options = $processor->processConfiguration($configuration, array());
$defaults = array(
'auto_generate_hydrator_classes' => false,
'auto_generate_proxy_classes' => false,
'default_database' => 'default',
'document_managers' => array(),
'connections' => array(),
'proxy_dir' => '%kernel.cache_dir%/doctrine/odm/mongodb/Proxies',
'proxy_namespace' => 'Proxies',
'hydrator_dir' => '%kernel.cache_dir%/doctrine/odm/mongodb/Hydrators',
'hydrator_namespace' => 'Hydrators',
);
foreach ($defaults as $key => $default) {
$this->assertTrue(array_key_exists($key, $options), sprintf('The default "%s" exists', $key));
$this->assertEquals($default, $options[$key]);
unset($options[$key]);
}
if (count($options)) {
$this->fail('Extra defaults were returned: '. print_r($options, true));
}
}
/**
* Tests a full configuration.
*
* @dataProvider fullConfigurationProvider
*/
public function testFullConfiguration($config)
{
$processor = new Processor();
$configuration = new Configuration(false);
$options = $processor->processConfiguration($configuration, array($config));
$expected = array(
'proxy_dir' => '%kernel.cache_dir%/doctrine/odm/mongodb/Proxies',
'proxy_namespace' => 'Test_Proxies',
'auto_generate_proxy_classes' => true,
'hydrator_dir' => '%kernel.cache_dir%/doctrine/odm/mongodb/Hydrators',
'hydrator_namespace' => 'Test_Hydrators',
'auto_generate_hydrator_classes' => true,
'default_document_manager' => 'default_dm_name',
'default_database' => 'default_db_name',
'default_connection' => 'conn1',
'connections' => array(
'conn1' => array(
'server' => 'http://server',
'options' => array(
'connect' => true,
'persist' => 'persist_val',
'timeout' => 500,
'replicaSet' => true,
'username' => 'username_val',
'password' => 'password_val',
),
),
'conn2' => array(
'server' => 'http://server2',
'options' => array(),
),
),
'document_managers' => array(
'dm1' => array(
'mappings' => array(
'FooBundle' => array(
'type' => 'annotations',
),
),
'metadata_cache_driver' => array(
'type' => 'memcache',
'class' => 'fooClass',
'host' => 'host_val',
'port' => 1234,
'instance_class' => 'instance_val',
),
'logging' => false,
),
'dm2' => array(
'connection' => 'dm2_connection',
'database' => 'db1',
'mappings' => array(
'BarBundle' => array(
'type' => 'yml',
'dir' => '%kernel.cache_dir%',
'prefix' => 'prefix_val',
'alias' => 'alias_val',
'is_bundle' => false,
)
),
'metadata_cache_driver' => array(
'type' => 'apc',
),
'logging' => true,
)
)
);
$this->assertEquals($expected, $options);
}
public function fullConfigurationProvider()
{
$yaml = Yaml::load(__DIR__.'/Fixtures/config/yml/full.yml');
$yaml = $yaml['doctrine_mongo_db'];
return array(
array($yaml),
);
}
/**
* @dataProvider optionProvider
* @param array $configs The source array of configuration arrays
* @param array $correctValues A key-value pair of end values to check
*/
public function testMergeOptions(array $configs, array $correctValues)
{
$processor = new Processor();
$configuration = new Configuration(false);
$options = $processor->processConfiguration($configuration, $configs);
foreach ($correctValues as $key => $correctVal)
{
$this->assertEquals($correctVal, $options[$key]);
}
}
public function optionProvider()
{
$cases = array();
// single config, testing normal option setting
$cases[] = array(
array(
array('default_document_manager' => 'foo'),
),
array('default_document_manager' => 'foo')
);
// single config, testing normal option setting with dashes
$cases[] = array(
array(
array('default-document-manager' => 'bar'),
),
array('default_document_manager' => 'bar')
);
// testing the normal override merging - the later config array wins
$cases[] = array(
array(
array('default_document_manager' => 'foo'),
array('default_document_manager' => 'baz'),
),
array('default_document_manager' => 'baz')
);
// the "options" array is totally replaced
$cases[] = array(
array(
array('connections' => array('default' => array('options' => array('timeout' => 2000)))),
array('connections' => array('default' => array('options' => array('username' => 'foo')))),
),
array('connections' => array('default' => array('options' => array('username' => 'foo'), 'server' => null))),
);
// mappings are merged non-recursively.
$cases[] = array(
array(
array('document_managers' => array('default' => array('mappings' => array('foomap' => array('type' => 'val1'), 'barmap' => array('dir' => 'val2'))))),
array('document_managers' => array('default' => array('mappings' => array('barmap' => array('prefix' => 'val3'))))),
),
array('document_managers' => array('default' => array('logging' => false, 'mappings' => array('foomap' => array('type' => 'val1'), 'barmap' => array('prefix' => 'val3'))))),
);
// connections are merged non-recursively.
$cases[] = array(
array(
array('connections' => array('foocon' => array('server' => 'val1'), 'barcon' => array('options' => array('username' => 'val2')))),
array('connections' => array('barcon' => array('server' => 'val3'))),
),
array('connections' => array(
'foocon' => array('server' => 'val1', 'options' => array()),
'barcon' => array('server' => 'val3', 'options' => array())
)),
);
// managers are merged non-recursively.
$cases[] = array(
array(
array('document_managers' => array('foodm' => array('database' => 'val1'), 'bardm' => array('database' => 'val2'))),
array('document_managers' => array('bardm' => array('database' => 'val3'))),
),
array('document_managers' => array(
'foodm' => array('database' => 'val1', 'logging' => false, 'mappings' => array()),
'bardm' => array('database' => 'val3', 'logging' => false, 'mappings' => array()),
)),
);
return $cases;
}
/**
* @dataProvider getNormalizationTests
*/
public function testNormalizeOptions(array $config, $targetKey, array $normalized)
{
$processor = new Processor();
$configuration = new Configuration(false);
$options = $processor->processConfiguration($configuration, array($config));
$this->assertSame($normalized, $options[$targetKey]);
}
public function getNormalizationTests()
{
return array(
// connection versus connections (id is the identifier)
array(
array('connection' => array(
array('server' => 'mongodb://abc', 'id' => 'foo'),
array('server' => 'mongodb://def', 'id' => 'bar'),
)),
'connections',
array(
'foo' => array('server' => 'mongodb://abc', 'options' => array()),
'bar' => array('server' => 'mongodb://def', 'options' => array()),
),
),
// document_manager versus document_managers (id is the identifier)
array(
array('document_manager' => array(
array('connection' => 'conn1', 'id' => 'foo'),
array('connection' => 'conn2', 'id' => 'bar'),
)),
'document_managers',
array(
'foo' => array('connection' => 'conn1', 'logging' => false, 'mappings' => array()),
'bar' => array('connection' => 'conn2', 'logging' => false, 'mappings' => array()),
),
),
// mapping configuration that's beneath a specific document manager
array(
array('document_manager' => array(
array('id' => 'foo', 'connection' => 'conn1', 'mapping' => array(
'type' => 'xml', 'name' => 'foo-mapping'
)),
)),
'document_managers',
array(
'foo' => array('connection' => 'conn1', 'mappings' => array(
'foo-mapping' => array('type' => 'xml'),
), 'logging' => false),
),
),
);
}
}

View File

@ -1,41 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\DoctrineMongoDBExtension;
use Symfony\Component\Config\Definition\Processor;
class DoctrineMongoDBExtensionTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider parameterProvider
*/
public function testParameterOverride($option, $parameter, $value)
{
$container = new ContainerBuilder();
$container->setParameter('kernel.debug', false);
$loader = new DoctrineMongoDBExtension();
$loader->load(array(array($option => $value)), $container);
$this->assertEquals($value, $container->getParameter('doctrine.odm.mongodb.'.$parameter));
}
public function parameterProvider()
{
return array(
array('proxy_namespace', 'proxy_namespace', 'foo'),
array('proxy-namespace', 'proxy_namespace', 'bar'),
);
}
}

View File

@ -1,9 +0,0 @@
<?php
namespace DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\AnnotationsBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AnnotationsBundle extends Bundle
{
}

View File

@ -1,7 +0,0 @@
<?php
namespace DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\AnnotationsBundle\Document;
class Test
{
}

View File

@ -1,7 +0,0 @@
<?php
namespace DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\XmlBundle\Document;
class Test
{
}

View File

@ -1,9 +0,0 @@
<?php
namespace DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\XmlBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class XmlBundle extends Bundle
{
}

View File

@ -1,7 +0,0 @@
<?php
namespace DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\YamlBundle\Document;
class Test
{
}

View File

@ -1,9 +0,0 @@
<?php
namespace DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\YamlBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class YamlBundle extends Bundle
{
}

View File

@ -1,29 +0,0 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:doctrine="http://symfony.com/schema/dic/doctrine/odm/mongodb"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/doctrine/odm/mongodb http://symfony.com/schema/dic/doctrine/odm/mongodb/mongodb-1.0.xsd">
<doctrine:mongodb
default-document-manager="dm2"
default-connection="conn1"
proxy-namespace="Proxies"
auto-generate-proxy-classes="true"
>
<doctrine:connection id="conn1" server="mongodb://localhost:27017">
<doctrine:options>
<doctrine:connect>true</doctrine:connect>
</doctrine:options>
</doctrine:connection>
<doctrine:connection id="conn2" server="mongodb://localhost:27017">
<doctrine:options>
<doctrine:connect>true</doctrine:connect>
</doctrine:options>
</doctrine:connection>
<doctrine:document-manager id="dm1" metadata-cache-driver="xcache" connection="conn1" />
<doctrine:document-manager id="dm2" connection="conn2" metadata-cache-driver="apc" />
</doctrine:mongodb>
</container>

View File

@ -1,24 +0,0 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:doctrine="http://symfony.com/schema/dic/doctrine/odm/mongodb"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/doctrine/odm/mongodb http://symfony.com/schema/dic/doctrine/odm/mongodb/mongodb-1.0.xsd">
<doctrine:mongodb default_database="mydb">
<doctrine:connection server="mongodb://localhost:27017" id="default">
<doctrine:options>
<doctrine:connect>true</doctrine:connect>
</doctrine:options>
</doctrine:connection>
<doctrine:document-manager id="default" connection="default">
<doctrine:metadata-cache-driver type="memcache">
<doctrine:class>Doctrine\Common\Cache\MemcacheCache</doctrine:class>
<doctrine:host>localhost</doctrine:host>
<doctrine:port>11211</doctrine:port>
<doctrine:instance-class>Memcache</doctrine:instance-class>
</doctrine:metadata-cache-driver>
</doctrine:document-manager>
</doctrine:mongodb>
</container>

View File

@ -1,27 +0,0 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:doctrine="http://symfony.com/schema/dic/doctrine/odm/mongodb"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/doctrine/odm/mongodb http://symfony.com/schema/dic/doctrine/odm/mongodb/mongodb-1.0.xsd">
<doctrine:mongodb>
<doctrine:connection id="default" server="mongodb://localhost:27017">
<doctrine:options>
<doctrine:connect>true</doctrine:connect>
</doctrine:options>
</doctrine:connection>
<doctrine:document-manager id="default" connection="default">
<doctrine:metadata-cache-driver type="memcache">
<doctrine:class>Doctrine\Common\Cache\MemcacheCache</doctrine:class>
<doctrine:host>localhost</doctrine:host>
<doctrine:port>11211</doctrine:port>
<doctrine:instance-class>Memcache</doctrine:instance-class>
</doctrine:metadata-cache-driver>
</doctrine:document-manager>
</doctrine:mongodb>
</container>

View File

@ -1,17 +0,0 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:doctrine="http://symfony.com/schema/dic/doctrine/odm/mongodb"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/doctrine/odm/mongodb http://symfony.com/schema/dic/doctrine/odm/mongodb/mongodb-1.0.xsd">
<imports>
<import resource="odm_imports_import.xml" />
</imports>
<doctrine:mongodb
auto-generate-proxy-classes="true"
>
</doctrine:mongodb>
</container>

View File

@ -1,13 +0,0 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:doctrine="http://symfony.com/schema/dic/doctrine/odm/mongodb"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/doctrine/odm/mongodb http://symfony.com/schema/dic/doctrine/odm/mongodb/mongodb-1.0.xsd">
<doctrine:mongodb
auto-generate-proxy-classes="false"
>
</doctrine:mongodb>
</container>

View File

@ -1,47 +0,0 @@
doctrine_mongo_db:
proxy_namespace: Test_Proxies
auto_generate_proxy_classes: true
hydrator_namespace: Test_Hydrators
auto_generate_hydrator_classes: true
default_document_manager: default_dm_name
default_database: default_db_name
default_connection: conn1
connections:
conn1:
server: http://server
options:
connect: true
persist: persist_val
timeout: 500
replicaSet: true
username: username_val
password: password_val
conn2:
server: http://server2
document_managers:
dm1:
mappings:
FooBundle: annotations
metadata_cache_driver:
type: memcache
class: fooClass
host: host_val
port: 1234
instance_class: instance_val
dm2:
connection: dm2_connection
database: db1
mappings:
BarBundle:
type: yml
dir: %kernel.cache_dir%
prefix: prefix_val
alias: alias_val
is_bundle: false
metadata_cache_driver: apc
logging: true

View File

@ -1,19 +0,0 @@
doctrine_mongo_db:
default_document_manager: dm2
default_connection: conn2
connections:
conn1:
server: mongodb://localhost:27017
options:
connect: true
conn2:
server: mongodb://localhost:27017
options:
connect: true
document_managers:
dm1:
connection: conn1
metadata_cache_driver: xcache
dm2:
connection: conn2
metadata_cache_driver: apc

View File

@ -1,14 +0,0 @@
doctrine_mongo_db:
connections:
default:
server: mongodb://localhost:27017
options: { connect: true }
default_database: mydb
document_managers:
default:
metadata_cache_driver:
type: memcache
class: Doctrine\Common\Cache\MemcacheCache
host: localhost
port: 11211
instance_class: Memcache

View File

@ -1,15 +0,0 @@
doctrine_mongo_db:
connections:
default:
server: mongodb://localhost:27017
options:
connect: true
document_managers:
default:
connection: default
metadata_cache_driver:
type: memcache
class: Doctrine\Common\Cache\MemcacheCache
host: localhost
port: 11211
instance_class: Memcache

View File

@ -1,5 +0,0 @@
imports:
- { resource: odm_imports_import.yml }
doctrine_mongo_db:
auto_generate_proxy_classes: true

View File

@ -1,2 +0,0 @@
doctrine_mongo_db:
auto_generate_proxy_classes: false

View File

@ -1,25 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\Config\FileLocator;
class XmlMongoDBExtensionTest extends AbstractMongoDBExtensionTest
{
protected function loadFromFile(ContainerBuilder $container, $file)
{
$loadXml = new XmlFileLoader($container, new FileLocator(__DIR__.'/Fixtures/config/xml'));
$loadXml->load($file.'.xml');
}
}

View File

@ -1,25 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Config\FileLocator;
class YamlMongoDBExtensionTest extends AbstractMongoDBExtensionTest
{
protected function loadFromFile(ContainerBuilder $container, $file)
{
$loadYaml = new YamlFileLoader($container, new FileLocator(__DIR__.'/Fixtures/config/yml'));
$loadYaml->load($file.'.yml');
}
}

View File

@ -1,9 +0,0 @@
<?php
namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\Fixtures\Validator;
class Document
{
public $id;
public $unique;
}

View File

@ -1,50 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\Logger;
use Symfony\Bundle\DoctrineMongoDBBundle\Logger\DoctrineMongoDBLogger;
class DoctrineMongoDBLoggerTest extends \PHPUnit_Framework_TestCase
{
protected $logger;
protected function setUp()
{
$this->logger = new DoctrineMongoDBLogger();
}
/**
* @dataProvider getQueries
*/
public function testLogger($query, $formatted)
{
$this->logger->logQuery($query);
$this->assertEquals($formatted, $this->logger->getQueries());
}
public function getQueries()
{
return array(
// batchInsert
array(
array('db' => 'foo', 'collection' => 'bar', 'batchInsert' => true, 'num' => 1, 'data' => array('foo'), 'options' => array()),
array('use foo;', 'db.bar.batchInsert(**1 item(s)**);'),
),
// find
array(
array('db' => 'foo', 'collection' => 'bar', 'find' => true, 'query' => array('foo' => null), 'fields' => array()),
array('use foo;', 'db.bar.find({ "foo": null });'),
),
);
}
}

View File

@ -1,42 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\MongoDB\Connection;
class TestCase extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Doctrine\\ODM\\MongoDB\\Version')) {
$this->markTestSkipped('Doctrine MongoDB ODM is not available.');
}
}
/**
* @return DocumentManager
*/
protected function createTestDocumentManager($paths = array())
{
$config = new \Doctrine\ODM\MongoDB\Configuration();
$config->setAutoGenerateProxyClasses(true);
$config->setProxyDir(\sys_get_temp_dir());
$config->setHydratorDir(\sys_get_temp_dir());
$config->setProxyNamespace('SymfonyTests\Doctrine');
$config->setHydratorNamespace('SymfonyTests\Doctrine');
$config->setMetadataDriverImpl($config->newDefaultAnnotationDriver($paths));
$config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache());
return DocumentManager::create(new Connection(), $config);
}
}

View File

@ -1,156 +0,0 @@
<?php
namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\Validator\Constraints;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
use Doctrine\ODM\MongoDB\DocumentRepository;
use Symfony\Bundle\DoctrineMongoDBBundle\Tests\Fixtures\Validator\Document;
use Symfony\Bundle\DoctrineMongoDBBundle\Tests\TestCase;
use Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints\Unique;
use Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints\UniqueValidator;
class UniqueValidatorTest extends TestCase
{
private $dm;
private $repository;
private $validator;
private $classMetadata;
private $uniqueFieldName = 'unique';
public function setUp()
{
parent::setUp();
$this->classMetadata = $this->getClassMetadata();
$this->repository = $this->getDocumentRepository();
$this->dm = $this->getDocumentManager($this->classMetadata, $this->repository);
$container = $this->getContainer();
$this->validator = new UniqueValidator($container);
}
public function tearDown()
{
unset($this->validator, $this->dm, $this->repository, $this->classMetadata);
}
/**
* @dataProvider getFieldsPathsValuesDocumentsAndReturns
*/
public function testShouldValidateValidStringMappingValues($field, $path, $value, $document, $return)
{
$this->setFieldMapping($field, 'string');
$this->repository->expects($this->once())
->method('findOneBy')
->with(array($path => $value))
->will($this->returnValue($return));
$this->assertTrue($this->validator->isValid($document, new Unique($path)));
}
public function getFieldsPathsValuesDocumentsAndReturns()
{
$field = 'unique';
$path = $field;
$value = 'someUniqueValueToBeValidated';
$document = $this->getFixtureDocument($field, $value);
return array(
array('unique', 'unique', 'someUniqueValueToBeValidated', $document, null),
array('unique', 'unique', 'someUniqueValueToBeValidated', $document, $document),
array('unique', 'unique', 'someUniqueValueToBeValidated', $document, $this->getFixtureDocument($field, $value)),
);
}
/**
* @dataProvider getFieldTypesFieldsPathsValuesAndQueries
*/
public function testGetsCorrectQueryArrayForCollection($type, $field, $path, $value, $query)
{
$this->setFieldMapping($field, $type);
$document = $this->getFixtureDocument($field, $value);
$this->repository->expects($this->once())
->method('findOneBy')
->with($query);
$this->validator->isValid($document, new Unique($path));
}
public function getFieldTypesFieldsPathsValuesAndQueries()
{
$field = 'unique';
$key = 'uniqueValue';
$path = $field.'.'.$key;
$value = 'someUniqueValueToBeValidated';
return array(
array('collection', $field, $path, array($value), array($field => array('$in' => array($value)))),
array('hash', $field, $path, array($key => $value), array($path => $value)),
);
}
private function getContainer()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->once())
->method('get')
->will($this->returnValue($this->dm));
return $container;
}
private function getDocumentManager(ClassMetadata $classMetadata, DocumentRepository $repository)
{
$dm = $this->getMockBuilder('Doctrine\ODM\MongoDB\DocumentManager')
->disableOriginalConstructor()
->setMethods(array('getClassMetadata', 'getRepository'))
->getMock();
$dm->expects($this->any())
->method('getClassMetadata')
->will($this->returnValue($classMetadata));
$dm->expects($this->any())
->method('getRepository')
->will($this->returnValue($repository));
return $dm;
}
protected function getDocumentRepository()
{
$dm = $this->getMock('Doctrine\ODM\MongoDB\DocumentRepository', array('findOneBy'), array(), '', false, false);
return $dm;
}
protected function getClassMetadata()
{
$classMetadata = $this->getMock('Doctrine\ODM\MongoDB\Mapping\ClassMetadata', array(), array(), '', false, false);
$classMetadata->expects($this->any())
->method('getFieldValue')
->will($this->returnCallback(function($document, $fieldName) {
return $document->{$fieldName};
}));
$classMetadata->fieldmappings = array();
return $classMetadata;
}
protected function setFieldMapping($fieldName, $type, array $attributes = array())
{
$this->classMetadata->fieldMappings[$fieldName] = array_merge(array(
'fieldName' => $fieldName,
'type' => $type,
), $attributes);
}
protected function getFixtureDocument($field, $value, $id = 1)
{
$document = new Document();
$document->{$field} = $value;
$document->id = 1;
return $document;
}
}

View File

@ -1,56 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* Doctrine MongoDB ODM unique value constraint.
*
* @author Bulat Shakirzyanov <bulat@theopenskyproject.com>
*/
class Unique extends Constraint
{
public $message = 'The value for {{ property }} already exists.';
public $path;
public $documentManager;
public function getDefaultOption()
{
return 'path';
}
public function getRequiredOptions()
{
return array('path');
}
public function validatedBy()
{
return 'doctrine_odm.mongodb.unique';
}
public function getTargets()
{
return Constraint::CLASS_CONSTRAINT;
}
public function getDocumentManagerId()
{
$id = 'doctrine.odm.mongodb.document_manager';
if (null !== $this->documentManager) {
$id = sprintf('doctrine.odm.mongodb.%s_document_manager', $this->documentManager);
}
return $id;
}
}

View File

@ -1,138 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Proxy\Proxy;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Doctrine MongoDB ODM unique value validator.
*
* @author Bulat Shakirzyanov <bulat@theopenskyproject.com>
*/
class UniqueValidator extends ConstraintValidator
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* @param Doctrine\ODM\MongoDB\Document $value
* @param Constraint $constraint
* @return Boolean
*/
public function isValid($document, Constraint $constraint)
{
$class = get_class($document);
$dm = $this->getDocumentManager($constraint);
$metadata = $dm->getClassMetadata($class);
if ($metadata->isEmbeddedDocument) {
throw new \InvalidArgumentException(sprintf("Document '%s' is an embedded document, and cannot be validated", $class));
}
$query = $this->getQueryArray($metadata, $document, $constraint->path);
// check if document exists in mongodb
if (null === ($doc = $dm->getRepository($class)->findOneBy($query))) {
return true;
}
// check if document in mongodb is the same document as the checked one
if ($doc === $document) {
return true;
}
// check if returned document is proxy and initialize the minimum identifier if needed
if ($doc instanceof Proxy) {
$metadata->setIdentifierValue($doc, $doc->__identifier);
}
// check if document has the same identifier as the current one
if ($metadata->getIdentifierValue($doc) === $metadata->getIdentifierValue($document)) {
return true;
}
$this->context->setPropertyPath($this->context->getPropertyPath() . '.' . $constraint->path);
$this->setMessage($constraint->message, array(
'{{ property }}' => $constraint->path,
));
return false;
}
protected function getQueryArray(ClassMetadata $metadata, $document, $path)
{
$class = $metadata->name;
$field = $this->getFieldNameFromPropertyPath($path);
if (!isset($metadata->fieldMappings[$field])) {
throw new \LogicException('Mapping for \'' . $path . '\' doesn\'t exist for ' . $class);
}
$mapping = $metadata->fieldMappings[$field];
if (isset($mapping['reference']) && $mapping['reference']) {
throw new \LogicException('Cannot determine uniqueness of referenced document values');
}
switch ($mapping['type']) {
case 'one':
// TODO: implement support for embed one documents
case 'many':
// TODO: implement support for embed many documents
throw new \RuntimeException('Not Implemented.');
case 'hash':
$value = $metadata->getFieldValue($document, $mapping['fieldName']);
return array($path => $this->getFieldValueRecursively($path, $value));
case 'collection':
return array($mapping['fieldName'] => array('$in' => $metadata->getFieldValue($document, $mapping['fieldName'])));
default:
return array($mapping['fieldName'] => $metadata->getFieldValue($document, $mapping['fieldName']));
}
}
/**
* Returns the actual document field value
*
* E.g. document.someVal -> document
* user.emails -> user
* username -> username
*
* @param string $field
* @return string
*/
private function getFieldNameFromPropertyPath($field)
{
$pieces = explode('.', $field);
return $pieces[0];
}
private function getFieldValueRecursively($fieldName, $value)
{
$pieces = explode('.', $fieldName);
unset($pieces[0]);
foreach ($pieces as $piece) {
$value = $value[$piece];
}
return $value;
}
private function getDocumentManager(Unique $constraint)
{
return $this->container->get($constraint->getDocumentManagerId());
}
}

View File

@ -47,17 +47,11 @@ install_git doctrine-data-fixtures git://github.com/doctrine/data-fixtures.git
install_git doctrine-dbal git://github.com/doctrine/dbal.git 2.0.4
# Doctrine Common
install_git doctrine-common git://github.com/doctrine/common.git
install_git doctrine-common git://github.com/doctrine/common.git 2.0.2
# Doctrine migrations
install_git doctrine-migrations git://github.com/doctrine/migrations.git
# Doctrine MongoDB
install_git doctrine-mongodb git://github.com/doctrine/mongodb.git
# Doctrine MongoDB
install_git doctrine-mongodb-odm git://github.com/doctrine/mongodb-odm.git
# Monolog
install_git monolog git://github.com/Seldaek/monolog.git