pax_global_header00006660000000000000000000000064126445114500014514gustar00rootroot0000000000000052 comment=e9c2ccf573b59b7cea566390f34254fed3c20ed9 DoctrineBundle-1.6.2/000077500000000000000000000000001264451145000144235ustar00rootroot00000000000000DoctrineBundle-1.6.2/.gitignore000066400000000000000000000000571264451145000164150ustar00rootroot00000000000000vendor composer.phar composer.lock phpunit.xml DoctrineBundle-1.6.2/.travis.yml000066400000000000000000000015111264451145000165320ustar00rootroot00000000000000language: php sudo: false cache: directories: - $HOME/.composer/cache php: - 5.3 - 5.4 - 5.5 - 5.6 - 7.0 - hhvm matrix: include: - php: 5.3 env: deps=low SYMFONY_DEPRECATIONS_HELPER=weak - php: 5.6 env: SYMFONY_VERSION="2.3.*" - php: 5.6 env: SYMFONY_VERSION="2.8.*@dev" - php: 5.6 env: SYMFONY_VERSION="3.0.*@dev" env: global: - deps=no before_install: - composer self-update - if [ "$SYMFONY_VERSION" != "" ]; then composer require --no-update symfony/symfony:${SYMFONY_VERSION}; fi; install: - if [ "$deps" = "no" ]; then composer update; fi; - if [ "$deps" = "low" ]; then composer --prefer-lowest --prefer-stable update; fi; script: - ./vendor/bin/phpunit -v --coverage-clover ./build/logs/clover.xml after_script: - php ./vendor/bin/coveralls -v DoctrineBundle-1.6.2/Changelog.md000066400000000000000000000123331264451145000166360ustar00rootroot00000000000000## 1.5.2 (2015-08-31) Security: * Fix Security Misconfiguration Vulnerability, allowing potential local arbitrary code execution. ## 1.5.1 (2015-08-12) Bugfix: * Fixed the JS expanding all queries in the profiler in case of multiple connections * Fixed the retrieval of the namespace in DisconnectedMetadataFactory * Changed the composer constraint to allow Symfony 3.0 for people wanting to do early testing ## 1.5.0 (2015-05-28) Features: * Added the possibility to configure the quote strategy in the configuration * Improved the rendering of the query explanation for Postgres * Added support for tagging entity listeners, without the need to map the listener Bugfix: * Fixed the serverVersion configuration for master slave connections * Fixed the enabling of the profiler to avoid automatically enabling the logger * Fixed the detection of existing databases when quoted names are used * Fixed the profiler template when having a manager without any loaded metadata ## 1.4.0 (2015-02-28) Features: * Added the ``--if-not-exists`` option in the ``doctrine:database:create`` command * Added the ``--if-exists`` option in the ``doctrine:database:drop`` command * Added the support for the ``url`` DBAL setting * Added profiling ability for SQL Server Bugfix: * Fixed the cache configuration when using ``cache_provider`` * Removed usage of deprecated DI features when using Symfony 2.6+ * Close connections and clear managers on shutdown. This avoids leaking connections in tests. * Added an exception when the ORM layer is configured but not DBAL ## 1.3.0 (2014-11-28) Features: * add support for bundle namespace alias in the mapping compiler pass * Added support for server_version connection parameter * Added a way to enable auto_mapping option using multiple entity managers Bugfix: * Inlined the profiler picto images instead of getting from FrameworkBundle (where they are gone) * Remove duplicates in the list of mapped entities in the profile * Fixed the compatibility with PHP 5.3 (broken in 1.3.0-beta1) ## 1.3.0-beta2 (2014-07-09) Feature: * add auto-commit DBAL configuration option * Use DoctrineCacheBundle to create cache drivers, supporting more configuration * Added sorting by time in DB panel Bugfix: * Fixed the compatibility of the DataCollector with Doctrine 2.4 (bug introduced in 1.3.0-beta1) * Fixed the exit code of commands on failure * Fixed the replacement of query parameters in the profiler ## 1.3.0-beta1 (2014-01-26) Features: * Added option to configure entity listener resolver service * add compiler pass for bundles to register mappings * Added a button to expand/collapse all queries in the profiler * Added configuration for sharding * Added support for the new ways to generate proxies in Doctrine Common * Added configuration for the second-level cache Bugfix: * Removed deprecated call * fix drop and create command for connections with master slave configuration * Remove usage of deprecated Twig features ## 1.2.0 (2013-03-25) * Bumped the requirement to Symfony 2.2 * Updated the profiler templates for Symfony 2.2 ## 1.1.0 (2013-01-12) * Added syntax highlighting for queries in teh profiler * Added the validation of the mapping in the profiler panel * Added return codes for doctrine:database:[create|drop] commands ## 1.0.0 (2012-09-07) * Removed the mysql charset hack for 5.3.6+ as PDO has been fixed * Implement "keep_slave"/"keepSlave" configuration * Added missing Redis cache class mapping. * Fixed the XSD schema for the configuration. * Added support for schema assets filter configuration * integrate naming_strategy into config ## 1.0.0-RC1 (2012-07-04) * Add support for targetEntity resolving through the ORM 2.2 listener. * Fixed quote database name in doctrine:database:create and doctrine:database:drop commands * added a way to use cache services * Added a way to configure the default entity repository class * Added the support for SQL filters * Removed the InfoCommand and proxy the ORM command instead * Made the ORM fully optional by avoiding breaking the console * Added support for master_slave connections * Fixed xml config for proxy parameters * Fixes doctrine:generate:entities when called with the --path argument * Added missing Memcached cache driver * Fix memory leak in Doctrine Autoload Proxy Magic * adds lazy-loading event manager, improved listener registration * Added a configuration setting for commented types * Fixed bug with MetadataFactory having problem when the StaticReflection is used. * Added the possibility to explain queries in the profiler * Splitted the configuration for the logging and the profiling of the connection ## 1.0.0-beta1 (2011-12-15) * [BC break] Changed the namespace from Symfony\Bundle to Doctrine\Bundle * Enhance error reporting during mapping validation when nested exceptions occur. * Add DoctrineValidationPass to load validation files conditionally * Moved the entity provider service to DoctrineBundle * Added Stopwatch support in debug mode to integrate in the profiler timeline * Removed the IndexedReader * Added the implementation of the ManagerRegistry to replace the symfony 2.0 registry * Added access to Doctrine's ValidateSchema command from the console. See symfony/symfony#2200. * Extracted the bundle from Symfony 2.0 DoctrineBundle-1.6.2/Command/000077500000000000000000000000001264451145000160015ustar00rootroot00000000000000DoctrineBundle-1.6.2/Command/CreateDatabaseDoctrineCommand.php000066400000000000000000000077331264451145000243430ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Doctrine\DBAL\DriverManager; /** * Database tool allows you to easily drop and create your configured databases. * * @author Fabien Potencier * @author Jonathan H. Wage */ class CreateDatabaseDoctrineCommand extends DoctrineCommand { /** * {@inheritDoc} */ protected function configure() { $this ->setName('doctrine:database:create') ->setDescription('Creates the configured database') ->addOption('connection', null, InputOption::VALUE_OPTIONAL, 'The connection to use for this command') ->addOption('if-not-exists', null, InputOption::VALUE_NONE, 'Don\'t trigger an error, when the database already exists') ->setHelp(<<%command.name% command creates the default connections database: php %command.full_name% You can also optionally specify the name of a connection to create the database for: php %command.full_name% --connection=default EOT ); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $connectionName = $input->getOption('connection'); if (empty($connectionName) === true) { $connectionName = $this->getContainer()->get('doctrine')->getDefaultConnectionName(); } $connection = $this->getDoctrineConnection($connectionName); $ifNotExists = $input->getOption('if-not-exists'); $params = $connection->getParams(); if (isset($params['master'])) { $params = $params['master']; } $hasPath = isset($params['path']); $name = $hasPath ? $params['path'] : (isset($params['dbname']) ? $params['dbname'] : false); if (!$name) { throw new \InvalidArgumentException("Connection does not contain a 'path' or 'dbname' parameter and cannot be dropped."); } // Need to get rid of _every_ occurrence of dbname from connection configuration and we have already extracted all relevant info from url unset($params['dbname'], $params['path'], $params['url']); $tmpConnection = DriverManager::getConnection($params); $shouldNotCreateDatabase = $ifNotExists && in_array($name, $tmpConnection->getSchemaManager()->listDatabases()); // Only quote if we don't have a path if (!$hasPath) { $name = $tmpConnection->getDatabasePlatform()->quoteSingleIdentifier($name); } $error = false; try { if ($shouldNotCreateDatabase) { $output->writeln(sprintf('Database %s for connection named %s already exists. Skipped.', $name, $connectionName)); } else { $tmpConnection->getSchemaManager()->createDatabase($name); $output->writeln(sprintf('Created database %s for connection named %s', $name, $connectionName)); } } catch (\Exception $e) { $output->writeln(sprintf('Could not create database %s for connection named %s', $name, $connectionName)); $output->writeln(sprintf('%s', $e->getMessage())); $error = true; } $tmpConnection->close(); return $error ? 1 : 0; } } DoctrineBundle-1.6.2/Command/DoctrineCommand.php000066400000000000000000000035071264451145000215650ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Doctrine\ORM\Tools\EntityGenerator; /** * Base class for Doctrine console commands to extend from. * * @author Fabien Potencier */ abstract class DoctrineCommand extends ContainerAwareCommand { /** * get a doctrine entity generator * * @return EntityGenerator */ protected function getEntityGenerator() { $entityGenerator = new EntityGenerator(); $entityGenerator->setGenerateAnnotations(false); $entityGenerator->setGenerateStubMethods(true); $entityGenerator->setRegenerateEntityIfExists(false); $entityGenerator->setUpdateEntityIfExists(true); $entityGenerator->setNumSpaces(4); $entityGenerator->setAnnotationPrefix('ORM\\'); return $entityGenerator; } /** * Get a doctrine entity manager by symfony name. * * @param string $name * * @return \Doctrine\ORM\EntityManager */ protected function getEntityManager($name) { return $this->getContainer()->get('doctrine')->getManager($name); } /** * Get a doctrine dbal connection by symfony name. * * @param string $name * * @return \Doctrine\DBAL\Connection */ protected function getDoctrineConnection($name) { return $this->getContainer()->get('doctrine')->getConnection($name); } } DoctrineBundle-1.6.2/Command/DropDatabaseDoctrineCommand.php000066400000000000000000000107511264451145000240360ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command; use Doctrine\DBAL\DriverManager; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Database tool allows you to easily drop and create your configured databases. * * @author Fabien Potencier * @author Jonathan H. Wage */ class DropDatabaseDoctrineCommand extends DoctrineCommand { const RETURN_CODE_NOT_DROP = 1; const RETURN_CODE_NO_FORCE = 2; /** * {@inheritDoc} */ protected function configure() { $this ->setName('doctrine:database:drop') ->setDescription('Drops the configured database') ->addOption('connection', null, InputOption::VALUE_OPTIONAL, 'The connection to use for this command') ->addOption('if-exists', null, InputOption::VALUE_NONE, 'Don\'t trigger an error, when the database doesn\'t exist') ->addOption('force', null, InputOption::VALUE_NONE, 'Set this parameter to execute this action') ->setHelp(<<%command.name% command drops the default connections database: php %command.full_name% The --force parameter has to be used to actually drop the database. You can also optionally specify the name of a connection to drop the database for: php %command.full_name% --connection=default Be careful: All data in a given database will be lost when executing this command. EOT ); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $connection = $this->getDoctrineConnection($input->getOption('connection')); $ifExists = $input->getOption('if-exists'); $params = $connection->getParams(); if (isset($params['master'])) { $params = $params['master']; } $name = isset($params['path']) ? $params['path'] : (isset($params['dbname']) ? $params['dbname'] : false); if (!$name) { throw new \InvalidArgumentException("Connection does not contain a 'path' or 'dbname' parameter and cannot be dropped."); } unset($params['dbname']); if ($input->getOption('force')) { // Reopen connection without database name set // as some vendors do not allow dropping the database connected to. $connection->close(); $connection = DriverManager::getConnection($params); $shouldDropDatabase = !$ifExists || in_array($name, $connection->getSchemaManager()->listDatabases()); // Only quote if we don't have a path if (!isset($params['path'])) { $name = $connection->getDatabasePlatform()->quoteSingleIdentifier($name); } try { if ($shouldDropDatabase) { $connection->getSchemaManager()->dropDatabase($name); $output->writeln(sprintf('Dropped database for connection named %s', $name)); } else { $output->writeln(sprintf('Database for connection named %s doesn\'t exist. Skipped.', $name)); } } catch (\Exception $e) { $output->writeln(sprintf('Could not drop database for connection named %s', $name)); $output->writeln(sprintf('%s', $e->getMessage())); return self::RETURN_CODE_NOT_DROP; } } else { $output->writeln('ATTENTION: This operation should not be executed in a production environment.'); $output->writeln(''); $output->writeln(sprintf('Would drop the database named %s.', $name)); $output->writeln('Please run the operation with --force to execute'); $output->writeln('All data will be lost!'); return self::RETURN_CODE_NO_FORCE; } } } DoctrineBundle-1.6.2/Command/GenerateEntitiesDoctrineCommand.php000066400000000000000000000131051264451145000247400ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\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 Doctrine\ORM\Tools\EntityRepositoryGenerator; use Doctrine\Bundle\DoctrineBundle\Mapping\DisconnectedMetadataFactory; /** * Generate entity classes from mapping information * * @author Fabien Potencier * @author Jonathan H. Wage */ class GenerateEntitiesDoctrineCommand extends DoctrineCommand { /** * {@inheritDoc} */ protected function configure() { $this ->setName('doctrine:generate:entities') ->setAliases(array('generate:doctrine:entities')) ->setDescription('Generates entity classes and method stubs from your mapping information') ->addArgument('name', InputArgument::REQUIRED, 'A bundle name, a namespace, or a class name') ->addOption('path', null, InputOption::VALUE_REQUIRED, 'The path where to generate entities when it cannot be guessed') ->addOption('no-backup', null, InputOption::VALUE_NONE, 'Do not backup existing entities files.') ->setHelp(<<%command.name% command generates entity classes and method stubs from your mapping information: You have to limit generation of entities: * To a bundle: php %command.full_name% MyCustomBundle * To a single entity: php %command.full_name% MyCustomBundle:User php %command.full_name% MyCustomBundle/Entity/User * To a namespace php %command.full_name% MyCustomBundle/Entity If the entities are not stored in a bundle, and if the classes do not exist, the command has no way to guess where they should be generated. In this case, you must provide the --path option: php %command.full_name% Blog/Entity --path=src/ By default, the unmodified version of each entity is backed up and saved (e.g. Product.php~). To prevent this task from creating the backup file, pass the --no-backup option: php %command.full_name% Blog/Entity --no-backup Important: Even if you specified Inheritance options in your XML or YAML Mapping files the generator cannot generate the base and child classes for you correctly, because it doesn't know which class is supposed to extend which. You have to adjust the entity code manually for inheritance to work! EOT ); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $manager = new DisconnectedMetadataFactory($this->getContainer()->get('doctrine')); try { $bundle = $this->getApplication()->getKernel()->getBundle($input->getArgument('name')); $output->writeln(sprintf('Generating entities for bundle "%s"', $bundle->getName())); $metadata = $manager->getBundleMetadata($bundle); } catch (\InvalidArgumentException $e) { $name = strtr($input->getArgument('name'), '/', '\\'); if (false !== $pos = strpos($name, ':')) { $name = $this->getContainer()->get('doctrine')->getAliasNamespace(substr($name, 0, $pos)).'\\'.substr($name, $pos + 1); } if (class_exists($name)) { $output->writeln(sprintf('Generating entity "%s"', $name)); $metadata = $manager->getClassMetadata($name, $input->getOption('path')); } else { $output->writeln(sprintf('Generating entities for namespace "%s"', $name)); $metadata = $manager->getNamespaceMetadata($name, $input->getOption('path')); } } $generator = $this->getEntityGenerator(); $backupExisting = !$input->getOption('no-backup'); $generator->setBackupExisting($backupExisting); $repoGenerator = new EntityRepositoryGenerator(); foreach ($metadata->getMetadata() as $m) { if ($backupExisting) { $basename = substr($m->name, strrpos($m->name, '\\') + 1); $output->writeln(sprintf(' > backing up %s.php to %s.php~', $basename, $basename)); } // Getting the metadata for the entity class once more to get the correct path if the namespace has multiple occurrences try { $entityMetadata = $manager->getClassMetadata($m->getName(), $input->getOption('path')); } catch (\RuntimeException $e) { // fall back to the bundle metadata when no entity class could be found $entityMetadata = $metadata; } $output->writeln(sprintf(' > generating %s', $m->name)); $generator->generate(array($m), $entityMetadata->getPath()); if ($m->customRepositoryClassName && false !== strpos($m->customRepositoryClassName, $metadata->getNamespace())) { $repoGenerator->writeEntityRepositoryClass($m->customRepositoryClassName, $metadata->getPath()); } } } } DoctrineBundle-1.6.2/Command/ImportMappingDoctrineCommand.php000066400000000000000000000123751264451145000242770ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\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 Doctrine\ORM\Mapping\Driver\DatabaseDriver; use Doctrine\ORM\Tools\DisconnectedClassMetadataFactory; use Doctrine\ORM\Tools\Export\ClassMetadataExporter; use Doctrine\ORM\Tools\Console\MetadataFilter; /** * Import Doctrine ORM metadata mapping information from an existing database. * * @author Fabien Potencier * @author Jonathan H. Wage */ class ImportMappingDoctrineCommand extends DoctrineCommand { /** * {@inheritDoc} */ protected function configure() { $this ->setName('doctrine:mapping:import') ->addArgument('bundle', InputArgument::REQUIRED, 'The bundle to import the mapping information to') ->addArgument('mapping-type', InputArgument::OPTIONAL, 'The mapping type to export the imported mapping information to') ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command') ->addOption('filter', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'A string pattern used to match entities that should be mapped.') ->addOption('force', null, InputOption::VALUE_NONE, 'Force to overwrite existing mapping files.') ->setDescription('Imports mapping information from an existing database') ->setHelp(<<%command.name% command imports mapping information from an existing database: php %command.full_name% "MyCustomBundle" xml You can also optionally specify which entity manager to import from with the --em option: php %command.full_name% "MyCustomBundle" xml --em=default If you don't want to map every entity that can be found in the database, use the --filter option. It will try to match the targeted mapped entity with the provided pattern string. php %command.full_name% "MyCustomBundle" xml --filter=MyMatchedEntity Use the --force option, if you want to override existing mapping files: php %command.full_name% "MyCustomBundle" xml --force EOT ); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $bundle = $this->getApplication()->getKernel()->getBundle($input->getArgument('bundle')); $destPath = $bundle->getPath(); $type = $input->getArgument('mapping-type') ? $input->getArgument('mapping-type') : 'xml'; if ('annotation' === $type) { $destPath .= '/Entity'; } else { $destPath .= '/Resources/config/doctrine'; } if ('yaml' === $type) { $type = 'yml'; } $cme = new ClassMetadataExporter(); $exporter = $cme->getExporter($type); $exporter->setOverwriteExistingFiles($input->getOption('force')); if ('annotation' === $type) { $entityGenerator = $this->getEntityGenerator(); $exporter->setEntityGenerator($entityGenerator); } $em = $this->getEntityManager($input->getOption('em')); $databaseDriver = new DatabaseDriver($em->getConnection()->getSchemaManager()); $em->getConfiguration()->setMetadataDriverImpl($databaseDriver); $emName = $input->getOption('em'); $emName = $emName ? $emName : 'default'; $cmf = new DisconnectedClassMetadataFactory(); $cmf->setEntityManager($em); $metadata = $cmf->getAllMetadata(); $metadata = MetadataFilter::filter($metadata, $input->getOption('filter')); if ($metadata) { $output->writeln(sprintf('Importing mapping information from "%s" entity manager', $emName)); foreach ($metadata as $class) { $className = $class->name; $class->name = $bundle->getNamespace().'\\Entity\\'.$className; if ('annotation' === $type) { $path = $destPath.'/'.str_replace('\\', '.', $className).'.php'; } else { $path = $destPath.'/'.str_replace('\\', '.', $className).'.orm.'.$type; } $output->writeln(sprintf(' > writing %s', $path)); $code = $exporter->exportClassMetadata($class); if (!is_dir($dir = dirname($path))) { mkdir($dir, 0775, true); } file_put_contents($path, $code); chmod($path, 0664); } return 0; } else { $output->writeln('Database does not have any mapping information.', 'ERROR'); $output->writeln('', 'ERROR'); return 1; } } } DoctrineBundle-1.6.2/Command/Proxy/000077500000000000000000000000001264451145000171225ustar00rootroot00000000000000DoctrineBundle-1.6.2/Command/Proxy/ClearMetadataCacheDoctrineCommand.php000066400000000000000000000030321264451145000262330ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand; /** * Command to clear the metadata cache of the various cache drivers. * * @author Fabien Potencier * @author Jonathan H. Wage */ class ClearMetadataCacheDoctrineCommand extends MetadataCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this ->setName('doctrine:cache:clear-metadata') ->setDescription('Clears all metadata cache for an entity manager') ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em')); return parent::execute($input, $output); } } DoctrineBundle-1.6.2/Command/Proxy/ClearQueryCacheDoctrineCommand.php000066400000000000000000000030101264451145000256140ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand; /** * Command to clear the query cache of the various cache drivers. * * @author Fabien Potencier * @author Jonathan H. Wage */ class ClearQueryCacheDoctrineCommand extends QueryCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this ->setName('doctrine:cache:clear-query') ->setDescription('Clears all query cache for an entity manager') ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em')); return parent::execute($input, $output); } } DoctrineBundle-1.6.2/Command/Proxy/ClearResultCacheDoctrineCommand.php000066400000000000000000000030121264451145000257670ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand; /** * Command to clear the result cache of the various cache drivers. * * @author Fabien Potencier * @author Jonathan H. Wage */ class ClearResultCacheDoctrineCommand extends ResultCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this ->setName('doctrine:cache:clear-result') ->setDescription('Clears result cache for an entity manager') ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em')); return parent::execute($input, $output); } } DoctrineBundle-1.6.2/Command/Proxy/CollectionRegionDoctrineCommand.php000066400000000000000000000021401264451145000260560ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Doctrine\ORM\Tools\Console\Command\ClearCache\CollectionRegionCommand; /** * Command to clear a collection cache region. * * @author Fabio B. Silva */ class CollectionRegionDoctrineCommand extends DelegateCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this->setName('doctrine:cache:clear-collection-region'); } /** * {@inheritDoc} */ protected function createCommand() { return new CollectionRegionCommand(); } /** * {@inheritDoc} */ protected function getMinimalVersion() { return '2.5.0-DEV'; } } DoctrineBundle-1.6.2/Command/Proxy/ConvertMappingDoctrineCommand.php000066400000000000000000000042251264451145000255610ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand; use Doctrine\ORM\Tools\Export\Driver\XmlExporter; use Doctrine\ORM\Tools\Export\Driver\YamlExporter; /** * Convert Doctrine ORM metadata mapping information between the various supported * formats. * * @author Fabien Potencier * @author Jonathan H. Wage */ class ConvertMappingDoctrineCommand extends ConvertMappingCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this ->setName('doctrine:mapping:convert') ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em')); return parent::execute($input, $output); } /** * @param string $toType * @param string $destPath * * @return \Doctrine\ORM\Tools\Export\Driver\AbstractExporter */ protected function getExporter($toType, $destPath) { /** @var $exporter \Doctrine\ORM\Tools\Export\Driver\AbstractExporter */ $exporter = parent::getExporter($toType, $destPath); if ($exporter instanceof XmlExporter) { $exporter->setExtension('.orm.xml'); } elseif ($exporter instanceof YamlExporter) { $exporter->setExtension('.orm.yml'); } return $exporter; } } DoctrineBundle-1.6.2/Command/Proxy/CreateSchemaDoctrineCommand.php000066400000000000000000000030641264451145000251510ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand; /** * Command to execute the SQL needed to generate the database schema for * a given entity manager. * * @author Fabien Potencier * @author Jonathan H. Wage */ class CreateSchemaDoctrineCommand extends CreateCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this ->setName('doctrine:schema:create') ->setDescription('Executes (or dumps) the SQL needed to generate the database schema') ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em')); parent::execute($input, $output); } } DoctrineBundle-1.6.2/Command/Proxy/DelegateCommand.php000066400000000000000000000060611264451145000226470ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Command Delegate. * * @author Fabio B. Silva */ abstract class DelegateCommand extends Command { /** * @var \Symfony\Component\Console\Command\Command */ protected $command; /** * @return \Symfony\Component\Console\Command\Command */ abstract protected function createCommand(); /** * @return string */ protected function getMinimalVersion() { return '2.3.0-DEV'; } /** * @return boolean */ private function isVersionCompatible() { return (version_compare(\Doctrine\ORM\Version::VERSION, $this->getMinimalVersion()) >= 0); } /** * {@inheritDoc} */ public function isEnabled() { return $this->isVersionCompatible(); } /** * @param string $entityManagerName * * @return Command */ protected function wrapCommand($entityManagerName) { if (!$this->isVersionCompatible()) { throw new \RuntimeException(sprintf('"%s" requires doctrine-orm "%s" or newer', $this->getName(), $this->getMinimalVersion())); } DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $entityManagerName); $this->command->setApplication($this->getApplication()); return $this->command; } /** * {@inheritDoc} */ protected function configure() { if ($this->isVersionCompatible()) { $this->command = $this->createCommand(); $this->setHelp($this->command->getHelp()); $this->setDefinition($this->command->getDefinition()); $this->setDescription($this->command->getDescription()); } $this->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { return $this->wrapCommand($input->getOption('em'))->execute($input, $output); } /** * {@inheritDoc} */ protected function interact(InputInterface $input, OutputInterface $output) { $this->wrapCommand($input->getOption('em'))->interact($input, $output); } /** * {@inheritDoc} */ protected function initialize(InputInterface $input, OutputInterface $output) { $this->wrapCommand($input->getOption('em'))->initialize($input, $output); } } DoctrineBundle-1.6.2/Command/Proxy/DoctrineCommandHelper.php000066400000000000000000000037221264451145000240450ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Symfony\Bundle\FrameworkBundle\Console\Application; use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper; use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper; /** * Provides some helper and convenience methods to configure doctrine commands in the context of bundles * and multiple connections/entity managers. * * @author Fabien Potencier */ abstract class DoctrineCommandHelper { /** * Convenience method to push the helper sets of a given entity manager into the application. * * @param Application $application * @param string $emName */ public static function setApplicationEntityManager(Application $application, $emName) { /** @var $em \Doctrine\ORM\EntityManager */ $em = $application->getKernel()->getContainer()->get('doctrine')->getManager($emName); $helperSet = $application->getHelperSet(); $helperSet->set(new ConnectionHelper($em->getConnection()), 'db'); $helperSet->set(new EntityManagerHelper($em), 'em'); } /** * Convenience method to push the helper sets of a given connection into the application. * * @param Application $application * @param string $connName */ public static function setApplicationConnection(Application $application, $connName) { $connection = $application->getKernel()->getContainer()->get('doctrine')->getConnection($connName); $helperSet = $application->getHelperSet(); $helperSet->set(new ConnectionHelper($connection), 'db'); } } DoctrineBundle-1.6.2/Command/Proxy/DropSchemaDoctrineCommand.php000066400000000000000000000030411264451145000246450ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand; /** * Command to drop the database schema for a set of classes based on their mappings. * * @author Fabien Potencier * @author Jonathan H. Wage */ class DropSchemaDoctrineCommand extends DropCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this ->setName('doctrine:schema:drop') ->setDescription('Executes (or dumps) the SQL needed to drop the current database schema') ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em')); parent::execute($input, $output); } } DoctrineBundle-1.6.2/Command/Proxy/EnsureProductionSettingsDoctrineCommand.php000066400000000000000000000027571264451145000276660ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand; /** * Ensure the Doctrine ORM is configured properly for a production environment. * * @author Fabien Potencier * @author Jonathan H. Wage */ class EnsureProductionSettingsDoctrineCommand extends EnsureProductionSettingsCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this ->setName('doctrine:ensure-production-settings') ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em')); parent::execute($input, $output); } } DoctrineBundle-1.6.2/Command/Proxy/EntityRegionCacheDoctrineCommand.php000066400000000000000000000021211264451145000261620ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Doctrine\ORM\Tools\Console\Command\ClearCache\EntityRegionCommand; /** * Command to clear a entity cache region. * * @author Fabio B. Silva */ class EntityRegionCacheDoctrineCommand extends DelegateCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this->setName('doctrine:cache:clear-entity-region'); } /** * {@inheritDoc} */ protected function createCommand() { return new EntityRegionCommand(); } /** * {@inheritDoc} */ protected function getMinimalVersion() { return '2.5.0-DEV'; } } DoctrineBundle-1.6.2/Command/Proxy/InfoDoctrineCommand.php000066400000000000000000000024711264451145000235210ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Doctrine\ORM\Tools\Console\Command\InfoCommand; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Show information about mapped entities * * @author Benjamin Eberlei */ class InfoDoctrineCommand extends InfoCommand { /** * {@inheritDoc} */ protected function configure() { $this ->setName('doctrine:mapping:info') ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em')); return parent::execute($input, $output); } } DoctrineBundle-1.6.2/Command/Proxy/QueryRegionCacheDoctrineCommand.php000066400000000000000000000021141264451145000260150ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Doctrine\ORM\Tools\Console\Command\ClearCache\QueryRegionCommand; /** * Command to clear a query cache region. * * @author Fabio B. Silva */ class QueryRegionCacheDoctrineCommand extends DelegateCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this->setName('doctrine:cache:clear-query-region'); } /** * {@inheritDoc} */ protected function createCommand() { return new QueryRegionCommand(); } /** * {@inheritDoc} */ protected function getMinimalVersion() { return '2.5.0-DEV'; } } DoctrineBundle-1.6.2/Command/Proxy/RunDqlDoctrineCommand.php000066400000000000000000000037631264451145000240400ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Doctrine\ORM\Tools\Console\Command\RunDqlCommand; /** * Execute a Doctrine DQL query and output the results. * * @author Fabien Potencier * @author Jonathan H. Wage */ class RunDqlDoctrineCommand extends RunDqlCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this ->setName('doctrine:query:dql') ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command') ->setHelp(<<%command.name% command executes the given DQL query and outputs the results: php %command.full_name% "SELECT u FROM UserBundle:User u" You can also optional specify some additional options like what type of hydration to use when executing the query: php %command.full_name% "SELECT u FROM UserBundle:User u" --hydrate=array Additionally you can specify the first result and maximum amount of results to show: php %command.full_name% "SELECT u FROM UserBundle:User u" --first-result=0 --max-result=30 EOT ); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em')); return parent::execute($input, $output); } } DoctrineBundle-1.6.2/Command/Proxy/RunSqlDoctrineCommand.php000066400000000000000000000031341264451145000240470ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Doctrine\DBAL\Tools\Console\Command\RunSqlCommand; /** * Execute a SQL query and output the results. * * @author Fabien Potencier * @author Jonathan H. Wage */ class RunSqlDoctrineCommand extends RunSqlCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this ->setName('doctrine:query:sql') ->addOption('connection', null, InputOption::VALUE_OPTIONAL, 'The connection to use for this command') ->setHelp(<<%command.name% command executes the given SQL query and outputs the results: php %command.full_name% "SELECT * from user" EOT ); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationConnection($this->getApplication(), $input->getOption('connection')); return parent::execute($input, $output); } } DoctrineBundle-1.6.2/Command/Proxy/UpdateSchemaDoctrineCommand.php000066400000000000000000000027451264451145000251750ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand; /** * Command to generate the SQL needed to update the database schema to match * the current mapping information. * * @author Fabien Potencier * @author Jonathan H. Wage */ class UpdateSchemaDoctrineCommand extends UpdateCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this ->setName('doctrine:schema:update') ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em')); return parent::execute($input, $output); } } DoctrineBundle-1.6.2/Command/Proxy/ValidateSchemaCommand.php000066400000000000000000000030171264451145000240050ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand as DoctrineValidateSchemaCommand; /** * Command to run Doctrine ValidateSchema() on the current mappings. * * @author Fabien Potencier * @author Jonathan H. Wage * @author Neil Katin */ class ValidateSchemaCommand extends DoctrineValidateSchemaCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this ->setName('doctrine:schema:validate') ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em')); return parent::execute($input, $output); } } DoctrineBundle-1.6.2/ConnectionFactory.php000066400000000000000000000046061264451145000205710ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle; use Doctrine\Common\EventManager; use Doctrine\DBAL\Configuration; use Doctrine\DBAL\DriverManager; use Doctrine\DBAL\Types\Type; /** * Connection */ class ConnectionFactory { private $typesConfig = array(); private $commentedTypes = array(); private $initialized = false; /** * Construct. * * @param array $typesConfig */ public function __construct(array $typesConfig) { $this->typesConfig = $typesConfig; } /** * Create a connection by name. * * @param array $params * @param Configuration $config * @param EventManager $eventManager * @param array $mappingTypes * * @return \Doctrine\DBAL\Connection */ public function createConnection(array $params, Configuration $config = null, EventManager $eventManager = null, array $mappingTypes = array()) { if (!$this->initialized) { $this->initializeTypes(); $this->initialized = true; } $connection = DriverManager::getConnection($params, $config, $eventManager); if (!empty($mappingTypes)) { $platform = $connection->getDatabasePlatform(); foreach ($mappingTypes as $dbType => $doctrineType) { $platform->registerDoctrineTypeMapping($dbType, $doctrineType); } foreach ($this->commentedTypes as $type) { $platform->markDoctrineTypeCommented(Type::getType($type)); } } return $connection; } /** * initialize the types */ private function initializeTypes() { foreach ($this->typesConfig as $type => $typeConfig) { if (Type::hasType($type)) { Type::overrideType($type, $typeConfig['class']); } else { Type::addType($type, $typeConfig['class']); } if ($typeConfig['commented']) { $this->commentedTypes[] = $type; } } } } DoctrineBundle-1.6.2/Controller/000077500000000000000000000000001264451145000165465ustar00rootroot00000000000000DoctrineBundle-1.6.2/Controller/ProfilerController.php000066400000000000000000000066601264451145000231150ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Controller; use Doctrine\DBAL\Connection; use Doctrine\DBAL\Platforms\SQLServerPlatform; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\Response; /** * ProfilerController. * * @author Christophe Coevoet */ class ProfilerController implements ContainerAwareInterface { /** * @var ContainerInterface */ private $container; /** * {@inheritDoc} */ public function setContainer(ContainerInterface $container = null) { $this->container = $container; } /** * Renders the profiler panel for the given token. * * @param string $token The profiler token * @param string $connectionName * @param integer $query * * @return Response A Response instance */ public function explainAction($token, $connectionName, $query) { /** @var $profiler \Symfony\Component\HttpKernel\Profiler\Profiler */ $profiler = $this->container->get('profiler'); $profiler->disable(); $profile = $profiler->loadProfile($token); $queries = $profile->getCollector('db')->getQueries(); if (!isset($queries[$connectionName][$query])) { return new Response('This query does not exist.'); } $query = $queries[$connectionName][$query]; if (!$query['explainable']) { return new Response('This query cannot be explained.'); } /** @var $connection \Doctrine\DBAL\Connection */ $connection = $this->container->get('doctrine')->getConnection($connectionName); try { if ($connection->getDatabasePlatform() instanceof SQLServerPlatform) { $results = $this->explainSQLServerPlatform($connection, $query); } else { $results = $this->explainOtherPlatform($connection, $query); } } catch (\Exception $e) { return new Response('This query cannot be explained.'); } return $this->container->get('templating')->renderResponse('@Doctrine/Collector/explain.html.twig', array( 'data' => $results, 'query' => $query, )); } private function explainSQLServerPlatform(Connection $connection, $query) { if (stripos($query['sql'], 'SELECT') === 0) { $sql = 'SET STATISTICS PROFILE ON; ' . $query['sql'] . '; SET STATISTICS PROFILE OFF;'; } else { $sql = 'SET SHOWPLAN_TEXT ON; GO; SET NOEXEC ON; ' . $query['sql'] .'; SET NOEXEC OFF; GO; SET SHOWPLAN_TEXT OFF;'; } $stmt = $connection->executeQuery($sql, $query['params'], $query['types']); $stmt->nextRowset(); return $stmt->fetchAll(\PDO::FETCH_ASSOC); } private function explainOtherPlatform(Connection $connection, $query) { return $connection->executeQuery('EXPLAIN '.$query['sql'], $query['params'], $query['types']) ->fetchAll(\PDO::FETCH_ASSOC); } } DoctrineBundle-1.6.2/DataCollector/000077500000000000000000000000001264451145000171435ustar00rootroot00000000000000DoctrineBundle-1.6.2/DataCollector/DoctrineDataCollector.php000066400000000000000000000134221264451145000240660ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\DataCollector; use Doctrine\Common\Persistence\ManagerRegistry; use Doctrine\ORM\Tools\SchemaValidator; use Doctrine\ORM\Version; use Symfony\Bridge\Doctrine\DataCollector\DoctrineDataCollector as BaseCollector; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** * DoctrineDataCollector. * * @author Christophe Coevoet */ class DoctrineDataCollector extends BaseCollector { private $registry; private $invalidEntityCount; public function __construct(ManagerRegistry $registry) { $this->registry = $registry; parent::__construct($registry); } /** * {@inheritdoc} */ public function collect(Request $request, Response $response, \Exception $exception = null) { parent::collect($request, $response, $exception); $errors = array(); $entities = array(); $caches = array( 'enabled' => false, 'log_enabled' => false, 'counts' => array( 'puts' => 0, 'hits' => 0, 'misses' => 0, ), 'regions' => array( 'puts' => array(), 'hits' => array(), 'misses' => array(), ), ); foreach ($this->registry->getManagers() as $name => $em) { $entities[$name] = array(); /** @var $factory \Doctrine\ORM\Mapping\ClassMetadataFactory */ $factory = $em->getMetadataFactory(); $validator = new SchemaValidator($em); /** @var $class \Doctrine\ORM\Mapping\ClassMetadataInfo */ foreach ($factory->getLoadedMetadata() as $class) { if (!isset($entities[$name][$class->getName()])) { $classErrors = $validator->validateClass($class); $entities[$name][$class->getName()] = $class->getName(); if (!empty($classErrors)) { $errors[$name][$class->getName()] = $classErrors; } } } if (version_compare(Version::VERSION, '2.5.0-DEV') < 0) { continue; } /** @var $emConfig \Doctrine\ORM\Configuration */ $emConfig = $em->getConfiguration(); $slcEnabled = $emConfig->isSecondLevelCacheEnabled(); if (!$slcEnabled) { continue; } $caches['enabled'] = true; /** @var $cacheConfiguration \Doctrine\ORM\Cache\CacheConfiguration */ /** @var $cacheLoggerChain \Doctrine\ORM\Cache\Logging\CacheLoggerChain */ $cacheConfiguration = $emConfig->getSecondLevelCacheConfiguration(); $cacheLoggerChain = $cacheConfiguration->getCacheLogger(); if (!$cacheLoggerChain || !$cacheLoggerChain->getLogger('statistics')) { continue; } /** @var $cacheLoggerStats \Doctrine\ORM\Cache\Logging\StatisticsCacheLogger */ $cacheLoggerStats = $cacheLoggerChain->getLogger('statistics'); $caches['log_enabled'] = true; $caches['counts']['puts'] += $cacheLoggerStats->getPutCount(); $caches['counts']['hits'] += $cacheLoggerStats->getHitCount(); $caches['counts']['misses'] += $cacheLoggerStats->getMissCount(); foreach ($cacheLoggerStats->getRegionsPut() as $key => $value) { if (!isset($caches['regions']['puts'][$key])) { $caches['regions']['puts'][$key] = 0; } $caches['regions']['puts'][$key] += $value; } foreach ($cacheLoggerStats->getRegionsHit() as $key => $value) { if (!isset($caches['regions']['hits'][$key])) { $caches['regions']['hits'][$key] = 0; } $caches['regions']['hits'][$key] += $value; } foreach ($cacheLoggerStats->getRegionsMiss() as $key => $value) { if (!isset($caches['regions']['misses'][$key])) { $caches['regions']['misses'][$key] = 0; } $caches['regions']['misses'][$key] += $value; } } $this->data['entities'] = $entities; $this->data['errors'] = $errors; $this->data['caches'] = $caches; } public function getEntities() { return $this->data['entities']; } public function getMappingErrors() { return $this->data['errors']; } public function getCacheHitsCount() { return $this->data['caches']['counts']['hits']; } public function getCachePutsCount() { return $this->data['caches']['counts']['puts']; } public function getCacheMissesCount() { return $this->data['caches']['counts']['misses']; } public function getCacheEnabled() { return $this->data['caches']['enabled']; } public function getCacheRegions() { return $this->data['caches']['regions']; } public function getCacheCounts() { return $this->data['caches']['counts']; } public function getInvalidEntityCount() { if (null === $this->invalidEntityCount) { $this->invalidEntityCount = array_sum(array_map('count', $this->data['errors'])); } return $this->invalidEntityCount; } } DoctrineBundle-1.6.2/DependencyInjection/000077500000000000000000000000001264451145000203445ustar00rootroot00000000000000DoctrineBundle-1.6.2/DependencyInjection/Compiler/000077500000000000000000000000001264451145000221165ustar00rootroot00000000000000DoctrineBundle-1.6.2/DependencyInjection/Compiler/DoctrineOrmMappingsPass.php000066400000000000000000000216601264451145000274070ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler; use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\RegisterMappingsPass; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; /** * Class for Symfony bundles to configure mappings for model classes not in the * auto-mapped folder. * * NOTE: alias is only supported by Symfony 2.6+ and will be ignored with older versions. * * @author David Buchmann */ class DoctrineOrmMappingsPass extends RegisterMappingsPass { /** * You should not directly instantiate this class but use one of the * factory methods. * * @param Definition|Reference $driver Driver DI definition or reference. * @param array $namespaces List of namespaces handled by $driver. * @param string[] $managerParameters Ordered list of container parameters that * could hold the manager name. * doctrine.default_entity_manager is appended * automatically. * @param string|false $enabledParameter If specified, the compiler pass only executes * if this parameter is defined in the service * container. * @param array $aliasMap Map of alias to namespace. */ public function __construct($driver, array $namespaces, array $managerParameters, $enabledParameter = false, array $aliasMap = array()) { $managerParameters[] = 'doctrine.default_entity_manager'; parent::__construct( $driver, $namespaces, $managerParameters, 'doctrine.orm.%s_metadata_driver', $enabledParameter, 'doctrine.orm.%s_configuration', 'addEntityNamespace', $aliasMap ); } /** * @param array $namespaces Hashmap of directory path to namespace. * @param string[] $managerParameters List of parameters that could which object manager name * your bundle uses. This compiler pass will automatically * append the parameter name for the default entity manager * to this list. * @param string|false $enabledParameter Service container parameter that must be present to * enable the mapping. Set to false to not do any check, * optional. * @param string[] $aliasMap Map of alias to namespace. * * @return self */ public static function createXmlMappingDriver(array $namespaces, array $managerParameters = array(), $enabledParameter = false, array $aliasMap = array()) { $arguments = array($namespaces, '.orm.xml'); $locator = new Definition('Doctrine\Common\Persistence\Mapping\Driver\SymfonyFileLocator', $arguments); $driver = new Definition('Doctrine\ORM\Mapping\Driver\XmlDriver', array($locator)); return new DoctrineOrmMappingsPass($driver, $namespaces, $managerParameters, $enabledParameter, $aliasMap); } /** * @param array $namespaces Hashmap of directory path to namespace * @param string[] $managerParameters List of parameters that could which object manager name * your bundle uses. This compiler pass will automatically * append the parameter name for the default entity manager * to this list. * @param string|false $enabledParameter Service container parameter that must be present to * enable the mapping. Set to false to not do any check, * optional. * @param string[] $aliasMap Map of alias to namespace. * * @return self */ public static function createYamlMappingDriver(array $namespaces, array $managerParameters = array(), $enabledParameter = false, array $aliasMap = array()) { $arguments = array($namespaces, '.orm.yml'); $locator = new Definition('Doctrine\Common\Persistence\Mapping\Driver\SymfonyFileLocator', $arguments); $driver = new Definition('Doctrine\ORM\Mapping\Driver\YamlDriver', array($locator)); return new DoctrineOrmMappingsPass($driver, $namespaces, $managerParameters, $enabledParameter, $aliasMap); } /** * @param array $namespaces Hashmap of directory path to namespace * @param string[] $managerParameters List of parameters that could which object manager name * your bundle uses. This compiler pass will automatically * append the parameter name for the default entity manager * to this list. * @param string $enabledParameter Service container parameter that must be present to * enable the mapping. Set to false to not do any check, * optional. * @param string[] $aliasMap Map of alias to namespace. * * @return self */ public static function createPhpMappingDriver(array $namespaces, array $managerParameters = array(), $enabledParameter = false, array $aliasMap = array()) { $arguments = array($namespaces, '.php'); $locator = new Definition('Doctrine\Common\Persistence\Mapping\Driver\SymfonyFileLocator', $arguments); $driver = new Definition('Doctrine\Common\Persistence\Mapping\Driver\PHPDriver', array($locator)); return new DoctrineOrmMappingsPass($driver, $namespaces, $managerParameters, $enabledParameter, $aliasMap); } /** * @param array $namespaces List of namespaces that are handled with annotation mapping * @param array $directories List of directories to look for annotated classes * @param string[] $managerParameters List of parameters that could which object manager name * your bundle uses. This compiler pass will automatically * append the parameter name for the default entity manager * to this list. * @param string|false $enabledParameter Service container parameter that must be present to * enable the mapping. Set to false to not do any check, * optional. * @param string[] $aliasMap Map of alias to namespace. * * @return self */ public static function createAnnotationMappingDriver(array $namespaces, array $directories, array $managerParameters = array(), $enabledParameter = false, array $aliasMap = array()) { $reader = new Reference('annotation_reader'); $driver = new Definition('Doctrine\ORM\Mapping\Driver\AnnotationDriver', array($reader, $directories)); return new DoctrineOrmMappingsPass($driver, $namespaces, $managerParameters, $enabledParameter, $aliasMap); } /** * @param array $namespaces List of namespaces that are handled with static php mapping * @param array $directories List of directories to look for static php mapping files * @param string[] $managerParameters List of parameters that could which object manager name * your bundle uses. This compiler pass will automatically * append the parameter name for the default entity manager * to this list. * @param string|false $enabledParameter Service container parameter that must be present to * enable the mapping. Set to false to not do any check, * optional. * @param string[] $aliasMap Map of alias to namespace. * * @return self */ public static function createStaticPhpMappingDriver(array $namespaces, array $directories, array $managerParameters = array(), $enabledParameter = false, array $aliasMap = array()) { $driver = new Definition('Doctrine\Common\Persistence\Mapping\Driver\StaticPHPDriver', array($directories)); return new DoctrineOrmMappingsPass($driver, $namespaces, $managerParameters, $enabledParameter, $aliasMap); } } DoctrineBundle-1.6.2/DependencyInjection/Compiler/EntityListenerPass.php000066400000000000000000000052521264451145000264440ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\Reference; /** * Class for Symfony bundles to register entity listeners * * @author Sander Marechal */ class EntityListenerPass implements CompilerPassInterface { /** * {@inheritDoc} */ public function process(ContainerBuilder $container) { $resolvers = $container->findTaggedServiceIds('doctrine.orm.entity_listener'); foreach ($resolvers as $id => $tagAttributes) { foreach ($tagAttributes as $attributes) { $name = isset($attributes['entity_manager']) ? $attributes['entity_manager'] : $container->getParameter('doctrine.default_entity_manager'); $entityManager = sprintf('doctrine.orm.%s_entity_manager', $name); if (!$container->hasDefinition($entityManager)) { continue; } $resolver = sprintf('doctrine.orm.%s_entity_listener_resolver', $name); if ($container->hasAlias($resolver)) { $resolver = (string) $container->getAlias($resolver); } if (!$container->hasDefinition($resolver)) { continue; } if (isset($attributes['entity']) && isset($attributes['event'])) { $this->attachToListener($container, $name, $id, $attributes); } $container->getDefinition($resolver)->addMethodCall('register', array(new Reference($id))); } } } private function attachToListener(ContainerBuilder $container, $name, $id, array $attributes) { $listenerId = sprintf('doctrine.orm.%s_listeners.attach_entity_listeners', $name); if (!$container->has($listenerId)) { return; } $serviceDef = $container->getDefinition($id); $args = array( $attributes['entity'], $serviceDef->getClass(), $attributes['event'], ); if (isset($attributes['method'])) { $args[] = $attributes['method']; } $container->findDefinition($listenerId)->addMethodCall('addEntityListener', $args); } } DoctrineBundle-1.6.2/DependencyInjection/Configuration.php000066400000000000000000000671041264451145000236740ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This class contains the configuration information for the bundle * * This information is solely responsible for how the different configuration * sections are normalized, and merged. * * @author Christophe Coevoet */ class Configuration implements ConfigurationInterface { private $debug; /** * Constructor * * @param Boolean $debug Whether to use the debug mode */ public function __construct($debug) { $this->debug = (Boolean) $debug; } /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('doctrine'); $this->addDbalSection($rootNode); $this->addOrmSection($rootNode); return $treeBuilder; } /** * Add DBAL section to configuration tree * * @param ArrayNodeDefinition $node */ private function addDbalSection(ArrayNodeDefinition $node) { $node ->children() ->arrayNode('dbal') ->beforeNormalization() ->ifTrue(function ($v) { return is_array($v) && !array_key_exists('connections', $v) && !array_key_exists('connection', $v); }) ->then(function ($v) { // Key that should not be rewritten to the connection config $excludedKeys = array('default_connection' => true, 'types' => true, 'type' => true); $connection = array(); foreach ($v as $key => $value) { if (isset($excludedKeys[$key])) { continue; } $connection[$key] = $v[$key]; unset($v[$key]); } $v['default_connection'] = isset($v['default_connection']) ? (string) $v['default_connection'] : 'default'; $v['connections'] = array($v['default_connection'] => $connection); return $v; }) ->end() ->children() ->scalarNode('default_connection')->end() ->end() ->fixXmlConfig('type') ->children() ->arrayNode('types') ->useAttributeAsKey('name') ->prototype('array') ->beforeNormalization() ->ifString() ->then(function ($v) { return array('class' => $v); }) ->end() ->children() ->scalarNode('class')->isRequired()->end() ->booleanNode('commented')->defaultTrue()->end() ->end() ->end() ->end() ->end() ->fixXmlConfig('connection') ->append($this->getDbalConnectionsNode()) ->end() ; } /** * Return the dbal connections node * * @return ArrayNodeDefinition */ private function getDbalConnectionsNode() { $treeBuilder = new TreeBuilder(); $node = $treeBuilder->root('connections'); /** @var $connectionNode ArrayNodeDefinition */ $connectionNode = $node ->requiresAtLeastOneElement() ->useAttributeAsKey('name') ->prototype('array') ; $this->configureDbalDriverNode($connectionNode); $connectionNode ->fixXmlConfig('option') ->fixXmlConfig('mapping_type') ->fixXmlConfig('slave') ->fixXmlConfig('shard') ->fixXmlConfig('default_table_option') ->children() ->scalarNode('driver')->defaultValue('pdo_mysql')->end() ->scalarNode('platform_service')->end() ->booleanNode('auto_commit')->end() ->scalarNode('schema_filter')->end() ->booleanNode('logging')->defaultValue($this->debug)->end() ->booleanNode('profiling')->defaultValue($this->debug)->end() ->scalarNode('server_version')->end() ->scalarNode('driver_class')->end() ->scalarNode('wrapper_class')->end() ->scalarNode('shard_choser')->end() ->scalarNode('shard_choser_service')->end() ->booleanNode('keep_slave')->end() ->arrayNode('options') ->useAttributeAsKey('key') ->prototype('scalar')->end() ->end() ->arrayNode('mapping_types') ->useAttributeAsKey('name') ->prototype('scalar')->end() ->end() ->arrayNode('default_table_options') ->info("This option is used by the schema-tool and affects generated SQL. Possible keys include 'charset','collate', and 'engine'.") ->useAttributeAsKey('name') ->prototype('scalar')->end() ->end() ->end() ; $slaveNode = $connectionNode ->children() ->arrayNode('slaves') ->useAttributeAsKey('name') ->prototype('array') ; $this->configureDbalDriverNode($slaveNode); $shardNode = $connectionNode ->children() ->arrayNode('shards') ->prototype('array') ->children() ->integerNode('id') ->min(1) ->isRequired() ->end() ->end() ; $this->configureDbalDriverNode($shardNode); return $node; } /** * Adds config keys related to params processed by the DBAL drivers * * These keys are available for slave configurations too. * * @param ArrayNodeDefinition $node */ private function configureDbalDriverNode(ArrayNodeDefinition $node) { $node ->children() ->scalarNode('url')->info('A URL with connection information; any parameter value parsed from this string will override explicitly set parameters')->end() ->scalarNode('dbname')->end() ->scalarNode('host')->defaultValue('localhost')->end() ->scalarNode('port')->defaultNull()->end() ->scalarNode('user')->defaultValue('root')->end() ->scalarNode('password')->defaultNull()->end() ->scalarNode('application_name')->end() ->scalarNode('charset')->end() ->scalarNode('path')->end() ->booleanNode('memory')->end() ->scalarNode('unix_socket')->info('The unix socket to use for MySQL')->end() ->booleanNode('persistent')->info('True to use as persistent connection for the ibm_db2 driver')->end() ->scalarNode('protocol')->info('The protocol to use for the ibm_db2 driver (default to TCPIP if ommited)')->end() ->booleanNode('service') ->info('True to use SERVICE_NAME as connection parameter instead of SID for Oracle') ->end() ->scalarNode('servicename') ->info( 'Overrules dbname parameter if given and used as SERVICE_NAME or SID connection parameter '. 'for Oracle depending on the service parameter.' ) ->end() ->scalarNode('sessionMode') ->info('The session mode to use for the oci8 driver') ->end() ->scalarNode('server') ->info('The name of a running database server to connect to for SQL Anywhere.') ->end() ->scalarNode('sslmode') ->info( 'Determines whether or with what priority a SSL TCP/IP connection will be negotiated with '. 'the server for PostgreSQL.' ) ->end() ->scalarNode('sslrootcert') ->info( 'The name of a file containing SSL certificate authority (CA) certificate(s). '. 'If the file exists, the server\'s certificate will be verified to be signed by one of these authorities.' ) ->end() ->booleanNode('pooled')->info('True to use a pooled server with the oci8/pdo_oracle driver')->end() ->booleanNode('MultipleActiveResultSets')->info('Configuring MultipleActiveResultSets for the pdo_sqlsrv driver')->end() ->booleanNode('use_savepoints')->info('Use savepoints for nested transactions')->end() ->end() ->beforeNormalization() ->ifTrue(function ($v) {return !isset($v['sessionMode']) && isset($v['session_mode']);}) ->then(function ($v) { $v['sessionMode'] = $v['session_mode']; unset($v['session_mode']); return $v; }) ->end() ->beforeNormalization() ->ifTrue(function ($v) {return !isset($v['MultipleActiveResultSets']) && isset($v['multiple_active_result_sets']);}) ->then(function ($v) { $v['MultipleActiveResultSets'] = $v['multiple_active_result_sets']; unset($v['multiple_active_result_sets']); return $v; }) ->end() ; } /** * Add the ORM section to configuration tree * * @param ArrayNodeDefinition $node */ private function addOrmSection(ArrayNodeDefinition $node) { $generationModes = $this->getAutoGenerateModes(); $node ->children() ->arrayNode('orm') ->beforeNormalization() ->ifTrue(function ($v) { return null === $v || (is_array($v) && !array_key_exists('entity_managers', $v) && !array_key_exists('entity_manager', $v)); }) ->then(function ($v) { $v = (array) $v; // Key that should not be rewritten to the connection config $excludedKeys = array( 'default_entity_manager' => true, 'auto_generate_proxy_classes' => true, 'proxy_dir' => true, 'proxy_namespace' => true, 'resolve_target_entities' => true, 'resolve_target_entity' => true, ); $entityManager = array(); foreach ($v as $key => $value) { if (isset($excludedKeys[$key])) { continue; } $entityManager[$key] = $v[$key]; unset($v[$key]); } $v['default_entity_manager'] = isset($v['default_entity_manager']) ? (string) $v['default_entity_manager'] : 'default'; $v['entity_managers'] = array($v['default_entity_manager'] => $entityManager); return $v; }) ->end() ->children() ->scalarNode('default_entity_manager')->end() ->scalarNode('auto_generate_proxy_classes')->defaultValue(false) ->info('Auto generate mode possible values are: "NEVER", "ALWAYS", "FILE_NOT_EXISTS", "EVAL"') ->validate() ->ifTrue(function ($v) use ($generationModes) { if (is_int($v) && in_array($v, $generationModes['values']/*array(0, 1, 2, 3)*/)) { return false; } if (is_bool($v)) { return false; } if (is_string($v)) { if (in_array(strtoupper($v), $generationModes['names']/*array('NEVER', 'ALWAYS', 'FILE_NOT_EXISTS', 'EVAL')*/)) { return false; } } return true; }) ->thenInvalid('Invalid auto generate mode value %s') ->end() ->validate() ->ifString() ->then(function ($v) { return constant('Doctrine\Common\Proxy\AbstractProxyFactory::AUTOGENERATE_'.strtoupper($v)); }) ->end() ->end() ->scalarNode('proxy_dir')->defaultValue('%kernel.cache_dir%/doctrine/orm/Proxies')->end() ->scalarNode('proxy_namespace')->defaultValue('Proxies')->end() ->end() ->fixXmlConfig('entity_manager') ->append($this->getOrmEntityManagersNode()) ->fixXmlConfig('resolve_target_entity', 'resolve_target_entities') ->append($this->getOrmTargetEntityResolverNode()) ->end() ->end() ; } /** * Return ORM target entity resolver node * * @return \Symfony\Component\Config\Definition\Builder\NodeDefinition */ private function getOrmTargetEntityResolverNode() { $treeBuilder = new TreeBuilder(); $node = $treeBuilder->root('resolve_target_entities'); $node ->useAttributeAsKey('interface') ->prototype('scalar') ->cannotBeEmpty() ->end() ; return $node; } /** * Return ORM entity listener node * * @return \Symfony\Component\Config\Definition\Builder\NodeDefinition */ private function getOrmEntityListenersNode() { $builder = new TreeBuilder(); $node = $builder->root('entity_listeners'); $normalizer = function ($mappings) { $entities = array(); foreach ($mappings as $entityClass => $mapping) { $listeners = array(); foreach ($mapping as $listenerClass => $listenerEvent) { $events = array(); foreach ($listenerEvent as $eventType => $eventMapping) { if ($eventMapping === null) { $eventMapping = array(null); } foreach ($eventMapping as $method) { $events[] = array( 'type' => $eventType, 'method' => $method, ); } } $listeners[] = array( 'class' => $listenerClass, 'event' => $events, ); } $entities[] = array( 'class' => $entityClass, 'listener' => $listeners, ); } return array('entities' => $entities); }; $node ->beforeNormalization() // Yaml normalization ->ifTrue(function ($v) { return is_array(reset($v)) && is_string(key(reset($v))); }) ->then($normalizer) ->end() ->fixXmlConfig('entity', 'entities') ->children() ->arrayNode('entities') ->useAttributeAsKey('class') ->prototype('array') ->fixXmlConfig('listener') ->children() ->arrayNode('listeners') ->useAttributeAsKey('class') ->prototype('array') ->fixXmlConfig('event') ->children() ->arrayNode('events') ->prototype('array') ->children() ->scalarNode('type')->end() ->scalarNode('method')->defaultNull()->end() ->end() ->end() ->end() ->end() ->end() ->end() ->end() ->end() ->end() ->end() ; return $node; } /** * Return ORM entity manager node * * @return ArrayNodeDefinition */ private function getOrmEntityManagersNode() { $treeBuilder = new TreeBuilder(); $node = $treeBuilder->root('entity_managers'); $node ->requiresAtLeastOneElement() ->useAttributeAsKey('name') ->prototype('array') ->addDefaultsIfNotSet() ->append($this->getOrmCacheDriverNode('query_cache_driver')) ->append($this->getOrmCacheDriverNode('metadata_cache_driver')) ->append($this->getOrmCacheDriverNode('result_cache_driver')) ->append($this->getOrmEntityListenersNode()) ->children() ->scalarNode('connection')->end() ->scalarNode('class_metadata_factory_name')->defaultValue('Doctrine\ORM\Mapping\ClassMetadataFactory')->end() ->scalarNode('default_repository_class')->defaultValue('Doctrine\ORM\EntityRepository')->end() ->scalarNode('auto_mapping')->defaultFalse()->end() ->scalarNode('naming_strategy')->defaultValue('doctrine.orm.naming_strategy.default')->end() ->scalarNode('quote_strategy')->defaultValue('doctrine.orm.quote_strategy.default')->end() ->scalarNode('entity_listener_resolver')->defaultNull()->end() ->scalarNode('repository_factory')->defaultNull()->end() ->end() ->children() ->arrayNode('second_level_cache') ->children() ->append($this->getOrmCacheDriverNode('region_cache_driver')) ->scalarNode('region_lock_lifetime')->defaultValue(60)->end() ->booleanNode('log_enabled')->defaultValue($this->debug)->end() ->scalarNode('region_lifetime')->defaultValue(0)->end() ->booleanNode('enabled')->defaultValue(true)->end() ->scalarNode('factory')->end() ->end() ->fixXmlConfig('region') ->children() ->arrayNode('regions') ->useAttributeAsKey('name') ->prototype('array') ->children() ->append($this->getOrmCacheDriverNode('cache_driver')) ->scalarNode('lock_path')->defaultValue('%kernel.cache_dir%/doctrine/orm/slc/filelock')->end() ->scalarNode('lock_lifetime')->defaultValue(60)->end() ->scalarNode('type')->defaultValue('default')->end() ->scalarNode('lifetime')->defaultValue(0)->end() ->scalarNode('service')->end() ->scalarNode('name')->end() ->end() ->end() ->end() ->end() ->fixXmlConfig('logger') ->children() ->arrayNode('loggers') ->useAttributeAsKey('name') ->prototype('array') ->children() ->scalarNode('name')->end() ->scalarNode('service')->end() ->end() ->end() ->end() ->end() ->end() ->end() ->fixXmlConfig('hydrator') ->children() ->arrayNode('hydrators') ->useAttributeAsKey('name') ->prototype('scalar')->end() ->end() ->end() ->fixXmlConfig('mapping') ->children() ->arrayNode('mappings') ->useAttributeAsKey('name') ->prototype('array') ->beforeNormalization() ->ifString() ->then(function ($v) { return array('type' => $v); }) ->end() ->treatNullLike(array()) ->treatFalseLike(array('mapping' => false)) ->performNoDeepMerging() ->children() ->scalarNode('mapping')->defaultValue(true)->end() ->scalarNode('type')->end() ->scalarNode('dir')->end() ->scalarNode('alias')->end() ->scalarNode('prefix')->end() ->booleanNode('is_bundle')->end() ->end() ->end() ->end() ->arrayNode('dql') ->fixXmlConfig('string_function') ->fixXmlConfig('numeric_function') ->fixXmlConfig('datetime_function') ->children() ->arrayNode('string_functions') ->useAttributeAsKey('name') ->prototype('scalar')->end() ->end() ->arrayNode('numeric_functions') ->useAttributeAsKey('name') ->prototype('scalar')->end() ->end() ->arrayNode('datetime_functions') ->useAttributeAsKey('name') ->prototype('scalar')->end() ->end() ->end() ->end() ->end() ->fixXmlConfig('filter') ->children() ->arrayNode('filters') ->info('Register SQL Filters in the entity manager') ->useAttributeAsKey('name') ->prototype('array') ->beforeNormalization() ->ifString() ->then(function ($v) { return array('class' => $v); }) ->end() ->beforeNormalization() // The content of the XML node is returned as the "value" key so we need to rename it ->ifTrue(function ($v) { return is_array($v) && isset($v['value']); }) ->then(function ($v) { $v['class'] = $v['value']; unset($v['value']); return $v; }) ->end() ->fixXmlConfig('parameter') ->children() ->scalarNode('class')->isRequired()->end() ->booleanNode('enabled')->defaultFalse()->end() ->arrayNode('parameters') ->useAttributeAsKey('name') ->prototype('variable')->end() ->end() ->end() ->end() ->end() ->end() ->end() ; return $node; } /** * Return a ORM cache driver node for an given entity manager * * @param string $name * * @return ArrayNodeDefinition */ private function getOrmCacheDriverNode($name) { $treeBuilder = new TreeBuilder(); $node = $treeBuilder->root($name); $node ->addDefaultsIfNotSet() ->beforeNormalization() ->ifString() ->then(function ($v) { return array('type' => $v); }) ->end() ->children() ->scalarNode('type')->defaultValue('array')->end() ->scalarNode('host')->end() ->scalarNode('port')->end() ->scalarNode('instance_class')->end() ->scalarNode('class')->end() ->scalarNode('id')->end() ->scalarNode('namespace')->defaultNull()->end() ->scalarNode('cache_provider')->defaultNull()->end() ->end() ; return $node; } /** * Find proxy auto generate modes for their names and int values * * @return array */ private function getAutoGenerateModes() { $constPrefix = 'AUTOGENERATE_'; $prefixLen = strlen($constPrefix); $refClass = new \ReflectionClass('Doctrine\Common\Proxy\AbstractProxyFactory'); $constsArray = $refClass->getConstants(); $namesArray = array(); $valuesArray = array(); foreach ($constsArray as $key => $value) { if (strpos($key, $constPrefix) === 0) { $namesArray[] = substr($key, $prefixLen); $valuesArray[] = (int) $value; } } return array( 'names' => $namesArray, 'values' => $valuesArray, ); } } DoctrineBundle-1.6.2/DependencyInjection/DoctrineExtension.php000066400000000000000000001047631264451145000245340ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\DependencyInjection; use Doctrine\ORM\Version; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\DefinitionDecorator; use Symfony\Component\DependencyInjection\Reference; use Symfony\Bridge\Doctrine\DependencyInjection\AbstractDoctrineExtension; use Symfony\Component\Config\FileLocator; use Doctrine\Bundle\DoctrineCacheBundle\DependencyInjection\SymfonyBridgeAdapter; use Doctrine\Bundle\DoctrineCacheBundle\DependencyInjection\CacheProviderLoader; /** * DoctrineExtension is an extension for the Doctrine DBAL and ORM library. * * @author Jonathan H. Wage * @author Fabien Potencier * @author Benjamin Eberlei * @author Fabio B. Silva * @author Kinn Coelho Julião */ class DoctrineExtension extends AbstractDoctrineExtension { /** * @var string */ private $defaultConnection; /** * @var array */ private $entityManagers; /** * @var SymfonyBridgeAdapter */ private $adapter; /** * @param SymfonyBridgeAdapter $adapter */ public function __construct(SymfonyBridgeAdapter $adapter = null) { $this->adapter = $adapter ?: new SymfonyBridgeAdapter(new CacheProviderLoader(), 'doctrine.orm', 'orm'); } /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = $this->getConfiguration($configs, $container); $config = $this->processConfiguration($configuration, $configs); $this->adapter->loadServicesConfiguration($container); if (!empty($config['dbal'])) { $this->dbalLoad($config['dbal'], $container); } if (!empty($config['orm'])) { if (empty($config['dbal'])) { throw new \LogicException('Configuring the ORM layer requires to configure the DBAL layer as well.'); } $this->ormLoad($config['orm'], $container); } $this->addClassesToCompile(array( 'Doctrine\\Common\\Annotations\\DocLexer', 'Doctrine\\Common\\Annotations\\FileCacheReader', 'Doctrine\\Common\\Annotations\\PhpParser', 'Doctrine\\Common\\Annotations\\Reader', 'Doctrine\\Common\\Lexer', 'Doctrine\\Common\\Persistence\\ConnectionRegistry', 'Doctrine\\Common\\Persistence\\Proxy', 'Doctrine\\Common\\Util\\ClassUtils', 'Doctrine\\Bundle\\DoctrineBundle\\Registry', )); } /** * Loads the DBAL configuration. * * Usage example: * * * * @param array $config An array of configuration settings * @param ContainerBuilder $container A ContainerBuilder instance */ protected function dbalLoad(array $config, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('dbal.xml'); if (empty($config['default_connection'])) { $keys = array_keys($config['connections']); $config['default_connection'] = reset($keys); } $this->defaultConnection = $config['default_connection']; $container->setAlias('database_connection', sprintf('doctrine.dbal.%s_connection', $this->defaultConnection)); $container->setAlias('doctrine.dbal.event_manager', new Alias(sprintf('doctrine.dbal.%s_connection.event_manager', $this->defaultConnection), false)); $container->setParameter('doctrine.dbal.connection_factory.types', $config['types']); $connections = array(); foreach (array_keys($config['connections']) as $name) { $connections[$name] = sprintf('doctrine.dbal.%s_connection', $name); } $container->setParameter('doctrine.connections', $connections); $container->setParameter('doctrine.default_connection', $this->defaultConnection); $def = $container->getDefinition('doctrine.dbal.connection'); if (method_exists($def, 'setFactory')) { // to be inlined in dbal.xml when dependency on Symfony DependencyInjection is bumped to 2.6 $def->setFactory(array(new Reference('doctrine.dbal.connection_factory'), 'createConnection')); } else { // to be removed when dependency on Symfony DependencyInjection is bumped to 2.6 $def->setFactoryService('doctrine.dbal.connection_factory'); $def->setFactoryMethod('createConnection'); } foreach ($config['connections'] as $name => $connection) { $this->loadDbalConnection($name, $connection, $container); } } /** * Loads a configured DBAL connection. * * @param string $name The name of the connection * @param array $connection A dbal connection configuration. * @param ContainerBuilder $container A ContainerBuilder instance */ protected function loadDbalConnection($name, array $connection, ContainerBuilder $container) { // configuration $configuration = $container->setDefinition(sprintf('doctrine.dbal.%s_connection.configuration', $name), new DefinitionDecorator('doctrine.dbal.connection.configuration')); $logger = null; if ($connection['logging']) { $logger = new Reference('doctrine.dbal.logger'); } unset ($connection['logging']); if ($connection['profiling']) { $profilingLoggerId = 'doctrine.dbal.logger.profiling.'.$name; $container->setDefinition($profilingLoggerId, new DefinitionDecorator('doctrine.dbal.logger.profiling')); $profilingLogger = new Reference($profilingLoggerId); $container->getDefinition('data_collector.doctrine')->addMethodCall('addLogger', array($name, $profilingLogger)); if (null !== $logger) { $chainLogger = new DefinitionDecorator('doctrine.dbal.logger.chain'); $chainLogger->addMethodCall('addLogger', array($profilingLogger)); $loggerId = 'doctrine.dbal.logger.chain.'.$name; $container->setDefinition($loggerId, $chainLogger); $logger = new Reference($loggerId); } else { $logger = $profilingLogger; } } unset($connection['profiling']); if (isset($connection['auto_commit'])) { $configuration->addMethodCall('setAutoCommit', array($connection['auto_commit'])); } unset($connection['auto_commit']); if (isset($connection['schema_filter']) && $connection['schema_filter']) { $configuration->addMethodCall('setFilterSchemaAssetsExpression', array($connection['schema_filter'])); } unset($connection['schema_filter']); if ($logger) { $configuration->addMethodCall('setSQLLogger', array($logger)); } // event manager $container->setDefinition(sprintf('doctrine.dbal.%s_connection.event_manager', $name), new DefinitionDecorator('doctrine.dbal.connection.event_manager')); // connection // PDO ignores the charset property before 5.3.6 so the init listener has to be used instead. if (isset($connection['charset']) && version_compare(PHP_VERSION, '5.3.6', '<')) { if ((isset($connection['driver']) && stripos($connection['driver'], 'mysql') !== false) || (isset($connection['driver_class']) && stripos($connection['driver_class'], 'mysql') !== false)) { $mysqlSessionInit = new Definition('%doctrine.dbal.events.mysql_session_init.class%'); $mysqlSessionInit->setArguments(array($connection['charset'])); $mysqlSessionInit->setPublic(false); $mysqlSessionInit->addTag('doctrine.event_subscriber', array('connection' => $name)); $container->setDefinition( sprintf('doctrine.dbal.%s_connection.events.mysqlsessioninit', $name), $mysqlSessionInit ); unset($connection['charset']); } } $options = $this->getConnectionOptions($connection); $def = $container ->setDefinition(sprintf('doctrine.dbal.%s_connection', $name), new DefinitionDecorator('doctrine.dbal.connection')) ->setArguments(array( $options, new Reference(sprintf('doctrine.dbal.%s_connection.configuration', $name)), new Reference(sprintf('doctrine.dbal.%s_connection.event_manager', $name)), $connection['mapping_types'], )) ; if (!empty($connection['use_savepoints'])) { $def->addMethodCall('setNestTransactionsWithSavepoints', array($connection['use_savepoints'])); } } protected function getConnectionOptions($connection) { $options = $connection; if (isset($options['platform_service'])) { $options['platform'] = new Reference($options['platform_service']); unset($options['platform_service']); } unset($options['mapping_types']); if (isset($options['shard_choser_service'])) { $options['shard_choser'] = new Reference($options['shard_choser_service']); unset($options['shard_choser_service']); } foreach (array( 'options' => 'driverOptions', 'driver_class' => 'driverClass', 'wrapper_class' => 'wrapperClass', 'keep_slave' => 'keepSlave', 'shard_choser' => 'shardChoser', 'server_version' => 'serverVersion', 'default_table_options' => 'defaultTableOptions', ) as $old => $new) { if (isset($options[$old])) { $options[$new] = $options[$old]; unset($options[$old]); } } if (!empty($options['slaves']) && !empty($options['shards'])) { throw new InvalidArgumentException('Sharding and master-slave connection cannot be used together'); } if (!empty($options['slaves'])) { $nonRewrittenKeys = array( 'driver' => true, 'driverOptions' => true, 'driverClass' => true, 'wrapperClass' => true, 'keepSlave' => true, 'shardChoser' => true, 'platform' => true, 'slaves' => true, 'master' => true, 'shards' => true, 'serverVersion' => true, // included by safety but should have been unset already 'logging' => true, 'profiling' => true, 'mapping_types' => true, 'platform_service' => true, ); foreach ($options as $key => $value) { if (isset($nonRewrittenKeys[$key])) { continue; } $options['master'][$key] = $value; unset($options[$key]); } if (empty($options['wrapperClass'])) { // Change the wrapper class only if the user does not already forced using a custom one. $options['wrapperClass'] = 'Doctrine\\DBAL\\Connections\\MasterSlaveConnection'; } } else { unset($options['slaves']); } if (!empty($options['shards'])) { $nonRewrittenKeys = array( 'driver' => true, 'driverOptions' => true, 'driverClass' => true, 'wrapperClass' => true, 'keepSlave' => true, 'shardChoser' => true, 'platform' => true, 'slaves' => true, 'global' => true, 'shards' => true, // included by safety but should have been unset already 'logging' => true, 'profiling' => true, 'mapping_types' => true, 'platform_service' => true, ); foreach ($options as $key => $value) { if (isset($nonRewrittenKeys[$key])) { continue; } $options['global'][$key] = $value; unset($options[$key]); } if (empty($options['wrapperClass'])) { // Change the wrapper class only if the user does not already forced using a custom one. $options['wrapperClass'] = 'Doctrine\\DBAL\\Sharding\\PoolingShardConnection'; } } else { unset($options['shards']); } return $options; } /** * Loads the Doctrine ORM configuration. * * Usage example: * * * * @param array $config An array of configuration settings * @param ContainerBuilder $container A ContainerBuilder instance */ protected function ormLoad(array $config, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('orm.xml'); $this->entityManagers = array(); foreach (array_keys($config['entity_managers']) as $name) { $this->entityManagers[$name] = sprintf('doctrine.orm.%s_entity_manager', $name); } $container->setParameter('doctrine.entity_managers', $this->entityManagers); if (empty($config['default_entity_manager'])) { $tmp = array_keys($this->entityManagers); $config['default_entity_manager'] = reset($tmp); } $container->setParameter('doctrine.default_entity_manager', $config['default_entity_manager']); $options = array('auto_generate_proxy_classes', 'proxy_dir', 'proxy_namespace'); foreach ($options as $key) { $container->setParameter('doctrine.orm.'.$key, $config[$key]); } $container->setAlias('doctrine.orm.entity_manager', sprintf('doctrine.orm.%s_entity_manager', $config['default_entity_manager'])); // BC logic to handle DoctrineBridge < 2.6 if (!method_exists($this, 'fixManagersAutoMappings')) { foreach ($config['entity_managers'] as $entityManager) { if ($entityManager['auto_mapping'] && count($config['entity_managers']) > 1) { throw new \LogicException('You cannot enable "auto_mapping" when several entity managers are defined.'); } } } else { $config['entity_managers'] = $this->fixManagersAutoMappings($config['entity_managers'], $container->getParameter('kernel.bundles')); } $def = $container->getDefinition('doctrine.orm.entity_manager.abstract'); if (method_exists($def, 'setFactory')) { // to be inlined in dbal.xml when dependency on Symfony DependencyInjection is bumped to 2.6 $def->setFactory(array('%doctrine.orm.entity_manager.class%', 'create')); } else { // to be removed when dependency on Symfony DependencyInjection is bumped to 2.6 $def->setFactoryClass('%doctrine.orm.entity_manager.class%'); $def->setFactoryMethod('create'); } foreach ($config['entity_managers'] as $name => $entityManager) { $entityManager['name'] = $name; $this->loadOrmEntityManager($entityManager, $container); } if ($config['resolve_target_entities']) { $def = $container->findDefinition('doctrine.orm.listeners.resolve_target_entity'); foreach ($config['resolve_target_entities'] as $name => $implementation) { $def->addMethodCall('addResolveTargetEntity', array( $name, $implementation, array(), )); } // BC: ResolveTargetEntityListener implements the subscriber interface since // v2.5.0-beta1 (Commit 437f812) if (version_compare(Version::VERSION, '2.5.0-DEV') < 0) { $def->addTag('doctrine.event_listener', array('event' => 'loadClassMetadata')); } else { $def->addTag('doctrine.event_subscriber'); } } } /** * Loads a configured ORM entity manager. * * @param array $entityManager A configured ORM entity manager. * @param ContainerBuilder $container A ContainerBuilder instance */ protected function loadOrmEntityManager(array $entityManager, ContainerBuilder $container) { $ormConfigDef = $container->setDefinition(sprintf('doctrine.orm.%s_configuration', $entityManager['name']), new DefinitionDecorator('doctrine.orm.configuration')); $this->loadOrmEntityManagerMappingInformation($entityManager, $ormConfigDef, $container); $this->loadOrmCacheDrivers($entityManager, $container); if (isset($entityManager['entity_listener_resolver']) && $entityManager['entity_listener_resolver']) { $container->setAlias(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name']), $entityManager['entity_listener_resolver']); } else { $container->setDefinition(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name']), new Definition('%doctrine.orm.entity_listener_resolver.class%')); } $methods = array( 'setMetadataCacheImpl' => new Reference(sprintf('doctrine.orm.%s_metadata_cache', $entityManager['name'])), 'setQueryCacheImpl' => new Reference(sprintf('doctrine.orm.%s_query_cache', $entityManager['name'])), 'setResultCacheImpl' => new Reference(sprintf('doctrine.orm.%s_result_cache', $entityManager['name'])), 'setMetadataDriverImpl' => new Reference('doctrine.orm.'.$entityManager['name'].'_metadata_driver'), 'setProxyDir' => '%doctrine.orm.proxy_dir%', 'setProxyNamespace' => '%doctrine.orm.proxy_namespace%', 'setAutoGenerateProxyClasses' => '%doctrine.orm.auto_generate_proxy_classes%', 'setClassMetadataFactoryName' => $entityManager['class_metadata_factory_name'], 'setDefaultRepositoryClassName' => $entityManager['default_repository_class'], ); // check for version to keep BC if (version_compare(Version::VERSION, "2.3.0-DEV") >= 0) { $methods = array_merge($methods, array( 'setNamingStrategy' => new Reference($entityManager['naming_strategy']), 'setQuoteStrategy' => new Reference($entityManager['quote_strategy']), )); } if (version_compare(Version::VERSION, "2.4.0-DEV") >= 0) { $methods = array_merge($methods, array( 'setEntityListenerResolver' => new Reference(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name'])), )); } if (version_compare(Version::VERSION, "2.5.0-DEV") >= 0) { $listenerId = sprintf('doctrine.orm.%s_listeners.attach_entity_listeners', $entityManager['name']); $listenerDef = $container->setDefinition($listenerId, new Definition('%doctrine.orm.listeners.attach_entity_listeners.class%')); $listenerDef->addTag('doctrine.event_listener', array('event' => 'loadClassMetadata')); } if (isset($entityManager['second_level_cache'])) { $this->loadOrmSecondLevelCache($entityManager, $ormConfigDef, $container); } if ($entityManager['repository_factory']) { $methods['setRepositoryFactory'] = new Reference($entityManager['repository_factory']); } foreach ($methods as $method => $arg) { $ormConfigDef->addMethodCall($method, array($arg)); } foreach ($entityManager['hydrators'] as $name => $class) { $ormConfigDef->addMethodCall('addCustomHydrationMode', array($name, $class)); } if (!empty($entityManager['dql'])) { foreach ($entityManager['dql']['string_functions'] as $name => $function) { $ormConfigDef->addMethodCall('addCustomStringFunction', array($name, $function)); } foreach ($entityManager['dql']['numeric_functions'] as $name => $function) { $ormConfigDef->addMethodCall('addCustomNumericFunction', array($name, $function)); } foreach ($entityManager['dql']['datetime_functions'] as $name => $function) { $ormConfigDef->addMethodCall('addCustomDatetimeFunction', array($name, $function)); } } $enabledFilters = array(); $filtersParameters = array(); foreach ($entityManager['filters'] as $name => $filter) { $ormConfigDef->addMethodCall('addFilter', array($name, $filter['class'])); if ($filter['enabled']) { $enabledFilters[] = $name; } if ($filter['parameters']) { $filtersParameters[$name] = $filter['parameters']; } } $managerConfiguratorName = sprintf('doctrine.orm.%s_manager_configurator', $entityManager['name']); $container ->setDefinition($managerConfiguratorName, new DefinitionDecorator('doctrine.orm.manager_configurator.abstract')) ->replaceArgument(0, $enabledFilters) ->replaceArgument(1, $filtersParameters) ; if (!isset($entityManager['connection'])) { $entityManager['connection'] = $this->defaultConnection; } $container ->setDefinition(sprintf('doctrine.orm.%s_entity_manager', $entityManager['name']), new DefinitionDecorator('doctrine.orm.entity_manager.abstract')) ->setArguments(array( new Reference(sprintf('doctrine.dbal.%s_connection', $entityManager['connection'])), new Reference(sprintf('doctrine.orm.%s_configuration', $entityManager['name'])), )) ->setConfigurator(array(new Reference($managerConfiguratorName), 'configure')) ; $container->setAlias( sprintf('doctrine.orm.%s_entity_manager.event_manager', $entityManager['name']), new Alias(sprintf('doctrine.dbal.%s_connection.event_manager', $entityManager['connection']), false) ); if (isset($entityManager['entity_listeners'])) { if (!isset($listenerDef)) { throw new InvalidArgumentException('Entity listeners configuration requires doctrine-orm 2.5.0 or newer'); } $entities = $entityManager['entity_listeners']['entities']; foreach ($entities as $entityListenerClass => $entity) { foreach ($entity['listeners'] as $listenerClass => $listener) { foreach ($listener['events'] as $listenerEvent) { $listenerEventName = $listenerEvent['type']; $listenerMethod = $listenerEvent['method']; $listenerDef->addMethodCall('addEntityListener', array( $entityListenerClass, $listenerClass, $listenerEventName, $listenerMethod, )); } } } } } /** * Loads an ORM entity 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: Entities/ } * MyBundle4: { type: xml, dir: Resources/config/doctrine/mapping } * MyBundle5: * type: yml * dir: bundle-mappings/ * alias: BundleAlias * arbitrary_key: * type: xml * dir: %kernel.root_dir%/../src/vendor/DoctrineExtensions/lib/DoctrineExtensions/Entities * prefix: DoctrineExtensions\Entities\ * 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 $entityManager A configured ORM entity manager * @param Definition $ormConfigDef A Definition instance * @param ContainerBuilder $container A ContainerBuilder instance */ protected function loadOrmEntityManagerMappingInformation(array $entityManager, Definition $ormConfigDef, 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($entityManager, $container); $this->registerMappingDrivers($entityManager, $container); $ormConfigDef->addMethodCall('setEntityNamespaces', array($this->aliasMap)); } /** * Loads an ORM second level cache bundle mapping information. * * @example * entity_managers: * default: * second_level_cache: * region_cache_driver: apc * log_enabled: true * regions: * my_service_region: * type: service * service : "my_service_region" * * my_query_region: * lifetime: 300 * cache_driver: array * type: filelock * * my_entity_region: * lifetime: 600 * cache_driver: * type: apc * * @param array $entityManager A configured ORM entity manager * @param Definition $ormConfigDef A Definition instance * @param ContainerBuilder $container A ContainerBuilder instance */ protected function loadOrmSecondLevelCache(array $entityManager, Definition $ormConfigDef, ContainerBuilder $container) { if (version_compare(Version::VERSION, '2.5.0-DEV') < 0) { throw new \InvalidArgumentException('Second-level cache requires doctrine-orm 2.5.0 or newer'); } $driverId = null; $enabled = $entityManager['second_level_cache']['enabled']; if (isset($entityManager['second_level_cache']['region_cache_driver'])) { $driverName = 'second_level_cache.region_cache_driver'; $driverMap = $entityManager['second_level_cache']['region_cache_driver']; $driverId = $this->loadCacheDriver($driverName, $entityManager['name'], $driverMap, $container); } $configId = sprintf('doctrine.orm.%s_second_level_cache.cache_configuration', $entityManager['name']); $regionsId = sprintf('doctrine.orm.%s_second_level_cache.regions_configuration', $entityManager['name']); $driverId = $driverId ?: sprintf('doctrine.orm.%s_second_level_cache.region_cache_driver', $entityManager['name']); $configDef = $container->setDefinition($configId, new Definition('%doctrine.orm.second_level_cache.cache_configuration.class%')); $regionsDef = $container->setDefinition($regionsId, new Definition('%doctrine.orm.second_level_cache.regions_configuration.class%')); $slcFactoryId = sprintf('doctrine.orm.%s_second_level_cache.default_cache_factory', $entityManager['name']); $slcFactoryDef = $container ->setDefinition($slcFactoryId, new Definition('%doctrine.orm.second_level_cache.default_cache_factory.class%')) ->setArguments(array(new Reference($regionsId), new Reference($driverId))); if (isset($entityManager['second_level_cache']['regions'])) { foreach ($entityManager['second_level_cache']['regions'] as $name => $region) { $regionRef = null; $regionType = $region['type']; if ($regionType === 'service') { $regionId = sprintf('doctrine.orm.%s_second_level_cache.region.%s', $entityManager['name'], $name); $regionRef = new Reference($region['service']); $container->setAlias($regionId, new Alias($region['service'], false)); } if ($regionType === 'default' || $regionType === 'filelock') { $regionId = sprintf('doctrine.orm.%s_second_level_cache.region.%s', $entityManager['name'], $name); $driverName = sprintf('second_level_cache.region.%s_driver', $name); $driverMap = $region['cache_driver']; $driverId = $this->loadCacheDriver($driverName, $entityManager['name'], $driverMap, $container); $regionRef = new Reference($regionId); $container ->setDefinition($regionId, new Definition('%doctrine.orm.second_level_cache.default_region.class%')) ->setArguments(array($name, new Reference($driverId), $region['lifetime'])); } if ($regionType === 'filelock') { $regionId = sprintf('doctrine.orm.%s_second_level_cache.region.%s_filelock', $entityManager['name'], $name); $container ->setDefinition($regionId, new Definition('%doctrine.orm.second_level_cache.filelock_region.class%')) ->setArguments(array($regionRef, $region['lock_path'], $region['lock_lifetime'])); $regionRef = new Reference($regionId); $regionsDef->addMethodCall('getLockLifetime', array($name, $region['lock_lifetime'])); } $regionsDef->addMethodCall('setLifetime', array($name, $region['lifetime'])); $slcFactoryDef->addMethodCall('setRegion', array($regionRef)); } } if ($entityManager['second_level_cache']['log_enabled']) { $loggerChainId = sprintf('doctrine.orm.%s_second_level_cache.logger_chain', $entityManager['name']); $loggerStatsId = sprintf('doctrine.orm.%s_second_level_cache.logger_statistics', $entityManager['name']); $loggerChaingDef = $container->setDefinition($loggerChainId, new Definition('%doctrine.orm.second_level_cache.logger_chain.class%')); $loggerStatsDef = $container->setDefinition($loggerStatsId, new Definition('%doctrine.orm.second_level_cache.logger_statistics.class%')); $loggerChaingDef->addMethodCall('setLogger', array('statistics', $loggerStatsDef)); $configDef->addMethodCall('setCacheLogger', array($loggerChaingDef)); foreach ($entityManager['second_level_cache']['loggers'] as $name => $logger) { $loggerId = sprintf('doctrine.orm.%s_second_level_cache.logger.%s', $entityManager['name'], $name); $loggerRef = new Reference($logger['service']); $container->setAlias($loggerId, new Alias($logger['service'], false)); $loggerChaingDef->addMethodCall('setLogger', array($name, $loggerRef)); } } $configDef->addMethodCall('setCacheFactory', array($slcFactoryDef)); $configDef->addMethodCall('setRegionsConfiguration', array($regionsDef)); $ormConfigDef->addMethodCall('setSecondLevelCacheEnabled', array($enabled)); $ormConfigDef->addMethodCall('setSecondLevelCacheConfiguration', array($configDef)); } /** * {@inheritDoc} */ protected function getObjectManagerElementName($name) { return 'doctrine.orm.'.$name; } protected function getMappingObjectDefaultName() { return 'Entity'; } /** * {@inheritDoc} */ protected function getMappingResourceConfigDirectory() { return 'Resources/config/doctrine'; } /** * {@inheritDoc} */ protected function getMappingResourceExtension() { return 'orm'; } /** * {@inheritDoc} */ protected function loadCacheDriver($driverName, $entityManagerName, array $driverMap, ContainerBuilder $container) { if (!empty($driverMap['cache_provider'])) { $aliasId = $this->getObjectManagerElementName(sprintf('%s_%s', $entityManagerName, $driverName)); $serviceId = sprintf('doctrine_cache.providers.%s', $driverMap['cache_provider']); $container->setAlias($aliasId, new Alias($serviceId, false)); return $aliasId; } return $this->adapter->loadCacheDriver($driverName, $entityManagerName, $driverMap, $container); } /** * Loads a configured entity managers cache drivers. * * @param array $entityManager A configured ORM entity manager. * @param ContainerBuilder $container A ContainerBuilder instance */ protected function loadOrmCacheDrivers(array $entityManager, ContainerBuilder $container) { $this->loadCacheDriver('metadata_cache', $entityManager['name'], $entityManager['metadata_cache_driver'], $container); $this->loadCacheDriver('result_cache', $entityManager['name'], $entityManager['result_cache_driver'], $container); $this->loadCacheDriver('query_cache', $entityManager['name'], $entityManager['query_cache_driver'], $container); } /** * @param array $objectManager * @param ContainerBuilder $container * @param string $cacheName */ public function loadObjectManagerCacheDriver(array $objectManager, ContainerBuilder $container, $cacheName) { $this->loadCacheDriver($cacheName, $objectManager['name'], $objectManager[$cacheName.'_driver'], $container); } /** * {@inheritDoc} */ public function getXsdValidationBasePath() { return __DIR__.'/../Resources/config/schema'; } /** * {@inheritDoc} */ public function getNamespace() { return 'http://symfony.com/schema/dic/doctrine'; } /** * {@inheritDoc} */ public function getConfiguration(array $config, ContainerBuilder $container) { return new Configuration($container->getParameter('kernel.debug')); } } DoctrineBundle-1.6.2/DoctrineBundle.php000066400000000000000000000136731264451145000200470ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle; use Doctrine\Common\Util\ClassUtils; use Doctrine\Bundle\DoctrineBundle\Command\CreateDatabaseDoctrineCommand; use Doctrine\Bundle\DoctrineBundle\Command\DropDatabaseDoctrineCommand; use Doctrine\Bundle\DoctrineBundle\Command\Proxy\RunSqlDoctrineCommand; use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\EntityListenerPass; use Doctrine\ORM\Proxy\Autoloader; use Symfony\Component\Console\Application; use Symfony\Component\DependencyInjection\Compiler\PassConfig; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\IntrospectableContainerInterface; use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\DoctrineValidationPass; use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\RegisterEventListenersAndSubscribersPass; use Symfony\Bridge\Doctrine\DependencyInjection\Security\UserProvider\EntityFactory; /** * Bundle. * * @author Fabien Potencier * @author Jonathan H. Wage */ class DoctrineBundle extends Bundle { private $autoloader; /** * {@inheritDoc} */ public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new RegisterEventListenersAndSubscribersPass('doctrine.connections', 'doctrine.dbal.%s_connection.event_manager', 'doctrine'), PassConfig::TYPE_BEFORE_OPTIMIZATION); if ($container->hasExtension('security')) { $container->getExtension('security')->addUserProviderFactory(new EntityFactory('entity', 'doctrine.orm.security.user.provider')); } $container->addCompilerPass(new DoctrineValidationPass('orm')); $container->addCompilerPass(new EntityListenerPass()); } /** * {@inheritDoc} */ public function boot() { // Register an autoloader for proxies to avoid issues when unserializing them // when the ORM is used. if ($this->container->hasParameter('doctrine.orm.proxy_namespace')) { $namespace = $this->container->getParameter('doctrine.orm.proxy_namespace'); $dir = $this->container->getParameter('doctrine.orm.proxy_dir'); $proxyGenerator = null; if ($this->container->getParameter('doctrine.orm.auto_generate_proxy_classes')) { // See https://github.com/symfony/symfony/pull/3419 for usage of references $container = &$this->container; $proxyGenerator = function ($proxyDir, $proxyNamespace, $class) use (&$container) { $originalClassName = ClassUtils::getRealClass($class); /** @var $registry Registry */ $registry = $container->get('doctrine'); // Tries to auto-generate the proxy file /** @var $em \Doctrine\ORM\EntityManager */ foreach ($registry->getManagers() as $em) { if (!$em->getConfiguration()->getAutoGenerateProxyClasses()) { continue; } $metadataFactory = $em->getMetadataFactory(); if ($metadataFactory->isTransient($originalClassName)) { continue; } $classMetadata = $metadataFactory->getMetadataFor($originalClassName); $em->getProxyFactory()->generateProxyClasses(array($classMetadata)); clearstatcache(true, Autoloader::resolveFile($proxyDir, $proxyNamespace, $class)); break; } }; } $this->autoloader = Autoloader::register($dir, $namespace, $proxyGenerator); } } /** * {@inheritDoc} */ public function shutdown() { if (null !== $this->autoloader) { spl_autoload_unregister($this->autoloader); $this->autoloader = null; } // Clear all entity managers to clear references to entities for GC if ($this->container->hasParameter('doctrine.entity_managers')) { foreach ($this->container->getParameter('doctrine.entity_managers') as $id) { if (!$this->container instanceof IntrospectableContainerInterface || $this->container->initialized($id)) { $this->container->get($id)->clear(); } } } // Close all connections to avoid reaching too many connections in the process when booting again later (tests) if ($this->container->hasParameter('doctrine.connections')) { foreach ($this->container->getParameter('doctrine.connections') as $id) { if (!$this->container instanceof IntrospectableContainerInterface || $this->container->initialized($id)) { $this->container->get($id)->close(); } } } } /** * {@inheritDoc} */ public function registerCommands(Application $application) { // Use the default logic when the ORM is available. // This avoids listing all ORM commands by hand. if (class_exists('Doctrine\\ORM\\Version')) { parent::registerCommands($application); return; } // Register only the DBAL commands if the ORM is not available. $application->add(new CreateDatabaseDoctrineCommand()); $application->add(new DropDatabaseDoctrineCommand()); $application->add(new RunSqlDoctrineCommand()); } } DoctrineBundle-1.6.2/LICENSE000066400000000000000000000020661264451145000154340ustar00rootroot00000000000000Copyright (c) 2011 Fabien Potencier, Doctrine Project Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. DoctrineBundle-1.6.2/ManagerConfigurator.php000066400000000000000000000042321264451145000210720ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle; use Doctrine\ORM\EntityManager; use Doctrine\ORM\Query\Filter\SQLFilter; /** * Configurator for an EntityManager * * @author Christophe Coevoet */ class ManagerConfigurator { private $enabledFilters = array(); private $filtersParameters = array(); public function __construct(array $enabledFilters, array $filtersParameters) { $this->enabledFilters = $enabledFilters; $this->filtersParameters = $filtersParameters; } /** * Create a connection by name. * * @param EntityManager $entityManager */ public function configure(EntityManager $entityManager) { $this->enableFilters($entityManager); } /** * Enables filters for a given entity manager * * @param EntityManager $entityManager */ private function enableFilters(EntityManager $entityManager) { if (empty($this->enabledFilters)) { return; } $filterCollection = $entityManager->getFilters(); foreach ($this->enabledFilters as $filter) { $filterObject = $filterCollection->enable($filter); if (null !== $filterObject) { $this->setFilterParameters($filter, $filterObject); } } } /** * Sets default parameters for a given filter * * @param string $name Filter name * @param SQLFilter $filter Filter object */ private function setFilterParameters($name, SQLFilter $filter) { if (!empty($this->filtersParameters[$name])) { $parameters = $this->filtersParameters[$name]; foreach ($parameters as $paramName => $paramValue) { $filter->setParameter($paramName, $paramValue); } } } } DoctrineBundle-1.6.2/Mapping/000077500000000000000000000000001264451145000160165ustar00rootroot00000000000000DoctrineBundle-1.6.2/Mapping/ClassMetadataCollection.php000066400000000000000000000025211264451145000232510ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Mapping; /** * @author Fabien Potencier */ class ClassMetadataCollection { private $path; private $namespace; private $metadata; /** * Constructor * * @param array $metadata */ public function __construct(array $metadata) { $this->metadata = $metadata; } /** * @return array */ public function getMetadata() { return $this->metadata; } /** * @param string $path */ public function setPath($path) { $this->path = $path; } /** * @return string */ public function getPath() { return $this->path; } /** * @param string $namespace */ public function setNamespace($namespace) { $this->namespace = $namespace; } /** * @return string */ public function getNamespace() { return $this->namespace; } } DoctrineBundle-1.6.2/Mapping/DisconnectedMetadataFactory.php000066400000000000000000000151221264451145000241230ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Mapping; use Doctrine\Common\Persistence\ManagerRegistry; use Doctrine\ORM\Mapping\MappingException; use Doctrine\ORM\Tools\DisconnectedClassMetadataFactory; use Symfony\Component\HttpKernel\Bundle\BundleInterface; /** * This class provides methods to access Doctrine entity class metadata for a * given bundle, namespace or entity class, for generation purposes * * @author Fabien Potencier */ class DisconnectedMetadataFactory { private $registry; /** * Constructor. * * @param ManagerRegistry $registry A ManagerRegistry instance */ public function __construct(ManagerRegistry $registry) { $this->registry = $registry; } /** * Gets the metadata of all classes of a bundle. * * @param BundleInterface $bundle A BundleInterface instance * * @return ClassMetadataCollection A ClassMetadataCollection instance * * @throws \RuntimeException When bundle does not contain mapped entities */ public function getBundleMetadata(BundleInterface $bundle) { $namespace = $bundle->getNamespace(); $metadata = $this->getMetadataForNamespace($namespace); if (!$metadata->getMetadata()) { throw new \RuntimeException(sprintf('Bundle "%s" does not contain any mapped entities.', $bundle->getName())); } $path = $this->getBasePathForClass($bundle->getName(), $bundle->getNamespace(), $bundle->getPath()); $metadata->setPath($path); $metadata->setNamespace($bundle->getNamespace()); return $metadata; } /** * Gets the metadata of a class. * * @param string $class A class name * @param string $path The path where the class is stored (if known) * * @return ClassMetadataCollection A ClassMetadataCollection instance * * @throws MappingException When class is not valid entity or mapped superclass */ public function getClassMetadata($class, $path = null) { $metadata = $this->getMetadataForClass($class); if (!$metadata->getMetadata()) { throw MappingException::classIsNotAValidEntityOrMappedSuperClass($class); } $this->findNamespaceAndPathForMetadata($metadata, $path); return $metadata; } /** * Gets the metadata of all classes of a namespace. * * @param string $namespace A namespace name * @param string $path The path where the class is stored (if known) * * @return ClassMetadataCollection A ClassMetadataCollection instance * * @throws \RuntimeException When namespace not contain mapped entities */ public function getNamespaceMetadata($namespace, $path = null) { $metadata = $this->getMetadataForNamespace($namespace); if (!$metadata->getMetadata()) { throw new \RuntimeException(sprintf('Namespace "%s" does not contain any mapped entities.', $namespace)); } $this->findNamespaceAndPathForMetadata($metadata, $path); return $metadata; } /** * Find and configure path and namespace for the metadata collection. * * @param ClassMetadataCollection $metadata * @param string|null $path * * @throws \RuntimeException When unable to determine the path */ public function findNamespaceAndPathForMetadata(ClassMetadataCollection $metadata, $path = null) { $all = $metadata->getMetadata(); if (class_exists($all[0]->name)) { $r = new \ReflectionClass($all[0]->name); $path = $this->getBasePathForClass($r->getName(), $r->getNamespaceName(), dirname($r->getFilename())); $ns = $r->getNamespaceName(); } elseif ($path) { // Get namespace by removing the last component of the FQCN $nsParts = explode('\\', $all[0]->name); array_pop($nsParts); $ns = implode('\\', $nsParts); } else { throw new \RuntimeException(sprintf('Unable to determine where to save the "%s" class (use the --path option).', $all[0]->name)); } $metadata->setPath($path); $metadata->setNamespace($ns); } /** * Get a base path for a class * * @param string $name class name * @param string $namespace class namespace * @param string $path class path * * @return string * @throws \RuntimeException When base path not found */ private function getBasePathForClass($name, $namespace, $path) { $namespace = str_replace('\\', '/', $namespace); $search = str_replace('\\', '/', $path); $destination = str_replace('/'.$namespace, '', $search, $c); if ($c != 1) { throw new \RuntimeException(sprintf('Can\'t find base path for "%s" (path: "%s", destination: "%s").', $name, $path, $destination)); } return $destination; } /** * @param string $namespace * * @return ClassMetadataCollection */ private function getMetadataForNamespace($namespace) { $metadata = array(); foreach ($this->getAllMetadata() as $m) { if (strpos($m->name, $namespace) === 0) { $metadata[] = $m; } } return new ClassMetadataCollection($metadata); } /** * @param string $entity * * @return ClassMetadataCollection */ private function getMetadataForClass($entity) { foreach ($this->registry->getManagers() as $em) { $cmf = new DisconnectedClassMetadataFactory(); $cmf->setEntityManager($em); if (!$cmf->isTransient($entity)) { return new ClassMetadataCollection(array($cmf->getMetadataFor($entity))); } } return new ClassMetadataCollection(array()); } /** * @return array */ private function getAllMetadata() { $metadata = array(); foreach ($this->registry->getManagers() as $em) { $cmf = new DisconnectedClassMetadataFactory(); $cmf->setEntityManager($em); foreach ($cmf->getAllMetadata() as $m) { $metadata[] = $m; } } return $metadata; } } DoctrineBundle-1.6.2/README.md000066400000000000000000000025101264451145000157000ustar00rootroot00000000000000# Doctrine Bundle Doctrine DBAL & ORM Bundle for the Symfony Framework. Build Status: [![Build Status](https://secure.travis-ci.org/doctrine/DoctrineBundle.png?branch=master)](http://travis-ci.org/doctrine/DoctrineBundle) ## What is Doctrine? The Doctrine Project is the home of a selected set of PHP libraries primarily focused on providing persistence services and related functionality. Its prize projects are a Object Relational Mapper and the Database Abstraction Layer it is built on top of. You can read more about the projects below or view a list of all projects. Object relational mapper (ORM) for PHP that sits on top of a powerful database abstraction layer (DBAL). One of its key features is the option to write database queries in a proprietary object oriented SQL dialect called Doctrine Query Language (DQL), inspired by Hibernates HQL. This provides developers with a powerful alternative to SQL that maintains flexibility without requiring unnecessary code duplication. DBAL is a powerful database abstraction layer with many features for database schema introspection, schema management and PDO abstraction. ## Documentation The documentation is rendered on [the symfony.com website](http://symfony.com/doc/master/bundles/DoctrineBundle/index.html). The source of the documentation is available in the Resources/docs folder. DoctrineBundle-1.6.2/Registry.php000066400000000000000000000130051264451145000167430ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Bridge\Doctrine\RegistryInterface; use Symfony\Bridge\Doctrine\ManagerRegistry; use Doctrine\ORM\ORMException; use Doctrine\ORM\EntityManager; /** * References all Doctrine connections and entity managers in a given Container. * * @author Fabien Potencier */ class Registry extends ManagerRegistry implements RegistryInterface { /** * Construct. * * @param ContainerInterface $container * @param array $connections * @param array $entityManagers * @param string $defaultConnection * @param string $defaultEntityManager */ public function __construct(ContainerInterface $container, array $connections, array $entityManagers, $defaultConnection, $defaultEntityManager) { $this->setContainer($container); parent::__construct('ORM', $connections, $entityManagers, $defaultConnection, $defaultEntityManager, 'Doctrine\ORM\Proxy\Proxy'); } /** * Gets the default entity manager name. * * @return string The default entity manager name * * @deprecated */ public function getDefaultEntityManagerName() { trigger_error('getDefaultEntityManagerName is deprecated since Symfony 2.1. Use getDefaultManagerName instead', E_USER_DEPRECATED); return $this->getDefaultManagerName(); } /** * Gets a named entity manager. * * @param string $name The entity manager name (null for the default one) * * @return EntityManager * * @deprecated */ public function getEntityManager($name = null) { trigger_error('getEntityManager is deprecated since Symfony 2.1. Use getManager instead', E_USER_DEPRECATED); return $this->getManager($name); } /** * Gets an array of all registered entity managers * * @return EntityManager[] an array of all EntityManager instances * * @deprecated */ public function getEntityManagers() { trigger_error('getEntityManagers is deprecated since Symfony 2.1. Use getManagers instead', E_USER_DEPRECATED); return $this->getManagers(); } /** * Resets a named entity manager. * * This method is useful when an entity manager has been closed * because of a rollbacked transaction AND when you think that * it makes sense to get a new one to replace the closed one. * * Be warned that you will get a brand new entity manager as * the existing one is not useable anymore. This means that any * other object with a dependency on this entity manager will * hold an obsolete reference. You can inject the registry instead * to avoid this problem. * * @param string $name The entity manager name (null for the default one) * * @return EntityManager * * @deprecated */ public function resetEntityManager($name = null) { trigger_error('resetEntityManager is deprecated since Symfony 2.1. Use resetManager instead', E_USER_DEPRECATED); $this->resetManager($name); } /** * Resolves a registered namespace alias to the full namespace. * * This method looks for the alias in all registered entity managers. * * @param string $alias The alias * * @return string The full namespace * * @deprecated */ public function getEntityNamespace($alias) { trigger_error('getEntityNamespace is deprecated since Symfony 2.1. Use getAliasNamespace instead', E_USER_DEPRECATED); return $this->getAliasNamespace($alias); } /** * Resolves a registered namespace alias to the full namespace. * * This method looks for the alias in all registered entity managers. * * @param string $alias The alias * * @return string The full namespace * * @see Configuration::getEntityNamespace */ public function getAliasNamespace($alias) { foreach (array_keys($this->getManagers()) as $name) { try { return $this->getManager($name)->getConfiguration()->getEntityNamespace($alias); } catch (ORMException $e) { } } throw ORMException::unknownEntityNamespace($alias); } /** * Gets all connection names. * * @return array An array of connection names * * @deprecated */ public function getEntityManagerNames() { trigger_error('getEntityManagerNames is deprecated since Symfony 2.1. Use getManagerNames instead', E_USER_DEPRECATED); return $this->getManagerNames(); } /** * Gets the entity manager associated with a given class. * * @param string $class A Doctrine Entity class name * * @return EntityManager|null * * @deprecated */ public function getEntityManagerForClass($class) { trigger_error('getEntityManagerForClass is deprecated since Symfony 2.1. Use getManagerForClass instead', E_USER_DEPRECATED); return $this->getManagerForClass($class); } } DoctrineBundle-1.6.2/Resources/000077500000000000000000000000001264451145000163755ustar00rootroot00000000000000DoctrineBundle-1.6.2/Resources/config/000077500000000000000000000000001264451145000176425ustar00rootroot00000000000000DoctrineBundle-1.6.2/Resources/config/dbal.xml000066400000000000000000000075241264451145000212760ustar00rootroot00000000000000 Doctrine\DBAL\Logging\LoggerChain Doctrine\DBAL\Logging\DebugStack Symfony\Bridge\Doctrine\Logger\DbalLogger Doctrine\DBAL\Configuration Doctrine\Bundle\DoctrineBundle\DataCollector\DoctrineDataCollector Symfony\Bridge\Doctrine\ContainerAwareEventManager Doctrine\Bundle\DoctrineBundle\ConnectionFactory Doctrine\DBAL\Event\Listeners\MysqlSessionInit Doctrine\DBAL\Event\Listeners\OracleSessionInit Doctrine\Bundle\DoctrineBundle\Registry %doctrine.dbal.connection_factory.types% %doctrine.connections% %doctrine.entity_managers% %doctrine.default_connection% %doctrine.default_entity_manager% DoctrineBundle-1.6.2/Resources/config/orm.xml000066400000000000000000000210571264451145000211660ustar00rootroot00000000000000 Doctrine\ORM\Configuration Doctrine\ORM\EntityManager Doctrine\Bundle\DoctrineBundle\ManagerConfigurator Doctrine\Common\Cache\ArrayCache Doctrine\Common\Cache\ApcCache Doctrine\Common\Cache\MemcacheCache localhost 11211 Memcache Doctrine\Common\Cache\MemcachedCache localhost 11211 Memcached Doctrine\Common\Cache\RedisCache localhost 6379 Redis Doctrine\Common\Cache\XcacheCache Doctrine\Common\Cache\WinCacheCache Doctrine\Common\Cache\ZendDataCache Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain Doctrine\ORM\Mapping\Driver\AnnotationDriver Doctrine\ORM\Mapping\Driver\SimplifiedXmlDriver Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver Doctrine\ORM\Mapping\Driver\PHPDriver Doctrine\ORM\Mapping\Driver\StaticPHPDriver Symfony\Bridge\Doctrine\CacheWarmer\ProxyCacheWarmer Symfony\Bridge\Doctrine\Form\DoctrineOrmTypeGuesser Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator Symfony\Bridge\Doctrine\Validator\DoctrineInitializer Symfony\Bridge\Doctrine\Security\User\EntityUserProvider Doctrine\ORM\Tools\ResolveTargetEntityListener Doctrine\ORM\Tools\AttachEntityListenersListener Doctrine\ORM\Mapping\DefaultNamingStrategy Doctrine\ORM\Mapping\UnderscoreNamingStrategy Doctrine\ORM\Mapping\DefaultQuoteStrategy Doctrine\ORM\Mapping\AnsiQuoteStrategy Doctrine\ORM\Mapping\DefaultEntityListenerResolver Doctrine\ORM\Cache\DefaultCacheFactory Doctrine\ORM\Cache\Region\DefaultRegion Doctrine\ORM\Cache\Region\FileLockRegion Doctrine\ORM\Cache\Logging\CacheLoggerChain Doctrine\ORM\Cache\Logging\StatisticsCacheLogger Doctrine\ORM\Cache\CacheConfiguration Doctrine\ORM\Cache\RegionsConfiguration DoctrineBundle-1.6.2/Resources/config/schema/000077500000000000000000000000001264451145000211025ustar00rootroot00000000000000DoctrineBundle-1.6.2/Resources/config/schema/doctrine-1.0.xsd000066400000000000000000000312701264451145000237300ustar00rootroot00000000000000 DoctrineBundle-1.6.2/Resources/doc/000077500000000000000000000000001264451145000171425ustar00rootroot00000000000000DoctrineBundle-1.6.2/Resources/doc/configuration.rst000066400000000000000000001323431264451145000225510ustar00rootroot00000000000000.. index:: single: Doctrine; ORM Configuration Reference single: Configuration Reference; Doctrine ORM Configuration Reference ======================= .. configuration-block:: .. code-block:: yaml doctrine: dbal: default_connection: default # A collection of custom types types: # example some_custom_type: class: Acme\HelloBundle\MyCustomType commented: true connections: # A collection of different named connections (e.g. default, conn2, etc) default: dbname: ~ host: localhost port: ~ user: root password: ~ charset: "UTF8" # SQLite specific path: ~ # SQLite specific memory: ~ # MySQL specific. The unix socket to use for MySQL unix_socket: ~ # IBM DB2 specific. True to use as persistent connection for the ibm_db2 driver persistent: ~ # IBM DB2 specific. The protocol to use for the ibm_db2 driver (default to TCPIP if omitted) protocol: ~ # Oracle specific. True to use SERVICE_NAME as connection parameter instead of SID for Oracle service: ~ # Oracle specific. Overrules dbname parameter if given and used as SERVICE_NAME or SID connection # parameter for Oracle depending on the service parameter. servicename: ~ # oci8 driver specific. The session mode to use for the oci8 driver. sessionMode: ~ # SQL Anywhere specific (ServerName). The name of a running database server to connect to for SQL Anywhere. server: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLMODE). # Determines whether or with what priority a SSL TCP/IP connection will be negotiated with the server for PostgreSQL. sslmode: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLROOTCERT). # The name of a file containing SSL certificate authority (CA) certificate(s). # If the file exists, the server's certificate will be verified to be signed by one of these authorities. sslrootcert: ~ # Oracle specific (SERVER=POOLED). True to use a pooled server with the oci8/pdo_oracle driver pooled: ~ # pdo_sqlsrv driver specific. Configuring MultipleActiveResultSets for the pdo_sqlsrv driver MultipleActiveResultSets: ~ # Enable savepoints for nested transactions use_savepoints: true driver: pdo_mysql platform_service: ~ auto_commit: ~ # If set to "^sf2_" all tables not prefixed with "sf2_" will be ignored by the schema # tool. This is for custom tables which should not be altered automatically. schema_filter: ~ # When true, queries are logged to a "doctrine" monolog channel logging: "%kernel.debug%" profiling: "%kernel.debug%" server_version: ~ driver_class: ~ wrapper_class: ~ shard_choser: ~ shard_choser_service: ~ keep_slave: ~ # An array of options options: # example # key: value # An array of mapping types mapping_types: # example # enum: string default_table_options: # Affects schema-tool. If absent, DBAL chooses defaults # based on the platform. Examples here are for MySQL. # charset: utf8 # collate: utf8_unicode_ci # engine: InnoDB slaves: # A collection of named slave connections (e.g. slave1, slave2) slave1: dbname: ~ host: localhost port: ~ user: root password: ~ charset: ~ path: ~ memory: ~ # MySQL specific. The unix socket to use for MySQL unix_socket: ~ # IBM DB2 specific. True to use as persistent connection for the ibm_db2 driver persistent: ~ # IBM DB2 specific. The protocol to use for the ibm_db2 driver (default to TCPIP if omitted) protocol: ~ # Oracle specific. True to use SERVICE_NAME as connection parameter instead of SID for Oracle service: ~ # Oracle specific. Overrules dbname parameter if given and used as SERVICE_NAME or SID connection # parameter for Oracle depending on the service parameter. servicename: ~ # oci8 driver specific. The session mode to use for the oci8 driver. sessionMode: ~ # SQL Anywhere specific (ServerName). The name of a running database server to connect to for SQL Anywhere. server: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLMODE). # Determines whether or with what priority a SSL TCP/IP connection will be negotiated with the server for PostgreSQL. sslmode: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLROOTCERT). # The name of a file containing SSL certificate authority (CA) certificate(s). # If the file exists, the server's certificate will be verified to be signed by one of these authorities. sslrootcert: ~ # Oracle specific (SERVER=POOLED). True to use a pooled server with the oci8/pdo_oracle driver pooled: ~ # pdo_sqlsrv driver specific. Configuring MultipleActiveResultSets for the pdo_sqlsrv driver MultipleActiveResultSets: ~ shards: id: ~ # Required dbname: ~ host: localhost port: ~ user: root password: ~ charset: ~ path: ~ memory: ~ # MySQL specific. The unix socket to use for MySQL unix_socket: ~ # IBM DB2 specific. True to use as persistent connection for the ibm_db2 driver persistent: ~ # IBM DB2 specific. The protocol to use for the ibm_db2 driver (default to TCPIP if omitted) protocol: ~ # Oracle specific. True to use SERVICE_NAME as connection parameter instead of SID for Oracle service: ~ # Oracle specific. Overrules dbname parameter if given and used as SERVICE_NAME or SID connection # parameter for Oracle depending on the service parameter. servicename: ~ # oci8 driver specific. The session mode to use for the oci8 driver. sessionMode: ~ # SQL Anywhere specific (ServerName). The name of a running database server to connect to for SQL Anywhere. server: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLMODE). # Determines whether or with what priority a SSL TCP/IP connection will be negotiated with the server for PostgreSQL. sslmode: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLROOTCERT). # The name of a file containing SSL certificate authority (CA) certificate(s). # If the file exists, the server's certificate will be verified to be signed by one of these authorities. sslrootcert: ~ # Oracle specific (SERVER=POOLED). True to use a pooled server with the oci8/pdo_oracle driver pooled: ~ # pdo_sqlsrv driver specific. Configuring MultipleActiveResultSets for the pdo_sqlsrv driver MultipleActiveResultSets: ~ orm: default_entity_manager: ~ # The first defined is used if not set # Auto generate mode possible values are: "NEVER", "ALWAYS", "FILE_NOT_EXISTS", "EVAL" auto_generate_proxy_classes: false proxy_dir: "%kernel.cache_dir%/doctrine/orm/Proxies" proxy_namespace: Proxies entity_managers: # A collection of different named entity managers (e.g. some_em, another_em) some_em: query_cache_driver: type: array host: ~ port: ~ instance_class: ~ class: ~ id: ~ namespace: ~ cache_provider: ~ metadata_cache_driver: type: array host: ~ port: ~ instance_class: ~ class: ~ id: ~ namespace: ~ cache_provider: ~ result_cache_driver: type: array host: ~ port: ~ instance_class: ~ class: ~ id: ~ namespace: ~ cache_provider: ~ entity_listeners: entities: # example Acme\HelloBundle\Entity\Author: listeners: # example Acme\HelloBundle\EventListener\ExampleListener: events: type: preUpdate method: preUpdate # The name of a DBAL connection (the one marked as default is used if not set) connection: ~ class_metadata_factory_name: Doctrine\ORM\Mapping\ClassMetadataFactory default_repository_class: Doctrine\ORM\EntityRepository auto_mapping: false naming_strategy: doctrine.orm.naming_strategy.default quote_strategy: doctrine.orm.quote_strategy.default entity_listener_resolver: ~ repository_factory: ~ second_level_cache: region_cache_driver: type: array host: ~ port: ~ instance_class: ~ class: ~ id: ~ namespace: ~ cache_provider: ~ region_lock_lifetime: 60 log_enabled: true region_lifetime: 0 enabled: true factory: ~ regions: # Prototype name: cache_driver: type: array host: ~ port: ~ instance_class: ~ class: ~ id: ~ namespace: ~ cache_provider: ~ lock_path: '%kernel.cache_dir%/doctrine/orm/slc/filelock' lock_lifetime: 60 type: default lifetime: 0 service: ~ name: ~ loggers: # Prototype name: name: ~ service: ~ # An array of hydrator names hydrators: # example ListHydrator: Acme\HelloBundle\Hydrators\ListHydrator mappings: # An array of mappings, which may be a bundle name or something else mapping_name: mapping: true type: ~ dir: ~ alias: ~ prefix: ~ is_bundle: ~ dql: # A collection of string functions string_functions: # example # test_string: Acme\HelloBundle\DQL\StringFunction # A collection of numeric functions numeric_functions: # example # test_numeric: Acme\HelloBundle\DQL\NumericFunction # A collection of datetime functions datetime_functions: # example # test_datetime: Acme\HelloBundle\DQL\DatetimeFunction # Register SQL Filters in the entity manager filters: # An array of filters some_filter: class: Acme\HelloBundle\Filter\SomeFilter # Required enabled: false # An array of parameters parameters: # example foo_param: bar_value # Search for the "ResolveTargetEntityListener" class for a cookbook about this resolve_target_entities: # Prototype Acme\InvoiceBundle\Model\InvoiceSubjectInterface: Acme\AppBundle\Entity\Customer .. code-block:: xml value string utf8 utf8_unicode_ci InnoDB Acme\HelloBundle\Hydrators\ListHydrator Acme\HelloBundle\DQL\StringFunction Acme\HelloBundle\DQL\NumericFunction Acme\HelloBundle\DQL\DatetimeFunction bar_value Acme\AppBundle\Entity\Customer Configuration Overview ---------------------- This following configuration example shows all the configuration defaults that the ORM resolves to: .. code-block:: yaml doctrine: orm: auto_mapping: true # the standard distribution overrides this to be true in debug, false otherwise auto_generate_proxy_classes: false proxy_namespace: Proxies proxy_dir: "%kernel.cache_dir%/doctrine/orm/Proxies" default_entity_manager: default metadata_cache_driver: array query_cache_driver: array result_cache_driver: array There are lots of other configuration options that you can use to overwrite certain classes, but those are for very advanced use-cases only. Caching Drivers ~~~~~~~~~~~~~~~ For the caching drivers you can specify the values ``array``, ``apc``, ``memcache``, ``memcached`` or ``xcache``. The following example shows an overview of the caching configurations: .. code-block:: yaml doctrine: orm: auto_mapping: true metadata_cache_driver: apc query_cache_driver: xcache result_cache_driver: type: memcache host: localhost port: 11211 instance_class: Memcache Mapping Configuration ~~~~~~~~~~~~~~~~~~~~~ Explicit definition of all the mapped entities is the only necessary configuration for the ORM and there are several configuration options that you can control. The following configuration options exist for a mapping: ``type`` One of ``annotation``, ``xml``, ``yml``, ``php`` or ``staticphp``. This specifies which type of metadata type your mapping uses. ``dir`` Path to the mapping or entity files (depending on the driver). If this path is relative it is assumed to be relative to the bundle root. This only works if the name of your mapping is a bundle name. If you want to use this option to specify absolute paths you should prefix the path with the kernel parameters that exist in the DIC (for example ``%kernel.root_dir%``). ``prefix`` A common namespace prefix that all entities of this mapping share. This prefix should never conflict with prefixes of other defined mappings otherwise some of your entities cannot be found by Doctrine. This option defaults to the bundle namespace + ``Entity``, for example for an application bundle called ``AcmeHelloBundle`` prefix would be ``Acme\HelloBundle\Entity``. ``alias`` Doctrine offers a way to alias entity namespaces to simpler, shorter names to be used in DQL queries or for Repository access. When using a bundle the alias defaults to the bundle name. ``is_bundle`` This option is a derived value from ``dir`` and by default is set to true if dir is relative proved by a ``file_exists()`` check that returns false. It is false if the existence check returns true. In this case an absolute path was specified and the metadata files are most likely in a directory outside of a bundle. .. index:: single: Configuration; Doctrine DBAL single: Doctrine; DBAL configuration Filters Configuration ~~~~~~~~~~~~~~~~~~~~~ You can easily define `doctrine filters`_ in your configuration file: .. code-block:: yaml doctrine: orm: filters: myFilter: class: MyVendor\MyBundle\Filters\MyFilter enabled: true parameters: myParameter: myValue mySecondParameter: mySecondValue ``myFilter`` Filter identifier (Required) ``class`` Filter target class (Required) ``enabled`` Enable/Disable the filter by default (Optional - Default disabled) ``parameters:`` Set default parameters (Optional) ``myParameter: myValue`` Bind the value ``myValue`` to the parameter ``myParameter`` (Optional) .. _doctrine filters: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/filters.html .. _`reference-dbal-configuration`: Doctrine DBAL Configuration --------------------------- .. note:: DoctrineBundle supports all parameters that default Doctrine drivers accept, converted to the XML or YAML naming standards that Symfony enforces. See the Doctrine `DBAL documentation`_ for more information. .. note:: When specifying a ``url`` parameter, any information extracted from that URL will override explicitly set parameters. An example database URL would be ``mysql://snoopy:redbaron@localhost/baseball``, and any explicitly set driver, user, password and dbname parameter would be overridden by this URL. See the Doctrine `DBAL documentation`_ for more information. Besides default Doctrine options, there are some Symfony-related ones that you can configure. The following block shows all possible configuration keys: .. configuration-block:: .. code-block:: yaml doctrine: dbal: url: mysql://user:secret@localhost:1234/otherdatabase # this would override the values below dbname: database host: localhost port: 1234 user: user password: secret driver: pdo_mysql driver_class: MyNamespace\MyDriverImpl options: foo: bar path: %kernel.data_dir%/data.sqlite # SQLite specific memory: true # SQLite specific unix_socket: /tmp/mysql.sock persistent: true MultipleActiveResultSets: true # pdo_sqlsrv driver specific pooled: true # Oracle specific (SERVER=POOLED) protocol: TCPIP # IBM DB2 specific (PROTOCOL) server: my_database_server # SQL Anywhere specific (ServerName) service: true # Oracle specific (SERVICE_NAME instead of SID) servicename: MyOracleServiceName # Oracle specific (SERVICE_NAME) sessionMode: 2 # oci8 driver specific (session_mode) sslmode: require # PostgreSQL specific (LIBPQ-CONNECT-SSLMODE) sslrootcert: postgresql-ca.pem # PostgreSQL specific (LIBPQ-CONNECT-SSLROOTCERT) wrapper_class: MyDoctrineDbalConnectionWrapper charset: UTF8 logging: %kernel.debug% platform_service: MyOwnDatabasePlatformService auto_commit: false schema_filter: ^sf2_ mapping_types: enum: string types: custom: Acme\HelloBundle\MyCustomType default_table_options: # Affects schema-tool. If absent, DBAL chooses defaults # based on the platform. charset: utf8 collate: utf8_unicode_ci engine: InnoDB .. code-block:: xml dbname="database" host="localhost" port="1234" user="user" password="secret" driver="pdo_mysql" driver-class="MyNamespace\MyDriverImpl" path="%kernel.data_dir%/data.sqlite" memory="true" unix-socket="/tmp/mysql.sock" persistent="true" multiple-active-result-sets="true" pooled="true" protocol="TCPIP" server="my_database_server" service="true" servicename="MyOracleServiceName" sessionMode"2" sslmode="require" sslrootcert="postgresql-ca.pem" wrapper-class="MyDoctrineDbalConnectionWrapper" charset="UTF8" logging="%kernel.debug%" platform-service="MyOwnDatabasePlatformService" auto-commit="false" schema-filter="^sf2_" > bar string utf8 utf8_unicode_ci InnoDB Acme\HelloBundle\MyCustomType If you want to configure multiple connections in YAML, put them under the ``connections`` key and give them a unique name: .. code-block:: yaml doctrine: dbal: default_connection: default connections: default: dbname: Symfony2 user: root password: null host: localhost customer: dbname: customer user: root password: null host: localhost The ``database_connection`` service always refers to the *default* connection, which is the first one defined or the one configured via the ``default_connection`` parameter. Each connection is also accessible via the ``doctrine.dbal.[name]_connection`` service where ``[name]`` if the name of the connection. .. _DBAL documentation: http://www.doctrine-project.org/docs/dbal/2.0/en DoctrineBundle-1.6.2/Resources/doc/entity-listeners.rst000066400000000000000000000021441264451145000232170ustar00rootroot00000000000000Entity Listeners ================ Entity listeners that are services must be registered with the entity listener resolver. You can tag your entity listeners and they will automatically be added to the resolver. Use the entity_manager attribute to specify which entity manager it should be registered with. Example: .. configuration-block:: .. code-block:: yaml services: user_listener: class: \UserListener tags: - { name: doctrine.orm.entity_listener } - { name: doctrine.orm.entity_listener, entity_manager: custom } .. code-block:: xml DoctrineBundle-1.6.2/Resources/doc/index.rst000066400000000000000000000004111264451145000207770ustar00rootroot00000000000000DoctrineBundle ============== Integrates Doctrine's ORM and DBAL projects into Symfony applications. It provides configuration options, console commands and even a web debug toolbar collector. .. toctree:: installation entity-listeners configuration DoctrineBundle-1.6.2/Resources/doc/installation.rst000066400000000000000000000017421264451145000224010ustar00rootroot00000000000000Installation ============ Step 1: Download the Bundle --------------------------- Open a command console, enter your project directory and execute the following command to download the latest stable version of this bundle: .. code-block:: bash $ composer require doctrine/doctrine-bundle This command requires you to have Composer installed globally, as explained in the `installation chapter`_ of the Composer documentation. Step 2: Enable the Bundle ------------------------- Then, enable the bundle by adding the following line in the ``app/AppKernel.php`` file of your project:: 0 or collector.invalidEntityCount > 0 %} {% set profiler_markup_version = profiler_markup_version|default(1) %} {% set icon %} {% if profiler_markup_version == 1 %} Database {{ collector.querycount }} {% if collector.querycount > 0 %} in {{ '%0.2f'|format(collector.time * 1000) }} ms {% endif %} {% if collector.invalidEntityCount > 0 %} {{ collector.invalidEntityCount }} {% endif %} {% else %} {% set status = collector.invalidEntityCount > 0 ? 'red' : collector.querycount > 50 ? 'yellow' %} {{ include('@Doctrine/Collector/icon.svg') }} {% if collector.querycount == 0 and collector.invalidEntityCount > 0 %} {{ collector.invalidEntityCount }} errors {% else %} {{ collector.querycount }} in {{ '%0.2f'|format(collector.time * 1000) }} ms {% endif %} {% endif %} {% endset %} {% set text %}
Database Queries {{ collector.querycount }}
Query time {{ '%0.2f'|format(collector.time * 1000) }} ms
Invalid entities {{ collector.invalidEntityCount }}
{% if collector.cacheEnabled %}
Cache hits {{ collector.cacheHitsCount }}
Cache misses {{ collector.cacheMissesCount }}
Cache puts {{ collector.cachePutsCount }}
{% else %}
Second Level Cache disabled
{% endif %} {% endset %} {{ include('@WebProfiler/Profiler/toolbar_item.html.twig', { link: profiler_url, status: status|default('') }) }} {% endif %} {% endblock %} {% block menu %} {% set profiler_markup_version = profiler_markup_version|default(1) %} {% if profiler_markup_version == 1 %} Doctrine {{ collector.querycount }} {{ '%0.0f'|format(collector.time * 1000) }} ms {% else %} {{ include('@Doctrine/Collector/icon.svg') }} Doctrine {% if collector.invalidEntityCount %} {{ collector.invalidEntityCount }} {% endif %} {% endif %} {% endblock %} {% block panel %} {% set profiler_markup_version = profiler_markup_version|default(1) %} {% if 'explain' == page %} {{ render(controller('DoctrineBundle:Profiler:explain', { token: token, panel: 'db', connectionName: app.request.query.get('connection'), query: app.request.query.get('query') })) }} {% else %} {{ block('queries') }} {% endif %} {% endblock %} {% block queries %} {% if profiler_markup_version == 1 %} {% endif %}

Queries

{% for connection, queries in collector.queries %} {% if collector.connections|length > 1 %}

{{ connection }} connection

{% endif %} {% if queries is empty %}

No database queries were performed.

{% else %} {% for i, query in queries %} {% endfor %}
# Time Info
{{ loop.index }} {{ '%0.2f'|format(query.executionMS * 1000) }} ms {{ query.sql|doctrine_pretty_query(highlight_only = true) }}
Parameters: {{ query.params|yaml_encode }}
View formatted query    View runnable query {% if query.explainable %}    Explain query {% endif %}
{% if query.explainable %}
{% endif %}
{% endif %} {% endfor %}

Database Connections

{% if not collector.connections %}

There are no configured database connections.

{% else %} {{ include('@WebProfiler/Profiler/table.html.twig', { data: collector.connections, labels: ['Name', 'Service'] }, with_context = false ) }} {% endif %}

Entity Managers

{% if not collector.managers %}

There are no configured entity managers.

{% else %} {{ include('@WebProfiler/Profiler/table.html.twig', { data: collector.managers, labels: ['Name', 'Service'] }, with_context = false ) }} {% endif %}

Second Level Cache

{% if not collector.cacheEnabled %}

Second Level Cache is not enabled.

{% else %} {% if not collector.cacheCounts %}

Second level cache information is not available.

{% else %} {% if profiler_markup_version == 1 %} {{ include('@WebProfiler/Profiler/table.html.twig', { data: collector.cacheCounts }, with_context = false) }} {% else %}
{{ collector.cacheCounts.hits }} Hits
{{ collector.cacheCounts.misses }} Misses
{{ collector.cacheCounts.puts }} Puts
{% endif %} {% if collector.cacheRegions.hits %}

Number of cache hits

{{ include('@WebProfiler/Profiler/table.html.twig', { data: collector.cacheRegions.hits }, with_context = false) }} {% endif %} {% if collector.cacheRegions.misses %}

Number of cache misses

{{ include('@WebProfiler/Profiler/table.html.twig', { data: collector.cacheRegions.misses }, with_context = false) }} {% endif %} {% if collector.cacheRegions.puts %}

Number of cache puts

{{ include('@WebProfiler/Profiler/table.html.twig', { data: collector.cacheRegions.puts }, with_context = false) }} {% endif %} {% endif %} {% endif %}

Entities Mapping

{% for manager, classes in collector.entities %} {% if collector.managers|length > 1 %}

{{ manager }} entity manager

{% endif %} {% if classes is empty %}

No loaded entities.

{% else %} {% for class in classes %} {% set contains_errors = collector.mappingErrors[manager] is defined and collector.mappingErrors[manager][class] is defined %} {% endfor %}
Class Mapping errors
{{ class }} {% if contains_errors %}
    {% for error in collector.mappingErrors[manager][class] %}
  • {{ error }}
  • {% endfor %}
{% else %} No errors. {% endif %}
{% endif %} {% endfor %} {% endblock %} DoctrineBundle-1.6.2/Resources/views/Collector/explain.html.twig000066400000000000000000000015651264451145000247660ustar00rootroot00000000000000{% if data[0]|length > 1 %} {# The platform returns a table for the explanation (e.g. MySQL), display all columns #} {% for label in data[0]|keys %} {% endfor %} {% for row in data %} {% for key, item in row %} {% endfor %} {% endfor %}
{{ label }}
{{ item|replace({',': ', '}) }}
{% else %} {# The Platform returns a single column for a textual explanation (e.g. PostgreSQL), display all lines #}
        {%- for row in data -%}
            {{ row|first }}{{ "\n" }}
        {%- endfor -%}
    
{% endif %} DoctrineBundle-1.6.2/Resources/views/Collector/icon.svg000066400000000000000000000012071264451145000231310ustar00rootroot00000000000000 DoctrineBundle-1.6.2/Tests/000077500000000000000000000000001264451145000155255ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/BundleTest.php000066400000000000000000000031311264451145000203050ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests; use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\DoctrineValidationPass; use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\RegisterEventListenersAndSubscribersPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Doctrine\Bundle\DoctrineBundle\DoctrineBundle; class BundleTest extends \PHPUnit_Framework_TestCase { public function testBuildCompilerPasses() { $container = new ContainerBuilder(); $bundle = new DoctrineBundle(); $bundle->build($container); $config = $container->getCompilerPassConfig(); $passes = $config->getBeforeOptimizationPasses(); $foundEventListener = false; $foundValidation = false; foreach ($passes as $pass) { if ($pass instanceof RegisterEventListenersAndSubscribersPass) { $foundEventListener = true; } elseif ($pass instanceof DoctrineValidationPass) { $foundValidation = true; } } $this->assertTrue($foundEventListener, 'RegisterEventListenersAndSubscribersPass was not found'); $this->assertTrue($foundValidation, 'DoctrineValidationPass was not found'); } } DoctrineBundle-1.6.2/Tests/Command/000077500000000000000000000000001264451145000171035ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/Command/CreateDatabaseDoctrineTest.php000066400000000000000000000056061264451145000250030ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests\Command; use Doctrine\Bundle\DoctrineBundle\Command\CreateDatabaseDoctrineCommand; use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; class CreateDatabaseDoctrineTest extends \PHPUnit_Framework_TestCase { public function testExecute() { $connectionName = 'default'; $dbName = 'test'; $params = array( 'dbname' => $dbName, 'memory' => true, 'driver' => 'pdo_sqlite' ); $application = new Application(); $application->add(new CreateDatabaseDoctrineCommand()); $command = $application->find('doctrine:database:create'); $command->setContainer($this->getMockContainer($connectionName, $params)); $commandTester = new CommandTester($command); $commandTester->execute( array_merge(array('command' => $command->getName())) ); $this->assertContains("Created database \"$dbName\" for connection named $connectionName", $commandTester->getDisplay()); } /** * @param $connectionName * @param null $params Connection parameters * @return \PHPUnit_Framework_MockObject_MockObject */ private function getMockContainer($connectionName, $params=null) { // Mock the container and everything you'll need here $mockDoctrine = $this->getMockBuilder('Doctrine\Common\Persistence\ConnectionRegistry') ->getMock(); $mockDoctrine->expects($this->any()) ->method('getDefaultConnectionName') ->withAnyParameters() ->willReturn($connectionName) ; $mockConnection = $this->getMockBuilder('Doctrine\DBAL\Connection') ->disableOriginalConstructor() ->setMethods(array('getParams')) ->getMockForAbstractClass(); $mockConnection->expects($this->any()) ->method('getParams') ->withAnyParameters() ->willReturn($params); $mockDoctrine->expects($this->any()) ->method('getConnection') ->withAnyParameters() ->willReturn($mockConnection); ; $mockContainer = $this->getMockBuilder('Symfony\Component\DependencyInjection\Container') ->setMethods(array('get')) ->getMock(); $mockContainer->expects($this->any()) ->method('get') ->with('doctrine') ->willReturn($mockDoctrine); return $mockContainer; } } DoctrineBundle-1.6.2/Tests/ContainerTest.php000066400000000000000000000072441264451145000210270ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests; use Doctrine\DBAL\Types\Type; class ContainerTest extends TestCase { protected function setUp() { parent::setUp(); if (!class_exists('Doctrine\\ORM\\Version')) { $this->markTestSkipped('Doctrine ORM is not available.'); } } public function testContainer() { $container = $this->createYamlBundleTestContainer(); $this->assertInstanceOf('Symfony\Bridge\Doctrine\Logger\DbalLogger', $container->get('doctrine.dbal.logger')); $this->assertInstanceOf('Symfony\Bridge\Doctrine\DataCollector\DoctrineDataCollector', $container->get('data_collector.doctrine')); $this->assertInstanceOf('Doctrine\DBAL\Configuration', $container->get('doctrine.dbal.default_connection.configuration')); $this->assertInstanceOf('Doctrine\Common\EventManager', $container->get('doctrine.dbal.default_connection.event_manager')); $this->assertInstanceOf('Doctrine\DBAL\Connection', $container->get('doctrine.dbal.default_connection')); $this->assertInstanceOf('Doctrine\Common\Annotations\Reader', $container->get('doctrine.orm.metadata.annotation_reader')); $this->assertInstanceOf('Doctrine\ORM\Configuration', $container->get('doctrine.orm.default_configuration')); $this->assertInstanceOf('Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain', $container->get('doctrine.orm.default_metadata_driver')); $this->assertInstanceOf('Doctrine\Common\Cache\ArrayCache', $container->get('doctrine.orm.default_metadata_cache')); $this->assertInstanceOf('Doctrine\Common\Cache\ArrayCache', $container->get('doctrine.orm.default_query_cache')); $this->assertInstanceOf('Doctrine\Common\Cache\ArrayCache', $container->get('doctrine.orm.default_result_cache')); $this->assertInstanceOf('Doctrine\ORM\EntityManager', $container->get('doctrine.orm.default_entity_manager')); $this->assertInstanceOf('Doctrine\DBAL\Connection', $container->get('database_connection')); $this->assertInstanceOf('Doctrine\ORM\EntityManager', $container->get('doctrine.orm.entity_manager')); $this->assertInstanceOf('Doctrine\Common\EventManager', $container->get('doctrine.orm.default_entity_manager.event_manager')); $this->assertInstanceOf('Doctrine\Common\EventManager', $container->get('doctrine.dbal.event_manager')); $this->assertInstanceOf('Symfony\Bridge\Doctrine\CacheWarmer\ProxyCacheWarmer', $container->get('doctrine.orm.proxy_cache_warmer')); $this->assertInstanceOf('Doctrine\Common\Persistence\ManagerRegistry', $container->get('doctrine')); $this->assertInstanceOf('Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator', $container->get('doctrine.orm.validator.unique')); $this->assertSame($container->get('my.platform'), $container->get('doctrine.dbal.default_connection')->getDatabasePlatform()); $this->assertTrue(Type::hasType('test')); if (version_compare(PHP_VERSION, '5.3.6', '<')) { $this->assertInstanceOf('Doctrine\DBAL\Event\Listeners\MysqlSessionInit', $container->get('doctrine.dbal.default_connection.events.mysqlsessioninit')); } else { $this->assertFalse($container->has('doctrine.dbal.default_connection.events.mysqlsessioninit')); } } } DoctrineBundle-1.6.2/Tests/DataCollector/000077500000000000000000000000001264451145000202455ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DataCollector/DoctrineDataCollectorTest.php000066400000000000000000000070151264451145000260310ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests\DataCollector; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Doctrine\ORM\Mapping\ClassMetadataInfo; use Doctrine\Bundle\DoctrineBundle\DataCollector\DoctrineDataCollector; class DoctrineDataCollectorTest extends \PHPUnit_Framework_TestCase { const FIRST_ENTITY = 'TestBundle\Test\Entity\Test1'; const SECOND_ENTITY = 'TestBundle\Test\Entity\Test2'; public function testCollectEntities() { $manager = $this->getMockBuilder('Doctrine\ORM\EntityManager')->disableOriginalConstructor()->getMock(); $config = $this->getMock('Doctrine\ORM\Configuration'); $factory = $this->getMockBuilder('Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory') ->setMethods(array('getLoadedMetadata'))->getMockForAbstractClass(); $collector = $this->createCollector(array('default' => $manager)); $manager->expects($this->any()) ->method('getMetadataFactory') ->will($this->returnValue($factory)); $manager->expects($this->any()) ->method('getConfiguration') ->will($this->returnValue($config)); if (method_exists($config, 'isSecondLevelCacheEnabled')) { $config->expects($this->once()) ->method('isSecondLevelCacheEnabled') ->will($this->returnValue(false)); } $metadatas = array( $this->createEntityMetadata(self::FIRST_ENTITY), $this->createEntityMetadata(self::SECOND_ENTITY), $this->createEntityMetadata(self::FIRST_ENTITY), ); $factory->expects($this->once()) ->method('getLoadedMetadata') ->will($this->returnValue($metadatas)); $collector->collect(new Request(), new Response()); $entities = $collector->getEntities(); $this->assertArrayHasKey('default', $entities); $this->assertCount(2, $entities['default']); } /** * @param string $entityFQCN * * @return ClassMetadataInfo */ private function createEntityMetadata($entityFQCN) { $metadata = new ClassMetadataInfo($entityFQCN); $metadata->name = $entityFQCN; $metadata->reflClass = new \ReflectionClass('stdClass'); return $metadata; } /** * @param array $managers * * @return DoctrineDataCollector */ private function createCollector(array $managers) { $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry'); $registry ->expects($this->any()) ->method('getConnectionNames') ->will($this->returnValue(array('default' => 'doctrine.dbal.default_connection'))); $registry ->expects($this->any()) ->method('getManagerNames') ->will($this->returnValue(array('default' => 'doctrine.orm.default_entity_manager'))); $registry ->expects($this->any()) ->method('getManagers') ->will($this->returnValue($managers)); $collector = new DoctrineDataCollector($registry); return $collector; } } DoctrineBundle-1.6.2/Tests/DependencyInjection/000077500000000000000000000000001264451145000214465ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/AbstractDoctrineExtensionTest.php000066400000000000000000001322611264451145000301540ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection; use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\EntityListenerPass; use Doctrine\Bundle\DoctrineBundle\DependencyInjection\DoctrineExtension; use Doctrine\ORM\Version; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Compiler\ResolveDefinitionTemplatesPass; abstract class AbstractDoctrineExtensionTest extends \PHPUnit_Framework_TestCase { abstract protected function loadFromFile(ContainerBuilder $container, $file); public function testDbalLoadFromXmlMultipleConnections() { $container = $this->loadContainer('dbal_service_multiple_connections'); // doctrine.dbal.mysql_connection $config = $container->getDefinition('doctrine.dbal.mysql_connection')->getArgument(0); $this->assertEquals('mysql_s3cr3t', $config['password']); $this->assertEquals('mysql_user', $config['user']); $this->assertEquals('mysql_db', $config['dbname']); $this->assertEquals('/path/to/mysqld.sock', $config['unix_socket']); // doctrine.dbal.sqlite_connection $config = $container->getDefinition('doctrine.dbal.sqlite_connection')->getArgument(0); $this->assertSame('pdo_sqlite', $config['driver']); $this->assertSame('sqlite_db', $config['dbname']); $this->assertSame('sqlite_user', $config['user']); $this->assertSame('sqlite_s3cr3t', $config['password']); $this->assertSame('/tmp/db.sqlite', $config['path']); $this->assertTrue($config['memory']); // doctrine.dbal.oci8_connection $config = $container->getDefinition('doctrine.dbal.oci_connection')->getArgument(0); $this->assertSame('oci8', $config['driver']); $this->assertSame('oracle_db', $config['dbname']); $this->assertSame('oracle_user', $config['user']); $this->assertSame('oracle_s3cr3t', $config['password']); $this->assertSame('oracle_service', $config['servicename']); $this->assertTrue($config['service']); $this->assertTrue($config['pooled']); $this->assertSame('utf8', $config['charset']); // doctrine.dbal.ibmdb2_connection $config = $container->getDefinition('doctrine.dbal.ibmdb2_connection')->getArgument(0); $this->assertSame('ibm_db2', $config['driver']); $this->assertSame('ibmdb2_db', $config['dbname']); $this->assertSame('ibmdb2_user', $config['user']); $this->assertSame('ibmdb2_s3cr3t', $config['password']); $this->assertSame('TCPIP', $config['protocol']); // doctrine.dbal.pgsql_connection $config = $container->getDefinition('doctrine.dbal.pgsql_connection')->getArgument(0); $this->assertSame('pdo_pgsql', $config['driver']); $this->assertSame('pgsql_db', $config['dbname']); $this->assertSame('pgsql_user', $config['user']); $this->assertSame('pgsql_s3cr3t', $config['password']); $this->assertSame('require', $config['sslmode']); $this->assertSame('postgresql-ca.pem', $config['sslrootcert']); $this->assertSame('utf8', $config['charset']); // doctrine.dbal.sqlanywhere_connection $config = $container->getDefinition('doctrine.dbal.sqlanywhere_connection')->getArgument(0); $this->assertSame('sqlanywhere', $config['driver']); $this->assertSame('localhost', $config['host']); $this->assertSame(2683, $config['port']); $this->assertSame('sqlanywhere_server', $config['server']); $this->assertSame('sqlanywhere_db', $config['dbname']); $this->assertSame('sqlanywhere_user', $config['user']); $this->assertSame('sqlanywhere_s3cr3t', $config['password']); $this->assertTrue($config['persistent']); $this->assertSame('utf8', $config['charset']); } public function testDbalLoadFromXmlSingleConnections() { $container = $this->loadContainer('dbal_service_single_connection'); // doctrine.dbal.mysql_connection $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0); $this->assertEquals('mysql_s3cr3t', $config['password']); $this->assertEquals('mysql_user', $config['user']); $this->assertEquals('mysql_db', $config['dbname']); $this->assertEquals('/path/to/mysqld.sock', $config['unix_socket']); $this->assertEquals('5.6.20', $config['serverVersion']); } public function testDbalLoadSingleMasterSlaveConnection() { $container = $this->loadContainer('dbal_service_single_master_slave_connection'); // doctrine.dbal.mysql_connection $param = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0); $this->assertEquals('Doctrine\\DBAL\\Connections\\MasterSlaveConnection', $param['wrapperClass']); $this->assertTrue($param['keepSlave']); $this->assertEquals( array('user' => 'mysql_user', 'password' => 'mysql_s3cr3t', 'port' => null, 'dbname' => 'mysql_db', 'host' => 'localhost', 'unix_socket' => '/path/to/mysqld.sock', 'defaultTableOptions' => array(), ), $param['master'] ); $this->assertEquals( array( 'user' => 'slave_user', 'password' => 'slave_s3cr3t', 'port' => null, 'dbname' => 'slave_db', 'host' => 'localhost', 'unix_socket' => '/path/to/mysqld_slave.sock', ), $param['slaves']['slave1'] ); } public function testDbalLoadPoolShardingConnection() { $container = $this->loadContainer('dbal_service_pool_sharding_connection'); // doctrine.dbal.mysql_connection $param = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0); $this->assertEquals('Doctrine\\DBAL\\Sharding\\PoolingShardConnection', $param['wrapperClass']); $this->assertEquals(new Reference('foo.shard_choser'), $param['shardChoser']); $this->assertEquals( array('user' => 'mysql_user', 'password' => 'mysql_s3cr3t', 'port' => null, 'dbname' => 'mysql_db', 'host' => 'localhost', 'unix_socket' => '/path/to/mysqld.sock', 'defaultTableOptions' => array(), ), $param['global'] ); $this->assertEquals( array( 'user' => 'shard_user', 'password' => 'shard_s3cr3t', 'port' => null, 'dbname' => 'shard_db', 'host' => 'localhost', 'unix_socket' => '/path/to/mysqld_shard.sock', 'id' => 1, ), $param['shards'][0] ); } public function testDbalLoadSavepointsForNestedTransactions() { $container = $this->loadContainer('dbal_savepoints'); $calls = $container->getDefinition('doctrine.dbal.savepoints_connection')->getMethodCalls(); $this->assertCount(1, $calls); $this->assertEquals('setNestTransactionsWithSavepoints', $calls[0][0]); $this->assertTrue($calls[0][1][0]); $calls = $container->getDefinition('doctrine.dbal.nosavepoints_connection')->getMethodCalls(); $this->assertCount(0, $calls); $calls = $container->getDefinition('doctrine.dbal.notset_connection')->getMethodCalls(); $this->assertCount(0, $calls); } public function testLoadSimpleSingleConnection() { $container = $this->loadContainer('orm_service_simple_single_entity_manager'); $definition = $container->getDefinition('doctrine.dbal.default_connection'); $this->assertDICConstructorArguments($definition, array( array( 'dbname' => 'db', 'host' => 'localhost', 'port' => null, 'user' => 'root', 'password' => null, 'driver' => 'pdo_mysql', 'driverOptions' => array(), 'defaultTableOptions' => array(), ), new Reference('doctrine.dbal.default_connection.configuration'), new Reference('doctrine.dbal.default_connection.event_manager'), array(), )); $definition = $container->getDefinition('doctrine.orm.default_entity_manager'); $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass()); if (method_exists($definition, 'getFactory')) { $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory()); } else { $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getFactoryClass()); $this->assertEquals('create', $definition->getFactoryMethod()); } $this->assertDICConstructorArguments($definition, array( new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'), )); } /** * The PDO driver doesn't require a database name to be to set when connecting to a database server */ public function testLoadSimpleSingleConnectionWithoutDbName() { $container = $this->loadContainer('orm_service_simple_single_entity_manager_without_dbname'); /** @var Definition $definition */ $definition = $container->getDefinition('doctrine.dbal.default_connection'); $this->assertDICConstructorArguments($definition, array( array( 'host' => 'localhost', 'port' => null, 'user' => 'root', 'password' => null, 'driver' => 'pdo_mysql', 'driverOptions' => array(), 'defaultTableOptions' => array(), ), new Reference('doctrine.dbal.default_connection.configuration'), new Reference('doctrine.dbal.default_connection.event_manager'), array(), )); $definition = $container->getDefinition('doctrine.orm.default_entity_manager'); $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass()); if (method_exists($definition, 'getFactory')) { $factory = $definition->getFactory(); } else { $factory[0] = $definition->getFactoryClass(); $factory[1] = $definition->getFactoryMethod(); } $this->assertEquals('%doctrine.orm.entity_manager.class%', $factory[0]); $this->assertEquals('create', $factory[1]); $this->assertDICConstructorArguments($definition, array( new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration') )); } public function testLoadSingleConnection() { $container = $this->loadContainer('orm_service_single_entity_manager'); $definition = $container->getDefinition('doctrine.dbal.default_connection'); $this->assertDICConstructorArguments($definition, array( array( 'host' => 'localhost', 'driver' => 'pdo_sqlite', 'driverOptions' => array(), 'user' => 'sqlite_user', 'port' => null, 'password' => 'sqlite_s3cr3t', 'dbname' => 'sqlite_db', 'memory' => true, 'defaultTableOptions' => array(), ), new Reference('doctrine.dbal.default_connection.configuration'), new Reference('doctrine.dbal.default_connection.event_manager'), array(), )); $definition = $container->getDefinition('doctrine.orm.default_entity_manager'); $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass()); if (method_exists($definition, 'setFactory')) { $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory()); } else { $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getFactoryClass()); $this->assertEquals('create', $definition->getFactoryMethod()); } $this->assertDICConstructorArguments($definition, array( new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'), )); $configDef = $container->getDefinition('doctrine.orm.default_configuration'); $this->assertDICDefinitionMethodCallOnce($configDef, 'setDefaultRepositoryClassName', array('Acme\Doctrine\Repository')); } public function testLoadMultipleConnections() { $container = $this->loadContainer('orm_service_multiple_entity_managers'); $definition = $container->getDefinition('doctrine.dbal.conn1_connection'); $args = $definition->getArguments(); $this->assertEquals('pdo_sqlite', $args[0]['driver']); $this->assertEquals('localhost', $args[0]['host']); $this->assertEquals('sqlite_user', $args[0]['user']); $this->assertEquals('doctrine.dbal.conn1_connection.configuration', (string) $args[1]); $this->assertEquals('doctrine.dbal.conn1_connection.event_manager', (string) $args[2]); $this->assertEquals('doctrine.orm.em2_entity_manager', (string) $container->getAlias('doctrine.orm.entity_manager')); $definition = $container->getDefinition('doctrine.orm.em1_entity_manager'); $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass()); if (method_exists($definition, 'getFactory')) { $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory()); } else { $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getFactoryClass()); $this->assertEquals('create', $definition->getFactoryMethod()); } $arguments = $definition->getArguments(); $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]); $this->assertEquals('doctrine.dbal.conn1_connection', (string) $arguments[0]); $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]); $this->assertEquals('doctrine.orm.em1_configuration', (string) $arguments[1]); $definition = $container->getDefinition('doctrine.dbal.conn2_connection'); $args = $definition->getArguments(); $this->assertEquals('pdo_sqlite', $args[0]['driver']); $this->assertEquals('localhost', $args[0]['host']); $this->assertEquals('sqlite_user', $args[0]['user']); $this->assertEquals('doctrine.dbal.conn2_connection.configuration', (string) $args[1]); $this->assertEquals('doctrine.dbal.conn2_connection.event_manager', (string) $args[2]); $definition = $container->getDefinition('doctrine.orm.em2_entity_manager'); $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass()); if (method_exists($definition, 'getFactory')) { $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory()); } else { $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getFactoryClass()); $this->assertEquals('create', $definition->getFactoryMethod()); } $arguments = $definition->getArguments(); $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]); $this->assertEquals('doctrine.dbal.conn2_connection', (string) $arguments[0]); $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]); $this->assertEquals('doctrine.orm.em2_configuration', (string) $arguments[1]); $definition = $container->getDefinition($container->getAlias('doctrine.orm.em1_metadata_cache')); $this->assertEquals('%doctrine_cache.xcache.class%', $definition->getClass()); $definition = $container->getDefinition($container->getAlias('doctrine.orm.em1_query_cache')); $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass()); $definition = $container->getDefinition($container->getAlias('doctrine.orm.em1_result_cache')); $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass()); } public function testLoadLogging() { $container = $this->loadContainer('dbal_logging'); $definition = $container->getDefinition('doctrine.dbal.log_connection.configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', array(new Reference('doctrine.dbal.logger'))); $definition = $container->getDefinition('doctrine.dbal.profile_connection.configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', array(new Reference('doctrine.dbal.logger.profiling.profile'))); $definition = $container->getDefinition('doctrine.dbal.both_connection.configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', array(new Reference('doctrine.dbal.logger.chain.both'))); } public function testEntityManagerMetadataCacheDriverConfiguration() { $container = $this->loadContainer('orm_service_multiple_entity_managers'); $definition = $container->getDefinition($container->getAlias('doctrine.orm.em1_metadata_cache')); $this->assertDICDefinitionClass($definition, '%doctrine_cache.xcache.class%'); $definition = $container->getDefinition($container->getAlias('doctrine.orm.em2_metadata_cache')); $this->assertDICDefinitionClass($definition, '%doctrine_cache.apc.class%'); } public function testEntityManagerMemcacheMetadataCacheDriverConfiguration() { $container = $this->loadContainer('orm_service_simple_single_entity_manager'); $definition = $container->getDefinition($container->getAlias('doctrine.orm.default_metadata_cache')); $this->assertDICDefinitionClass($definition, '%doctrine_cache.memcache.class%'); $this->assertDICDefinitionMethodCallOnce($definition, 'setMemcache', array(new Reference('doctrine_cache.services.doctrine.orm.default_metadata_cache.connection')) ); $definition = $container->getDefinition('doctrine_cache.services.doctrine.orm.default_metadata_cache.connection'); $this->assertDICDefinitionClass($definition, '%doctrine_cache.memcache.connection.class%'); $this->assertDICDefinitionMethodCallOnce($definition, 'addServer', array( 'localhost', '11211', )); } public function testDependencyInjectionImportsOverrideDefaults() { $container = $this->loadContainer('orm_imports'); $cacheDefinition = $container->getDefinition($container->getAlias('doctrine.orm.default_metadata_cache')); $this->assertEquals('%doctrine_cache.apc.class%', $cacheDefinition->getClass()); $configDefinition = $container->getDefinition('doctrine.orm.default_configuration'); $this->assertDICDefinitionMethodCallOnce($configDefinition, 'setAutoGenerateProxyClasses', array('%doctrine.orm.auto_generate_proxy_classes%')); } public function testSingleEntityManagerMultipleMappingBundleDefinitions() { $container = $this->loadContainer('orm_single_em_bundle_mappings', array('YamlBundle', 'AnnotationsBundle', 'XmlBundle')); $definition = $container->getDefinition('doctrine.orm.default_metadata_driver'); $this->assertDICDefinitionMethodCallAt(0, $definition, 'addDriver', array( new Reference('doctrine.orm.default_annotation_metadata_driver'), 'Fixtures\Bundles\AnnotationsBundle\Entity', )); $this->assertDICDefinitionMethodCallAt(1, $definition, 'addDriver', array( new Reference('doctrine.orm.default_yml_metadata_driver'), 'Fixtures\Bundles\YamlBundle\Entity', )); $this->assertDICDefinitionMethodCallAt(2, $definition, 'addDriver', array( new Reference('doctrine.orm.default_xml_metadata_driver'), 'Fixtures\Bundles\XmlBundle', )); $annDef = $container->getDefinition('doctrine.orm.default_annotation_metadata_driver'); $this->assertDICConstructorArguments($annDef, array( new Reference('doctrine.orm.metadata.annotation_reader'), array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.'Bundles'.DIRECTORY_SEPARATOR.'AnnotationsBundle'.DIRECTORY_SEPARATOR.'Entity'), )); $ymlDef = $container->getDefinition('doctrine.orm.default_yml_metadata_driver'); $this->assertDICConstructorArguments($ymlDef, array( array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.'Bundles'.DIRECTORY_SEPARATOR.'YamlBundle'.DIRECTORY_SEPARATOR.'Resources'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'doctrine' => 'Fixtures\Bundles\YamlBundle\Entity'), )); $xmlDef = $container->getDefinition('doctrine.orm.default_xml_metadata_driver'); $this->assertDICConstructorArguments($xmlDef, array( array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.'Bundles'.DIRECTORY_SEPARATOR.'XmlBundle'.DIRECTORY_SEPARATOR.'Resources'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'doctrine' => 'Fixtures\Bundles\XmlBundle'), )); } public function testMultipleEntityManagersMappingBundleDefinitions() { $container = $this->loadContainer('orm_multiple_em_bundle_mappings', array('YamlBundle', 'AnnotationsBundle', 'XmlBundle')); $this->assertEquals(array('em1' => 'doctrine.orm.em1_entity_manager', 'em2' => 'doctrine.orm.em2_entity_manager'), $container->getParameter('doctrine.entity_managers'), "Set of the existing EntityManagers names is incorrect."); $this->assertEquals('%doctrine.entity_managers%', $container->getDefinition('doctrine')->getArgument(2), "Set of the existing EntityManagers names is incorrect."); $def1 = $container->getDefinition('doctrine.orm.em1_metadata_driver'); $def2 = $container->getDefinition('doctrine.orm.em2_metadata_driver'); $this->assertDICDefinitionMethodCallAt(0, $def1, 'addDriver', array( new Reference('doctrine.orm.em1_annotation_metadata_driver'), 'Fixtures\Bundles\AnnotationsBundle\Entity', )); $this->assertDICDefinitionMethodCallAt(0, $def2, 'addDriver', array( new Reference('doctrine.orm.em2_yml_metadata_driver'), 'Fixtures\Bundles\YamlBundle\Entity', )); $this->assertDICDefinitionMethodCallAt(1, $def2, 'addDriver', array( new Reference('doctrine.orm.em2_xml_metadata_driver'), 'Fixtures\Bundles\XmlBundle', )); $annDef = $container->getDefinition('doctrine.orm.em1_annotation_metadata_driver'); $this->assertDICConstructorArguments($annDef, array( new Reference('doctrine.orm.metadata.annotation_reader'), array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.'Bundles'.DIRECTORY_SEPARATOR.'AnnotationsBundle'.DIRECTORY_SEPARATOR.'Entity'), )); $ymlDef = $container->getDefinition('doctrine.orm.em2_yml_metadata_driver'); $this->assertDICConstructorArguments($ymlDef, array( array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.'Bundles'.DIRECTORY_SEPARATOR.'YamlBundle'.DIRECTORY_SEPARATOR.'Resources'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'doctrine' => 'Fixtures\Bundles\YamlBundle\Entity'), )); $xmlDef = $container->getDefinition('doctrine.orm.em2_xml_metadata_driver'); $this->assertDICConstructorArguments($xmlDef, array( array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.'Bundles'.DIRECTORY_SEPARATOR.'XmlBundle'.DIRECTORY_SEPARATOR.'Resources'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'doctrine' => 'Fixtures\Bundles\XmlBundle'), )); } public function testSingleEntityManagerDefaultTableOptions() { $container = $this->loadContainer('orm_single_em_default_table_options', array('YamlBundle', 'AnnotationsBundle', 'XmlBundle')); $param = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0); $this->assertArrayHasKey('defaultTableOptions',$param); $defaults = $param['defaultTableOptions']; $this->assertArrayHasKey('charset', $defaults); $this->assertArrayHasKey('collate', $defaults); $this->assertArrayHasKey('engine', $defaults); $this->assertEquals('utf8mb4',$defaults['charset']); $this->assertEquals('utf8mb4_unicode_ci',$defaults['collate']); $this->assertEquals('InnoDB',$defaults['engine']); } public function testSetTypes() { $container = $this->loadContainer('dbal_types'); $this->assertEquals( array('test' => array('class' => 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestType', 'commented' => true)), $container->getParameter('doctrine.dbal.connection_factory.types') ); $this->assertEquals('%doctrine.dbal.connection_factory.types%', $container->getDefinition('doctrine.dbal.connection_factory')->getArgument(0)); } public function testSetCustomFunctions() { $container = $this->loadContainer('orm_functions'); $definition = $container->getDefinition('doctrine.orm.default_configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomStringFunction', array('test_string', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction')); $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomNumericFunction', array('test_numeric', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestNumericFunction')); $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomDatetimeFunction', array('test_datetime', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestDatetimeFunction')); } public function testSetNamingStrategy() { if (version_compare(Version::VERSION, "2.3.0-DEV") < 0) { $this->markTestSkipped('Naming Strategies are not available'); } $container = $this->loadContainer('orm_namingstrategy'); $def1 = $container->getDefinition('doctrine.orm.em1_configuration'); $def2 = $container->getDefinition('doctrine.orm.em2_configuration'); $this->assertDICDefinitionMethodCallOnce($def1, 'setNamingStrategy', array(0 => new Reference('doctrine.orm.naming_strategy.default'))); $this->assertDICDefinitionMethodCallOnce($def2, 'setNamingStrategy', array(0 => new Reference('doctrine.orm.naming_strategy.underscore'))); } public function testSetQuoteStrategy() { if (version_compare(Version::VERSION, "2.3.0-DEV") < 0) { $this->markTestSkipped('Quote Strategies are not available'); } $container = $this->loadContainer('orm_quotestrategy'); $def1 = $container->getDefinition('doctrine.orm.em1_configuration'); $def2 = $container->getDefinition('doctrine.orm.em2_configuration'); $this->assertDICDefinitionMethodCallOnce($def1, 'setQuoteStrategy', array(0 => new Reference('doctrine.orm.quote_strategy.default'))); $this->assertDICDefinitionMethodCallOnce($def2, 'setQuoteStrategy', array(0 => new Reference('doctrine.orm.quote_strategy.ansi'))); } public function testSecondLevelCache() { if (version_compare(Version::VERSION, '2.5.0-DEV') < 0) { $this->markTestSkipped('Second-level cache requires doctrine-orm 2.5.0 or newer'); } $container = $this->loadContainer('orm_second_level_cache'); $this->assertTrue($container->has('doctrine.orm.default_configuration')); $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.cache_configuration')); $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.region_cache_driver')); $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.regions_configuration')); $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.default_cache_factory')); $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.logger_chain')); $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.logger_statistics')); $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.logger.my_service_logger1')); $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.logger.my_service_logger2')); $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.region.my_entity_region')); $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.region.my_service_region')); $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.region.my_query_region_filelock')); $slcFactoryDef = $container->getDefinition('doctrine.orm.default_second_level_cache.default_cache_factory'); $myEntityRegionDef = $container->getDefinition('doctrine.orm.default_second_level_cache.region.my_entity_region'); $loggerChainDef = $container->getDefinition('doctrine.orm.default_second_level_cache.logger_chain'); $loggerStatisticsDef = $container->getDefinition('doctrine.orm.default_second_level_cache.logger_statistics'); $myQueryRegionDef = $container->getDefinition('doctrine.orm.default_second_level_cache.region.my_query_region_filelock'); $cacheDriverDef = $container->getDefinition($container->getAlias('doctrine.orm.default_second_level_cache.region_cache_driver')); $configDef = $container->getDefinition('doctrine.orm.default_configuration'); $myEntityRegionArgs = $myEntityRegionDef->getArguments(); $myQueryRegionArgs = $myQueryRegionDef->getArguments(); $slcFactoryArgs = $slcFactoryDef->getArguments(); $this->assertDICDefinitionClass($slcFactoryDef, '%doctrine.orm.second_level_cache.default_cache_factory.class%'); $this->assertDICDefinitionClass($myQueryRegionDef, '%doctrine.orm.second_level_cache.filelock_region.class%'); $this->assertDICDefinitionClass($myEntityRegionDef, '%doctrine.orm.second_level_cache.default_region.class%'); $this->assertDICDefinitionClass($loggerChainDef, '%doctrine.orm.second_level_cache.logger_chain.class%'); $this->assertDICDefinitionClass($loggerStatisticsDef, '%doctrine.orm.second_level_cache.logger_statistics.class%'); $this->assertDICDefinitionClass($cacheDriverDef, '%doctrine_cache.array.class%'); $this->assertDICDefinitionMethodCallOnce($configDef, 'setSecondLevelCacheConfiguration'); $this->assertDICDefinitionMethodCallCount($slcFactoryDef, 'setRegion', array(), 3); $this->assertDICDefinitionMethodCallCount($loggerChainDef, 'setLogger', array(), 3); $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $slcFactoryArgs[0]); $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $slcFactoryArgs[1]); $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $myEntityRegionArgs[1]); $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $myQueryRegionArgs[0]); $this->assertEquals('my_entity_region', $myEntityRegionArgs[0]); $this->assertEquals('doctrine.orm.default_second_level_cache.region.my_entity_region_driver', $myEntityRegionArgs[1]); $this->assertEquals(600, $myEntityRegionArgs[2]); $this->assertEquals('doctrine.orm.default_second_level_cache.region.my_query_region', $myQueryRegionArgs[0]); $this->assertContains('/doctrine/orm/slc/filelock', $myQueryRegionArgs[1]); $this->assertEquals(60, $myQueryRegionArgs[2]); $this->assertEquals('doctrine.orm.default_second_level_cache.regions_configuration', $slcFactoryArgs[0]); $this->assertEquals('doctrine.orm.default_second_level_cache.region_cache_driver', $slcFactoryArgs[1]); } public function testSingleEMSetCustomFunctions() { $container = $this->loadContainer('orm_single_em_dql_functions'); $definition = $container->getDefinition('doctrine.orm.default_configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomStringFunction', array('test_string', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction')); } public function testAddCustomHydrationMode() { $container = $this->loadContainer('orm_hydration_mode'); $definition = $container->getDefinition('doctrine.orm.default_configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomHydrationMode', array('test_hydrator', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestHydrator')); } public function testAddFilter() { $container = $this->loadContainer('orm_filters'); $definition = $container->getDefinition('doctrine.orm.default_configuration'); $args = array( array('soft_delete', 'Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\TestFilter'), array('myFilter', 'Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\TestFilter'), ); $this->assertDICDefinitionMethodCallCount($definition, 'addFilter', $args, 2); $definition = $container->getDefinition('doctrine.orm.default_manager_configurator'); $this->assertDICConstructorArguments($definition, array(array('soft_delete', 'myFilter'), array('myFilter' => array('myParameter' => 'myValue', 'mySecondParameter' => 'mySecondValue')))); // Let's create the instance to check the configurator work. /** @var $entityManager \Doctrine\ORM\EntityManager */ $entityManager = $container->get('doctrine.orm.entity_manager'); $this->assertCount(2, $entityManager->getFilters()->getEnabledFilters()); } public function testResolveTargetEntity() { $container = $this->loadContainer('orm_resolve_target_entity'); $definition = $container->getDefinition('doctrine.orm.listeners.resolve_target_entity'); $this->assertDICDefinitionMethodCallOnce($definition, 'addResolveTargetEntity', array('Symfony\Component\Security\Core\User\UserInterface', 'MyUserClass', array())); if (version_compare(Version::VERSION, '2.5.0-DEV') < 0) { $this->assertEquals(array('doctrine.event_listener' => array(array('event' => 'loadClassMetadata'))), $definition->getTags()); } else { $this->assertEquals(array('doctrine.event_subscriber' => array(array())), $definition->getTags()); } } public function testAttachEntityListeners() { if (version_compare(Version::VERSION, '2.5.0-DEV') < 0 ) { $this->markTestSkipped('This test requires ORM 2.5-dev.'); } $container = $this->loadContainer('orm_attach_entity_listener'); $definition = $container->getDefinition('doctrine.orm.default_listeners.attach_entity_listeners'); $methodCalls = $definition->getMethodCalls(); $this->assertDICDefinitionMethodCallCount($definition, 'addEntityListener', array(), 6); $this->assertEquals(array('doctrine.event_listener' => array( array('event' => 'loadClassMetadata') ) ), $definition->getTags()); $this->assertEquals($methodCalls[0], array('addEntityListener', array ( 'ExternalBundles\Entities\FooEntity', 'MyBundles\Listeners\FooEntityListener', 'prePersist', null, ))); $this->assertEquals($methodCalls[1], array('addEntityListener', array ( 'ExternalBundles\Entities\FooEntity', 'MyBundles\Listeners\FooEntityListener', 'postPersist', 'postPersist', ))); $this->assertEquals($methodCalls[2], array('addEntityListener', array ( 'ExternalBundles\Entities\FooEntity', 'MyBundles\Listeners\FooEntityListener', 'postLoad', 'postLoadHandler', ))); $this->assertEquals($methodCalls[3], array('addEntityListener', array ( 'ExternalBundles\Entities\BarEntity', 'MyBundles\Listeners\BarEntityListener', 'prePersist', 'prePersist', ))); $this->assertEquals($methodCalls[4], array('addEntityListener', array ( 'ExternalBundles\Entities\BarEntity', 'MyBundles\Listeners\BarEntityListener', 'prePersist', 'prePersistHandler', ))); $this->assertEquals($methodCalls[5], array('addEntityListener', array ( 'ExternalBundles\Entities\BarEntity', 'MyBundles\Listeners\LogDeleteEntityListener', 'postDelete', 'postDelete', ))); } public function testDbalAutoCommit() { $container = $this->loadContainer('dbal_auto_commit'); $definition = $container->getDefinition('doctrine.dbal.default_connection.configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'setAutoCommit', array(false)); } public function testDbalSchemaFilter() { $container = $this->loadContainer('dbal_schema_filter'); $definition = $container->getDefinition('doctrine.dbal.default_connection.configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'setFilterSchemaAssetsExpression', array('^sf2_')); } public function testEntityListenerResolver() { $container = $this->loadContainer('orm_entity_listener_resolver', array('YamlBundle'), new EntityListenerPass()); $definition = $container->getDefinition('doctrine.orm.em1_configuration'); if (version_compare(Version::VERSION, "2.4.0-DEV") >= 0) { $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityListenerResolver', array(new Reference('doctrine.orm.em1_entity_listener_resolver'))); } $definition = $container->getDefinition('doctrine.orm.em2_configuration'); if (version_compare(Version::VERSION, "2.4.0-DEV") >= 0) { $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityListenerResolver', array(new Reference('doctrine.orm.em2_entity_listener_resolver'))); } $listener = $container->getDefinition('doctrine.orm.em1_entity_listener_resolver'); $this->assertDICDefinitionMethodCallOnce($listener, 'register', array(new Reference('entity_listener1'))); $listener = $container->getDefinition('entity_listener_resolver'); $this->assertDICDefinitionMethodCallOnce($listener, 'register', array(new Reference('entity_listener2'))); } public function testAttachEntityListenerTag() { if (version_compare(Version::VERSION, '2.5.0-DEV') < 0) { $this->markTestSkipped('Attaching entity listeners by tag requires doctrine-orm 2.5.0 or newer'); } $container = $this->getContainer(array()); $loader = new DoctrineExtension(); $container->registerExtension($loader); $container->addCompilerPass(new EntityListenerPass()); $this->loadFromFile($container, 'orm_attach_entity_listener_tag'); $this->compileContainer($container); $listener = $container->getDefinition('doctrine.orm.em1_entity_listener_resolver'); $this->assertDICDefinitionMethodCallOnce($listener, 'register', array(new Reference('entity_listener1'))); $listener = $container->getDefinition('doctrine.orm.em2_entity_listener_resolver'); $this->assertDICDefinitionMethodCallOnce($listener, 'register', array(new Reference('entity_listener2'))); $attachListener = $container->getDefinition('doctrine.orm.em1_listeners.attach_entity_listeners'); $this->assertDICDefinitionMethodCallOnce($attachListener, 'addEntityListener', array('My/Entity1', 'EntityListener1', 'postLoad')); $attachListener = $container->getDefinition('doctrine.orm.em2_listeners.attach_entity_listeners'); $this->assertDICDefinitionMethodCallOnce($attachListener, 'addEntityListener', array('My/Entity2', 'EntityListener2', 'preFlush', 'preFlushHandler')); } public function testRepositoryFactory() { $container = $this->loadContainer('orm_repository_factory'); $definition = $container->getDefinition('doctrine.orm.default_configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'setRepositoryFactory', array('repository_factory')); } private function loadContainer($fixture, array $bundles = array('YamlBundle'), CompilerPassInterface $compilerPass = null) { $container = $this->getContainer($bundles); $container->registerExtension(new DoctrineExtension()); $this->loadFromFile($container, $fixture); if (null !== $compilerPass) { $container->addCompilerPass($compilerPass); } $this->compileContainer($container); return $container; } private function getContainer(array $bundles) { $map = array(); foreach ($bundles as $bundle) { require_once __DIR__.'/Fixtures/Bundles/'.$bundle.'/'.$bundle.'.php'; $map[$bundle] = 'Fixtures\\Bundles\\'.$bundle.'\\'.$bundle; } return new ContainerBuilder(new ParameterBag(array( 'kernel.debug' => false, 'kernel.bundles' => $map, 'kernel.cache_dir' => sys_get_temp_dir(), 'kernel.environment' => 'test', 'kernel.root_dir' => __DIR__.'/../../', // src dir ))); } /** * Assertion on the Class of a DIC Service Definition. * * @param Definition $definition * @param string $expectedClass */ private function assertDICDefinitionClass(Definition $definition, $expectedClass) { $this->assertEquals($expectedClass, $definition->getClass(), 'Expected Class of the DIC Container Service Definition is wrong.'); } private function assertDICConstructorArguments(Definition $definition, $args) { $this->assertEquals($args, $definition->getArguments(), "Expected and actual DIC Service constructor arguments of definition '".$definition->getClass()."' don't match."); } private function assertDICDefinitionMethodCallAt($pos, Definition $definition, $methodName, array $params = null) { $calls = $definition->getMethodCalls(); if (isset($calls[$pos][0])) { $this->assertEquals($methodName, $calls[$pos][0], "Method '".$methodName."' is expected to be called at position $pos."); if ($params !== null) { $this->assertEquals($params, $calls[$pos][1], "Expected parameters to methods '".$methodName."' do not match the actual parameters."); } } } /** * Assertion for the DI Container, check if the given definition contains a method call with the given parameters. * * @param Definition $definition * @param string $methodName * @param array $params */ private function assertDICDefinitionMethodCallOnce(Definition $definition, $methodName, array $params = null) { $calls = $definition->getMethodCalls(); $called = false; foreach ($calls as $call) { if ($call[0] == $methodName) { if ($called) { $this->fail("Method '".$methodName."' is expected to be called only once, a second call was registered though."); } else { $called = true; if ($params !== null) { $this->assertEquals($params, $call[1], "Expected parameters to methods '".$methodName."' do not match the actual parameters."); } } } } if (!$called) { $this->fail("Method '".$methodName."' is expected to be called once, definition does not contain a call though."); } } private function assertDICDefinitionMethodCallCount(Definition $definition, $methodName, array $params = array(), $nbCalls = 1) { $calls = $definition->getMethodCalls(); $called = 0; foreach ($calls as $call) { if ($call[0] == $methodName) { if ($called > $nbCalls) { break; } if (isset($params[$called])) { $this->assertEquals($params[$called], $call[1], "Expected parameters to methods '".$methodName."' do not match the actual parameters."); } $called++; } } $this->assertEquals($nbCalls, $called, sprintf('The method "%s" should be called %d times', $methodName, $nbCalls)); } private function compileContainer(ContainerBuilder $container) { $container->getCompilerPassConfig()->setOptimizationPasses(array(new ResolveDefinitionTemplatesPass())); $container->getCompilerPassConfig()->setRemovingPasses(array()); $container->compile(); } } DoctrineBundle-1.6.2/Tests/DependencyInjection/DoctrineExtensionTest.php000066400000000000000000000645361264451145000265010ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection; use Doctrine\Bundle\DoctrineBundle\DependencyInjection\DoctrineExtension; use Doctrine\Common\Proxy\AbstractProxyFactory; use Doctrine\ORM\Version; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Compiler\ResolveDefinitionTemplatesPass; class DoctrineExtensionTest extends \PHPUnit_Framework_TestCase { public function testDbalOverrideDefaultConnection() { $container = $this->getContainer(); $extension = new DoctrineExtension(); $container->registerExtension($extension); $extension->load(array(array(), array('dbal' => array('default_connection' => 'foo')), array()), $container); // doctrine.dbal.default_connection $this->assertEquals('%doctrine.default_connection%', $container->getDefinition('doctrine')->getArgument(3), '->load() overrides existing configuration options'); $this->assertEquals('foo', $container->getParameter('doctrine.default_connection'), '->load() overrides existing configuration options'); } /** * @expectedException \LogicException * @expectedExceptionMessage Configuring the ORM layer requires to configure the DBAL layer as well. */ public function testOrmRequiresDbal() { $extension = new DoctrineExtension(); $extension->load(array(array('orm' => array('auto_mapping' => true))), $this->getContainer()); } public function getAutomappingConfigurations() { return array( array( array( 'em1' => array( 'mappings' => array( 'YamlBundle' => null, ), ), 'em2' => array( 'mappings' => array( 'XmlBundle' => null, ), ), ), ), array( array( 'em1' => array( 'auto_mapping' => true, ), 'em2' => array( 'mappings' => array( 'XmlBundle' => null, ), ), ), ), array( array( 'em1' => array( 'auto_mapping' => true, 'mappings' => array( 'YamlBundle' => null, ), ), 'em2' => array( 'mappings' => array( 'XmlBundle' => null, ), ), ), ), ); } /** * @dataProvider getAutomappingConfigurations */ public function testAutomapping(array $entityManagers) { $extension = new DoctrineExtension(); if (!method_exists($extension, 'fixManagersAutoMappings')) { $this->markTestSkipped('Auto mapping with multiple managers available with Symfony ~2.6'); } $container = $this->getContainer(array( 'YamlBundle', 'XmlBundle', )); $extension->load( array( array( 'dbal' => array( 'default_connection' => 'cn1', 'connections' => array( 'cn1' => array(), 'cn2' => array(), ), ), 'orm' => array( 'entity_managers' => $entityManagers, ), ), ), $container); $configEm1 = $container->getDefinition('doctrine.orm.em1_configuration'); $configEm2 = $container->getDefinition('doctrine.orm.em2_configuration'); $this->assertContains( array( 'setEntityNamespaces', array( array( 'YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity', ), ), ), $configEm1->getMethodCalls() ); $this->assertContains( array( 'setEntityNamespaces', array( array( 'XmlBundle' => 'Fixtures\Bundles\XmlBundle\Entity', ), ), ), $configEm2->getMethodCalls() ); } public function testDbalLoad() { $container = $this->getContainer(); $extension = new DoctrineExtension(); $extension->load(array(array('dbal' => array('connections' => array('default' => array('password' => 'foo')))), array(), array('dbal' => array('default_connection' => 'foo')), array()), $container); $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0); $this->assertEquals('foo', $config['password']); $this->assertEquals('root', $config['user']); } public function testDependencyInjectionConfigurationDefaults() { $container = $this->getContainer(); $extension = new DoctrineExtension(); $extension->load(array(array('dbal' => array('connections' => array('default' => array('password' => 'foo'))), 'orm' => array('default_entity_manager' => 'default', 'entity_managers' => array('default' => array('mappings' => array('YamlBundle' => array())))))), $container); $this->assertFalse($container->getParameter('doctrine.orm.auto_generate_proxy_classes')); $this->assertEquals('Doctrine\ORM\Configuration', $container->getParameter('doctrine.orm.configuration.class')); $this->assertEquals('Doctrine\ORM\EntityManager', $container->getParameter('doctrine.orm.entity_manager.class')); $this->assertEquals('Proxies', $container->getParameter('doctrine.orm.proxy_namespace')); $this->assertEquals('Doctrine\Common\Cache\ArrayCache', $container->getParameter('doctrine.orm.cache.array.class')); $this->assertEquals('Doctrine\Common\Cache\ApcCache', $container->getParameter('doctrine.orm.cache.apc.class')); $this->assertEquals('Doctrine\Common\Cache\MemcacheCache', $container->getParameter('doctrine.orm.cache.memcache.class')); $this->assertEquals('localhost', $container->getParameter('doctrine.orm.cache.memcache_host')); $this->assertEquals('11211', $container->getParameter('doctrine.orm.cache.memcache_port')); $this->assertEquals('Memcache', $container->getParameter('doctrine.orm.cache.memcache_instance.class')); $this->assertEquals('Doctrine\Common\Cache\XcacheCache', $container->getParameter('doctrine.orm.cache.xcache.class')); $this->assertEquals('Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain', $container->getParameter('doctrine.orm.metadata.driver_chain.class')); $this->assertEquals('Doctrine\ORM\Mapping\Driver\AnnotationDriver', $container->getParameter('doctrine.orm.metadata.annotation.class')); $this->assertEquals('Doctrine\ORM\Mapping\Driver\SimplifiedXmlDriver', $container->getParameter('doctrine.orm.metadata.xml.class')); $this->assertEquals('Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver', $container->getParameter('doctrine.orm.metadata.yml.class')); // second-level cache $this->assertEquals('Doctrine\ORM\Cache\DefaultCacheFactory', $container->getParameter('doctrine.orm.second_level_cache.default_cache_factory.class')); $this->assertEquals('Doctrine\ORM\Cache\Region\DefaultRegion', $container->getParameter('doctrine.orm.second_level_cache.default_region.class')); $this->assertEquals('Doctrine\ORM\Cache\Region\FileLockRegion', $container->getParameter('doctrine.orm.second_level_cache.filelock_region.class')); $this->assertEquals('Doctrine\ORM\Cache\Logging\CacheLoggerChain', $container->getParameter('doctrine.orm.second_level_cache.logger_chain.class')); $this->assertEquals('Doctrine\ORM\Cache\Logging\StatisticsCacheLogger', $container->getParameter('doctrine.orm.second_level_cache.logger_statistics.class')); $this->assertEquals('Doctrine\ORM\Cache\CacheConfiguration', $container->getParameter('doctrine.orm.second_level_cache.cache_configuration.class')); $this->assertEquals('Doctrine\ORM\Cache\RegionsConfiguration', $container->getParameter('doctrine.orm.second_level_cache.regions_configuration.class')); $config = array( 'proxy_namespace' => 'MyProxies', 'auto_generate_proxy_classes' => true, 'default_entity_manager' => 'default', 'entity_managers' => array( 'default' => array( 'mappings' => array('YamlBundle' => array()), ), ), ); $container = $this->getContainer(); $extension->load(array(array('dbal' => array('connections' => array('default' => array('password' => 'foo'))), 'orm' => $config)), $container); $this->compileContainer($container); $definition = $container->getDefinition('doctrine.dbal.default_connection'); $args = $definition->getArguments(); $this->assertEquals('pdo_mysql', $args[0]['driver']); $this->assertEquals('localhost', $args[0]['host']); $this->assertEquals('root', $args[0]['user']); $this->assertEquals('doctrine.dbal.default_connection.configuration', (string) $args[1]); $this->assertEquals('doctrine.dbal.default_connection.event_manager', (string) $args[2]); $this->assertCount(0, $definition->getMethodCalls()); $definition = $container->getDefinition('doctrine.orm.default_entity_manager'); $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass()); if (method_exists($definition, 'getFactory')) { $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory()); } else { $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getFactoryClass()); $this->assertEquals('create', $definition->getFactoryMethod()); } $this->assertEquals(array('default' => 'doctrine.orm.default_entity_manager'), $container->getParameter('doctrine.entity_managers'), "Set of the existing EntityManagers names is incorrect."); $this->assertEquals('%doctrine.entity_managers%', $container->getDefinition('doctrine')->getArgument(2), "Set of the existing EntityManagers names is incorrect."); $arguments = $definition->getArguments(); $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]); $this->assertEquals('doctrine.dbal.default_connection', (string) $arguments[0]); $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]); $this->assertEquals('doctrine.orm.default_configuration', (string) $arguments[1]); $definition = $container->getDefinition('doctrine.orm.default_configuration'); $calls = array_values($definition->getMethodCalls()); $this->assertEquals(array('YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity'), $calls[0][1][0]); $this->assertEquals('doctrine.orm.default_metadata_cache', (string) $calls[1][1][0]); $this->assertEquals('doctrine.orm.default_query_cache', (string) $calls[2][1][0]); $this->assertEquals('doctrine.orm.default_result_cache', (string) $calls[3][1][0]); if (version_compare(Version::VERSION, "2.3.0-DEV") >= 0) { $this->assertEquals('doctrine.orm.naming_strategy.default', (string) $calls[10][1][0]); $this->assertEquals('doctrine.orm.quote_strategy.default', (string) $calls[11][1][0]); } if (version_compare(Version::VERSION, "2.4.0-DEV") >= 0) { $this->assertEquals('doctrine.orm.default_entity_listener_resolver', (string) $calls[12][1][0]); } $definition = $container->getDefinition($container->getAlias('doctrine.orm.default_metadata_cache')); $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass()); $definition = $container->getDefinition($container->getAlias('doctrine.orm.default_query_cache')); $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass()); $definition = $container->getDefinition($container->getAlias('doctrine.orm.default_result_cache')); $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass()); } public function testUseSavePointsAddMethodCallToAddSavepointsToTheConnection() { $container = $this->getContainer(); $extension = new DoctrineExtension(); $extension->load(array(array('dbal' => array('connections' => array( 'default' => array('password' => 'foo', 'use_savepoints' => true) )))), $container); $calls = $container->getDefinition('doctrine.dbal.default_connection')->getMethodCalls(); $this->assertCount(1, $calls); $this->assertEquals('setNestTransactionsWithSavepoints', $calls[0][0]); $this->assertTrue($calls[0][1][0]); } public function testAutoGenerateProxyClasses() { $container = $this->getContainer(); $extension = new DoctrineExtension(); $config = array( 'proxy_namespace' => 'MyProxies', 'auto_generate_proxy_classes' => 'eval', 'default_entity_manager' => 'default', 'entity_managers' => array( 'default' => array( 'mappings' => array('YamlBundle' => array()), ), ), ); $extension->load(array(array('dbal' => array('connections' => array('default' => array('password' => 'foo'))), 'orm' => $config)), $container); $this->assertEquals(AbstractProxyFactory::AUTOGENERATE_EVAL, $container->getParameter('doctrine.orm.auto_generate_proxy_classes')); } public function testSingleEntityManagerConfiguration() { $container = $this->getContainer(); $extension = new DoctrineExtension(); $extension->load(array(array('dbal' => array('connections' => array('default' => array('password' => 'foo'))), 'orm' => array('default_entity_manager' => 'default', 'entity_managers' => array('default' => array('mappings' => array('YamlBundle' => array())))))), $container); $this->compileContainer($container); $definition = $container->getDefinition('doctrine.orm.default_entity_manager'); $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass()); if (method_exists($definition, 'getFactory')) { $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory()); } else { $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getFactoryClass()); $this->assertEquals('create', $definition->getFactoryMethod()); } $this->assertDICConstructorArguments($definition, array( new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'), )); } public function testBundleEntityAliases() { $container = $this->getContainer(); $extension = new DoctrineExtension(); $config = $this->getConnectionConfig(); $config['orm'] = array('default_entity_manager' => 'default', 'entity_managers' => array('default' => array('mappings' => array('YamlBundle' => array())))); $extension->load(array($config), $container); $definition = $container->getDefinition('doctrine.orm.default_configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityNamespaces', array(array('YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity')) ); } public function testOverwriteEntityAliases() { $container = $this->getContainer(); $extension = new DoctrineExtension(); $config = $this->getConnectionConfig(); $config['orm'] = array('default_entity_manager' => 'default', 'entity_managers' => array('default' => array('mappings' => array('YamlBundle' => array('alias' => 'yml'))))); $extension->load(array($config), $container); $definition = $container->getDefinition('doctrine.orm.default_configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityNamespaces', array(array('yml' => 'Fixtures\Bundles\YamlBundle\Entity')) ); } public function testYamlBundleMappingDetection() { $container = $this->getContainer('YamlBundle'); $extension = new DoctrineExtension(); $config = $this->getConnectionConfig(); $config['orm'] = array('default_entity_manager' => 'default', 'entity_managers' => array('default' => array('mappings' => array('YamlBundle' => array())))); $extension->load(array($config), $container); $definition = $container->getDefinition('doctrine.orm.default_metadata_driver'); $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', array( new Reference('doctrine.orm.default_yml_metadata_driver'), 'Fixtures\Bundles\YamlBundle\Entity', )); } public function testXmlBundleMappingDetection() { $container = $this->getContainer('XmlBundle'); $extension = new DoctrineExtension(); $config = $this->getConnectionConfig(); $config['orm'] = array('default_entity_manager' => 'default', 'entity_managers' => array('default' => array('mappings' => array('XmlBundle' => array())))); $extension->load(array($config), $container); $definition = $container->getDefinition('doctrine.orm.default_metadata_driver'); $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', array( new Reference('doctrine.orm.default_xml_metadata_driver'), 'Fixtures\Bundles\XmlBundle\Entity', )); } public function testAnnotationsBundleMappingDetection() { $container = $this->getContainer('AnnotationsBundle'); $extension = new DoctrineExtension(); $config = $this->getConnectionConfig(); $config['orm'] = array('default_entity_manager' => 'default', 'entity_managers' => array('default' => array('mappings' => array('AnnotationsBundle' => array())))); $extension->load(array($config), $container); $definition = $container->getDefinition('doctrine.orm.default_metadata_driver'); $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', array( new Reference('doctrine.orm.default_annotation_metadata_driver'), 'Fixtures\Bundles\AnnotationsBundle\Entity', )); } public function testOrmMergeConfigs() { $container = $this->getContainer(array('XmlBundle', 'AnnotationsBundle')); $extension = new DoctrineExtension(); $config1 = $this->getConnectionConfig(); $config1['orm'] = array( 'auto_generate_proxy_classes' => true, 'default_entity_manager' => 'default', 'entity_managers' => array( 'default' => array('mappings' => array('AnnotationsBundle' => array())), ), ); $config2 = $this->getConnectionConfig(); $config2['orm'] = array( 'auto_generate_proxy_classes' => false, 'default_entity_manager' => 'default', 'entity_managers' => array( 'default' => array('mappings' => array('XmlBundle' => array())), ), ); $extension->load(array($config1, $config2), $container); $definition = $container->getDefinition('doctrine.orm.default_metadata_driver'); $this->assertDICDefinitionMethodCallAt(0, $definition, 'addDriver', array( new Reference('doctrine.orm.default_annotation_metadata_driver'), 'Fixtures\Bundles\AnnotationsBundle\Entity', )); $this->assertDICDefinitionMethodCallAt(1, $definition, 'addDriver', array( new Reference('doctrine.orm.default_xml_metadata_driver'), 'Fixtures\Bundles\XmlBundle\Entity', )); $configDef = $container->getDefinition('doctrine.orm.default_configuration'); $this->assertDICDefinitionMethodCallOnce($configDef, 'setAutoGenerateProxyClasses'); $calls = $configDef->getMethodCalls(); foreach ($calls as $call) { if ($call[0] === 'setAutoGenerateProxyClasses') { $this->assertFalse($container->getParameterBag()->resolveValue($call[1][0])); break; } } } public function testAnnotationsBundleMappingDetectionWithVendorNamespace() { $container = $this->getContainer('AnnotationsBundle', 'Vendor'); $extension = new DoctrineExtension(); $config = $this->getConnectionConfig(); $config['orm'] = array('default_entity_manager' => 'default', 'entity_managers' => array('default' => array('mappings' => array('AnnotationsBundle' => array())))); $extension->load(array($config), $container); $calls = $container->getDefinition('doctrine.orm.default_metadata_driver')->getMethodCalls(); $this->assertEquals('doctrine.orm.default_annotation_metadata_driver', (string) $calls[0][1][0]); $this->assertEquals('Fixtures\Bundles\Vendor\AnnotationsBundle\Entity', $calls[0][1][1]); } public function testCacheConfiguration() { $container = $this->getContainer(); $extension = new DoctrineExtension(); $config = $this->getConnectionConfig(); $config['orm'] = array( 'metadata_cache_driver' => array( 'cache_provider' => 'metadata_cache', ), 'query_cache_driver' => array( 'cache_provider' => 'query_cache', ), 'result_cache_driver' => array( 'cache_provider' => 'result_cache', ), ); $extension->load(array($config), $container); $this->assertTrue($container->hasAlias('doctrine.orm.default_metadata_cache')); $alias = $container->getAlias('doctrine.orm.default_metadata_cache'); $this->assertEquals('doctrine_cache.providers.metadata_cache', (string) $alias); $this->assertTrue($container->hasAlias('doctrine.orm.default_query_cache')); $alias = $container->getAlias('doctrine.orm.default_query_cache'); $this->assertEquals('doctrine_cache.providers.query_cache', (string) $alias); $this->assertTrue($container->hasAlias('doctrine.orm.default_result_cache')); $alias = $container->getAlias('doctrine.orm.default_result_cache'); $this->assertEquals('doctrine_cache.providers.result_cache', (string) $alias); } private function getContainer($bundles = 'YamlBundle', $vendor = null) { $bundles = (array) $bundles; $map = array(); foreach ($bundles as $bundle) { require_once __DIR__.'/Fixtures/Bundles/'.($vendor ? $vendor.'/' : '').$bundle.'/'.$bundle.'.php'; $map[$bundle] = 'Fixtures\\Bundles\\'.($vendor ? $vendor.'\\' : '').$bundle.'\\'.$bundle; } return new ContainerBuilder(new ParameterBag(array( 'kernel.debug' => false, 'kernel.bundles' => $map, 'kernel.cache_dir' => sys_get_temp_dir(), 'kernel.environment' => 'test', 'kernel.root_dir' => __DIR__.'/../../', // src dir ))); } private function assertDICConstructorArguments(Definition $definition, array $args) { $this->assertEquals($args, $definition->getArguments(), "Expected and actual DIC Service constructor arguments of definition '".$definition->getClass()."' don't match."); } private function assertDICDefinitionMethodCallAt($pos, Definition $definition, $methodName, array $params = null) { $calls = $definition->getMethodCalls(); if (isset($calls[$pos][0])) { $this->assertEquals($methodName, $calls[$pos][0], "Method '".$methodName."' is expected to be called at position $pos."); if ($params !== null) { $this->assertEquals($params, $calls[$pos][1], "Expected parameters to methods '".$methodName."' do not match the actual parameters."); } } } /** * Assertion for the DI Container, check if the given definition contains a method call with the given parameters. * * @param Definition $definition * @param string $methodName * @param array|null $params */ private function assertDICDefinitionMethodCallOnce(Definition $definition, $methodName, array $params = null) { $calls = $definition->getMethodCalls(); $called = false; foreach ($calls as $call) { if ($call[0] === $methodName) { if ($called) { $this->fail("Method '".$methodName."' is expected to be called only once, a second call was registered though."); } else { $called = true; if ($params !== null) { $this->assertEquals($params, $call[1], "Expected parameters to methods '".$methodName."' do not match the actual parameters."); } } } } if (!$called) { $this->fail("Method '".$methodName."' is expected to be called once, definition does not contain a call though."); } } private function compileContainer(ContainerBuilder $container) { $container->getCompilerPassConfig()->setOptimizationPasses(array(new ResolveDefinitionTemplatesPass())); $container->getCompilerPassConfig()->setRemovingPasses(array()); $container->compile(); } private function getConnectionConfig() { return array('dbal' => array('connections' => array('default' => array('password' => 'foo')))); } } DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/000077500000000000000000000000001264451145000232575ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/000077500000000000000000000000001264451145000246535ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/AnnotationsBundle/000077500000000000000000000000001264451145000303025ustar00rootroot00000000000000AnnotationsBundle.php000066400000000000000000000010001264451145000343520ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/AnnotationsBundle * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Fixtures\Bundles\AnnotationsBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class AnnotationsBundle extends Bundle { } DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/AnnotationsBundle/Entity/000077500000000000000000000000001264451145000315565ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/AnnotationsBundle/Entity/Test.php000066400000000000000000000006721264451145000332130ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Fixtures\Bundles\AnnotationsBundle\Entity; class Test { } DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/Vendor/000077500000000000000000000000001264451145000261105ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/Vendor/AnnotationsBundle/000077500000000000000000000000001264451145000315375ustar00rootroot00000000000000AnnotationsBundle.php000066400000000000000000000010071264451145000356160ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/Vendor/AnnotationsBundle * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Fixtures\Bundles\Vendor\AnnotationsBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class AnnotationsBundle extends Bundle { } DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/Vendor/AnnotationsBundle/Entity/000077500000000000000000000000001264451145000330135ustar00rootroot00000000000000Test.php000066400000000000000000000007011264451145000343620ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/Vendor/AnnotationsBundle/Entity * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Fixtures\Bundles\Vendor\AnnotationsBundle\Entity; class Test { } DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/XmlBundle/000077500000000000000000000000001264451145000265455ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/XmlBundle/Entity/000077500000000000000000000000001264451145000300215ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/XmlBundle/Entity/Test.php000066400000000000000000000006621264451145000314550ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Fixtures\Bundles\XmlBundle\Entity; class Test { } DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/XmlBundle/Resources/000077500000000000000000000000001264451145000305175ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/XmlBundle/Resources/config/000077500000000000000000000000001264451145000317645ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/XmlBundle/Resources/config/doctrine/000077500000000000000000000000001264451145000335735ustar00rootroot00000000000000Test.orm.xml000066400000000000000000000000001264451145000357370ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/XmlBundle/Resources/config/doctrineDoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/XmlBundle/XmlBundle.php000066400000000000000000000007601264451145000311530ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Fixtures\Bundles\XmlBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class XmlBundle extends Bundle { } DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/YamlBundle/000077500000000000000000000000001264451145000267075ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/YamlBundle/Entity/000077500000000000000000000000001264451145000301635ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/YamlBundle/Entity/Test.php000066400000000000000000000007041264451145000316140ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Fixtures\Bundles\YamlBundle\Entity; class Test { private $id; } DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/YamlBundle/Resources/000077500000000000000000000000001264451145000306615ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/YamlBundle/Resources/config/000077500000000000000000000000001264451145000321265ustar00rootroot00000000000000000077500000000000000000000000001264451145000336565ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/YamlBundle/Resources/config/doctrineTest.orm.yml000066400000000000000000000001321264451145000361100ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/YamlBundle/Resources/config/doctrineFixtures\Bundles\YamlBundle\Entity\Test: type: entity id: id: type: integer DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/Bundles/YamlBundle/YamlBundle.php000066400000000000000000000007621264451145000314610ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Fixtures\Bundles\YamlBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class YamlBundle extends Bundle { } DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/000077500000000000000000000000001264451145000245245ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/000077500000000000000000000000001264451145000253245ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/dbal_auto_commit.xml000066400000000000000000000010111264451145000313410ustar00rootroot00000000000000 DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/dbal_logging.xml000066400000000000000000000020001264451145000304460ustar00rootroot00000000000000 DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/dbal_savepoints.xml000066400000000000000000000014741264451145000312310ustar00rootroot00000000000000 DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/dbal_schema_filter.xml000066400000000000000000000010131264451145000316300ustar00rootroot00000000000000 dbal_service_multiple_connections.xml000066400000000000000000000043761264451145000347400ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml dbal_service_pool_sharding_connection.xml000066400000000000000000000014551264451145000355450ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml dbal_service_single_connection.xml000066400000000000000000000011541264451145000341720ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml dbal_service_single_master_slave_connection.xml000066400000000000000000000013751264451145000367440ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/dbal_types.xml000066400000000000000000000012601264451145000301730ustar00rootroot00000000000000 Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestType DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/orm_attach_entity_listener.xml000066400000000000000000000032001264451145000334630ustar00rootroot00000000000000 orm_attach_entity_listener_tag.xml000066400000000000000000000023671264451145000342540ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/orm_entity_listener_resolver.xml000066400000000000000000000024371264451145000340730ustar00rootroot00000000000000 DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/orm_filters.xml000066400000000000000000000020361264451145000303740ustar00rootroot00000000000000 Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\TestFilter myValue mySecondValue DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/orm_functions.xml000066400000000000000000000024051264451145000307340ustar00rootroot00000000000000 Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestNumericFunction Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestDatetimeFunction DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/orm_hydration_mode.xml000066400000000000000000000016141264451145000317320ustar00rootroot00000000000000 Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestHydrator DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/orm_imports.xml000066400000000000000000000011661264451145000304240ustar00rootroot00000000000000 DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/orm_imports_import.xml000066400000000000000000000015561264451145000320210ustar00rootroot00000000000000 orm_multiple_em_bundle_mappings.xml000066400000000000000000000022661264451145000344150ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/orm_namingstrategy.xml000066400000000000000000000017521264451145000317640ustar00rootroot00000000000000 DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/orm_proxy.xml000066400000000000000000000010661264451145000301070ustar00rootroot00000000000000 DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/orm_quotestrategy.xml000066400000000000000000000017401264451145000316450ustar00rootroot00000000000000 DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/orm_repository_factory.xml000066400000000000000000000012601264451145000326700ustar00rootroot00000000000000 DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/orm_resolve_target_entity.xml000066400000000000000000000014331264451145000333450ustar00rootroot00000000000000 MyUserClass DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/orm_second_level_cache.xml000066400000000000000000000047351264451145000325210ustar00rootroot00000000000000 3600 orm_service_multiple_entity_managers.xml000066400000000000000000000030251264451145000354700ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml Proxies orm_service_simple_single_entity_manager.xml000066400000000000000000000021051264451145000363020ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml Doctrine\Common\Cache\MemcacheCache localhost 11211 Memcache orm_service_simple_single_entity_manager_without_dbname.xml000066400000000000000000000020701264451145000413740ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml Doctrine\Common\Cache\MemcacheCache localhost 11211 Memcache orm_service_single_entity_manager.xml000066400000000000000000000030211264451145000347270ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml Proxies Doctrine\Common\Cache\MemcacheCache localhost 11211 Memcache DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/orm_single_em_bundle_mappings.xml000066400000000000000000000017651264451145000341250ustar00rootroot00000000000000 orm_single_em_default_table_options.xml000066400000000000000000000024221264451145000352340ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml utf8mb4 utf8mb4_unicode_ci InnoDB DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/xml/orm_single_em_dql_functions.xml000066400000000000000000000014521264451145000336170ustar00rootroot00000000000000 Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/000077500000000000000000000000001264451145000253255ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/dbal_auto_commit.yml000066400000000000000000000000571264451145000313540ustar00rootroot00000000000000doctrine: dbal: auto_commit: false DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/dbal_logging.yml000066400000000000000000000004771264451145000304700ustar00rootroot00000000000000doctrine: dbal: default_connection: mysql connections: log: logging: true profiling: false profile: logging: false profiling: true both: logging: true profiling: true DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/dbal_savepoints.yml000066400000000000000000000003741264451145000312310ustar00rootroot00000000000000doctrine: dbal: default_connection: savepoints connections: savepoints: use_savepoints: true nosavepoints: use_savepoints: false notset: user: root DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/dbal_schema_filter.yml000066400000000000000000000000611264451145000316340ustar00rootroot00000000000000doctrine: dbal: schema_filter: ^sf2_ dbal_service_multiple_connections.yml000066400000000000000000000030461264451145000347330ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: mysql connections: mysql: dbname: mysql_db user: mysql_user password: mysql_s3cr3t unix_socket: /path/to/mysqld.sock sqlite: driver: pdo_sqlite dbname: sqlite_db user: sqlite_user password: sqlite_s3cr3t path: /tmp/db.sqlite memory: true oci: driver: oci8 dbname: oracle_db user: oracle_user password: oracle_s3cr3t servicename: oracle_service service: true pooled: true charset: utf8 ibmdb2: driver: ibm_db2 dbname: ibmdb2_db user: ibmdb2_user password: ibmdb2_s3cr3t protocol: TCPIP pgsql: driver: pdo_pgsql dbname: pgsql_db user: pgsql_user password: pgsql_s3cr3t sslmode: require sslrootcert: postgresql-ca.pem charset: utf8 sqlanywhere: driver: sqlanywhere host: localhost port: 2683 server: sqlanywhere_server dbname: sqlanywhere_db user: sqlanywhere_user password: sqlanywhere_s3cr3t persistent: true charset: utf8 dbal_service_pool_sharding_connection.yml000066400000000000000000000006231264451145000355430ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: dbname: mysql_db user: mysql_user password: mysql_s3cr3t unix_socket: /path/to/mysqld.sock shard_choser_service: foo.shard_choser shards: - id: 1 user: shard_user dbname: shard_db password: shard_s3cr3t unix_socket: /path/to/mysqld_shard.sock dbal_service_single_connection.yml000066400000000000000000000002561264451145000341760ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: dbname: mysql_db user: mysql_user password: mysql_s3cr3t unix_socket: /path/to/mysqld.sock server_version: 5.6.20 dbal_service_single_master_slave_connection.yml000066400000000000000000000005551264451145000367450ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: dbname: mysql_db user: mysql_user password: mysql_s3cr3t unix_socket: /path/to/mysqld.sock keep_slave: true slaves: slave1: user: slave_user dbname: slave_db password: slave_s3cr3t unix_socket: /path/to/mysqld_slave.sock DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/dbal_types.yml000066400000000000000000000003061264451145000301750ustar00rootroot00000000000000doctrine: dbal: default_connection: default types: test: Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestType connections: default: ~ DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/orm_attach_entity_listener.yml000066400000000000000000000015261264451145000334760ustar00rootroot00000000000000doctrine: dbal: default_connection: default connections: default: dbname: db orm: entity_managers: default: entity_listeners: ExternalBundles\Entities\FooEntity: MyBundles\Listeners\FooEntityListener: prePersist: postPersist: [postPersist] postLoad: [postLoadHandler] ExternalBundles\Entities\BarEntity: MyBundles\Listeners\BarEntityListener: prePersist: [prePersist, prePersistHandler] MyBundles\Listeners\LogDeleteEntityListener: postDelete: [postDelete] orm_attach_entity_listener_tag.yml000066400000000000000000000011301264451145000342410ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/ymlservices: entity_listener1: class: EntityListener1 tags: - { name: doctrine.orm.entity_listener, entity: My/Entity1, event: postLoad} entity_listener2: class: EntityListener2 tags: - { name: doctrine.orm.entity_listener, entity_manager: em2, entity: My/Entity2, event: preFlush, method: preFlushHandler} doctrine: dbal: default_connection: default connections: default: dbname: db orm: default_entity_manager: em1 entity_managers: em1: em2: DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/orm_entity_listener_resolver.yml000066400000000000000000000012341264451145000340670ustar00rootroot00000000000000services: entity_listener_resolver: class: \Doctrine\ORM\Mapping\DefaultEntityListenerResolver entity_listener1: class: \EntityListener tags: - { name: doctrine.orm.entity_listener } entity_listener2: class: \EntityListener tags: - { name: doctrine.orm.entity_listener, entity_manager: em2 } doctrine: dbal: default_connection: default connections: default: dbname: db orm: default_entity_manager: em1 entity_managers: em1: em2: entity_listener_resolver: entity_listener_resolver DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/orm_filters.yml000066400000000000000000000010631264451145000303750ustar00rootroot00000000000000doctrine: dbal: default_connection: default connections: default: dbname: db orm: filters: soft_delete: class: Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\TestFilter enabled: true myFilter: class: Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\TestFilter enabled: true parameters: myParameter: myValue mySecondParameter: mySecondValue DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/orm_functions.yml000066400000000000000000000013211264451145000307320ustar00rootroot00000000000000doctrine: dbal: default_connection: default connections: default: dbname: db orm: entity_managers: default: mappings: YamlBundle: ~ dql: string_functions: test_string: Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction numeric_functions: test_numeric: Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestNumericFunction datetime_functions: test_datetime: Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestDatetimeFunction DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/orm_hydration_mode.yml000066400000000000000000000005641264451145000317370ustar00rootroot00000000000000doctrine: dbal: default_connection: default connections: default: dbname: db orm: entity_managers: default: hydrators: test_hydrator: Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestHydrator mappings: YamlBundle: ~ DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/orm_imports.yml000066400000000000000000000001601264451145000304170ustar00rootroot00000000000000imports: - { resource: orm_imports_import.yml } doctrine: orm: auto_generate_proxy_classes: true DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/orm_imports_import.yml000066400000000000000000000005571264451145000320230ustar00rootroot00000000000000doctrine: dbal: default_connection: default connections: default: dbname: db orm: auto_generate_proxy_classes: false default_entity_manager: default entity_managers: default: metadata_cache_driver: apc mappings: YamlBundle: ~ orm_multiple_em_bundle_mappings.yml000066400000000000000000000013351264451145000344130ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: default connections: default: dbname: db orm: default_entity_manager: em2 entity_managers: em1: mappings: AnnotationsBundle: ~ em2: mappings: YamlBundle: dir: Resources/config/doctrine alias: yml manual: type: xml prefix: Fixtures\Bundles\XmlBundle dir: %kernel.root_dir%/Tests/DependencyInjection/Fixtures/Bundles/XmlBundle/Resources/config/doctrine alias: TestAlias DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/orm_namingstrategy.yml000066400000000000000000000007551264451145000317700ustar00rootroot00000000000000doctrine: dbal: default_connection: default connections: default: dbname: db orm: default_entity_manager: em1 entity_managers: em1: mappings: YamlBundle: ~ naming_strategy: doctrine.orm.naming_strategy.default em2: mappings: YamlBundle: ~ naming_strategy: doctrine.orm.naming_strategy.underscore DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/orm_quotestrategy.yml000066400000000000000000000007431264451145000316510ustar00rootroot00000000000000doctrine: dbal: default_connection: default connections: default: dbname: db orm: default_entity_manager: em1 entity_managers: em1: mappings: YamlBundle: ~ quote_strategy: doctrine.orm.quote_strategy.default em2: mappings: YamlBundle: ~ quote_strategy: doctrine.orm.quote_strategy.ansi DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/orm_repository_factory.yml000066400000000000000000000002661264451145000326770ustar00rootroot00000000000000doctrine: dbal: default_connection: default connections: default: dbname: db orm: repository_factory: repository_factory DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/orm_resolve_target_entity.yml000066400000000000000000000003641264451145000333510ustar00rootroot00000000000000doctrine: dbal: default_connection: default connections: default: dbname: db orm: resolve_target_entities: Symfony\Component\Security\Core\User\UserInterface: MyUserClass DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/orm_second_level_cache.yml000066400000000000000000000036111264451145000325130ustar00rootroot00000000000000services: my_service_region_driver: class: Doctrine\Common\Cache\ArrayCache my_service_logger1: class: Doctrine\ORM\Cache\Logging\StatisticsCacheLogger my_service_logger2: class: Doctrine\ORM\Cache\Logging\StatisticsCacheLogger my_service_region: class: Doctrine\ORM\Cache\Region\DefaultRegion arguments: ["my_service_region", "@my_service_region_driver", 3600] my_factory_config: class: Doctrine\ORM\Cache\CacheConfiguration my_factory_driver: class: Doctrine\Common\Cache\ArrayCache my_factory: class: Doctrine\ORM\Cache\DefaultCacheFactory arguments: ["@my_factory_config", "@my_factory_driver"] doctrine: dbal: default_connection: default connections: default: dbname: db orm: entity_managers: custom_slc_factory: second_level_cache: factory: "my_factory" default: second_level_cache: log_enabled: true enabled: true region_cache_driver: array loggers: my_service_logger1 : service: "my_service_logger1" my_service_logger2 : service: "my_service_logger1" regions: my_service_region: type: service service : "my_service_region" my_query_region: lifetime: 300 cache_driver: array type: filelock lock_path: %kernel.cache_dir%/doctrine/orm/slc/filelock my_entity_region: lifetime: 600 cache_driver: type: apc orm_service_multiple_entity_managers.yml000066400000000000000000000016461264451145000355010ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/ymlparameters: doctrine.orm.proxy_namespace: Proxies doctrine: dbal: default_connection: conn1 connections: conn1: driver: pdo_sqlite dbname: sqlite_db user: sqlite_user password: sqlite_s3cr3t memory: true conn2: driver: pdo_sqlite dbname: sqlite_db user: sqlite_user password: sqlite_s3cr3t memory: true orm: default_entity_manager: em2 auto_generate_proxy_classes: true entity_managers: em1: metadata_cache_driver: xcache connection: conn1 mappings: YamlBundle: ~ em2: metadata_cache_driver: apc connection: conn2 mappings: YamlBundle: ~ orm_service_simple_single_entity_manager.yml000066400000000000000000000010231264451145000363020ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: default connections: default: dbname: db orm: default_entity_manager: default entity_managers: default: mappings: YamlBundle: ~ metadata_cache_driver: type: memcache class: Doctrine\Common\Cache\MemcacheCache host: localhost port: 11211 instance_class: Memcache orm_service_simple_single_entity_manager_without_dbname.yml000066400000000000000000000007701264451145000414030ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: default connections: default: orm: default_entity_manager: default entity_managers: default: mappings: YamlBundle: ~ metadata_cache_driver: type: memcache class: Doctrine\Common\Cache\MemcacheCache host: localhost port: 11211 instance_class: Memcache orm_service_single_entity_manager.yml000066400000000000000000000015221264451145000347350ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: default connections: default: driver: pdo_sqlite dbname: sqlite_db user: sqlite_user password: sqlite_s3cr3t memory: true orm: default_entity_manager: dm2 proxy_namespace: Proxies auto_generate_proxy_classes: true entity_managers: default: connection: default default_repository_class: Acme\Doctrine\Repository mappings: YamlBundle: ~ metadata_cache_driver: type: memcache class: Doctrine\Common\Cache\MemcacheCache host: localhost port: 11211 instance_class: Memcache DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/orm_single_em_bundle_mappings.yml000066400000000000000000000010241264451145000341130ustar00rootroot00000000000000doctrine: dbal: default_connection: default connections: default: dbname: db orm: mappings: AnnotationsBundle: ~ YamlBundle: dir: Resources/config/doctrine alias: yml manual: type: xml prefix: Fixtures\Bundles\XmlBundle dir: %kernel.root_dir%/Tests/DependencyInjection/Fixtures/Bundles/XmlBundle/Resources/config/doctrine alias: TestAlias orm_single_em_default_table_options.yml000066400000000000000000000012751264451145000352430ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: default connections: default: dbname: db default_table_options: charset: utf8mb4 collate: utf8mb4_unicode_ci engine: InnoDB orm: mappings: AnnotationsBundle: ~ YamlBundle: dir: Resources/config/doctrine alias: yml manual: type: xml prefix: Fixtures\Bundles\XmlBundle dir: %kernel.root_dir%/Tests/DependencyInjection/Fixtures/Bundles/XmlBundle/Resources/config/doctrine alias: TestAlias DoctrineBundle-1.6.2/Tests/DependencyInjection/Fixtures/config/yml/orm_single_em_dql_functions.yml000066400000000000000000000004321264451145000336160ustar00rootroot00000000000000doctrine: dbal: default_connection: default connections: default: dbname: db orm: dql: string_functions: test_string: Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction DoctrineBundle-1.6.2/Tests/DependencyInjection/TestDatetimeFunction.php000066400000000000000000000013751264451145000262670ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection; use Doctrine\ORM\Query\AST\Functions\FunctionNode; use Doctrine\ORM\Query\SqlWalker; use Doctrine\ORM\Query\Parser; class TestDatetimeFunction extends FunctionNode { public function getSql(SqlWalker $sqlWalker) { return ''; } public function parse(Parser $parser) { return ''; } } DoctrineBundle-1.6.2/Tests/DependencyInjection/TestFilter.php000066400000000000000000000014671264451145000242540ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection; use Doctrine\ORM\Query\Filter\SQLFilter; use Doctrine\ORM\Mapping\ClassMetadata; class TestFilter extends SQLFilter { /** * Gets the SQL query part to add to a query. * * @return string The constraint SQL if there is available, empty string otherwise */ public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) { } } DoctrineBundle-1.6.2/Tests/DependencyInjection/TestNumericFunction.php000066400000000000000000000013741264451145000261340ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection; use Doctrine\ORM\Query\AST\Functions\FunctionNode; use Doctrine\ORM\Query\SqlWalker; use Doctrine\ORM\Query\Parser; class TestNumericFunction extends FunctionNode { public function getSql(SqlWalker $sqlWalker) { return ''; } public function parse(Parser $parser) { return ''; } } DoctrineBundle-1.6.2/Tests/DependencyInjection/TestStringFunction.php000066400000000000000000000013731264451145000257770ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection; use Doctrine\ORM\Query\AST\Functions\FunctionNode; use Doctrine\ORM\Query\SqlWalker; use Doctrine\ORM\Query\Parser; class TestStringFunction extends FunctionNode { public function getSql(SqlWalker $sqlWalker) { return ''; } public function parse(Parser $parser) { return ''; } } DoctrineBundle-1.6.2/Tests/DependencyInjection/TestType.php000066400000000000000000000013321264451145000237370ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection; use Doctrine\DBAL\Platforms\AbstractPlatform; class TestType extends \Doctrine\DBAL\Types\Type { public function getName() { return 'test'; } public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) { return ''; } } DoctrineBundle-1.6.2/Tests/DependencyInjection/XMLSchemaTest.php000066400000000000000000000051471264451145000246070ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection; class XMLSchemaTest extends \PHPUnit_Framework_TestCase { public static function dataValidateSchemaFiles() { $schemaFiles = array(); $di = new \DirectoryIterator(__DIR__.'/Fixtures/config/xml'); foreach ($di as $element) { if ($element->isFile() && substr($element->getFilename(), -4) === ".xml") { $schemaFiles[] = array($element->getPathname()); } } return $schemaFiles; } /** * @dataProvider dataValidateSchemaFiles */ public function testValidateSchema($file) { $found = false; $dom = new \DOMDocument('1.0', 'UTF-8'); $dom->load($file); $xmlns = 'http://symfony.com/schema/dic/doctrine'; $dbalElements = $dom->getElementsByTagNameNS($xmlns, 'dbal'); if ($dbalElements->length) { $dbalDom = new \DOMDocument('1.0', 'UTF-8'); $dbalNode = $dbalDom->importNode($dbalElements->item(0)); $configNode = $dbalDom->createElementNS($xmlns, 'config'); $configNode->appendChild($dbalNode); $dbalDom->appendChild($configNode); $ret = $dbalDom->schemaValidate(__DIR__.'/../../Resources/config/schema/doctrine-1.0.xsd'); $this->assertTrue($ret, 'DoctrineBundle Dependency Injection XMLSchema did not validate this XML instance.'); $found = true; } $ormElements = $dom->getElementsByTagNameNS($xmlns, 'orm'); if ($ormElements->length) { $ormDom = new \DOMDocument('1.0', 'UTF-8'); $ormNode = $ormDom->importNode($ormElements->item(0)); $configNode = $ormDom->createElementNS($xmlns, 'config'); $configNode->appendChild($ormNode); $ormDom->appendChild($configNode); $ret = $ormDom->schemaValidate(__DIR__.'/../../Resources/config/schema/doctrine-1.0.xsd'); $this->assertTrue($ret, 'DoctrineBundle Dependency Injection XMLSchema did not validate this XML instance.'); $found = true; } $this->assertTrue($found, 'Neither nor elements found in given XML. Are namespaces configured correctly?'); } } DoctrineBundle-1.6.2/Tests/DependencyInjection/XmlDoctrineExtensionTest.php000066400000000000000000000016071264451145000271500ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\Config\FileLocator; class XmlDoctrineExtensionTest extends AbstractDoctrineExtensionTest { protected function loadFromFile(ContainerBuilder $container, $file) { $loadXml = new XmlFileLoader($container, new FileLocator(__DIR__.'/Fixtures/config/xml')); $loadXml->load($file.'.xml'); } } DoctrineBundle-1.6.2/Tests/DependencyInjection/YamlDoctrineExtensionTest.php000066400000000000000000000016141264451145000273100ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\Config\FileLocator; class YamlDoctrineExtensionTest extends AbstractDoctrineExtensionTest { protected function loadFromFile(ContainerBuilder $container, $file) { $loadYaml = new YamlFileLoader($container, new FileLocator(__DIR__.'/Fixtures/config/yml')); $loadYaml->load($file.'.yml'); } } DoctrineBundle-1.6.2/Tests/Mapping/000077500000000000000000000000001264451145000171205ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/Mapping/DisconnectedMetadataFactoryTest.php000066400000000000000000000035431264451145000260710ustar00rootroot00000000000000 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests\Mapping; use Doctrine\Bundle\DoctrineBundle\Mapping\ClassMetadataCollection; use Doctrine\Bundle\DoctrineBundle\Mapping\DisconnectedMetadataFactory; use Doctrine\Bundle\DoctrineBundle\Tests\TestCase; use Doctrine\ORM\Mapping\ClassMetadataInfo; class DisconnectedMetadataFactoryTest extends TestCase { protected function setUp() { parent::setUp(); if (!class_exists('Doctrine\\ORM\\Version')) { $this->markTestSkipped('Doctrine ORM is not available.'); } } public function testCannotFindNamespaceAndPathForMetadata() { $class = new ClassMetadataInfo(__CLASS__); $collection = new ClassMetadataCollection(array($class)); $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry'); $factory = new DisconnectedMetadataFactory($registry); $this->setExpectedException('RuntimeException', 'Can\'t find base path for "Doctrine\Bundle\DoctrineBundle\Tests\Mapping\DisconnectedMetadataFactoryTest'); $factory->findNamespaceAndPathForMetadata($collection); } public function testFindNamespaceAndPathForMetadata() { $class = new ClassMetadataInfo('\Vendor\Package\Class'); $collection = new ClassMetadataCollection(array($class)); $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry'); $factory = new DisconnectedMetadataFactory($registry); $factory->findNamespaceAndPathForMetadata($collection, '/path/to/code'); $this->assertEquals('\Vendor\Package', $collection->getNamespace()); } } DoctrineBundle-1.6.2/Tests/RegistryTest.php000066400000000000000000000142671264451145000207200ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests; use Doctrine\Bundle\DoctrineBundle\Registry; class RegistryTest extends TestCase { public function testGetDefaultConnectionName() { $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $registry = new Registry($container, array(), array(), 'default', 'default'); $this->assertEquals('default', $registry->getDefaultConnectionName()); } public function testGetDefaultEntityManagerName() { $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $registry = new Registry($container, array(), array(), 'default', 'default'); $this->assertEquals('default', $registry->getDefaultManagerName()); } public function testGetDefaultConnection() { $conn = $this->getMock('Doctrine\DBAL\Connection', array(), array(), '', false); $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $container->expects($this->once()) ->method('get') ->with($this->equalTo('doctrine.dbal.default_connection')) ->will($this->returnValue($conn)); $registry = new Registry($container, array('default' => 'doctrine.dbal.default_connection'), array(), 'default', 'default'); $this->assertSame($conn, $registry->getConnection()); } public function testGetConnection() { $conn = $this->getMock('Doctrine\DBAL\Connection', array(), array(), '', false); $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $container->expects($this->once()) ->method('get') ->with($this->equalTo('doctrine.dbal.default_connection')) ->will($this->returnValue($conn)); $registry = new Registry($container, array('default' => 'doctrine.dbal.default_connection'), array(), 'default', 'default'); $this->assertSame($conn, $registry->getConnection('default')); } public function testGetUnknownConnection() { $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $registry = new Registry($container, array(), array(), 'default', 'default'); $this->setExpectedException('InvalidArgumentException', 'Doctrine ORM Connection named "default" does not exist.'); $registry->getConnection('default'); } public function testGetConnectionNames() { $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $registry = new Registry($container, array('default' => 'doctrine.dbal.default_connection'), array(), 'default', 'default'); $this->assertEquals(array('default' => 'doctrine.dbal.default_connection'), $registry->getConnectionNames()); } public function testGetDefaultEntityManager() { $em = new \stdClass(); $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $container->expects($this->once()) ->method('get') ->with($this->equalTo('doctrine.orm.default_entity_manager')) ->will($this->returnValue($em)); $registry = new Registry($container, array(), array('default' => 'doctrine.orm.default_entity_manager'), 'default', 'default'); $this->assertSame($em, $registry->getManager()); } public function testGetEntityManager() { $em = new \stdClass(); $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $container->expects($this->once()) ->method('get') ->with($this->equalTo('doctrine.orm.default_entity_manager')) ->will($this->returnValue($em)); $registry = new Registry($container, array(), array('default' => 'doctrine.orm.default_entity_manager'), 'default', 'default'); $this->assertSame($em, $registry->getManager('default')); } public function testGetUnknownEntityManager() { $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $registry = new Registry($container, array(), array(), 'default', 'default'); $this->setExpectedException('InvalidArgumentException', 'Doctrine ORM Manager named "default" does not exist.'); $registry->getManager('default'); } public function testResetDefaultEntityManager() { $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $container->expects($this->once()) ->method('set') ->with($this->equalTo('doctrine.orm.default_entity_manager'), $this->equalTo(null)); $registry = new Registry($container, array(), array('default' => 'doctrine.orm.default_entity_manager'), 'default', 'default'); $registry->resetManager(); } public function testResetEntityManager() { $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $container->expects($this->once()) ->method('set') ->with($this->equalTo('doctrine.orm.default_entity_manager'), $this->equalTo(null)); $registry = new Registry($container, array(), array('default' => 'doctrine.orm.default_entity_manager'), 'default', 'default'); $registry->resetManager('default'); } public function testResetUnknownEntityManager() { $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $registry = new Registry($container, array(), array(), 'default', 'default'); $this->setExpectedException('InvalidArgumentException', 'Doctrine ORM Manager named "default" does not exist.'); $registry->resetManager('default'); } } DoctrineBundle-1.6.2/Tests/TestCase.php000066400000000000000000000063561264451145000177630ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests; use Doctrine\Common\Annotations\AnnotationReader; use Doctrine\Bundle\DoctrineBundle\DependencyInjection\DoctrineExtension; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\Compiler\ResolveDefinitionTemplatesPass; class TestCase extends \PHPUnit_Framework_TestCase { protected function setUp() { if (!class_exists('Doctrine\\Common\\Version')) { $this->markTestSkipped('Doctrine is not available.'); } } public function createYamlBundleTestContainer() { $container = new ContainerBuilder(new ParameterBag(array( 'kernel.debug' => false, 'kernel.bundles' => array('YamlBundle' => 'Fixtures\Bundles\YamlBundle\YamlBundle'), 'kernel.cache_dir' => sys_get_temp_dir(), 'kernel.environment' => 'test', 'kernel.root_dir' => __DIR__.'/../../../../', // src dir ))); $container->set('annotation_reader', new AnnotationReader()); $extension = new DoctrineExtension(); $container->registerExtension($extension); $extension->load(array(array( 'dbal' => array( 'connections' => array( 'default' => array( 'driver' => 'pdo_mysql', 'charset' => 'UTF8', 'platform-service' => 'my.platform', ), ), 'default_connection' => 'default', 'types' => array( 'test' => 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestType', ), ), 'orm' => array( 'default_entity_manager' => 'default', 'entity_managers' => array ( 'default' => array( 'mappings' => array('YamlBundle' => array( 'type' => 'yml', 'dir' => __DIR__.'/DependencyInjection/Fixtures/Bundles/YamlBundle/Resources/config/doctrine', 'prefix' => 'Fixtures\Bundles\YamlBundle\Entity', )), ), ), 'resolve_target_entities' => array( 'Symfony\Component\Security\Core\User\UserInterface' => 'stdClass', ), ), )), $container); $container->setDefinition('my.platform', new Definition('Doctrine\DBAL\Platforms\MySqlPlatform')); $container->getCompilerPassConfig()->setOptimizationPasses(array(new ResolveDefinitionTemplatesPass())); $container->getCompilerPassConfig()->setRemovingPasses(array()); $container->compile(); return $container; } } DoctrineBundle-1.6.2/Tests/Twig/000077500000000000000000000000001264451145000164375ustar00rootroot00000000000000DoctrineBundle-1.6.2/Tests/Twig/DoctrineExtensionTest.php000066400000000000000000000016161264451145000234600ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Tests\Twig; use Doctrine\Bundle\DoctrineBundle\Twig\DoctrineExtension; class DoctrineExtensionTest extends \PHPUnit_Framework_TestCase { public function testReplaceQueryParametersWithPostgresCasting() { $extension = new DoctrineExtension(); $query = 'a=? OR (1)::string OR b=?'; $parameters = array(1, 2); $result = $extension->replaceQueryParameters($query, $parameters, false); $this->assertEquals('a=1 OR (1)::string OR b=2', $result); } } DoctrineBundle-1.6.2/Twig/000077500000000000000000000000001264451145000153355ustar00rootroot00000000000000DoctrineBundle-1.6.2/Twig/DoctrineExtension.php000066400000000000000000000245571264451145000215270ustar00rootroot00000000000000 * (c) Doctrine Project, Benjamin Eberlei * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Twig; /** * This class contains the needed functions in order to do the query highlighting * * @author Florin Patan * @author Christophe Coevoet */ class DoctrineExtension extends \Twig_Extension { /** * Number of maximum characters that one single line can hold in the interface * * @var int */ private $maxCharWidth = 100; /** * Define our functions * * @return array */ public function getFilters() { return array( new \Twig_SimpleFilter('doctrine_minify_query', array($this, 'minifyQuery'), array('deprecated' => true)), new \Twig_SimpleFilter('doctrine_pretty_query', array($this, 'formatQuery'), array('is_safe' => array('html'))), new \Twig_SimpleFilter('doctrine_replace_query_parameters', array($this, 'replaceQueryParameters')), ); } /** * Get the possible combinations of elements from the given array * * @param array $elements * @param integer $combinationsLevel * * @return array */ private function getPossibleCombinations(array $elements, $combinationsLevel) { $baseCount = count($elements); $result = array(); if (1 === $combinationsLevel) { foreach ($elements as $element) { $result[] = array($element); } return $result; } $nextLevelElements = $this->getPossibleCombinations($elements, $combinationsLevel - 1); foreach ($nextLevelElements as $nextLevelElement) { $lastElement = $nextLevelElement[$combinationsLevel - 2]; $found = false; foreach ($elements as $key => $element) { if ($element == $lastElement) { $found = true; continue; } if ($found == true && $key < $baseCount) { $tmp = $nextLevelElement; $newCombination = array_slice($tmp, 0); $newCombination[] = $element; $result[] = array_slice($newCombination, 0); } } } return $result; } /** * Shrink the values of parameters from a combination * * @param array $parameters * @param array $combination * * @return string */ private function shrinkParameters(array $parameters, array $combination) { array_shift($parameters); $result = ''; $maxLength = $this->maxCharWidth; $maxLength -= count($parameters) * 5; $maxLength = $maxLength / count($parameters); foreach ($parameters as $key => $value) { $isLarger = false; if (strlen($value) > $maxLength) { $value = wordwrap($value, $maxLength, "\n", true); $value = explode("\n", $value); $value = $value[0]; $isLarger = true; } $value = self::escapeFunction($value); if (!is_numeric($value)) { $value = substr($value, 1, -1); } if ($isLarger) { $value .= ' [...]'; } $result .= ' '.$combination[$key].' '.$value; } return trim($result); } /** * Attempt to compose the best scenario minified query so that a user could find it without expanding it * * @param string $query * @param array $keywords * @param integer $required * * @return string */ private function composeMiniQuery($query, array $keywords, $required) { // Extract the mandatory keywords and consider the rest as optional keywords $mandatoryKeywords = array_splice($keywords, 0, $required); $combinations = array(); $combinationsCount = count($keywords); // Compute all the possible combinations of keywords to match the query for while ($combinationsCount > 0) { $combinations = array_merge($combinations, $this->getPossibleCombinations($keywords, $combinationsCount)); $combinationsCount--; } // Try and match the best case query pattern foreach ($combinations as $combination) { $combination = array_merge($mandatoryKeywords, $combination); $regexp = implode('(.*) ', $combination).' (.*)'; $regexp = '/^'.$regexp.'/is'; if (preg_match($regexp, $query, $matches)) { $result = $this->shrinkParameters($matches, $combination); return $result; } } // Try and match the simplest query form that contains only the mandatory keywords $regexp = implode(' (.*)', $mandatoryKeywords).' (.*)'; $regexp = '/^'.$regexp.'/is'; if (preg_match($regexp, $query, $matches)) { $result = $this->shrinkParameters($matches, $mandatoryKeywords); return $result; } // Fallback in case we didn't managed to find any good match (can we actually have that happen?!) $result = substr($query, 0, $this->maxCharWidth); return $result; } /** * Minify the query * * @param string $query * * @return string */ public function minifyQuery($query) { $result = ''; $keywords = array(); $required = 1; // Check if we can match the query against any of the major types switch (true) { case stripos($query, 'SELECT') !== false: $keywords = array('SELECT', 'FROM', 'WHERE', 'HAVING', 'ORDER BY', 'LIMIT'); $required = 2; break; case stripos($query, 'DELETE') !== false: $keywords = array('DELETE', 'FROM', 'WHERE', 'ORDER BY', 'LIMIT'); $required = 2; break; case stripos($query, 'UPDATE') !== false: $keywords = array('UPDATE', 'SET', 'WHERE', 'ORDER BY', 'LIMIT'); $required = 2; break; case stripos($query, 'INSERT') !== false: $keywords = array('INSERT', 'INTO', 'VALUE', 'VALUES'); $required = 2; break; // If there's no match so far just truncate it to the maximum allowed by the interface default: $result = substr($query, 0, $this->maxCharWidth); } // If we had a match then we should minify it if ($result == '') { $result = $this->composeMiniQuery($query, $keywords, $required); } return $result; } /** * Escape parameters of a SQL query * DON'T USE THIS FUNCTION OUTSIDE ITS INTENDED SCOPE * * @internal * * @param mixed $parameter * * @return string */ public static function escapeFunction($parameter) { $result = $parameter; switch (true) { case is_string($result): $result = "'".addslashes($result)."'"; break; case is_array($result): foreach ($result as &$value) { $value = static::escapeFunction($value); } $result = implode(', ', $result); break; case is_object($result): $result = addslashes((string) $result); break; case null === $result: $result = 'NULL'; break; case is_bool($result): $result = $result ? '1' : '0'; break; } return $result; } /** * Return a query with the parameters replaced * * @param string $query * @param array $parameters * * @return string */ public function replaceQueryParameters($query, array $parameters) { $i = 0; $result = preg_replace_callback( '/\?|((?([^"]*+)<\/pre>/Us', '\1', $html); } else { $html = \SqlFormatter::format($sql); $html = preg_replace('/
([^"]*+)<\/pre>/Us', '
\2
', $html); } return $html; } /** * Get the name of the extension * * @return string */ public function getName() { return 'doctrine_extension'; } } DoctrineBundle-1.6.2/composer.json000066400000000000000000000032161264451145000171470ustar00rootroot00000000000000{ "name": "doctrine/doctrine-bundle", "type": "symfony-bundle", "description": "Symfony DoctrineBundle", "keywords": ["DBAL", "ORM", "Database", "Persistence"], "homepage": "http://www.doctrine-project.org", "license": "MIT", "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com" }, { "name": "Benjamin Eberlei", "email": "kontakt@beberlei.de" }, { "name": "Symfony Community", "homepage": "http://symfony.com/contributors" }, { "name": "Doctrine Project", "homepage": "http://www.doctrine-project.org/" } ], "require": { "php": ">=5.3.2", "symfony/framework-bundle": "~2.3|~3.0", "symfony/console": "~2.3|~3.0", "doctrine/dbal": "~2.3", "jdorn/sql-formatter": "~1.1", "symfony/doctrine-bridge": "~2.2|~3.0", "doctrine/doctrine-cache-bundle": "~1.0" }, "require-dev": { "doctrine/orm": "~2.3", "symfony/yaml": "~2.2|~3.0", "symfony/validator": "~2.2|~3.0", "symfony/phpunit-bridge": "~2.7|~3.0", "twig/twig": "~1.10", "satooshi/php-coveralls": "~0.6.1", "phpunit/phpunit": "~4" }, "suggest": { "symfony/web-profiler-bundle": "to use the data collector", "doctrine/orm": "The Doctrine ORM integration is optional in the bundle." }, "autoload": { "psr-4": { "Doctrine\\Bundle\\DoctrineBundle\\": "" } }, "extra": { "branch-alias": { "dev-master": "1.6.x-dev" } } } DoctrineBundle-1.6.2/phpunit.xml.dist000066400000000000000000000010731264451145000175770ustar00rootroot00000000000000 ./Tests . ./Resources ./Tests ./vendor