pax_global_header00006660000000000000000000000064136155205520014516gustar00rootroot0000000000000052 comment=9d866f32b9f29442eb907066c83b3412bc2a35ea php-doctrine-bundle-2.0.7/000077500000000000000000000000001361552055200153675ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/.github/000077500000000000000000000000001361552055200167275ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/.github/FUNDING.yml000066400000000000000000000001761361552055200205500ustar00rootroot00000000000000patreon: phpdoctrine tidelift: packagist/doctrine%2Fdoctrine-bundle custom: https://www.doctrine-project.org/sponsorship.html php-doctrine-bundle-2.0.7/.gitignore000066400000000000000000000001101361552055200173470ustar00rootroot00000000000000vendor composer.phar composer.lock phpunit.xml /phpcs.xml /.phpcs-cache php-doctrine-bundle-2.0.7/.travis.yml000066400000000000000000000043321361552055200175020ustar00rootroot00000000000000language: php sudo: false dist: xenial cache: directories: - $HOME/.composer/cache php: - 7.1 - 7.2 - 7.3 - 7.4 env: global: - COMPOSER_MEMORY_LIMIT=-1 before_install: - mv ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/xdebug.ini{,.disabled} || echo "xdebug not available" - composer self-update - composer global require --no-progress --no-scripts --no-plugins symfony/flex dev-master install: - travis_retry composer update -n --prefer-dist --prefer-stable script: - ./vendor/bin/phpunit -v jobs: include: # Tests the lowest set of dependencies - php: 7.1 env: LOWEST SYMFONY_DEPRECATIONS_HELPER=weak install: - travis_retry composer update -n --prefer-lowest --prefer-stable --prefer-dist # Test against latest Symfony 4.3 stable - php: 7.3 env: SYMFONY_REQUIRE="4.3.*" install: - composer require --dev symfony/messenger --no-update - travis_retry composer update -n --prefer-dist --prefer-stable # Test against latest Symfony 4.4 dev - php: 7.3 env: SYMFONY_REQUIRE="4.4.*" install: - composer require --dev symfony/messenger --no-update - travis_retry composer update -n --prefer-dist # Test against latest Symfony 5.0 dev - php: 7.3 env: SYMFONY_REQUIRE="5.0.*" install: - composer require --dev symfony/messenger --no-update - travis_retry composer update -n --prefer-dist # Test dev versions - php: 7.3 if: type = cron env: DEV install: - travis_retry composer update -n --prefer-dist - stage: Code Quality env: CODING_STANDARDS php: 7.3 script: - ./vendor/bin/phpcs - stage: Coverage php: 7.3 install: - composer require --dev "symfony/messenger" --no-update - travis_retry composer update -n --prefer-dist before_script: - mv ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/xdebug.ini{.disabled,} - if [[ ! $(php -m | grep -si xdebug) ]]; then echo "xdebug required for coverage"; exit 1; fi script: - ./vendor/bin/phpunit -v --coverage-clover ./build/logs/clover.xml # after_script: # - php ./vendor/bin/coveralls -v php-doctrine-bundle-2.0.7/Command/000077500000000000000000000000001361552055200167455ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Command/CreateDatabaseDoctrineCommand.php000066400000000000000000000112071361552055200252760ustar00rootroot00000000000000setName('doctrine:database:create') ->setDescription('Creates the configured database') ->addOption('shard', null, InputOption::VALUE_REQUIRED, 'The shard connection to use for this command') ->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)) { $connectionName = $this->getDoctrine()->getDefaultConnectionName(); } $connection = $this->getDoctrineConnection($connectionName); $ifNotExists = $input->getOption('if-not-exists'); $params = $connection->getParams(); if (isset($params['master'])) { $params = $params['master']; } // Cannot inject `shard` option in parent::getDoctrineConnection // cause it will try to connect to a non-existing database if (isset($params['shards'])) { $shards = $params['shards']; // Default select global $params = array_merge($params, $params['global']); unset($params['global']['dbname'], $params['global']['path'], $params['global']['url']); if ($input->getOption('shard')) { foreach ($shards as $i => $shard) { if ($shard['id'] === (int) $input->getOption('shard')) { // Select sharded database $params = array_merge($params, $shard); unset($params['shards'][$i]['dbname'], $params['shards'][$i]['path'], $params['shards'][$i]['url'], $params['id']); break; } } } } $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 created."); } // 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); $tmpConnection->connect($input->getOption('shard')); $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; } } php-doctrine-bundle-2.0.7/Command/DoctrineCommand.php000066400000000000000000000043311361552055200225250ustar00rootroot00000000000000doctrine = $doctrine; } /** * 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 * @param int|null $shardId * * @return EntityManager */ protected function getEntityManager($name, $shardId = null) { $manager = $this->getDoctrine()->getManager($name); if ($shardId) { if (! $manager->getConnection() instanceof PoolingShardConnection) { throw new LogicException(sprintf("Connection of EntityManager '%s' must implement shards configuration.", $name)); } $manager->getConnection()->connect($shardId); } return $manager; } /** * Get a doctrine dbal connection by symfony name. * * @param string $name * * @return Connection */ protected function getDoctrineConnection($name) { return $this->getDoctrine()->getConnection($name); } /** * @return ManagerRegistry */ protected function getDoctrine() { return $this->doctrine; } } php-doctrine-bundle-2.0.7/Command/DropDatabaseDoctrineCommand.php000066400000000000000000000120501361552055200247740ustar00rootroot00000000000000setName('doctrine:database:drop') ->setDescription('Drops the configured database') ->addOption('shard', null, InputOption::VALUE_REQUIRED, 'The shard connection to use for this command') ->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) { $connectionName = $input->getOption('connection'); if (empty($connectionName)) { $connectionName = $this->getDoctrine()->getDefaultConnectionName(); } $connection = $this->getDoctrineConnection($connectionName); $ifExists = $input->getOption('if-exists'); $params = $connection->getParams(); if (isset($params['master'])) { $params = $params['master']; } if (isset($params['shards'])) { $shards = $params['shards']; // Default select global $params = array_merge($params, $params['global']); if ($input->getOption('shard')) { foreach ($shards as $shard) { if ($shard['id'] === (int) $input->getOption('shard')) { // Select sharded database $params = $shard; unset($params['id']); break; } } } } $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'], $params['url']); if (! $input->getOption('force')) { $output->writeln('ATTENTION: This operation should not be executed in a production environment.'); $output->writeln(''); $output->writeln(sprintf('Would drop the database %s for connection named %s.', $name, $connectionName)); $output->writeln('Please run the operation with --force to execute'); $output->writeln('All data will be lost!'); return self::RETURN_CODE_NO_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 %s for connection named %s', $name, $connectionName)); } else { $output->writeln(sprintf('Database %s for connection named %s doesn\'t exist. Skipped.', $name, $connectionName)); } return 0; } catch (Exception $e) { $output->writeln(sprintf('Could not drop database %s for connection named %s', $name, $connectionName)); $output->writeln(sprintf('%s', $e->getMessage())); return self::RETURN_CODE_NOT_DROP; } } } php-doctrine-bundle-2.0.7/Command/ImportMappingDoctrineCommand.php000066400000000000000000000145151361552055200252410ustar00rootroot00000000000000bundles = $bundles; } /** * {@inheritDoc} */ protected function configure() { $this ->setName('doctrine:mapping:import') ->addArgument('name', InputArgument::REQUIRED, 'The bundle or namespace 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('shard', null, InputOption::VALUE_REQUIRED, 'The shard connection 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.') ->addOption('path', null, InputOption::VALUE_REQUIRED, 'The path where the files would be generated (not used when a bundle is passed).') ->setDescription('Imports mapping information from an existing database') ->setHelp(<<%command.name% command imports mapping information from an existing database: Generate annotation mappings into the src/ directory using App as the namespace: php %command.full_name% App\\\Entity annotation --path=src/Entity Generate xml mappings into the config/doctrine/ directory using App as the namespace: php %command.full_name% App\\\Entity xml --path=config/doctrine Generate XML mappings into a bundle: 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) { $type = $input->getArgument('mapping-type') ?: 'xml'; if ($type === 'yaml') { $type = 'yml'; } $namespaceOrBundle = $input->getArgument('name'); if (isset($this->bundles[$namespaceOrBundle])) { $bundle = $this->getApplication()->getKernel()->getBundle($namespaceOrBundle); $namespace = $bundle->getNamespace() . '\Entity'; $destPath = $bundle->getPath(); if ($type === 'annotation') { $destPath .= '/Entity'; } else { $destPath .= '/Resources/config/doctrine'; } } else { // assume a namespace has been passed $namespace = $namespaceOrBundle; $destPath = $input->getOption('path'); if ($destPath === null) { throw new InvalidArgumentException('The --path option is required when passing a namespace (e.g. --path=src). If you intended to pass a bundle name, check your spelling.'); } } $cme = new ClassMetadataExporter(); $exporter = $cme->getExporter($type); $exporter->setOverwriteExistingFiles($input->getOption('force')); if ($type === 'annotation') { $entityGenerator = $this->getEntityGenerator(); $exporter->setEntityGenerator($entityGenerator); } $em = $this->getEntityManager($input->getOption('em'), $input->getOption('shard')); $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 = $namespace . '\\' . $className; if ($type === 'annotation') { $path = $destPath . '/' . str_replace('\\', '.', $className) . '.php'; } else { $path = $destPath . '/' . str_replace('\\', '.', $className) . '.orm.' . $type; } $output->writeln(sprintf(' > writing %s', $path)); $code = $exporter->exportClassMetadata($class); $dir = dirname($path); if (! is_dir($dir)) { mkdir($dir, 0775, true); } file_put_contents($path, $code); chmod($path, 0664); } return 0; } $output->writeln('Database does not have any mapping information.'); $output->writeln(''); return 1; } } php-doctrine-bundle-2.0.7/Command/Proxy/000077500000000000000000000000001361552055200200665ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Command/Proxy/ClearMetadataCacheDoctrineCommand.php000066400000000000000000000021101361552055200271730ustar00rootroot00000000000000setName('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); } } php-doctrine-bundle-2.0.7/Command/Proxy/ClearQueryCacheDoctrineCommand.php000066400000000000000000000020661361552055200265720ustar00rootroot00000000000000setName('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); } } php-doctrine-bundle-2.0.7/Command/Proxy/ClearResultCacheDoctrineCommand.php000066400000000000000000000020701361552055200267360ustar00rootroot00000000000000setName('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); } } php-doctrine-bundle-2.0.7/Command/Proxy/CollectionRegionDoctrineCommand.php000066400000000000000000000017241361552055200270310ustar00rootroot00000000000000setName('doctrine:cache:clear-collection-region') ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command'); } protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em')); return parent::execute($input, $output); } } php-doctrine-bundle-2.0.7/Command/Proxy/ConvertMappingDoctrineCommand.php000066400000000000000000000032661361552055200265310ustar00rootroot00000000000000setName('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 AbstractExporter */ protected function getExporter($toType, $destPath) { /** @var AbstractExporter $exporter */ $exporter = parent::getExporter($toType, $destPath); if ($exporter instanceof XmlExporter) { $exporter->setExtension('.orm.xml'); } elseif ($exporter instanceof YamlExporter) { $exporter->setExtension('.orm.yml'); } return $exporter; } } php-doctrine-bundle-2.0.7/Command/Proxy/CreateSchemaDoctrineCommand.php000066400000000000000000000021511361552055200261110ustar00rootroot00000000000000setName('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')); return parent::execute($input, $output); } } php-doctrine-bundle-2.0.7/Command/Proxy/DelegateCommand.php000066400000000000000000000046141361552055200236150ustar00rootroot00000000000000isVersionCompatible(); } /** * @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); } } php-doctrine-bundle-2.0.7/Command/Proxy/DoctrineCommandHelper.php000066400000000000000000000027631361552055200250150ustar00rootroot00000000000000getKernel()->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 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'); } } php-doctrine-bundle-2.0.7/Command/Proxy/DropSchemaDoctrineCommand.php000066400000000000000000000021261361552055200256140ustar00rootroot00000000000000setName('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')); return parent::execute($input, $output); } } php-doctrine-bundle-2.0.7/Command/Proxy/EnsureProductionSettingsDoctrineCommand.php000066400000000000000000000020441361552055200306170ustar00rootroot00000000000000setName('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')); return parent::execute($input, $output); } } php-doctrine-bundle-2.0.7/Command/Proxy/EntityRegionCacheDoctrineCommand.php000066400000000000000000000017051361552055200271350ustar00rootroot00000000000000setName('doctrine:cache:clear-entity-region') ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command'); } protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em')); return parent::execute($input, $output); } } php-doctrine-bundle-2.0.7/Command/Proxy/ImportDoctrineCommand.php000066400000000000000000000017031361552055200250410ustar00rootroot00000000000000setName('doctrine:database:import') ->addOption('connection', null, InputOption::VALUE_OPTIONAL, 'The connection to use for this command'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationConnection($this->getApplication(), $input->getOption('connection')); return parent::execute($input, $output); } } php-doctrine-bundle-2.0.7/Command/Proxy/InfoDoctrineCommand.php000066400000000000000000000016261361552055200244660ustar00rootroot00000000000000setName('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); } } php-doctrine-bundle-2.0.7/Command/Proxy/QueryRegionCacheDoctrineCommand.php000066400000000000000000000017001361552055200267610ustar00rootroot00000000000000setName('doctrine:cache:clear-query-region') ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command'); } protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em')); return parent::execute($input, $output); } } php-doctrine-bundle-2.0.7/Command/Proxy/RunDqlDoctrineCommand.php000066400000000000000000000030411361552055200247710ustar00rootroot00000000000000setName('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); } } php-doctrine-bundle-2.0.7/Command/Proxy/RunSqlDoctrineCommand.php000066400000000000000000000022131361552055200250100ustar00rootroot00000000000000setName('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 users" EOT ); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationConnection($this->getApplication(), $input->getOption('connection')); return parent::execute($input, $output); } } php-doctrine-bundle-2.0.7/Command/Proxy/UpdateSchemaDoctrineCommand.php000066400000000000000000000020231361552055200261260ustar00rootroot00000000000000setName('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); } } php-doctrine-bundle-2.0.7/Command/Proxy/ValidateSchemaCommand.php000066400000000000000000000020211361552055200247430ustar00rootroot00000000000000setName('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); } } php-doctrine-bundle-2.0.7/ConnectionFactory.php000066400000000000000000000102741361552055200215330ustar00rootroot00000000000000typesConfig = $typesConfig; } /** * Create a connection by name. * * @param mixed[] $params * @param string[]|Type[] $mappingTypes * * @return Connection */ public function createConnection(array $params, Configuration $config = null, EventManager $eventManager = null, array $mappingTypes = []) { if (! $this->initialized) { $this->initializeTypes(); } if (! isset($params['pdo']) && ! isset($params['charset'])) { $wrapperClass = null; if (isset($params['wrapperClass'])) { if (! is_subclass_of($params['wrapperClass'], Connection::class)) { throw DBALException::invalidWrapperClass($params['wrapperClass']); } $wrapperClass = $params['wrapperClass']; $params['wrapperClass'] = null; } $connection = DriverManager::getConnection($params, $config, $eventManager); $params = $connection->getParams(); $driver = $connection->getDriver(); if ($driver instanceof AbstractMySQLDriver) { $params['charset'] = 'utf8mb4'; if (! isset($params['defaultTableOptions']['collate'])) { $params['defaultTableOptions']['collate'] = 'utf8mb4_unicode_ci'; } } else { $params['charset'] = 'utf8'; } if ($wrapperClass !== null) { $params['wrapperClass'] = $wrapperClass; } else { $wrapperClass = Connection::class; } $connection = new $wrapperClass($params, $driver, $config, $eventManager); } else { $connection = DriverManager::getConnection($params, $config, $eventManager); } if (! empty($mappingTypes)) { $platform = $this->getDatabasePlatform($connection); foreach ($mappingTypes as $dbType => $doctrineType) { $platform->registerDoctrineTypeMapping($dbType, $doctrineType); } } return $connection; } /** * Try to get the database platform. * * This could fail if types should be registered to an predefined/unused connection * and the platform version is unknown. * For details have a look at DoctrineBundle issue #673. * * @throws DBALException */ private function getDatabasePlatform(Connection $connection) : AbstractPlatform { try { return $connection->getDatabasePlatform(); } catch (DriverException $driverException) { throw new DBALException( 'An exception occured while establishing a connection to figure out your platform version.' . PHP_EOL . "You can circumvent this by setting a 'server_version' configuration value" . PHP_EOL . PHP_EOL . 'For further information have a look at:' . PHP_EOL . 'https://github.com/doctrine/DoctrineBundle/issues/673', 0, $driverException ); } } /** * initialize the types */ private function initializeTypes() : void { foreach ($this->typesConfig as $typeName => $typeConfig) { if (Type::hasType($typeName)) { Type::overrideType($typeName, $typeConfig['class']); } else { Type::addType($typeName, $typeConfig['class']); } } $this->initialized = true; } } php-doctrine-bundle-2.0.7/Controller/000077500000000000000000000000001361552055200175125ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Controller/ProfilerController.php000066400000000000000000000076361361552055200240650ustar00rootroot00000000000000container = $container; } /** * Renders the profiler panel for the given token. * * @param string $token The profiler token * @param string $connectionName * @param int $query * * @return Response A Response instance */ public function explainAction($token, $connectionName, $query) { /** @var 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 $connection */ $connection = $this->container->get('doctrine')->getConnection($connectionName); try { $platform = $connection->getDatabasePlatform(); if ($platform instanceof SqlitePlatform) { $results = $this->explainSQLitePlatform($connection, $query); } elseif ($platform 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 new Response($this->container->get('twig')->render('@Doctrine/Collector/explain.html.twig', [ 'data' => $results, 'query' => $query, ])); } /** * @param mixed[] $query */ private function explainSQLitePlatform(Connection $connection, array $query) { $params = $query['params']; if ($params instanceof Data) { $params = $params->getValue(true); } return $connection->executeQuery('EXPLAIN QUERY PLAN ' . $query['sql'], $params, $query['types']) ->fetchAll(PDO::FETCH_ASSOC); } 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;'; } $params = $query['params']; if ($params instanceof Data) { $params = $params->getValue(true); } $stmt = $connection->executeQuery($sql, $params, $query['types']); $stmt->nextRowset(); return $stmt->fetchAll(PDO::FETCH_ASSOC); } private function explainOtherPlatform(Connection $connection, $query) { $params = $query['params']; if ($params instanceof Data) { $params = $params->getValue(true); } return $connection->executeQuery('EXPLAIN ' . $query['sql'], $params, $query['types']) ->fetchAll(PDO::FETCH_ASSOC); } } php-doctrine-bundle-2.0.7/DataCollector/000077500000000000000000000000001361552055200201075ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/DataCollector/DoctrineDataCollector.php000066400000000000000000000206411361552055200250330ustar00rootroot00000000000000registry = $registry; parent::__construct($registry); } /** * {@inheritdoc} */ public function collect(Request $request, Response $response, Throwable $exception = null) { parent::collect($request, $response, $exception); $errors = []; $entities = []; $caches = [ 'enabled' => false, 'log_enabled' => false, 'counts' => [ 'puts' => 0, 'hits' => 0, 'misses' => 0, ], 'regions' => [ 'puts' => [], 'hits' => [], 'misses' => [], ], ]; /** @var EntityManager $em */ foreach ($this->registry->getManagers() as $name => $em) { $entities[$name] = []; /** @var ClassMetadataFactory $factory */ $factory = $em->getMetadataFactory(); $validator = new SchemaValidator($em); /** @var ClassMetadataInfo $class */ foreach ($factory->getLoadedMetadata() as $class) { if (isset($entities[$name][$class->getName()])) { continue; } $classErrors = $validator->validateClass($class); $entities[$name][$class->getName()] = $class->getName(); if (empty($classErrors)) { continue; } $errors[$name][$class->getName()] = $classErrors; } /** @var Configuration $emConfig */ $emConfig = $em->getConfiguration(); $slcEnabled = $emConfig->isSecondLevelCacheEnabled(); if (! $slcEnabled) { continue; } $caches['enabled'] = true; /** @var $cacheConfiguration \Doctrine\ORM\Cache\CacheConfiguration */ /** @var CacheLoggerChain $cacheLoggerChain */ $cacheConfiguration = $emConfig->getSecondLevelCacheConfiguration(); $cacheLoggerChain = $cacheConfiguration->getCacheLogger(); if (! $cacheLoggerChain || ! $cacheLoggerChain->getLogger('statistics')) { continue; } /** @var StatisticsCacheLogger $cacheLoggerStats */ $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; } } // Might be good idea to replicate this block in doctrine bridge so we can drop this from here after some time. // This code is compatible with such change, because cloneVar is supposed to check if input is already cloned. foreach ($this->data['queries'] as &$queries) { foreach ($queries as &$query) { $query['params'] = $this->cloneVar($query['params']); // To be removed when the required minimum version of symfony/doctrine-bridge is >= 4.4 $query['runnable'] = $query['runnable'] ?? true; } } $this->data['entities'] = $entities; $this->data['errors'] = $errors; $this->data['caches'] = $caches; $this->groupedQueries = null; } 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 ($this->invalidEntityCount === null) { $this->invalidEntityCount = array_sum(array_map('count', $this->data['errors'])); } return $this->invalidEntityCount; } public function getGroupedQueries() { if ($this->groupedQueries !== null) { return $this->groupedQueries; } $this->groupedQueries = []; $totalExecutionMS = 0; foreach ($this->data['queries'] as $connection => $queries) { $connectionGroupedQueries = []; foreach ($queries as $i => $query) { $key = $query['sql']; if (! isset($connectionGroupedQueries[$key])) { $connectionGroupedQueries[$key] = $query; $connectionGroupedQueries[$key]['executionMS'] = 0; $connectionGroupedQueries[$key]['count'] = 0; $connectionGroupedQueries[$key]['index'] = $i; // "Explain query" relies on query index in 'queries'. } $connectionGroupedQueries[$key]['executionMS'] += $query['executionMS']; $connectionGroupedQueries[$key]['count']++; $totalExecutionMS += $query['executionMS']; } usort($connectionGroupedQueries, static function ($a, $b) { if ($a['executionMS'] === $b['executionMS']) { return 0; } return $a['executionMS'] < $b['executionMS'] ? 1 : -1; }); $this->groupedQueries[$connection] = $connectionGroupedQueries; } foreach ($this->groupedQueries as $connection => $queries) { foreach ($queries as $i => $query) { $this->groupedQueries[$connection][$i]['executionPercent'] = $this->executionTimePercentage($query['executionMS'], $totalExecutionMS); } } return $this->groupedQueries; } private function executionTimePercentage($executionTimeMS, $totalExecutionTimeMS) { if ($totalExecutionTimeMS === 0.0 || $totalExecutionTimeMS === 0) { return 0; } return $executionTimeMS / $totalExecutionTimeMS * 100; } public function getGroupedQueryCount() { $count = 0; foreach ($this->getGroupedQueries() as $connectionGroupedQueries) { $count += count($connectionGroupedQueries); } return $count; } } php-doctrine-bundle-2.0.7/Dbal/000077500000000000000000000000001361552055200162315ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Dbal/BlacklistSchemaAssetFilter.php000066400000000000000000000011171361552055200241410ustar00rootroot00000000000000blacklist = $blacklist; } public function __invoke($assetName) : bool { if ($assetName instanceof AbstractAsset) { $assetName = $assetName->getName(); } return ! in_array($assetName, $this->blacklist, true); } } php-doctrine-bundle-2.0.7/Dbal/Logging/000077500000000000000000000000001361552055200176175ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Dbal/Logging/BacktraceLogger.php000066400000000000000000000010771361552055200233540ustar00rootroot00000000000000queries[$this->currentQuery]['backtrace'] = $backtrace; } } php-doctrine-bundle-2.0.7/Dbal/RegexSchemaAssetFilter.php000066400000000000000000000010361361552055200233030ustar00rootroot00000000000000filterExpression = $filterExpression; } public function __invoke($assetName) : bool { if ($assetName instanceof AbstractAsset) { $assetName = $assetName->getName(); } return preg_match($this->filterExpression, $assetName); } } php-doctrine-bundle-2.0.7/Dbal/SchemaAssetsFilterManager.php000066400000000000000000000012561361552055200237720ustar00rootroot00000000000000schemaAssetFilters = $schemaAssetFilters; } public function __invoke($assetName) : bool { foreach ($this->schemaAssetFilters as $schemaAssetFilter) { if ($schemaAssetFilter($assetName) === false) { return false; } } return true; } } php-doctrine-bundle-2.0.7/DependencyInjection/000077500000000000000000000000001361552055200213105ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/DependencyInjection/Compiler/000077500000000000000000000000001361552055200230625ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/DependencyInjection/Compiler/DbalSchemaFilterPass.php000066400000000000000000000034531361552055200275600ustar00rootroot00000000000000findTaggedServiceIds('doctrine.dbal.schema_filter'); $connectionFilters = []; foreach ($filters as $id => $tagAttributes) { foreach ($tagAttributes as $attributes) { $name = isset($attributes['connection']) ? $attributes['connection'] : $container->getParameter('doctrine.default_connection'); if (! isset($connectionFilters[$name])) { $connectionFilters[$name] = []; } $connectionFilters[$name][] = new Reference($id); } } foreach ($connectionFilters as $name => $references) { $configurationId = sprintf('doctrine.dbal.%s_connection.configuration', $name); if (! $container->hasDefinition($configurationId)) { continue; } $definition = new ChildDefinition('doctrine.dbal.schema_asset_filter_manager'); $definition->setArgument(0, $references); $id = sprintf('doctrine.dbal.%s_schema_asset_filter_manager', $name); $container->setDefinition($id, $definition); $container->findDefinition($configurationId) ->addMethodCall('setSchemaAssetsFilter', [new Reference($id)]); } } } php-doctrine-bundle-2.0.7/DependencyInjection/Compiler/DoctrineOrmMappingsPass.php000066400000000000000000000211021361552055200303420ustar00rootroot00000000000000findTaggedServiceIds('doctrine.orm.entity_listener'); $lazyServiceReferencesByResolver = []; 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; } $resolverId = sprintf('doctrine.orm.%s_entity_listener_resolver', $name); if (! $container->has($resolverId)) { continue; } $resolver = $container->findDefinition($resolverId); $resolver->setPublic(true); if (isset($attributes['entity']) && isset($attributes['event'])) { $this->attachToListener($container, $name, $this->getConcreteDefinitionClass($container->findDefinition($id), $container, $id), $attributes); } $resolverClass = $this->getResolverClass($resolver, $container, $resolverId); $resolverSupportsLazyListeners = is_a($resolverClass, EntityListenerServiceResolver::class, true); $lazyByAttribute = isset($attributes['lazy']) && $attributes['lazy']; if ($lazyByAttribute && ! $resolverSupportsLazyListeners) { throw new InvalidArgumentException(sprintf( 'Lazy-loaded entity listeners can only be resolved by a resolver implementing %s.', EntityListenerServiceResolver::class )); } if (! isset($attributes['lazy']) && $resolverSupportsLazyListeners || $lazyByAttribute) { $listener = $container->findDefinition($id); if ($listener->isAbstract()) { throw new InvalidArgumentException(sprintf('The service "%s" must not be abstract as this entity listener is lazy-loaded.', $id)); } $resolver->addMethodCall('registerService', [$this->getConcreteDefinitionClass($listener, $container, $id), $id]); // if the resolver uses the default class we will use a service locator for all listeners if ($resolverClass === ContainerEntityListenerResolver::class) { if (! isset($lazyServiceReferencesByResolver[$resolverId])) { $lazyServiceReferencesByResolver[$resolverId] = []; } $lazyServiceReferencesByResolver[$resolverId][$id] = new Reference($id); } else { $listener->setPublic(true); } } else { $resolver->addMethodCall('register', [new Reference($id)]); } } } foreach ($lazyServiceReferencesByResolver as $resolverId => $listenerReferences) { $container->findDefinition($resolverId)->setArgument(0, ServiceLocatorTagPass::register($container, $listenerReferences)); } } private function attachToListener(ContainerBuilder $container, string $name, string $class, array $attributes) : void { $listenerId = sprintf('doctrine.orm.%s_listeners.attach_entity_listeners', $name); if (! $container->has($listenerId)) { return; } $args = [ $attributes['entity'], $class, $attributes['event'], ]; if (isset($attributes['method'])) { $args[] = $attributes['method']; } elseif (! method_exists($class, $attributes['event']) && method_exists($class, '__invoke')) { $args[] = '__invoke'; } $container->findDefinition($listenerId)->addMethodCall('addEntityListener', $args); } private function getResolverClass(Definition $resolver, ContainerBuilder $container, string $id) : string { $resolverClass = $this->getConcreteDefinitionClass($resolver, $container, $id); if (substr($resolverClass, 0, 1) === '%') { // resolve container parameter first $resolverClass = $container->getParameterBag()->resolveValue($resolverClass); } return $resolverClass; } private function getConcreteDefinitionClass(Definition $definition, ContainerBuilder $container, string $id) : string { $class = $definition->getClass(); if ($class) { return $class; } while ($definition instanceof ChildDefinition) { $definition = $container->findDefinition($definition->getParent()); $class = $definition->getClass(); if ($class) { return $class; } } throw new InvalidArgumentException(sprintf('The service "%s" must define its class.', $id)); } } php-doctrine-bundle-2.0.7/DependencyInjection/Compiler/ServiceRepositoryCompilerPass.php000066400000000000000000000022601361552055200316150ustar00rootroot00000000000000hasDefinition('doctrine.orm.container_repository_factory')) { return; } $locatorDef = $container->getDefinition('doctrine.orm.container_repository_factory'); $repoServiceIds = array_keys($container->findTaggedServiceIds(self::REPOSITORY_SERVICE_TAG)); $repoReferences = array_map(static function ($id) { return new Reference($id); }, $repoServiceIds); $ref = ServiceLocatorTagPass::register($container, array_combine($repoServiceIds, $repoReferences)); $locatorDef->replaceArgument(0, $ref); } } php-doctrine-bundle-2.0.7/DependencyInjection/Compiler/WellKnownSchemaFilterPass.php000066400000000000000000000037541361552055200306420ustar00rootroot00000000000000getDefinitions() as $definition) { if ($definition->isAbstract() || $definition->isSynthetic()) { continue; } switch ($definition->getClass()) { case PdoAdapter::class: $blacklist[] = $definition->getArguments()[3]['db_table'] ?? 'cache_items'; break; case PdoSessionHandler::class: $blacklist[] = $definition->getArguments()[1]['db_table'] ?? 'sessions'; break; case PdoStore::class: $blacklist[] = $definition->getArguments()[1]['db_table'] ?? 'lock_keys'; break; case Connection::class: $blacklist[] = $definition->getArguments()[0]['table_name'] ?? 'messenger_messages'; break; } } if (! $blacklist) { return; } $definition = $container->getDefinition('doctrine.dbal.well_known_schema_asset_filter'); $definition->replaceArgument(0, $blacklist); foreach (array_keys($container->getParameter('doctrine.connections')) as $name) { $definition->addTag('doctrine.dbal.schema_filter', ['connection' => $name]); } } } php-doctrine-bundle-2.0.7/DependencyInjection/Configuration.php000066400000000000000000000733041361552055200246370ustar00rootroot00000000000000debug = (bool) $debug; } /** * {@inheritDoc} */ public function getConfigTreeBuilder() : TreeBuilder { $treeBuilder = new TreeBuilder('doctrine'); $rootNode = $treeBuilder->getRootNode(); $this->addDbalSection($rootNode); $this->addOrmSection($rootNode); return $treeBuilder; } /** * Add DBAL section to configuration tree */ private function addDbalSection(ArrayNodeDefinition $node) : void { $node ->children() ->arrayNode('dbal') ->beforeNormalization() ->ifTrue(static function ($v) { return is_array($v) && ! array_key_exists('connections', $v) && ! array_key_exists('connection', $v); }) ->then(static function ($v) { // Key that should not be rewritten to the connection config $excludedKeys = ['default_connection' => true, 'types' => true, 'type' => true]; $connection = []; 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'] = [$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(static function ($v) { return ['class' => $v]; }) ->end() ->children() ->scalarNode('class')->isRequired()->end() ->booleanNode('commented')->setDeprecated()->end() ->end() ->end() ->end() ->end() ->fixXmlConfig('connection') ->append($this->getDbalConnectionsNode()) ->end(); } /** * Return the dbal connections node */ private function getDbalConnectionsNode() : ArrayNodeDefinition { $treeBuilder = new TreeBuilder('connections'); $node = $treeBuilder->getRootNode(); /** @var ArrayNodeDefinition $connectionNode */ $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() ->booleanNode('profiling_collect_backtrace') ->defaultValue(false) ->info('Enables collecting backtraces when profiling is enabled') ->end() ->scalarNode('server_version')->end() ->scalarNode('driver_class')->end() ->scalarNode('wrapper_class')->end() ->scalarNode('shard_manager_class')->end() ->scalarNode('shard_choser')->end() ->scalarNode('shard_choser_service')->end() ->booleanNode('keep_slave')->end() ->arrayNode('options') ->useAttributeAsKey('key') ->prototype('variable')->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. */ private function configureDbalDriverNode(ArrayNodeDefinition $node) : void { $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('default_dbname') ->info( 'Override the default database (postgres) to connect to for PostgreSQL connexion.' ) ->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() ->scalarNode('sslcert') ->info( 'The path to the SSL client certificate file for PostgreSQL.' ) ->end() ->scalarNode('sslkey') ->info( 'The path to the SSL client key file for PostgreSQL.' ) ->end() ->scalarNode('sslcrl') ->info( 'The file name of the SSL certificate revocation list for PostgreSQL.' ) ->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() ->scalarNode('instancename') ->info( 'Optional parameter, complete whether to add the INSTANCE_NAME parameter in the connection.' . ' It is generally used to connect to an Oracle RAC server to select the name' . ' of a particular instance.' ) ->end() ->scalarNode('connectstring') ->info( 'Complete Easy Connect connection descriptor, see https://docs.oracle.com/database/121/NETAG/naming.htm.' . 'When using this option, you will still need to provide the user and password parameters, but the other ' . 'parameters will no longer be used. Note that when using this parameter, the getHost and getPort methods' . ' from Doctrine\DBAL\Connection will no longer function as expected.' ) ->end() ->end() ->beforeNormalization() ->ifTrue(static function ($v) { return ! isset($v['sessionMode']) && isset($v['session_mode']); }) ->then(static function ($v) { $v['sessionMode'] = $v['session_mode']; unset($v['session_mode']); return $v; }) ->end() ->beforeNormalization() ->ifTrue(static function ($v) { return ! isset($v['MultipleActiveResultSets']) && isset($v['multiple_active_result_sets']); }) ->then(static 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 */ private function addOrmSection(ArrayNodeDefinition $node) : void { $node ->children() ->arrayNode('orm') ->beforeNormalization() ->ifTrue(static function ($v) { if (! empty($v) && ! class_exists(EntityManager::class)) { throw new LogicException('The doctrine/orm package is required when the doctrine.orm config is set.'); } return $v === null || (is_array($v) && ! array_key_exists('entity_managers', $v) && ! array_key_exists('entity_manager', $v)); }) ->then(static function ($v) { $v = (array) $v; // Key that should not be rewritten to the connection config $excludedKeys = [ 'default_entity_manager' => true, 'auto_generate_proxy_classes' => true, 'proxy_dir' => true, 'proxy_namespace' => true, 'resolve_target_entities' => true, 'resolve_target_entity' => true, ]; $entityManager = []; 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'] = [$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) { $generationModes = $this->getAutoGenerateModes(); 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(static 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 */ private function getOrmTargetEntityResolverNode() : NodeDefinition { $treeBuilder = new TreeBuilder('resolve_target_entities'); $node = $treeBuilder->getRootNode(); $node ->useAttributeAsKey('interface') ->prototype('scalar') ->cannotBeEmpty() ->end(); return $node; } /** * Return ORM entity listener node */ private function getOrmEntityListenersNode() : NodeDefinition { $treeBuilder = new TreeBuilder('entity_listeners'); $node = $treeBuilder->getRootNode(); $normalizer = static function ($mappings) { $entities = []; foreach ($mappings as $entityClass => $mapping) { $listeners = []; foreach ($mapping as $listenerClass => $listenerEvent) { $events = []; foreach ($listenerEvent as $eventType => $eventMapping) { if ($eventMapping === null) { $eventMapping = [null]; } foreach ($eventMapping as $method) { $events[] = [ 'type' => $eventType, 'method' => $method, ]; } } $listeners[] = [ 'class' => $listenerClass, 'event' => $events, ]; } $entities[] = [ 'class' => $entityClass, 'listener' => $listeners, ]; } return ['entities' => $entities]; }; $node ->beforeNormalization() // Yaml normalization ->ifTrue(static 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 */ private function getOrmEntityManagersNode() : ArrayNodeDefinition { $treeBuilder = new TreeBuilder('entity_managers'); $node = $treeBuilder->getRootNode(); $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')->defaultValue('doctrine.orm.container_repository_factory')->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(static function ($v) { return ['type' => $v]; }) ->end() ->treatNullLike([]) ->treatFalseLike(['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(static function ($v) { return ['class' => $v]; }) ->end() ->beforeNormalization() // The content of the XML node is returned as the "value" key so we need to rename it ->ifTrue(static function ($v) { return is_array($v) && isset($v['value']); }) ->then(static 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 */ private function getOrmCacheDriverNode(string $name) : ArrayNodeDefinition { $treeBuilder = new TreeBuilder($name); $node = $treeBuilder->getRootNode(); $node ->addDefaultsIfNotSet() ->beforeNormalization() ->ifString() ->then(static function ($v) : array { return ['type' => $v]; }) ->end() ->children() ->scalarNode('type')->defaultNull()->end() ->scalarNode('id')->end() ->scalarNode('pool')->end() ->end(); return $node; } /** * Find proxy auto generate modes for their names and int values */ private function getAutoGenerateModes() : array { $constPrefix = 'AUTOGENERATE_'; $prefixLen = strlen($constPrefix); $refClass = new ReflectionClass('Doctrine\Common\Proxy\AbstractProxyFactory'); $constsArray = $refClass->getConstants(); $namesArray = []; $valuesArray = []; foreach ($constsArray as $key => $value) { if (strpos($key, $constPrefix) !== 0) { continue; } $namesArray[] = substr($key, $prefixLen); $valuesArray[] = (int) $value; } return [ 'names' => $namesArray, 'values' => $valuesArray, ]; } } php-doctrine-bundle-2.0.7/DependencyInjection/DoctrineExtension.php000066400000000000000000001123121361552055200254650ustar00rootroot00000000000000getConfiguration($configs, $container); $config = $this->processConfiguration($configuration, $configs); if (! empty($config['dbal'])) { $this->dbalLoad($config['dbal'], $container); $this->loadMessengerServices($container); } if (empty($config['orm'])) { return; } if (empty($config['dbal'])) { throw new LogicException('Configuring the ORM layer requires to configure the DBAL layer as well.'); } $this->ormLoad($config['orm'], $container); } /** * 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->getAlias('database_connection')->setPublic(true); $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 = []; 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); 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 = $container->setDefinition(sprintf('doctrine.dbal.%s_connection.configuration', $name), new ChildDefinition('doctrine.dbal.connection.configuration')); $logger = null; if ($connection['logging']) { $logger = new Reference('doctrine.dbal.logger'); } unset($connection['logging']); if ($connection['profiling']) { $profilingAbstractId = $connection['profiling_collect_backtrace'] ? 'doctrine.dbal.logger.backtrace' : 'doctrine.dbal.logger.profiling'; $profilingLoggerId = $profilingAbstractId . '.' . $name; $container->setDefinition($profilingLoggerId, new ChildDefinition($profilingAbstractId)); $profilingLogger = new Reference($profilingLoggerId); $container->getDefinition('data_collector.doctrine')->addMethodCall('addLogger', [$name, $profilingLogger]); if ($logger !== null) { $chainLogger = new ChildDefinition('doctrine.dbal.logger.chain'); $chainLogger->addMethodCall('addLogger', [$profilingLogger]); $loggerId = 'doctrine.dbal.logger.chain.' . $name; $container->setDefinition($loggerId, $chainLogger); $logger = new Reference($loggerId); } else { $logger = $profilingLogger; } } unset($connection['profiling'], $connection['profiling_collect_backtrace']); if (isset($connection['auto_commit'])) { $configuration->addMethodCall('setAutoCommit', [$connection['auto_commit']]); } unset($connection['auto_commit']); if (isset($connection['schema_filter']) && $connection['schema_filter']) { $definition = new Definition(RegexSchemaAssetFilter::class, [$connection['schema_filter']]); $definition->addTag('doctrine.dbal.schema_filter', ['connection' => $name]); $container->setDefinition(sprintf('doctrine.dbal.%s_regex_schema_filter', $name), $definition); } unset($connection['schema_filter']); if ($logger) { $configuration->addMethodCall('setSQLLogger', [$logger]); } // event manager $container->setDefinition(sprintf('doctrine.dbal.%s_connection.event_manager', $name), new ChildDefinition('doctrine.dbal.connection.event_manager')); // connection $options = $this->getConnectionOptions($connection); $def = $container ->setDefinition(sprintf('doctrine.dbal.%s_connection', $name), new ChildDefinition('doctrine.dbal.connection')) ->setPublic(true) ->setArguments([ $options, new Reference(sprintf('doctrine.dbal.%s_connection.configuration', $name)), new Reference(sprintf('doctrine.dbal.%s_connection.event_manager', $name)), $connection['mapping_types'], ]); // Set class in case "wrapper_class" option was used to assist IDEs if (isset($options['wrapperClass'])) { $def->setClass($options['wrapperClass']); } if (! empty($connection['use_savepoints'])) { $def->addMethodCall('setNestTransactionsWithSavepoints', [$connection['use_savepoints']]); } // Create a shard_manager for this connection if (! isset($options['shards'])) { return; } $shardManagerDefinition = new Definition($options['shardManagerClass'], [new Reference(sprintf('doctrine.dbal.%s_connection', $name))]); $container->setDefinition(sprintf('doctrine.dbal.%s_shard_manager', $name), $shardManagerDefinition); } 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 ([ 'options' => 'driverOptions', 'driver_class' => 'driverClass', 'wrapper_class' => 'wrapperClass', 'keep_slave' => 'keepSlave', 'shard_choser' => 'shardChoser', 'shard_manager_class' => 'shardManagerClass', 'server_version' => 'serverVersion', 'default_table_options' => 'defaultTableOptions', ] as $old => $new) { if (! isset($options[$old])) { continue; } $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 = [ 'driver' => true, 'driverOptions' => true, 'driverClass' => true, 'wrapperClass' => true, 'keepSlave' => true, 'shardChoser' => true, 'platform' => true, 'slaves' => true, 'master' => true, 'shards' => true, 'serverVersion' => true, 'defaultTableOptions' => 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 = [ 'driver' => true, 'driverOptions' => true, 'driverClass' => true, 'wrapperClass' => true, 'keepSlave' => true, 'shardChoser' => true, 'platform' => true, 'slaves' => true, 'global' => true, 'shards' => true, 'serverVersion' => true, 'defaultTableOptions' => 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'; } if (empty($options['shardManagerClass'])) { // Change the shard manager class only if the user does not already forced using a custom one. $options['shardManagerClass'] = 'Doctrine\\DBAL\\Sharding\\PoolingShardManager'; } } 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) { if (! class_exists(UnitOfWork::class)) { throw new LogicException('To configure the ORM layer, you must first install the doctrine/orm package.'); } $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('orm.xml'); if (class_exists(AbstractType::class)) { $container->getDefinition('form.type.entity')->addTag('kernel.reset', ['method' => 'reset']); } $entityManagers = []; foreach (array_keys($config['entity_managers']) as $name) { $entityManagers[$name] = sprintf('doctrine.orm.%s_entity_manager', $name); } $container->setParameter('doctrine.entity_managers', $entityManagers); if (empty($config['default_entity_manager'])) { $tmp = array_keys($entityManagers); $config['default_entity_manager'] = reset($tmp); } $container->setParameter('doctrine.default_entity_manager', $config['default_entity_manager']); $options = ['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'])); $container->getAlias('doctrine.orm.entity_manager')->setPublic(true); $config['entity_managers'] = $this->fixManagersAutoMappings($config['entity_managers'], $container->getParameter('kernel.bundles')); foreach ($config['entity_managers'] as $name => $entityManager) { $entityManager['name'] = $name; $this->loadOrmEntityManager($entityManager, $container); if (interface_exists(PropertyInfoExtractorInterface::class)) { $this->loadPropertyInfoExtractor($name, $container); } $this->loadValidatorLoader($name, $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', [ $name, $implementation, [], ]); } $def->addTag('doctrine.event_subscriber'); } $container->registerForAutoconfiguration(ServiceEntityRepositoryInterface::class) ->addTag(ServiceRepositoryCompilerPass::REPOSITORY_SERVICE_TAG); } /** * 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 ChildDefinition('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 { $definition = new Definition('%doctrine.orm.entity_listener_resolver.class%'); $definition->addArgument(new Reference('service_container')); $container->setDefinition(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name']), $definition); } $methods = [ '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'], 'setNamingStrategy' => new Reference($entityManager['naming_strategy']), 'setQuoteStrategy' => new Reference($entityManager['quote_strategy']), 'setEntityListenerResolver' => new Reference(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name'])), ]; $listenerId = sprintf('doctrine.orm.%s_listeners.attach_entity_listeners', $entityManager['name']); $listenerDef = $container->setDefinition($listenerId, new Definition('%doctrine.orm.listeners.attach_entity_listeners.class%')); $listenerTagParams = ['event' => 'loadClassMetadata']; if (isset($entityManager['connection'])) { $listenerTagParams['connection'] = $entityManager['connection']; } $listenerDef->addTag('doctrine.event_listener', $listenerTagParams); 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, [$arg]); } foreach ($entityManager['hydrators'] as $name => $class) { $ormConfigDef->addMethodCall('addCustomHydrationMode', [$name, $class]); } if (! empty($entityManager['dql'])) { foreach ($entityManager['dql']['string_functions'] as $name => $function) { $ormConfigDef->addMethodCall('addCustomStringFunction', [$name, $function]); } foreach ($entityManager['dql']['numeric_functions'] as $name => $function) { $ormConfigDef->addMethodCall('addCustomNumericFunction', [$name, $function]); } foreach ($entityManager['dql']['datetime_functions'] as $name => $function) { $ormConfigDef->addMethodCall('addCustomDatetimeFunction', [$name, $function]); } } $enabledFilters = []; $filtersParameters = []; foreach ($entityManager['filters'] as $name => $filter) { $ormConfigDef->addMethodCall('addFilter', [$name, $filter['class']]); if ($filter['enabled']) { $enabledFilters[] = $name; } if (! $filter['parameters']) { continue; } $filtersParameters[$name] = $filter['parameters']; } $managerConfiguratorName = sprintf('doctrine.orm.%s_manager_configurator', $entityManager['name']); $container ->setDefinition($managerConfiguratorName, new ChildDefinition('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 ChildDefinition('doctrine.orm.entity_manager.abstract')) ->setPublic(true) ->setArguments([ new Reference(sprintf('doctrine.dbal.%s_connection', $entityManager['connection'])), new Reference(sprintf('doctrine.orm.%s_configuration', $entityManager['name'])), ]) ->setConfigurator([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'])) { return; } 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', [ $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. * * @param array $entityManager A configured ORM entity manager * @param Definition $ormConfigDef A Definition instance * @param ContainerBuilder $container A ContainerBuilder instance * * @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.project_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. */ 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 = []; $this->aliasMap = []; $this->loadMappingInformation($entityManager, $container); $this->registerMappingDrivers($entityManager, $container); $ormConfigDef->addMethodCall('setEntityNamespaces', [$this->aliasMap]); } /** * Loads an ORM second level cache bundle mapping information. * * @param array $entityManager A configured ORM entity manager * @param Definition $ormConfigDef A Definition instance * @param ContainerBuilder $container A ContainerBuilder instance * * @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 */ protected function loadOrmSecondLevelCache(array $entityManager, Definition $ormConfigDef, ContainerBuilder $container) { $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']); $factoryClass = isset($entityManager['second_level_cache']['factory']) ? $entityManager['second_level_cache']['factory'] : '%doctrine.orm.second_level_cache.default_cache_factory.class%'; $definition = new Definition($factoryClass, [new Reference($regionsId), new Reference($driverId)]); $slcFactoryDef = $container ->setDefinition($slcFactoryId, $definition); 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([$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([$regionRef, $region['lock_path'], $region['lock_lifetime']]); $regionRef = new Reference($regionId); $regionsDef->addMethodCall('getLockLifetime', [$name, $region['lock_lifetime']]); } $regionsDef->addMethodCall('setLifetime', [$name, $region['lifetime']]); $slcFactoryDef->addMethodCall('setRegion', [$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', ['statistics', $loggerStatsDef]); $configDef->addMethodCall('setCacheLogger', [$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', [$name, $loggerRef]); } } $configDef->addMethodCall('setCacheFactory', [$slcFactoryDef]); $configDef->addMethodCall('setRegionsConfiguration', [$regionsDef]); $ormConfigDef->addMethodCall('setSecondLevelCacheEnabled', [$enabled]); $ormConfigDef->addMethodCall('setSecondLevelCacheConfiguration', [$configDef]); } /** * {@inheritDoc} */ protected function getObjectManagerElementName($name) : string { return 'doctrine.orm.' . $name; } protected function getMappingObjectDefaultName() : string { return 'Entity'; } /** * {@inheritDoc} */ protected function getMappingResourceConfigDirectory() : string { return 'Resources/config/doctrine'; } /** * {@inheritDoc} */ protected function getMappingResourceExtension() : string { return 'orm'; } /** * {@inheritDoc} */ protected function loadCacheDriver($cacheName, $objectManagerName, array $cacheDriver, ContainerBuilder $container) : string { $serviceId = null; $aliasId = $this->getObjectManagerElementName(sprintf('%s_%s', $objectManagerName, $cacheName)); switch ($cacheDriver['type'] ?? 'pool') { case 'service': $serviceId = $cacheDriver['id']; break; case 'pool': $serviceId = $this->createPoolCacheDefinition($container, $cacheDriver['pool'] ?? $this->createArrayAdapterCachePool($container, $objectManagerName, $cacheName)); break; case 'provider': $serviceId = sprintf('doctrine_cache.providers.%s', $cacheDriver['cache_provider']); break; default: throw new \InvalidArgumentException(sprintf( 'Unknown cache of type "%s" configured for cache "%s" in entity manager "%s".', $cacheDriver['type'], $cacheName, $objectManagerName )); } $container->setAlias($aliasId, new Alias($serviceId, false)); return $aliasId; } /** * 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); } /** * Loads a property info extractor for each defined entity manager. */ private function loadPropertyInfoExtractor(string $entityManagerName, ContainerBuilder $container) : void { $propertyExtractorDefinition = $container->register(sprintf('doctrine.orm.%s_entity_manager.property_info_extractor', $entityManagerName), DoctrineExtractor::class); $argumentId = sprintf('doctrine.orm.%s_entity_manager', $entityManagerName); $propertyExtractorDefinition->addArgument(new Reference($argumentId)); $propertyExtractorDefinition->addTag('property_info.list_extractor', ['priority' => -1001]); $propertyExtractorDefinition->addTag('property_info.type_extractor', ['priority' => -999]); $propertyExtractorDefinition->addTag('property_info.access_extractor', ['priority' => -999]); } /** * Loads a validator loader for each defined entity manager. */ private function loadValidatorLoader(string $entityManagerName, ContainerBuilder $container) : void { $validatorLoaderDefinition = $container->register(sprintf('doctrine.orm.%s_entity_manager.validator_loader', $entityManagerName), DoctrineLoader::class); $validatorLoaderDefinition->addArgument(new Reference(sprintf('doctrine.orm.%s_entity_manager', $entityManagerName))); $validatorLoaderDefinition->addTag('validator.auto_mapper', ['priority' => -100]); } /** * @param array $objectManager * @param string $cacheName */ public function loadObjectManagerCacheDriver(array $objectManager, ContainerBuilder $container, $cacheName) { $this->loadCacheDriver($cacheName, $objectManager['name'], $objectManager[$cacheName . '_driver'], $container); } /** * {@inheritDoc} */ public function getXsdValidationBasePath() : string { return __DIR__ . '/../Resources/config/schema'; } /** * {@inheritDoc} */ public function getNamespace() : string { return 'http://symfony.com/schema/dic/doctrine'; } /** * {@inheritDoc} */ public function getConfiguration(array $config, ContainerBuilder $container) : Configuration { return new Configuration($container->getParameter('kernel.debug')); } protected function getMetadataDriverClass(string $driverType) : string { return '%' . $this->getObjectManagerElementName('metadata.' . $driverType . '.class%'); } private function loadMessengerServices(ContainerBuilder $container) : void { // If the Messenger component is installed and the doctrine transaction middleware is available, wire it: if (! interface_exists(MessageBusInterface::class) || ! class_exists(DoctrineTransactionMiddleware::class)) { return; } $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('messenger.xml'); if (! class_exists(DoctrineClearEntityManagerWorkerSubscriber::class)) { $container->removeDefinition('doctrine.orm.messenger.event_subscriber.doctrine_clear_entity_manager'); } if (! class_exists(DoctrineTransportFactory::class)) { return; } $transportFactoryDefinition = $container->getDefinition('messenger.transport.doctrine.factory'); $transportFactoryDefinition->addTag('messenger.transport_factory'); } private function createPoolCacheDefinition(ContainerBuilder $container, string $poolName) : string { $serviceId = sprintf('doctrine.orm.cache.provider.%s', $poolName); $definition = $container->register($serviceId, DoctrineProvider::class); $definition->addArgument(new Reference($poolName)); $definition->setPrivate(true); return $serviceId; } private function createArrayAdapterCachePool(ContainerBuilder $container, string $objectManagerName, string $cacheName) : string { $id = sprintf('cache.doctrine.orm.%s.%s', $objectManagerName, str_replace('_cache', '', $cacheName)); $poolDefinition = $container->register($id, ArrayAdapter::class); $poolDefinition->addTag('cache.pool'); $container->setDefinition($id, $poolDefinition); return $id; } } php-doctrine-bundle-2.0.7/DoctrineBundle.php000066400000000000000000000120651361552055200210050ustar00rootroot00000000000000addCompilerPass(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()); $container->addCompilerPass(new ServiceRepositoryCompilerPass()); $container->addCompilerPass(new WellKnownSchemaFilterPass()); $container->addCompilerPass(new DbalSchemaFilterPass()); } /** * {@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')) { return; } $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 = static 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 EntityManager $em */ 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([$classMetadata]); clearstatcache(true, Autoloader::resolveFile($proxyDir, $proxyNamespace, $class)); break; } }; } $this->autoloader = Autoloader::register($dir, $namespace, $proxyGenerator); } /** * {@inheritDoc} */ public function shutdown() { if ($this->autoloader !== null) { 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->initialized($id)) { continue; } $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')) { return; } foreach ($this->container->getParameter('doctrine.connections') as $id) { if (! $this->container->initialized($id)) { continue; } $this->container->get($id)->close(); } } /** * {@inheritDoc} */ public function registerCommands(Application $application) { } } php-doctrine-bundle-2.0.7/LICENSE000066400000000000000000000020661361552055200164000ustar00rootroot00000000000000Copyright (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. php-doctrine-bundle-2.0.7/ManagerConfigurator.php000066400000000000000000000035341361552055200220420ustar00rootroot00000000000000> */ private $filtersParameters = []; /** * @param string[] $enabledFilters * @param array> $filtersParameters */ public function __construct(array $enabledFilters, array $filtersParameters) { $this->enabledFilters = $enabledFilters; $this->filtersParameters = $filtersParameters; } /** * Create a connection by name. */ public function configure(EntityManagerInterface $entityManager) { $this->enableFilters($entityManager); } /** * Enables filters for a given entity manager */ private function enableFilters(EntityManagerInterface $entityManager) : void { if (empty($this->enabledFilters)) { return; } $filterCollection = $entityManager->getFilters(); foreach ($this->enabledFilters as $filter) { $filterObject = $filterCollection->enable($filter); if ($filterObject === null) { continue; } $this->setFilterParameters($filter, $filterObject); } } /** * Sets default parameters for a given filter */ private function setFilterParameters(string $name, SQLFilter $filter) : void { if (empty($this->filtersParameters[$name])) { return; } $parameters = $this->filtersParameters[$name]; foreach ($parameters as $paramName => $paramValue) { $filter->setParameter($paramName, $paramValue); } } } php-doctrine-bundle-2.0.7/Mapping/000077500000000000000000000000001361552055200167625ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Mapping/ClassMetadataCollection.php000066400000000000000000000020351361552055200242150ustar00rootroot00000000000000metadata = $metadata; } /** * @return ClassMetadata[] */ 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; } } php-doctrine-bundle-2.0.7/Mapping/ContainerEntityListenerResolver.php000066400000000000000000000047211361552055200260460ustar00rootroot00000000000000container = $container; } /** * {@inheritdoc} */ public function clear($className = null) { if ($className === null) { $this->instances = []; return; } $className = $this->normalizeClassName($className); unset($this->instances[$className]); } /** * {@inheritdoc} */ public function register($object) { if (! is_object($object)) { throw new InvalidArgumentException(sprintf('An object was expected, but got "%s".', gettype($object))); } $className = $this->normalizeClassName(get_class($object)); $this->instances[$className] = $object; } /** * {@inheritdoc} */ public function registerService($className, $serviceId) { $this->serviceIds[$this->normalizeClassName($className)] = $serviceId; } /** * {@inheritdoc} */ public function resolve($className) { $className = $this->normalizeClassName($className); if (! isset($this->instances[$className])) { if (isset($this->serviceIds[$className])) { $this->instances[$className] = $this->resolveService($this->serviceIds[$className]); } else { $this->instances[$className] = new $className(); } } return $this->instances[$className]; } /** * @return object */ private function resolveService(string $serviceId) { if (! $this->container->has($serviceId)) { throw new RuntimeException(sprintf('There is no service named "%s"', $serviceId)); } return $this->container->get($serviceId); } private function normalizeClassName(string $className) : string { return trim($className, '\\'); } } php-doctrine-bundle-2.0.7/Mapping/DisconnectedMetadataFactory.php000066400000000000000000000137541361552055200251000ustar00rootroot00000000000000registry = $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 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 * * @throws RuntimeException When base path not found. */ private function getBasePathForClass(string $name, string $namespace, string $path) : string { $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; } private function getMetadataForNamespace(string $namespace) : ClassMetadataCollection { $metadata = []; foreach ($this->getAllMetadata() as $m) { if (strpos($m->name, $namespace) !== 0) { continue; } $metadata[] = $m; } return new ClassMetadataCollection($metadata); } private function getMetadataForClass(string $entity) : ClassMetadataCollection { foreach ($this->registry->getManagers() as $em) { $cmf = new DisconnectedClassMetadataFactory(); $cmf->setEntityManager($em); if (! $cmf->isTransient($entity)) { return new ClassMetadataCollection([$cmf->getMetadataFor($entity)]); } } return new ClassMetadataCollection([]); } /** * @return ClassMetadata[] */ private function getAllMetadata() : array { $metadata = []; foreach ($this->registry->getManagers() as $em) { $cmf = new DisconnectedClassMetadataFactory(); $cmf->setEntityManager($em); foreach ($cmf->getAllMetadata() as $m) { $metadata[] = $m; } } return $metadata; } } php-doctrine-bundle-2.0.7/Mapping/EntityListenerServiceResolver.php000066400000000000000000000005041361552055200255170ustar00rootroot00000000000000container = $container; parent::__construct('ORM', $connections, $entityManagers, $defaultConnection, $defaultEntityManager, 'Doctrine\ORM\Proxy\Proxy'); } /** * Resolves a registered namespace alias to the full namespace. * * This method looks for the alias in all registered entity managers. * * @see Configuration::getEntityNamespace * * @param string $alias The alias * * @return string The full namespace */ 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); } public function reset() : void { foreach ($this->getManagerNames() as $managerName => $serviceId) { $this->resetOrClearManager($managerName, $serviceId); } } private function resetOrClearManager(string $managerName, string $serviceId) : void { if (! $this->container->initialized($serviceId)) { return; } $manager = $this->container->get($serviceId); assert($manager instanceof EntityManagerInterface); if (! $manager instanceof LazyLoadingInterface || $manager->isOpen()) { $manager->clear(); return; } $this->resetManager($managerName); } } php-doctrine-bundle-2.0.7/Repository/000077500000000000000000000000001361552055200175465ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Repository/ContainerRepositoryFactory.php000066400000000000000000000075261361552055200256430ustar00rootroot00000000000000container = $container; } /** * {@inheritdoc} */ public function getRepository(EntityManagerInterface $entityManager, $entityName) : ObjectRepository { $metadata = $entityManager->getClassMetadata($entityName); $repositoryServiceId = $metadata->customRepositoryClassName; $customRepositoryName = $metadata->customRepositoryClassName; if ($customRepositoryName !== null) { // fetch from the container if ($this->container && $this->container->has($customRepositoryName)) { $repository = $this->container->get($customRepositoryName); if (! $repository instanceof ObjectRepository) { throw new RuntimeException(sprintf('The service "%s" must implement ObjectRepository (or extend a base class, like ServiceEntityRepository).', $repositoryServiceId)); } return $repository; } // if not in the container but the class/id implements the interface, throw an error if (is_a($customRepositoryName, ServiceEntityRepositoryInterface::class, true)) { throw new RuntimeException(sprintf('The "%s" entity repository implements "%s", but its service could not be found. Make sure the service exists and is tagged with "%s".', $customRepositoryName, ServiceEntityRepositoryInterface::class, ServiceRepositoryCompilerPass::REPOSITORY_SERVICE_TAG)); } if (! class_exists($customRepositoryName)) { throw new RuntimeException(sprintf('The "%s" entity has a repositoryClass set to "%s", but this is not a valid class. Check your class naming. If this is meant to be a service id, make sure this service exists and is tagged with "%s".', $metadata->name, $customRepositoryName, ServiceRepositoryCompilerPass::REPOSITORY_SERVICE_TAG)); } // allow the repository to be created below } return $this->getOrCreateRepository($entityManager, $metadata); } private function getOrCreateRepository( EntityManagerInterface $entityManager, ClassMetadata $metadata ) : ObjectRepository { $repositoryHash = $metadata->getName() . spl_object_hash($entityManager); if (isset($this->managedRepositories[$repositoryHash])) { return $this->managedRepositories[$repositoryHash]; } $repositoryClassName = $metadata->customRepositoryClassName ?: $entityManager->getConfiguration()->getDefaultRepositoryClassName(); return $this->managedRepositories[$repositoryHash] = new $repositoryClassName($entityManager, $metadata); } } php-doctrine-bundle-2.0.7/Repository/ServiceEntityRepository.php000066400000000000000000000024461361552055200251620ustar00rootroot00000000000000getManagerForClass($entityClass); if ($manager === null) { throw new LogicException(sprintf( 'Could not find the entity manager for class "%s". Check your Doctrine configuration to make sure it is configured to load this entity’s metadata.', $entityClass )); } parent::__construct($manager, $manager->getClassMetadata($entityClass)); } } php-doctrine-bundle-2.0.7/Repository/ServiceEntityRepositoryInterface.php000066400000000000000000000003101361552055200267670ustar00rootroot00000000000000 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% php-doctrine-bundle-2.0.7/Resources/config/messenger.xml000066400000000000000000000046171361552055200233300ustar00rootroot00000000000000 php-doctrine-bundle-2.0.7/Resources/config/orm.xml000066400000000000000000000321201361552055200221230ustar00rootroot00000000000000 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\Bundle\DoctrineBundle\Mapping\ContainerEntityListenerResolver 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 CASE_LOWER true %kernel.bundles% php-doctrine-bundle-2.0.7/Resources/config/schema/000077500000000000000000000000001361552055200220465ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Resources/config/schema/doctrine-1.0.xsd000066400000000000000000000311111361552055200246660ustar00rootroot00000000000000 php-doctrine-bundle-2.0.7/Resources/doc/000077500000000000000000000000001361552055200201065ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Resources/doc/configuration.rst000066400000000000000000001437161361552055200235230ustar00rootroot00000000000000.. 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 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 (default_dbname). # Override the default database (postgres) to connect to. default_dbname: ~ # 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: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLCERT). # The name of a file containing the client SSL certificate. sslcert: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLKEY). # The name of a file containing the private key for the client SSL certificate. sslkey: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLCRL). # The name of a file containing the SSL certificate revocation list (CRL). sslcrl: ~ # 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%" # When true, profiling also collects a backtrace for each query profiling_collect_backtrace: false server_version: ~ driver_class: ~ # Allows to specify a custom wrapper implementation to use. # Must be a subclass of Doctrine\DBAL\Connection 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 (default_dbname). # Override the default database (postgres) to connect to. default_dbname: ~ # 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: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLCERT). # The name of a file containing the client SSL certificate. sslcert: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLKEY). # The name of a file containing the private key for the client SSL certificate. sslkey: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLCRL). # The name of a file containing the SSL certificate revocation list (CRL). sslcrl: ~ # 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 (default_dbname). # Override the default database (postgres) to connect to. default_dbname: ~ # 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: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLCERT). # The name of a file containing the client SSL certificate. sslcert: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLKEY). # The name of a file containing the private key for the client SSL certificate. sslkey: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLCRL). # The name of a file containing the SSL certificate revocation list (CRL). sslcrl: ~ # 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: ~ id: ~ pool: ~ metadata_cache_driver: type: ~ id: ~ pool: ~ result_cache_driver: type: ~ id: ~ pool: ~ 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: ~ id: ~ pool: ~ region_lock_lifetime: 60 log_enabled: true region_lifetime: 0 enabled: true factory: ~ regions: # Prototype name: cache_driver: type: ~ id: ~ pool: ~ 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: ~ query_cache_driver: ~ result_cache_driver: ~ There are lots of other configuration options that you can use to overwrite certain classes, but those are for very advanced use-cases only. Oracle DB ~~~~~~~~~ If the environment format configured in oracle does not meet doctrine requirements, you need to use the OracleSessionInit listener so that doctrine is aware of the format used by Oracle DB. You can do so easily with .. code-block:: yaml services: oracle.listener: class: Doctrine\DBAL\Event\Listeners\OracleSessionInit tags: - { name: doctrine.event_listener, event: postConnect } The environment variables that doctrine is going to change in the Oracle DB session are: .. code-block:: yaml NLS_TIME_FORMAT="HH24:MI:SS" NLS_DATE_FORMAT="YYYY-MM-DD HH24:MI:SS" NLS_TIMESTAMP_FORMAT="YYYY-MM-DD HH24:MI:SS" NLS_TIMESTAMP_TZ_FORMAT="YYYY-MM-DD HH24:MI:SS TZH:TZM" Caching Drivers ~~~~~~~~~~~~~~~ You can use a Symfony Cache pool by using the ``pool`` type and creating a cache pool through the FrameworkBundle configuration. The ``service`` type lets you define the ``ID`` of your own caching service. The following example shows an overview of the caching configurations: .. code-block:: yaml doctrine: orm: auto_mapping: true # With no cache set, this defaults to a sane 'pool' configuration metadata_cache_driver: ~ # the 'pool' type requires to define the 'pool' option and configure a cache pool using the FrameworkBundle result_cache_driver: type: pool pool: doctrine.result_cache_pool # the 'service' type requires to define the 'id' option too query_cache_driver: type: service id: App\ORM\MyCacheService framework: cache: pools: doctrine.result_cache_pool: adapter: cache.app 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.project_dir%/var/data.db" # 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) default_dbname: database # PostgreSQL specific (default_dbname) sslmode: require # PostgreSQL specific (LIBPQ-CONNECT-SSLMODE) sslrootcert: postgresql-ca.pem # PostgreSQL specific (LIBPQ-CONNECT-SSLROOTCERT) sslcert: postgresql-cert.pem # PostgreSQL specific (LIBPQ-CONNECT-SSLCERT) sslkey: postgresql-key.pem # PostgreSQL specific (LIBPQ-CONNECT-SSLKEY) sslcrl: postgresql.crl # PostgreSQL specific (LIBPQ-CONNECT-SSLCRL) 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 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]`` is the name of the connection. .. _DBAL documentation: http://www.doctrine-project.org/docs/dbal/2.0/en php-doctrine-bundle-2.0.7/Resources/doc/entity-listeners.rst000066400000000000000000000104701361552055200241640ustar00rootroot00000000000000Entity Listeners ================ Entity listeners that are services must be registered with the entity listener resolver. On top of the annotation in the entity class, you have to tag the service with ``doctrine.orm.entity_listener`` for it to be automatically added to the resolver. Use the (optional) ``entity_manager`` attribute to specify which entity manager it should be registered with. Full example: .. code-block:: php Starting with doctrine/orm 2.5 and Doctrine bundle 1.5.2, instead of registering the entity listener on the entity, you can declare all options from the service definition: .. configuration-block:: .. code-block:: yaml services: user_listener: class: \UserListener tags: - name: doctrine.orm.entity_listener event: preUpdate entity: App\Entity\User # entity_manager attribute is optional entity_manager: custom # method attribute is optional method: validateEmail .. code-block:: xml If you don't specify the ``method`` attribute, it falls back on the subscribed event name. Starting with Doctrine bundle 1.12, if this method does not exist but if your entity listener is invokable, it falls back on the ``__invoke()`` method. See also https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#entity-listeners for more info on entity listeners and the resolver required by Symfony. Lazy Entity Listeners --------------------- You can use the ``lazy`` attribute on the tag to make sure the listener services are only instantiated when they are actually used. .. configuration-block:: .. code-block:: yaml services: lazy_user_listener: class: \UserListener tags: - { name: doctrine.orm.entity_listener, lazy: true } .. code-block:: xml php-doctrine-bundle-2.0.7/Resources/doc/index.rst000066400000000000000000000004111361552055200217430ustar00rootroot00000000000000DoctrineBundle ============== 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 php-doctrine-bundle-2.0.7/Resources/doc/installation.rst000066400000000000000000000017351361552055200233470ustar00rootroot00000000000000Installation ============ 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: request.query.get('connection'), query: request.query.get('query') })) }} {% else %} {{ block('queries') }} {% endif %} {% endblock %} {% block queries %} {% if profiler_markup_version > 1 %}

Query Metrics

{{ collector.querycount }} Database Queries
{{ collector.groupedQueryCount }} Different statements
{{ '%0.2f'|format(collector.time * 1000) }} ms Query time
{{ collector.invalidEntityCount }} Invalid entities
{% if collector.cacheEnabled %}
{{ collector.cacheHitsCount }} Cache hits
{{ collector.cacheMissesCount }} Cache misses
{{ collector.cachePutsCount }} Cache puts
{% endif %}
{% endif %} {% set group_queries = request.query.getBoolean('group') %} {% if group_queries %}

Grouped Statements

Show all queries

{% else %}

Queries

Group similar statements

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

{{ connection }} connection

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

No database queries were performed.

{% else %} {% if group_queries %} {% set queries = collector.groupedQueries[connection] %} {% endif %} {% if group_queries %} {% else %} {% endif %} {% for i, query in queries %} {% set i = group_queries ? query.index : i %} {% if group_queries %} {% else %} {% endif %} {% endfor %}
Time Count# TimeInfo
{{ '%0.2f'|format(query.executionMS * 1000) }} ms
({{ '%0.2f'|format(query.executionPercent) }}%)
{{ query.count }}{{ loop.index }} {{ '%0.2f'|format(query.executionMS * 1000) }} ms {{ query.sql|doctrine_pretty_query(highlight_only = true) }}
Parameters: {{ profiler_dump(query.params, 2) }}
View formatted query {% if query.runnable %}    View runnable query {% endif %} {% if query.explainable %}    Explain query {% endif %} {% if query.backtrace is defined %}    View query backtrace {% endif %}
{% if query.runnable %} {% endif %} {% if query.explainable %}
{% endif %} {% if query.backtrace is defined %} {% endif %}
{% endif %} {% endfor %}

Database Connections

{% if not collector.connections %}

There are no configured database connections.

{% else %} {{ helper.render_simple_table('Name', 'Service', collector.connections) }} {% endif %}

Entity Managers

{% if not collector.managers %}

There are no configured entity managers.

{% else %} {{ helper.render_simple_table('Name', 'Service', collector.managers) }} {% 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 %} {{ helper.render_simple_table('Key', 'Value', collector.cacheCounts) }} {% else %}
{{ collector.cacheCounts.hits }} Hits
{{ collector.cacheCounts.misses }} Misses
{{ collector.cacheCounts.puts }} Puts
{% endif %} {% if collector.cacheRegions.hits %}

Number of cache hits

{{ helper.render_simple_table('Region', 'Hits', collector.cacheRegions.hits) }} {% endif %} {% if collector.cacheRegions.misses %}

Number of cache misses

{{ helper.render_simple_table('Region', 'Misses', collector.cacheRegions.misses) }} {% endif %} {% if collector.cacheRegions.puts %}

Number of cache puts

{{ helper.render_simple_table('Region', 'Puts', collector.cacheRegions.puts) }} {% 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 %} {% macro render_simple_table(label1, label2, data) %} {% for key, value in data %} {% endfor %}
{{ label1 }} {{ label2 }}
{{ key }} {{ value }}
{% endmacro %} php-doctrine-bundle-2.0.7/Resources/views/Collector/explain.html.twig000066400000000000000000000015651361552055200257320ustar00rootroot00000000000000{% 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 %} php-doctrine-bundle-2.0.7/Resources/views/Collector/icon.svg000066400000000000000000000012221361552055200240720ustar00rootroot00000000000000 php-doctrine-bundle-2.0.7/Tests/000077500000000000000000000000001361552055200164715ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/Builder/000077500000000000000000000000001361552055200200575ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/Builder/BundleConfigurationBuilder.php000066400000000000000000000036151361552055200260450ustar00rootroot00000000000000addBaseConnection(); $builder->addBaseEntityManager(); return $builder; } public function addBaseConnection() : self { $this->addConnection([ 'connections' => [ 'default' => ['password' => 'foo'], ], ]); return $this; } public function addBaseEntityManager() : self { $this->addEntityManager([ 'default_entity_manager' => 'default', 'entity_managers' => [ 'default' => [ 'mappings' => [ 'YamlBundle' => [], ], ], ], ]); return $this; } public function addBaseSecondLevelCache() : self { $this->addSecondLevelCache([ 'region_cache_driver' => ['type' => 'pool', 'pool' => 'my_pool'], 'regions' => [ 'hour_region' => ['lifetime' => 3600], ], ]); return $this; } public function addConnection($config) : self { $this->configuration['dbal'] = $config; return $this; } public function addEntityManager($config) : self { $this->configuration['orm'] = $config; return $this; } public function addSecondLevelCache($config, $manager = 'default') : self { $this->configuration['orm']['entity_managers'][$manager]['second_level_cache'] = $config; return $this; } public function build() : array { return $this->configuration; } } php-doctrine-bundle-2.0.7/Tests/BundleTest.php000066400000000000000000000030771361552055200212620ustar00rootroot00000000000000build($container); $config = $container->getCompilerPassConfig(); $passes = $config->getBeforeOptimizationPasses(); $foundEventListener = false; $foundValidation = false; $foundSchemaFilter = false; foreach ($passes as $pass) { if ($pass instanceof RegisterEventListenersAndSubscribersPass) { $foundEventListener = true; } elseif ($pass instanceof DoctrineValidationPass) { $foundValidation = true; } elseif ($pass instanceof DbalSchemaFilterPass) { $foundSchemaFilter = true; } } $this->assertTrue($foundEventListener, 'RegisterEventListenersAndSubscribersPass was not found'); $this->assertTrue($foundValidation, 'DoctrineValidationPass was not found'); $this->assertTrue($foundSchemaFilter, 'DbalSchemaFilterPass was not found'); } } php-doctrine-bundle-2.0.7/Tests/Command/000077500000000000000000000000001361552055200200475ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/Command/CreateDatabaseDoctrineTest.php000066400000000000000000000106271361552055200257460ustar00rootroot00000000000000 sys_get_temp_dir() . '/' . $dbName, 'driver' => 'pdo_sqlite', ]; $container = $this->getMockContainer($connectionName, $params); $application = new Application(); $application->add(new CreateDatabaseDoctrineCommand($container->get('doctrine'))); $command = $application->find('doctrine:database:create'); $commandTester = new CommandTester($command); $commandTester->execute( array_merge(['command' => $command->getName()]) ); $this->assertContains('Created database ' . sys_get_temp_dir() . '/' . $dbName . ' for connection named ' . $connectionName, $commandTester->getDisplay()); } public function testExecuteWithShardOption() : void { $connectionName = 'default'; $params = [ 'dbname' => 'test', 'memory' => true, 'driver' => 'pdo_sqlite', 'global' => [ 'driver' => 'pdo_sqlite', 'dbname' => 'test', 'path' => sys_get_temp_dir() . '/global', ], 'shards' => [ 'foo' => [ 'id' => 1, 'path' => sys_get_temp_dir() . '/shard_1', 'driver' => 'pdo_sqlite', ], 'bar' => [ 'id' => 2, 'path' => sys_get_temp_dir() . '/shard_2', 'driver' => 'pdo_sqlite', ], ], ]; $container = $this->getMockContainer($connectionName, $params); $application = new Application(); $application->add(new CreateDatabaseDoctrineCommand($container->get('doctrine'))); $command = $application->find('doctrine:database:create'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), '--shard' => 1]); $this->assertContains('Created database ' . sys_get_temp_dir() . '/shard_1 for connection named ' . $connectionName, $commandTester->getDisplay()); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), '--shard' => 2]); $this->assertContains('Created database ' . sys_get_temp_dir() . '/shard_2 for connection named ' . $connectionName, $commandTester->getDisplay()); } /** * @param mixed[]|null $params Connection parameters */ private function getMockContainer(string $connectionName, array $params = null) : MockObject { // Mock the container and everything you'll need here $mockDoctrine = $this->getMockBuilder('Doctrine\Persistence\ManagerRegistry') ->getMock(); $mockDoctrine->expects($this->any()) ->method('getDefaultConnectionName') ->withAnyParameters() ->willReturn($connectionName); $mockConnection = $this->getMockBuilder('Doctrine\DBAL\Connection') ->disableOriginalConstructor() ->setMethods(['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(['get']) ->getMock(); $mockContainer->expects($this->any()) ->method('get') ->with('doctrine') ->willReturn($mockDoctrine); return $mockContainer; } } php-doctrine-bundle-2.0.7/Tests/Command/DropDatabaseDoctrineTest.php000066400000000000000000000075011361552055200254440ustar00rootroot00000000000000 'sqlite:///' . sys_get_temp_dir() . '/test.db', 'path' => sys_get_temp_dir() . '/' . $dbName, 'driver' => 'pdo_sqlite', ]; $container = $this->getMockContainer($connectionName, $params); $application = new Application(); $application->add(new DropDatabaseDoctrineCommand($container->get('doctrine'))); $command = $application->find('doctrine:database:drop'); $commandTester = new CommandTester($command); $commandTester->execute( array_merge(['command' => $command->getName(), '--force' => true]) ); $this->assertContains( sprintf( 'Dropped database %s for connection named %s', sys_get_temp_dir() . '/' . $dbName, $connectionName ), $commandTester->getDisplay() ); } public function testExecuteWithoutOptionForceWillFailWithAttentionMessage() : void { $connectionName = 'default'; $dbName = 'test'; $params = [ 'path' => sys_get_temp_dir() . '/' . $dbName, 'driver' => 'pdo_sqlite', ]; $container = $this->getMockContainer($connectionName, $params); $application = new Application(); $application->add(new DropDatabaseDoctrineCommand($container->get('doctrine'))); $command = $application->find('doctrine:database:drop'); $commandTester = new CommandTester($command); $commandTester->execute( array_merge(['command' => $command->getName()]) ); $this->assertContains( sprintf( 'Would drop the database %s for connection named %s.', sys_get_temp_dir() . '/' . $dbName, $connectionName ), $commandTester->getDisplay() ); $this->assertContains('Please run the operation with --force to execute', $commandTester->getDisplay()); } /** * @param array|null $params Connection parameters */ private function getMockContainer(string $connectionName, array $params = null) : MockObject { // Mock the container and everything you'll need here $mockDoctrine = $this->getMockBuilder('Doctrine\Persistence\ManagerRegistry') ->getMock(); $mockDoctrine->expects($this->any()) ->method('getDefaultConnectionName') ->withAnyParameters() ->willReturn($connectionName); $mockConnection = $this->getMockBuilder('Doctrine\DBAL\Connection') ->disableOriginalConstructor() ->setMethods(['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(['get']) ->getMock(); $mockContainer->expects($this->any()) ->method('get') ->with('doctrine') ->willReturn($mockDoctrine); return $mockContainer; } } php-doctrine-bundle-2.0.7/Tests/Command/ImportMappingDoctrineCommandTest.php000066400000000000000000000103761361552055200272040ustar00rootroot00000000000000kernel = new class() extends TestKernel { public function registerBundles() : iterable { yield from parent::registerBundles(); yield new ImportMappingTestFooBundle(); } }; $this->kernel->boot(); $connection = $this->kernel->getContainer() ->get('doctrine') ->getConnection(); $connection->executeQuery('CREATE TABLE product (id integer primary key, name varchar(20), hint text)'); $application = new Application($this->kernel); $command = $application->find('doctrine:mapping:import'); $this->commandTester = new CommandTester($command); } protected function tearDown() : void { $fs = new Filesystem(); if ($this->kernel !== null) { $fs->remove($this->kernel->getCacheDir()); } $fs->remove(sys_get_temp_dir() . '/import_mapping_bundle'); $this->kernel = null; $this->commandTester = null; } public function testExecuteXmlWithBundle() : void { $this->commandTester->execute(['name' => 'ImportMappingTestFooBundle']); $expectedMetadataPath = sys_get_temp_dir() . '/import_mapping_bundle/Resources/config/doctrine/Product.orm.xml'; $this->assertFileExists($expectedMetadataPath); $this->assertContains('"Doctrine\Bundle\DoctrineBundle\Tests\Command\Entity\Product"', file_get_contents($expectedMetadataPath), 'Metadata contains correct namespace'); } public function testExecuteAnnotationsWithBundle() : void { $this->commandTester->execute([ 'name' => 'ImportMappingTestFooBundle', 'mapping-type' => 'annotation', ]); $expectedMetadataPath = sys_get_temp_dir() . '/import_mapping_bundle/Entity/Product.php'; $this->assertFileExists($expectedMetadataPath); $this->assertContains('namespace Doctrine\Bundle\DoctrineBundle\Tests\Command\Entity;', file_get_contents($expectedMetadataPath), 'File contains correct namespace'); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessageRegExp /The --path option is required/ */ public function testExecuteThrowsExceptionWithNamespaceAndNoPath() : void { $this->commandTester->execute(['name' => 'Some\Namespace']); } public function testExecuteXmlWithNamespace() : void { $this->commandTester->execute([ 'name' => 'Some\Namespace\Entity', '--path' => $this->kernel->getProjectDir() . '/config/doctrine', ]); $expectedMetadataPath = $this->kernel->getProjectDir() . '/config/doctrine/Product.orm.xml'; $this->assertFileExists($expectedMetadataPath); $this->assertContains('"Some\Namespace\Entity\Product"', file_get_contents($expectedMetadataPath), 'Metadata contains correct namespace'); } public function testExecuteAnnotationsWithNamespace() : void { $this->commandTester->execute([ 'name' => 'Some\Namespace\Entity', '--path' => $this->kernel->getProjectDir() . '/src/Entity', 'mapping-type' => 'annotation', ]); $expectedMetadataPath = $this->kernel->getProjectDir() . '/src/Entity/Product.php'; $this->assertFileExists($expectedMetadataPath); $this->assertContains('namespace Some\Namespace\Entity;', file_get_contents($expectedMetadataPath), 'Metadata contains correct namespace'); } } class ImportMappingTestFooBundle extends Bundle { public function getPath() : string { return sys_get_temp_dir() . '/import_mapping_bundle'; } } php-doctrine-bundle-2.0.7/Tests/ConnectionFactoryTest.php000066400000000000000000000101131361552055200234650ustar00rootroot00000000000000 FakeDriver::class]; $config = null; $eventManager = null; $mappingTypes = [0]; $exception = new DriverException('', $this->createMock(Driver\AbstractDriverException::class)); // put the mock into the fake driver FakeDriver::$exception = $exception; try { $factory->createConnection($params, $config, $eventManager, $mappingTypes); } catch (Exception $e) { $this->assertTrue(strpos($e->getMessage(), 'can circumvent this by setting') > 0); throw $e; } finally { FakeDriver::$exception = null; } } public function testDefaultCharset() : void { $factory = new ConnectionFactory([]); $params = [ 'driverClass' => FakeDriver::class, 'wrapperClass' => FakeConnection::class, ]; $creationCount = FakeConnection::$creationCount; $connection = $factory->createConnection($params); $this->assertInstanceof(FakeConnection::class, $connection); $this->assertSame('utf8', $connection->getParams()['charset']); $this->assertSame(1 + $creationCount, FakeConnection::$creationCount); } public function testDefaultCharsetMySql() : void { $factory = new ConnectionFactory([]); $params = ['driver' => 'pdo_mysql']; $connection = $factory->createConnection($params); $this->assertSame('utf8mb4', $connection->getParams()['charset']); } } /** * FakeDriver class to simulate a problem discussed in DoctrineBundle issue #673 * In order to not use a real database driver we have to create our own fake/mock implementation. * * @link https://github.com/doctrine/DoctrineBundle/issues/673 */ class FakeDriver implements Driver { /** * Exception Mock * * @var DriverException */ public static $exception; /** @var AbstractPlatform|null */ public static $platform; /** * This method gets called to determine the database version which in our case leeds to the problem. * So we have to fake the exception a driver would normally throw. * * @link https://github.com/doctrine/DoctrineBundle/issues/673 */ public function getDatabasePlatform() : AbstractPlatform { if (self::$exception !== null) { throw self::$exception; } return static::$platform ?? new MySqlPlatform(); } // ----- below this line follow only dummy methods to satisfy the interface requirements ---- /** * @param mixed[] $params * @param string|null $username * @param string|null $password * @param mixed[] $driverOptions */ public function connect(array $params, $username = null, $password = null, array $driverOptions = []) : void { throw new Exception('not implemented'); } public function getSchemaManager(Connection $conn) : void { throw new Exception('not implemented'); } public function getName() : string { return 'FakeDriver'; } public function getDatabase(Connection $conn) : string { return 'fake_db'; } } class FakeConnection extends Connection { /** @var int */ public static $creationCount = 0; public function __construct(array $params, FakeDriver $driver, ?Configuration $config = null, ?EventManager $eventManager = null) { ++self::$creationCount; parent::__construct($params, $driver, $config, $eventManager); } } php-doctrine-bundle-2.0.7/Tests/ContainerTest.php000066400000000000000000000072661361552055200217770ustar00rootroot00000000000000createXmlBundleTestContainer(); $this->assertInstanceOf(DbalLogger::class, $container->get('doctrine.dbal.logger')); $this->assertInstanceOf(DoctrineDataCollector::class, $container->get('data_collector.doctrine')); $this->assertInstanceOf(DBALConfiguration::class, $container->get('doctrine.dbal.default_connection.configuration')); $this->assertInstanceOf(EventManager::class, $container->get('doctrine.dbal.default_connection.event_manager')); $this->assertInstanceOf(Connection::class, $container->get('doctrine.dbal.default_connection')); $this->assertInstanceOf(Reader::class, $container->get('doctrine.orm.metadata.annotation_reader')); $this->assertInstanceOf(Configuration::class, $container->get('doctrine.orm.default_configuration')); $this->assertInstanceOf(MappingDriverChain::class, $container->get('doctrine.orm.default_metadata_driver')); $this->assertInstanceOf(DoctrineProvider::class, $container->get('doctrine.orm.default_metadata_cache')); $this->assertInstanceOf(DoctrineProvider::class, $container->get('doctrine.orm.default_query_cache')); $this->assertInstanceOf(DoctrineProvider::class, $container->get('doctrine.orm.default_result_cache')); $this->assertInstanceOf(EntityManager::class, $container->get('doctrine.orm.default_entity_manager')); $this->assertInstanceOf(Connection::class, $container->get('database_connection')); $this->assertInstanceOf(EntityManager::class, $container->get('doctrine.orm.entity_manager')); $this->assertInstanceOf(EventManager::class, $container->get('doctrine.orm.default_entity_manager.event_manager')); $this->assertInstanceOf(EventManager::class, $container->get('doctrine.dbal.event_manager')); $this->assertInstanceOf(ProxyCacheWarmer::class, $container->get('doctrine.orm.proxy_cache_warmer')); $this->assertInstanceOf(ManagerRegistry::class, $container->get('doctrine')); $this->assertInstanceOf(UniqueEntityValidator::class, $container->get('doctrine.orm.validator.unique')); $this->assertSame($container->get('my.platform'), $container->get('doctrine.dbal.default_connection')->getDatabasePlatform()); $this->assertTrue(Type::hasType('test')); $this->assertFalse($container->has('doctrine.dbal.default_connection.events.mysqlsessioninit')); $this->assertInstanceOf(DoctrineExtractor::class, $container->get('doctrine.orm.default_entity_manager.property_info_extractor')); $this->assertInstanceOf(DoctrineLoader::class, $container->get('doctrine.orm.default_entity_manager.validator_loader')); } } php-doctrine-bundle-2.0.7/Tests/DataCollector/000077500000000000000000000000001361552055200212115ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DataCollector/DoctrineDataCollectorTest.php000066400000000000000000000110101361552055200267630ustar00rootroot00000000000000getMockBuilder('Doctrine\ORM\EntityManager')->disableOriginalConstructor()->getMock(); $config = $this->getMockBuilder('Doctrine\ORM\Configuration')->getMock(); $factory = $this->getMockBuilder('Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory') ->setMethods(['getLoadedMetadata'])->getMockForAbstractClass(); $collector = $this->createCollector(['default' => $manager]); $manager->expects($this->any()) ->method('getMetadataFactory') ->will($this->returnValue($factory)); $manager->expects($this->any()) ->method('getConfiguration') ->will($this->returnValue($config)); $config->expects($this->once()) ->method('isSecondLevelCacheEnabled') ->will($this->returnValue(false)); $metadatas = [ $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']); } public function testGetGroupedQueries() : void { $logger = $this->getMockBuilder('Doctrine\DBAL\Logging\DebugStack')->getMock(); $logger->queries = []; $logger->queries[] = [ 'sql' => 'SELECT * FROM foo WHERE bar = :bar', 'params' => [':bar' => 1], 'types' => null, 'executionMS' => 32, ]; $logger->queries[] = [ 'sql' => 'SELECT * FROM foo WHERE bar = :bar', 'params' => [':bar' => 2], 'types' => null, 'executionMS' => 25, ]; $collector = $this->createCollector([]); $collector->addLogger('default', $logger); $collector->collect(new Request(), new Response()); $groupedQueries = $collector->getGroupedQueries(); $this->assertCount(1, $groupedQueries['default']); $this->assertSame('SELECT * FROM foo WHERE bar = :bar', $groupedQueries['default'][0]['sql']); $this->assertSame(2, $groupedQueries['default'][0]['count']); $logger->queries[] = [ 'sql' => 'SELECT * FROM bar', 'params' => [], 'types' => null, 'executionMS' => 25, ]; $collector->collect(new Request(), new Response()); $groupedQueries = $collector->getGroupedQueries(); $this->assertCount(2, $groupedQueries['default']); $this->assertSame('SELECT * FROM bar', $groupedQueries['default'][1]['sql']); $this->assertSame(1, $groupedQueries['default'][1]['count']); } private function createEntityMetadata(string $entityFQCN) : ClassMetadataInfo { $metadata = new ClassMetadataInfo($entityFQCN); $metadata->name = $entityFQCN; $metadata->reflClass = new ReflectionClass('stdClass'); return $metadata; } private function createCollector(array $managers) : DoctrineDataCollector { $registry = $this->getMockBuilder('Doctrine\Persistence\ManagerRegistry')->getMock(); $registry ->expects($this->any()) ->method('getConnectionNames') ->will($this->returnValue(['default' => 'doctrine.dbal.default_connection'])); $registry ->expects($this->any()) ->method('getManagerNames') ->will($this->returnValue(['default' => 'doctrine.orm.default_entity_manager'])); $registry ->expects($this->any()) ->method('getManagers') ->will($this->returnValue($managers)); return new DoctrineDataCollector($registry); } } php-doctrine-bundle-2.0.7/Tests/Dbal/000077500000000000000000000000001361552055200173335ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/Dbal/Logging/000077500000000000000000000000001361552055200207215ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/Dbal/Logging/BacktraceLoggerTest.php000066400000000000000000000012311361552055200253060ustar00rootroot00000000000000startQuery('SELECT column FROM table'); $currentQuery = current($logger->queries); self::assertSame('SELECT column FROM table', $currentQuery['sql']); self::assertNull($currentQuery['params']); self::assertNull($currentQuery['types']); self::assertGreaterThan(0, $currentQuery['backtrace']); } } php-doctrine-bundle-2.0.7/Tests/Dbal/RegexSchemaAssetFilterTest.php000066400000000000000000000006761361552055200252560ustar00rootroot00000000000000assertTrue($filter('do_not_t_ignore_me')); $this->assertFalse($filter('t_ignore_me')); } } php-doctrine-bundle-2.0.7/Tests/Dbal/SchemaAssetsFilterManagerTest.php000066400000000000000000000013261361552055200257320ustar00rootroot00000000000000assertSame( ['do_not_filter'], array_values(array_filter($tables, $manager)) ); } } php-doctrine-bundle-2.0.7/Tests/DependencyInjection/000077500000000000000000000000001361552055200224125ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/AbstractDoctrineExtensionTest.php000066400000000000000000001616541361552055200311300ustar00rootroot00000000000000loadContainer('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']); $this->assertSame(['asin' => ['callback' => 'asin', 'numArgs' => 1]], $config['driverOptions']['userDefinedFunctions']); $this->assertSame('foo', $config['driverOptions']['arbitraryValue']); // 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_schema', $config['dbname']); $this->assertSame('pgsql_user', $config['user']); $this->assertSame('pgsql_s3cr3t', $config['password']); $this->assertSame('pgsql_db', $config['default_dbname']); $this->assertSame('require', $config['sslmode']); $this->assertSame('postgresql-ca.pem', $config['sslrootcert']); $this->assertSame('postgresql-cert.pem', $config['sslcert']); $this->assertSame('postgresql-key.pem', $config['sslkey']); $this->assertSame('postgresql.crl', $config['sslcrl']); $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() : void { $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() : void { $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( [ 'user' => 'mysql_user', 'password' => 'mysql_s3cr3t', 'port' => null, 'dbname' => 'mysql_db', 'host' => 'localhost', 'unix_socket' => '/path/to/mysqld.sock', ], $param['master'] ); $this->assertEquals( [ 'user' => 'slave_user', 'password' => 'slave_s3cr3t', 'port' => null, 'dbname' => 'slave_db', 'host' => 'localhost', 'unix_socket' => '/path/to/mysqld_slave.sock', ], $param['slaves']['slave1'] ); $this->assertEquals(['engine' => 'InnoDB'], $param['defaultTableOptions']); } public function testDbalLoadPoolShardingConnection() : void { $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( [ 'user' => 'mysql_user', 'password' => 'mysql_s3cr3t', 'port' => null, 'dbname' => 'mysql_db', 'host' => 'localhost', 'unix_socket' => '/path/to/mysqld.sock', ], $param['global'] ); $this->assertEquals( [ '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] ); $this->assertEquals(['engine' => 'InnoDB'], $param['defaultTableOptions']); } public function testDbalLoadSavepointsForNestedTransactions() : void { $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() : void { $container = $this->loadContainer('orm_service_simple_single_entity_manager'); $definition = $container->getDefinition('doctrine.dbal.default_connection'); $this->assertDICConstructorArguments($definition, [ [ 'dbname' => 'db', 'host' => 'localhost', 'port' => null, 'user' => 'root', 'password' => null, 'driver' => 'pdo_mysql', 'driverOptions' => [], 'defaultTableOptions' => [], ], new Reference('doctrine.dbal.default_connection.configuration'), new Reference('doctrine.dbal.default_connection.event_manager'), [], ]); $definition = $container->getDefinition('doctrine.orm.default_entity_manager'); $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass()); $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory()); $this->assertDICConstructorArguments($definition, [ 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() : void { $container = $this->loadContainer('orm_service_simple_single_entity_manager_without_dbname'); /** @var Definition $definition */ $definition = $container->getDefinition('doctrine.dbal.default_connection'); $this->assertDICConstructorArguments($definition, [ [ 'host' => 'localhost', 'port' => null, 'user' => 'root', 'password' => null, 'driver' => 'pdo_mysql', 'driverOptions' => [], 'defaultTableOptions' => [], ], new Reference('doctrine.dbal.default_connection.configuration'), new Reference('doctrine.dbal.default_connection.event_manager'), [], ]); $definition = $container->getDefinition('doctrine.orm.default_entity_manager'); $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass()); $factory = $definition->getFactory(); $this->assertEquals('%doctrine.orm.entity_manager.class%', $factory[0]); $this->assertEquals('create', $factory[1]); $this->assertDICConstructorArguments($definition, [ new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'), ]); } public function testLoadSingleConnection() : void { $container = $this->loadContainer('orm_service_single_entity_manager'); $definition = $container->getDefinition('doctrine.dbal.default_connection'); $this->assertDICConstructorArguments($definition, [ [ 'host' => 'localhost', 'driver' => 'pdo_sqlite', 'driverOptions' => [], 'user' => 'sqlite_user', 'port' => null, 'password' => 'sqlite_s3cr3t', 'dbname' => 'sqlite_db', 'memory' => true, 'defaultTableOptions' => [], ], new Reference('doctrine.dbal.default_connection.configuration'), new Reference('doctrine.dbal.default_connection.event_manager'), [], ]); $definition = $container->getDefinition('doctrine.orm.default_entity_manager'); $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass()); $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory()); $this->assertDICConstructorArguments($definition, [ new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'), ]); $configDef = $container->getDefinition('doctrine.orm.default_configuration'); $this->assertDICDefinitionMethodCallOnce($configDef, 'setDefaultRepositoryClassName', ['Acme\Doctrine\Repository']); } public function testLoadMultipleConnections() : void { $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()); $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory()); $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()); $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory()); $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((string) $container->getAlias('doctrine.orm.em1_metadata_cache')); $this->assertEquals(DoctrineProvider::class, $definition->getClass()); $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em1_query_cache')); $this->assertEquals(DoctrineProvider::class, $definition->getClass()); $arguments = $definition->getArguments(); $this->assertInstanceOf(Reference::class, $arguments[0]); $this->assertEquals('cache.doctrine.orm.em1.query', (string) $arguments[0]); $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em1_result_cache')); $this->assertEquals(DoctrineProvider::class, $definition->getClass()); $arguments = $definition->getArguments(); $this->assertInstanceOf(Reference::class, $arguments[0]); $this->assertEquals('cache.doctrine.orm.em1.result', (string) $arguments[0]); } public function testLoadLogging() : void { $container = $this->loadContainer('dbal_logging'); $definition = $container->getDefinition('doctrine.dbal.log_connection.configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', [new Reference('doctrine.dbal.logger')]); $definition = $container->getDefinition('doctrine.dbal.profile_connection.configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', [new Reference('doctrine.dbal.logger.profiling.profile')]); $definition = $container->getDefinition('doctrine.dbal.profile_with_backtrace_connection.configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', [new Reference('doctrine.dbal.logger.backtrace.profile_with_backtrace')]); $definition = $container->getDefinition('doctrine.dbal.backtrace_without_profile_connection.configuration'); $this->assertDICDefinitionNoMethodCall($definition, 'setSQLLogger'); $definition = $container->getDefinition('doctrine.dbal.both_connection.configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', [new Reference('doctrine.dbal.logger.chain.both')]); } public function testEntityManagerMetadataCacheDriverConfiguration() : void { $container = $this->loadContainer('orm_service_multiple_entity_managers'); $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em1_metadata_cache')); $this->assertDICDefinitionClass($definition, DoctrineProvider::class); $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em2_metadata_cache')); $this->assertDICDefinitionClass($definition, DoctrineProvider::class); } public function testDependencyInjectionImportsOverrideDefaults() : void { $container = $this->loadContainer('orm_imports'); $cacheDefinition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_metadata_cache')); $this->assertEquals(DoctrineProvider::class, $cacheDefinition->getClass()); $configDefinition = $container->getDefinition('doctrine.orm.default_configuration'); $this->assertDICDefinitionMethodCallOnce($configDefinition, 'setAutoGenerateProxyClasses', ['%doctrine.orm.auto_generate_proxy_classes%']); } public function testSingleEntityManagerMultipleMappingBundleDefinitions() : void { $container = $this->loadContainer('orm_single_em_bundle_mappings', ['YamlBundle', 'AnnotationsBundle', 'XmlBundle']); $definition = $container->getDefinition('doctrine.orm.default_metadata_driver'); $this->assertDICDefinitionMethodCallAt(0, $definition, 'addDriver', [ new Reference('doctrine.orm.default_annotation_metadata_driver'), 'Fixtures\Bundles\AnnotationsBundle\Entity', ]); $this->assertDICDefinitionMethodCallAt(1, $definition, 'addDriver', [ new Reference('doctrine.orm.default_yml_metadata_driver'), 'Fixtures\Bundles\YamlBundle\Entity', ]); $this->assertDICDefinitionMethodCallAt(2, $definition, 'addDriver', [ new Reference('doctrine.orm.default_xml_metadata_driver'), 'Fixtures\Bundles\XmlBundle', ]); $annDef = $container->getDefinition('doctrine.orm.default_annotation_metadata_driver'); $this->assertDICConstructorArguments($annDef, [ new Reference('doctrine.orm.metadata.annotation_reader'), [__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, [ [__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, [ [__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() : void { $container = $this->loadContainer('orm_multiple_em_bundle_mappings', ['YamlBundle', 'AnnotationsBundle', 'XmlBundle']); $this->assertEquals(['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', [ new Reference('doctrine.orm.em1_annotation_metadata_driver'), 'Fixtures\Bundles\AnnotationsBundle\Entity', ]); $this->assertDICDefinitionMethodCallAt(0, $def2, 'addDriver', [ new Reference('doctrine.orm.em2_yml_metadata_driver'), 'Fixtures\Bundles\YamlBundle\Entity', ]); $this->assertDICDefinitionMethodCallAt(1, $def2, 'addDriver', [ new Reference('doctrine.orm.em2_xml_metadata_driver'), 'Fixtures\Bundles\XmlBundle', ]); $annDef = $container->getDefinition('doctrine.orm.em1_annotation_metadata_driver'); $this->assertDICConstructorArguments($annDef, [ new Reference('doctrine.orm.metadata.annotation_reader'), [__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, [ [__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, [ [__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() : void { $container = $this->loadContainer('orm_single_em_default_table_options', ['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() : void { $container = $this->loadContainer('dbal_types'); $this->assertEquals( ['test' => ['class' => TestType::class]], $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() : void { $container = $this->loadContainer('orm_functions'); $definition = $container->getDefinition('doctrine.orm.default_configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomStringFunction', ['test_string', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction']); $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomNumericFunction', ['test_numeric', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestNumericFunction']); $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomDatetimeFunction', ['test_datetime', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestDatetimeFunction']); } public function testSetNamingStrategy() : void { $container = $this->loadContainer('orm_namingstrategy'); $def1 = $container->getDefinition('doctrine.orm.em1_configuration'); $def2 = $container->getDefinition('doctrine.orm.em2_configuration'); $this->assertDICDefinitionMethodCallOnce($def1, 'setNamingStrategy', [0 => new Reference('doctrine.orm.naming_strategy.default')]); $this->assertDICDefinitionMethodCallOnce($def2, 'setNamingStrategy', [0 => new Reference('doctrine.orm.naming_strategy.underscore')]); } public function testSetQuoteStrategy() : void { $container = $this->loadContainer('orm_quotestrategy'); $def1 = $container->getDefinition('doctrine.orm.em1_configuration'); $def2 = $container->getDefinition('doctrine.orm.em2_configuration'); $this->assertDICDefinitionMethodCallOnce($def1, 'setQuoteStrategy', [0 => new Reference('doctrine.orm.quote_strategy.default')]); $this->assertDICDefinitionMethodCallOnce($def2, 'setQuoteStrategy', [0 => new Reference('doctrine.orm.quote_strategy.ansi')]); } public function testSecondLevelCache() : void { $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((string) $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, DoctrineProvider::class); $this->assertDICDefinitionMethodCallOnce($configDef, 'setSecondLevelCacheConfiguration'); $this->assertDICDefinitionMethodCallCount($slcFactoryDef, 'setRegion', [], 3); $this->assertDICDefinitionMethodCallCount($loggerChainDef, 'setLogger', [], 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() : void { $container = $this->loadContainer('orm_single_em_dql_functions'); $definition = $container->getDefinition('doctrine.orm.default_configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomStringFunction', ['test_string', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction']); } public function testAddCustomHydrationMode() : void { $container = $this->loadContainer('orm_hydration_mode'); $definition = $container->getDefinition('doctrine.orm.default_configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomHydrationMode', ['test_hydrator', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestHydrator']); } public function testAddFilter() : void { $container = $this->loadContainer('orm_filters'); $definition = $container->getDefinition('doctrine.orm.default_configuration'); $args = [ ['soft_delete', 'Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\TestFilter'], ['myFilter', 'Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\TestFilter'], ]; $this->assertDICDefinitionMethodCallCount($definition, 'addFilter', $args, 2); $definition = $container->getDefinition('doctrine.orm.default_manager_configurator'); $this->assertDICConstructorArguments($definition, [['soft_delete', 'myFilter'], ['myFilter' => ['myParameter' => 'myValue', 'mySecondParameter' => 'mySecondValue']]]); // Let's create the instance to check the configurator work. /** @var EntityManager $entityManager */ $entityManager = $container->get('doctrine.orm.entity_manager'); $this->assertCount(2, $entityManager->getFilters()->getEnabledFilters()); } public function testResolveTargetEntity() : void { $container = $this->loadContainer('orm_resolve_target_entity'); $definition = $container->getDefinition('doctrine.orm.listeners.resolve_target_entity'); $this->assertDICDefinitionMethodCallOnce($definition, 'addResolveTargetEntity', ['Symfony\Component\Security\Core\User\UserInterface', 'MyUserClass', []]); $this->assertEquals(['doctrine.event_subscriber' => [[]]], $definition->getTags()); } public function testAttachEntityListeners() : void { $container = $this->loadContainer('orm_attach_entity_listener'); $definition = $container->getDefinition('doctrine.orm.default_listeners.attach_entity_listeners'); $methodCalls = $definition->getMethodCalls(); $this->assertDICDefinitionMethodCallCount($definition, 'addEntityListener', [], 6); $this->assertEquals(['doctrine.event_listener' => [ ['event' => 'loadClassMetadata'] ] ], $definition->getTags()); $this->assertEquals($methodCalls[0], [ 'addEntityListener', [ 'ExternalBundles\Entities\FooEntity', 'MyBundles\Listeners\FooEntityListener', 'prePersist', null, ], ]); $this->assertEquals($methodCalls[1], [ 'addEntityListener', [ 'ExternalBundles\Entities\FooEntity', 'MyBundles\Listeners\FooEntityListener', 'postPersist', 'postPersist', ], ]); $this->assertEquals($methodCalls[2], [ 'addEntityListener', [ 'ExternalBundles\Entities\FooEntity', 'MyBundles\Listeners\FooEntityListener', 'postLoad', 'postLoadHandler', ], ]); $this->assertEquals($methodCalls[3], [ 'addEntityListener', [ 'ExternalBundles\Entities\BarEntity', 'MyBundles\Listeners\BarEntityListener', 'prePersist', 'prePersist', ], ]); $this->assertEquals($methodCalls[4], [ 'addEntityListener', [ 'ExternalBundles\Entities\BarEntity', 'MyBundles\Listeners\BarEntityListener', 'prePersist', 'prePersistHandler', ], ]); $this->assertEquals($methodCalls[5], [ 'addEntityListener', [ 'ExternalBundles\Entities\BarEntity', 'MyBundles\Listeners\LogDeleteEntityListener', 'postDelete', 'postDelete', ], ]); } public function testDbalAutoCommit() : void { $container = $this->loadContainer('dbal_auto_commit'); $definition = $container->getDefinition('doctrine.dbal.default_connection.configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'setAutoCommit', [false]); } public function testDbalOracleConnectstring() : void { $container = $this->loadContainer('dbal_oracle_connectstring'); $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0); $this->assertSame('scott@sales-server:1521/sales.us.example.com', $config['connectstring']); } public function testDbalOracleInstancename() : void { $container = $this->loadContainer('dbal_oracle_instancename'); $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0); $this->assertSame('mySuperInstance', $config['instancename']); } public function testDbalSchemaFilterNewConfig() : void { $container = $this->getContainer([]); $loader = new DoctrineExtension(); $container->registerExtension($loader); $container->addCompilerPass(new WellKnownSchemaFilterPass()); $container->addCompilerPass(new DbalSchemaFilterPass()); // ignore table1 table on "default" connection $container->register('dummy_filter1', DummySchemaAssetsFilter::class) ->setArguments(['table1']) ->addTag('doctrine.dbal.schema_filter'); // ignore table2 table on "connection2" connection $container->register('dummy_filter2', DummySchemaAssetsFilter::class) ->setArguments(['table2']) ->addTag('doctrine.dbal.schema_filter', ['connection' => 'connection2']); $this->loadFromFile($container, 'dbal_schema_filter'); $assetNames = ['table1', 'table2', 'table3', 't_ignored']; $expectedConnectionAssets = [ // ignores table1 + schema_filter applies 'connection1' => ['table2', 'table3'], // ignores table2, no schema_filter applies 'connection2' => ['table1', 'table3', 't_ignored'], // connection3 has no ignores, handled separately ]; $this->compileContainer($container); $getConfiguration = static function (string $connectionName) use ($container) : Configuration { return $container->get(sprintf('doctrine.dbal.%s_connection', $connectionName))->getConfiguration(); }; foreach ($expectedConnectionAssets as $connectionName => $expectedTables) { $connConfig = $getConfiguration($connectionName); $this->assertSame($expectedTables, array_values(array_filter($assetNames, $connConfig->getSchemaAssetsFilter())), sprintf('Filtering for connection "%s"', $connectionName)); } $this->assertNull($connConfig = $getConfiguration('connection3')->getSchemaAssetsFilter()); } public static function dataWellKnownSchemaFilterServices() { yield ['cache', 'cache_items']; yield ['lock', 'lock_keys']; yield ['messenger', 'messenger_messages']; yield ['session', 'sessions']; } /** * @dataProvider dataWellKnownSchemaFilterServices */ public function testWellKnownSchemaFilterDefaultTables(string $fileName, string $tableName) : void { $container = $this->getContainer([]); $loader = new DoctrineExtension(); $container->registerExtension($loader); $container->addCompilerPass(new WellKnownSchemaFilterPass()); $container->addCompilerPass(new DbalSchemaFilterPass()); $this->loadFromFile($container, 'well_known_schema_filter_default_tables_' . $fileName); $this->compileContainer($container); $definition = $container->getDefinition('doctrine.dbal.well_known_schema_asset_filter'); $this->assertSame([[$tableName]], $definition->getArguments()); $this->assertSame([['connection' => 'connection1'], ['connection' => 'connection2'], ['connection' => 'connection3']], $definition->getTag('doctrine.dbal.schema_filter')); $definition = $container->getDefinition('doctrine.dbal.connection1_schema_asset_filter_manager'); $this->assertEquals([new Reference('doctrine.dbal.well_known_schema_asset_filter'), new Reference('doctrine.dbal.connection1_regex_schema_filter')], $definition->getArgument(0)); $filter = $container->get('well_known_filter'); $this->assertFalse($filter($tableName)); $this->assertTrue($filter('anything_else')); } public static function dataWellKnownSchemaOverriddenTablesFilterServices() { yield ['cache', 'app_cache']; yield ['lock', 'app_locks']; yield ['messenger', 'app_messages']; yield ['session', 'app_session']; } /** * @dataProvider dataWellKnownSchemaOverriddenTablesFilterServices */ public function testWellKnownSchemaFilterOverriddenTables(string $fileName, string $tableName) : void { $container = $this->getContainer([]); $loader = new DoctrineExtension(); $container->registerExtension($loader); $container->addCompilerPass(new WellKnownSchemaFilterPass()); $container->addCompilerPass(new DbalSchemaFilterPass()); $this->loadFromFile($container, 'well_known_schema_filter_overridden_tables_' . $fileName); $this->compileContainer($container); $filter = $container->get('well_known_filter'); $this->assertFalse($filter($tableName)); } public function testEntityListenerResolver() : void { $container = $this->loadContainer('orm_entity_listener_resolver', ['YamlBundle'], new EntityListenerPass()); $definition = $container->getDefinition('doctrine.orm.em1_configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityListenerResolver', [new Reference('doctrine.orm.em1_entity_listener_resolver')]); $definition = $container->getDefinition('doctrine.orm.em2_configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityListenerResolver', [new Reference('doctrine.orm.em2_entity_listener_resolver')]); $listener = $container->getDefinition('doctrine.orm.em1_entity_listener_resolver'); $this->assertDICDefinitionMethodCallOnce($listener, 'registerService', ['EntityListener', 'entity_listener1']); $listener = $container->getDefinition('entity_listener_resolver'); $this->assertDICDefinitionMethodCallOnce($listener, 'register', [new Reference('entity_listener2')]); } public function testAttachEntityListenerTag() : void { $container = $this->getContainer([]); $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->assertDICDefinitionMethodCallCount($listener, 'registerService', [ ['EntityListener1', 'entity_listener1'], ['Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\Fixtures\InvokableEntityListener', 'invokable_entity_listener'], ['Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\Fixtures\InvokableEntityListener', 'invokable_entity_listener'], ['ParentEntityListener', 'children_entity_listener'], ], 4); $listener = $container->getDefinition('doctrine.orm.em2_entity_listener_resolver'); $this->assertDICDefinitionMethodCallOnce($listener, 'registerService', ['EntityListener2', 'entity_listener2']); $attachListener = $container->getDefinition('doctrine.orm.em1_listeners.attach_entity_listeners'); $this->assertDICDefinitionMethodCallAt(0, $attachListener, 'addEntityListener', ['My/Entity1', 'EntityListener1', 'postLoad']); $this->assertDICDefinitionMethodCallAt(1, $attachListener, 'addEntityListener', ['My/Entity1', 'Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\Fixtures\InvokableEntityListener', 'loadClassMetadata', '__invoke']); $this->assertDICDefinitionMethodCallAt(2, $attachListener, 'addEntityListener', ['My/Entity1', 'Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\Fixtures\InvokableEntityListener', 'postPersist']); $this->assertDICDefinitionMethodCallAt(3, $attachListener, 'addEntityListener', ['My/Entity3', 'ParentEntityListener', 'postLoad']); $attachListener = $container->getDefinition('doctrine.orm.em2_listeners.attach_entity_listeners'); $this->assertDICDefinitionMethodCallOnce($attachListener, 'addEntityListener', ['My/Entity2', 'EntityListener2', 'preFlush', 'preFlushHandler']); } public function testAttachEntityListenersTwoConnections() : void { $container = $this->getContainer(['YamlBundle']); $loader = new DoctrineExtension(); $container->registerExtension($loader); $container->addCompilerPass(new RegisterEventListenersAndSubscribersPass('doctrine.connections', 'doctrine.dbal.%s_connection.event_manager', 'doctrine')); $this->loadFromFile($container, 'orm_attach_entity_listeners_two_connections'); $this->compileContainer($container); $defaultEventManager = $container->getDefinition('doctrine.dbal.default_connection.event_manager'); $this->assertDICDefinitionNoMethodCall($defaultEventManager, 'addEventListener', [['loadClassMetadata'], new Reference('doctrine.orm.em2_listeners.attach_entity_listeners')]); $this->assertDICDefinitionMethodCallOnce($defaultEventManager, 'addEventListener', [['loadClassMetadata'], new Reference('doctrine.orm.em1_listeners.attach_entity_listeners')]); $foobarEventManager = $container->getDefinition('doctrine.dbal.foobar_connection.event_manager'); $this->assertDICDefinitionNoMethodCall($foobarEventManager, 'addEventListener', [['loadClassMetadata'], new Reference('doctrine.orm.em1_listeners.attach_entity_listeners')]); $this->assertDICDefinitionMethodCallOnce($foobarEventManager, 'addEventListener', [['loadClassMetadata'], new Reference('doctrine.orm.em2_listeners.attach_entity_listeners')]); } public function testAttachLazyEntityListener() : void { $container = $this->getContainer([]); $loader = new DoctrineExtension(); $container->registerExtension($loader); $container->addCompilerPass(new EntityListenerPass()); $this->loadFromFile($container, 'orm_attach_lazy_entity_listener'); $this->compileContainer($container); $resolver1 = $container->getDefinition('doctrine.orm.em1_entity_listener_resolver'); $this->assertDICDefinitionMethodCallAt(0, $resolver1, 'registerService', ['EntityListener1', 'entity_listener1']); $this->assertDICDefinitionMethodCallAt(1, $resolver1, 'register', [new Reference('entity_listener3')]); $this->assertDICDefinitionMethodCallAt(2, $resolver1, 'registerService', ['EntityListener4', 'entity_listener4']); $serviceLocatorReference = $resolver1->getArgument(0); $this->assertInstanceOf(Reference::class, $serviceLocatorReference); $serviceLocatorDefinition = $container->getDefinition((string) $serviceLocatorReference); $this->assertSame(ServiceLocator::class, $serviceLocatorDefinition->getClass()); $serviceLocatorMap = $serviceLocatorDefinition->getArgument(0); $this->assertSame(['entity_listener1', 'entity_listener4'], array_keys($serviceLocatorMap)); $resolver2 = $container->findDefinition('custom_entity_listener_resolver'); $this->assertDICDefinitionMethodCallOnce($resolver2, 'registerService', ['EntityListener2', 'entity_listener2']); } public function testAttachLazyEntityListenerForCustomResolver() : void { $container = $this->getContainer([]); $loader = new DoctrineExtension(); $container->registerExtension($loader); $container->addCompilerPass(new EntityListenerPass()); $this->loadFromFile($container, 'orm_entity_listener_custom_resolver'); $this->compileContainer($container); $resolver = $container->getDefinition('custom_entity_listener_resolver'); $this->assertTrue($resolver->isPublic()); $this->assertEmpty($resolver->getArguments(), 'We must not change the arguments for custom services.'); $this->assertDICDefinitionMethodCallOnce($resolver, 'registerService', ['EntityListener', 'entity_listener']); $this->assertTrue($container->getDefinition('entity_listener')->isPublic()); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage EntityListenerServiceResolver */ public function testLazyEntityListenerResolverWithoutCorrectInterface() : void { $container = $this->getContainer([]); $loader = new DoctrineExtension(); $container->registerExtension($loader); $container->addCompilerPass(new EntityListenerPass()); $this->loadFromFile($container, 'orm_entity_listener_lazy_resolver_without_interface'); $this->compileContainer($container); } public function testPrivateLazyEntityListener() : void { $container = $this->getContainer([]); $loader = new DoctrineExtension(); $container->registerExtension($loader); $container->addCompilerPass(new EntityListenerPass()); $this->loadFromFile($container, 'orm_entity_listener_lazy_private'); $this->compileContainer($container); $this->assertTrue($container->getDefinition('doctrine.orm.em1_entity_listener_resolver')->isPublic()); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessageRegExp /The service ".*" must not be abstract as this entity listener is lazy-loaded/ */ public function testAbstractLazyEntityListener() : void { $container = $this->getContainer([]); $loader = new DoctrineExtension(); $container->registerExtension($loader); $container->addCompilerPass(new EntityListenerPass()); $this->loadFromFile($container, 'orm_entity_listener_lazy_abstract'); $this->compileContainer($container); } public function testRepositoryFactory() : void { $container = $this->loadContainer('orm_repository_factory'); $definition = $container->getDefinition('doctrine.orm.default_configuration'); $this->assertDICDefinitionMethodCallOnce($definition, 'setRepositoryFactory', ['repository_factory']); } private function loadContainer( string $fixture, array $bundles = ['YamlBundle'], CompilerPassInterface $compilerPass = null ) : ContainerBuilder { $container = $this->getContainer($bundles); $container->registerExtension(new DoctrineExtension()); $this->loadFromFile($container, $fixture); if ($compilerPass !== null) { $container->addCompilerPass($compilerPass); } $this->compileContainer($container); return $container; } private function getContainer(array $bundles) : ContainerBuilder { $map = []; foreach ($bundles as $bundle) { require_once __DIR__ . '/Fixtures/Bundles/' . $bundle . '/' . $bundle . '.php'; $map[$bundle] = 'Fixtures\\Bundles\\' . $bundle . '\\' . $bundle; } $container = new ContainerBuilder(new ParameterBag([ 'kernel.name' => 'app', 'kernel.debug' => false, 'kernel.bundles' => $map, 'kernel.cache_dir' => sys_get_temp_dir(), 'kernel.environment' => 'test', 'kernel.root_dir' => __DIR__ . '/../../', // src dir 'kernel.project_dir' => __DIR__ . '/../../', // src dir 'kernel.bundles_metadata' => [], 'container.build_id' => uniqid(), ])); // Register dummy cache services so we don't have to load the FrameworkExtension $container->setDefinition('cache.system', (new Definition(ArrayAdapter::class))->setPublic(true)); $container->setDefinition('cache.app', (new Definition(ArrayAdapter::class))->setPublic(true)); return $container; } /** * Assertion on the Class of a DIC Service Definition. */ private function assertDICDefinitionClass(Definition $definition, string $expectedClass) : void { $this->assertEquals($expectedClass, $definition->getClass(), 'Expected Class of the DIC Container Service Definition is wrong.'); } private function assertDICConstructorArguments(Definition $definition, array $args) : void { $this->assertEquals($args, $definition->getArguments(), "Expected and actual DIC Service constructor arguments of definition '" . $definition->getClass() . "' don't match."); } private function assertDICDefinitionMethodCallAt( int $pos, Definition $definition, string $methodName, array $params = null ) : void { $calls = $definition->getMethodCalls(); if (! isset($calls[$pos][0])) { $this->fail(sprintf('Method call at position %s not found!', $pos)); return; } $this->assertEquals($methodName, $calls[$pos][0], "Method '" . $methodName . "' is expected to be called at position " . $pos . '.'); if ($params === null) { return; } $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. */ private function assertDICDefinitionMethodCallOnce( Definition $definition, string $methodName, array $params = null ) : void { $calls = $definition->getMethodCalls(); $called = false; foreach ($calls as $call) { if ($call[0] !== $methodName) { continue; } 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) { return; } $this->fail("Method '" . $methodName . "' is expected to be called once, definition does not contain a call though."); } private function assertDICDefinitionMethodCallCount( Definition $definition, string $methodName, array $params = [], int $nbCalls = 1 ) : void { $calls = $definition->getMethodCalls(); $called = 0; foreach ($calls as $call) { if ($call[0] !== $methodName) { continue; } 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)); } /** * Assertion for the DI Container, check if the given definition does not contain a method call with the given parameters. */ private function assertDICDefinitionNoMethodCall( Definition $definition, string $methodName, array $params = null ) : void { $calls = $definition->getMethodCalls(); foreach ($calls as $call) { if ($call[0] !== $methodName) { continue; } if ($params !== null) { $this->assertNotEquals($params, $call[1], "Method '" . $methodName . "' is not expected to be called with the given parameters."); } else { $this->fail("Method '" . $methodName . "' is not expected to be called"); } } } private function compileContainer(ContainerBuilder $container) : void { $container->getCompilerPassConfig()->setOptimizationPasses([new ResolveChildDefinitionsPass()]); $container->getCompilerPassConfig()->setRemovingPasses([]); $container->compile(); } } class DummySchemaAssetsFilter { /** @var string */ private $tableToIgnore; public function __construct(string $tableToIgnore) { $this->tableToIgnore = $tableToIgnore; } public function __invoke($assetName) : bool { if ($assetName instanceof AbstractAsset) { $assetName = $assetName->getName(); } return $assetName !== $this->tableToIgnore; } } php-doctrine-bundle-2.0.7/Tests/DependencyInjection/ConfigurationTest.php000066400000000000000000000016121361552055200265720ustar00rootroot00000000000000getConfigTreeBuilder(); $this->assertFalse(class_exists('Doctrine\Common\Proxy\AbstractProxyFactory', false)); } } php-doctrine-bundle-2.0.7/Tests/DependencyInjection/DoctrineExtensionTest.php000066400000000000000000001161501361552055200274330ustar00rootroot00000000000000getContainer(); $extension = new DoctrineExtension(); $config = BundleConfigurationBuilder::createBuilderWithBaseValues()->build(); $extension->load([$config], $container); $expectedAliases = [ DriverConnection::class => 'database_connection', Connection::class => 'database_connection', EntityManagerInterface::class => 'doctrine.orm.entity_manager', ]; foreach ($expectedAliases as $id => $target) { $this->assertTrue($container->hasAlias($id), sprintf('The container should have a `%s` alias for autowiring support.', $id)); $alias = $container->getAlias($id); $this->assertEquals($target, (string) $alias, sprintf('The autowiring for `%s` should use `%s`.', $id, $target)); $this->assertFalse($alias->isPublic(), sprintf('The autowiring alias for `%s` should be private.', $id, $target)); } } public function testPublicServicesAndAliases() : void { $container = $this->getContainer(); $extension = new DoctrineExtension(); $config = BundleConfigurationBuilder::createBuilderWithBaseValues()->build(); $extension->load([$config], $container); $this->assertTrue($container->getDefinition('doctrine')->isPublic()); $this->assertTrue($container->getAlias('doctrine.orm.entity_manager')->isPublic()); $this->assertTrue($container->getAlias('database_connection')->isPublic()); } public function testDbalGenerateDefaultConnectionConfiguration() : void { $container = $this->getContainer(); $extension = new DoctrineExtension(); $container->registerExtension($extension); $extension->load([['dbal' => []]], $container); // doctrine.dbal.default_connection $this->assertEquals('%doctrine.default_connection%', $container->getDefinition('doctrine')->getArgument(3)); $this->assertEquals('default', $container->getParameter('doctrine.default_connection')); $this->assertEquals('root', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['user']); $this->assertNull($container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['password']); $this->assertEquals('localhost', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['host']); $this->assertNull($container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['port']); $this->assertEquals('pdo_mysql', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['driver']); $this->assertEquals([], $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['driverOptions']); } public function testDbalOverrideDefaultConnection() : void { $container = $this->getContainer(); $extension = new DoctrineExtension(); $container->registerExtension($extension); $extension->load([[], ['dbal' => ['default_connection' => 'foo']], []], $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() : void { $extension = new DoctrineExtension(); $extension->load([['orm' => ['auto_mapping' => true]]], $this->getContainer()); } public function getAutomappingConfigurations() : array { return [ [ [ 'em1' => [ 'mappings' => ['YamlBundle' => null], ], 'em2' => [ 'mappings' => ['XmlBundle' => null], ], ], ], [ [ 'em1' => ['auto_mapping' => true], 'em2' => [ 'mappings' => ['XmlBundle' => null], ], ], ], [ [ 'em1' => [ 'auto_mapping' => true, 'mappings' => ['YamlBundle' => null], ], 'em2' => [ 'mappings' => ['XmlBundle' => null], ], ], ], ]; } /** * @dataProvider getAutomappingConfigurations */ public function testAutomapping(array $entityManagers) : void { $extension = new DoctrineExtension(); $container = $this->getContainer([ 'YamlBundle', 'XmlBundle', ]); $extension->load( [ [ 'dbal' => [ 'default_connection' => 'cn1', 'connections' => [ 'cn1' => [], 'cn2' => [], ], ], 'orm' => ['entity_managers' => $entityManagers], ], ], $container ); $configEm1 = $container->getDefinition('doctrine.orm.em1_configuration'); $configEm2 = $container->getDefinition('doctrine.orm.em2_configuration'); $this->assertContains( [ 'setEntityNamespaces', [ ['YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity'], ], ], $configEm1->getMethodCalls() ); $this->assertContains( [ 'setEntityNamespaces', [ ['XmlBundle' => 'Fixtures\Bundles\XmlBundle\Entity'], ], ], $configEm2->getMethodCalls() ); } public function testDbalLoad() : void { $container = $this->getContainer(); $extension = new DoctrineExtension(); $extension->load([ ['dbal' => ['connections' => ['default' => ['password' => 'foo']]]], [], ['dbal' => ['default_connection' => 'foo']], [], ], $container); $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0); $this->assertEquals('foo', $config['password']); $this->assertEquals('root', $config['user']); } public function testDbalWrapperClass() : void { $container = $this->getContainer(); $extension = new DoctrineExtension(); $extension->load( [ [ 'dbal' => [ 'connections' => [ 'default' => ['password' => 'foo', 'wrapper_class' => TestWrapperClass::class], 'second' => ['password' => 'boo'], ], ], ], [], ['dbal' => ['default_connection' => 'foo']], [], ], $container ); $this->assertEquals(TestWrapperClass::class, $container->getDefinition('doctrine.dbal.default_connection')->getClass()); $this->assertNull($container->getDefinition('doctrine.dbal.second_connection')->getClass()); } public function testDependencyInjectionConfigurationDefaults() : void { $container = $this->getContainer(); $extension = new DoctrineExtension(); $config = BundleConfigurationBuilder::createBuilderWithBaseValues()->build(); $extension->load([$config], $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 = BundleConfigurationBuilder::createBuilder() ->addBaseConnection() ->addEntityManager([ 'proxy_namespace' => 'MyProxies', 'auto_generate_proxy_classes' => true, 'default_entity_manager' => 'default', 'entity_managers' => [ 'default' => [ 'mappings' => ['YamlBundle' => []], ], ], ]) ->build(); $container = $this->getContainer(); $extension->load([$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()); $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory()); $this->assertEquals(['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(['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]); $this->assertEquals('doctrine.orm.naming_strategy.default', (string) $calls[10][1][0]); $this->assertEquals('doctrine.orm.quote_strategy.default', (string) $calls[11][1][0]); $this->assertEquals('doctrine.orm.default_entity_listener_resolver', (string) $calls[12][1][0]); $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_metadata_cache')); $this->assertEquals(DoctrineProvider::class, $definition->getClass()); $arguments = $definition->getArguments(); $this->assertInstanceOf(Reference::class, $arguments[0]); $this->assertEquals('cache.doctrine.orm.default.metadata', (string) $arguments[0]); $this->assertSame(ArrayAdapter::class, $container->getDefinition((string) $arguments[0])->getClass()); $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_query_cache')); $this->assertEquals(DoctrineProvider::class, $definition->getClass()); $arguments = $definition->getArguments(); $this->assertInstanceOf(Reference::class, $arguments[0]); $this->assertEquals('cache.doctrine.orm.default.query', (string) $arguments[0]); $this->assertSame(ArrayAdapter::class, $container->getDefinition((string) $arguments[0])->getClass()); $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_result_cache')); $this->assertEquals(DoctrineProvider::class, $definition->getClass()); $arguments = $definition->getArguments(); $this->assertInstanceOf(Reference::class, $arguments[0]); $this->assertEquals('cache.doctrine.orm.default.result', (string) $arguments[0]); $this->assertSame(ArrayAdapter::class, $container->getDefinition((string) $arguments[0])->getClass()); } public function testUseSavePointsAddMethodCallToAddSavepointsToTheConnection() : void { $container = $this->getContainer(); $extension = new DoctrineExtension(); $extension->load([[ 'dbal' => [ 'connections' => [ 'default' => ['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() : void { $container = $this->getContainer(); $extension = new DoctrineExtension(); $config = BundleConfigurationBuilder::createBuilder() ->addBaseConnection() ->addEntityManager([ 'proxy_namespace' => 'MyProxies', 'auto_generate_proxy_classes' => 'eval', 'default_entity_manager' => 'default', 'entity_managers' => [ 'default' => [ 'mappings' => ['YamlBundle' => []], ], ], ]) ->build(); $extension->load([$config], $container); $this->assertEquals(3 /* \Doctrine\Common\Proxy\AbstractProxyFactory::AUTOGENERATE_EVAL */, $container->getParameter('doctrine.orm.auto_generate_proxy_classes')); } public function testSingleEntityManagerWithDefaultConfiguration() : void { $container = $this->getContainer(); $extension = new DoctrineExtension(); $configurationArray = BundleConfigurationBuilder::createBuilderWithBaseValues()->build(); $extension->load([$configurationArray], $container); $this->compileContainer($container); $definition = $container->getDefinition('doctrine.orm.default_entity_manager'); $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass()); $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory()); $this->assertDICConstructorArguments($definition, [ new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'), ]); } public function testSingleEntityManagerWithDefaultSecondLevelCacheConfiguration() : void { $container = $this->getContainer(); $extension = new DoctrineExtension(); $configurationArray = BundleConfigurationBuilder::createBuilderWithBaseValues() ->addBaseSecondLevelCache() ->build(); $extension->load([$configurationArray], $container); $this->compileContainer($container); $definition = $container->getDefinition('doctrine.orm.default_entity_manager'); $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass()); $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory()); $this->assertDICConstructorArguments($definition, [ new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'), ]); $slcDefinition = $container->getDefinition('doctrine.orm.default_second_level_cache.default_cache_factory'); $this->assertEquals('%doctrine.orm.second_level_cache.default_cache_factory.class%', $slcDefinition->getClass()); } public function testSingleEntityManagerWithCustomSecondLevelCacheConfiguration() : void { $container = $this->getContainer(); $extension = new DoctrineExtension(); $configurationArray = BundleConfigurationBuilder::createBuilderWithBaseValues() ->addSecondLevelCache([ 'region_cache_driver' => ['type' => 'service', 'id' => 'my_cache'], 'regions' => [ 'hour_region' => ['lifetime' => 3600], ], 'factory' => 'YamlBundle\Cache\MyCacheFactory', ]) ->build(); $extension->load([$configurationArray], $container); $this->compileContainer($container); $definition = $container->getDefinition('doctrine.orm.default_entity_manager'); $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass()); $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory()); $this->assertDICConstructorArguments($definition, [ new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'), ]); $slcDefinition = $container->getDefinition('doctrine.orm.default_second_level_cache.default_cache_factory'); $this->assertEquals('YamlBundle\Cache\MyCacheFactory', $slcDefinition->getClass()); } public function testBundleEntityAliases() : void { $container = $this->getContainer(); $extension = new DoctrineExtension(); $config = BundleConfigurationBuilder::createBuilder() ->addBaseConnection() ->build(); $config['orm'] = ['default_entity_manager' => 'default', 'entity_managers' => ['default' => ['mappings' => ['YamlBundle' => []]]]]; $extension->load([$config], $container); $definition = $container->getDefinition('doctrine.orm.default_configuration'); $this->assertDICDefinitionMethodCallOnce( $definition, 'setEntityNamespaces', [['YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity']] ); } public function testOverwriteEntityAliases() : void { $container = $this->getContainer(); $extension = new DoctrineExtension(); $config = BundleConfigurationBuilder::createBuilder() ->addBaseConnection() ->build(); $config['orm'] = ['default_entity_manager' => 'default', 'entity_managers' => ['default' => ['mappings' => ['YamlBundle' => ['alias' => 'yml']]]]]; $extension->load([$config], $container); $definition = $container->getDefinition('doctrine.orm.default_configuration'); $this->assertDICDefinitionMethodCallOnce( $definition, 'setEntityNamespaces', [['yml' => 'Fixtures\Bundles\YamlBundle\Entity']] ); } public function testYamlBundleMappingDetection() : void { $container = $this->getContainer('YamlBundle'); $extension = new DoctrineExtension(); $config = BundleConfigurationBuilder::createBuilder() ->addBaseConnection() ->addBaseEntityManager() ->build(); $extension->load([$config], $container); $definition = $container->getDefinition('doctrine.orm.default_metadata_driver'); $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', [ new Reference('doctrine.orm.default_yml_metadata_driver'), 'Fixtures\Bundles\YamlBundle\Entity', ]); } public function testXmlBundleMappingDetection() : void { $container = $this->getContainer('XmlBundle'); $extension = new DoctrineExtension(); $config = BundleConfigurationBuilder::createBuilder() ->addBaseConnection() ->addEntityManager([ 'default_entity_manager' => 'default', 'entity_managers' => [ 'default' => [ 'mappings' => [ 'XmlBundle' => [], ], ], ], ]) ->build(); $extension->load([$config], $container); $definition = $container->getDefinition('doctrine.orm.default_metadata_driver'); $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', [ new Reference('doctrine.orm.default_xml_metadata_driver'), 'Fixtures\Bundles\XmlBundle\Entity', ]); } public function testAnnotationsBundleMappingDetection() : void { $container = $this->getContainer('AnnotationsBundle'); $extension = new DoctrineExtension(); $config = BundleConfigurationBuilder::createBuilder() ->addBaseConnection() ->addEntityManager([ 'default_entity_manager' => 'default', 'entity_managers' => [ 'default' => [ 'mappings' => [ 'AnnotationsBundle' => [], ], ], ], ]) ->build(); $extension->load([$config], $container); $definition = $container->getDefinition('doctrine.orm.default_metadata_driver'); $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', [ new Reference('doctrine.orm.default_annotation_metadata_driver'), 'Fixtures\Bundles\AnnotationsBundle\Entity', ]); } public function testOrmMergeConfigs() : void { $container = $this->getContainer(['XmlBundle', 'AnnotationsBundle']); $extension = new DoctrineExtension(); $config1 = BundleConfigurationBuilder::createBuilder() ->addBaseConnection() ->addEntityManager([ 'auto_generate_proxy_classes' => true, 'default_entity_manager' => 'default', 'entity_managers' => [ 'default' => [ 'mappings' => [ 'AnnotationsBundle' => [], ], ], ], ]) ->build(); $config2 = BundleConfigurationBuilder::createBuilder() ->addBaseConnection() ->addEntityManager([ 'auto_generate_proxy_classes' => false, 'default_entity_manager' => 'default', 'entity_managers' => [ 'default' => [ 'mappings' => [ 'XmlBundle' => [], ], ], ], ]) ->build(); $extension->load([$config1, $config2], $container); $definition = $container->getDefinition('doctrine.orm.default_metadata_driver'); $this->assertDICDefinitionMethodCallAt(0, $definition, 'addDriver', [ new Reference('doctrine.orm.default_annotation_metadata_driver'), 'Fixtures\Bundles\AnnotationsBundle\Entity', ]); $this->assertDICDefinitionMethodCallAt(1, $definition, 'addDriver', [ 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() : void { $container = $this->getContainer('AnnotationsBundle', 'Vendor'); $extension = new DoctrineExtension(); $config = BundleConfigurationBuilder::createBuilder() ->addBaseConnection() ->addEntityManager([ 'default_entity_manager' => 'default', 'entity_managers' => [ 'default' => [ 'mappings' => [ 'AnnotationsBundle' => [], ], ], ], ]) ->build(); $extension->load([$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 testMessengerIntegration() : void { if (! interface_exists(MessageBusInterface::class)) { $this->markTestSkipped('Symfony Messenger component is not installed'); } $container = $this->getContainer(); $extension = new DoctrineExtension(); $config = BundleConfigurationBuilder::createBuilder() ->addBaseConnection() ->build(); $extension->load([$config], $container); $this->assertNotNull($middlewarePrototype = $container->getDefinition('messenger.middleware.doctrine_transaction')); $this->assertCount(1, $middlewarePrototype->getArguments()); $this->assertNotNull($middlewarePrototype = $container->getDefinition('messenger.middleware.doctrine_ping_connection')); $this->assertCount(1, $middlewarePrototype->getArguments()); $this->assertNotNull($middlewarePrototype = $container->getDefinition('messenger.middleware.doctrine_close_connection')); $this->assertCount(1, $middlewarePrototype->getArguments()); if (class_exists(DoctrineClearEntityManagerWorkerSubscriber::class)) { $this->assertNotNull($subscriber = $container->getDefinition('doctrine.orm.messenger.event_subscriber.doctrine_clear_entity_manager')); $this->assertCount(1, $subscriber->getArguments()); } else { $this->assertFalse($container->hasDefinition('doctrine.orm.messenger.event_subscriber.doctrine_clear_entity_manager')); } } public function testInvalidCacheConfiguration() : void { $container = $this->getContainer(); $extension = new DoctrineExtension(); $config = BundleConfigurationBuilder::createBuilder() ->addBaseConnection() ->addEntityManager(['metadata_cache_driver' => 'redis']) ->build(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Unknown cache of type "redis" configured for cache "metadata_cache" in entity manager "default"'); $extension->load([$config], $container); } /** * @param array|string $cacheConfig * * @dataProvider cacheConfigurationProvider */ public function testCacheConfiguration(string $expectedAliasName, string $expectedAliasTarget, string $cacheName, $cacheConfig) : void { $container = $this->getContainer(); $extension = new DoctrineExtension(); $config = BundleConfigurationBuilder::createBuilder() ->addBaseConnection() ->addEntityManager([$cacheName => $cacheConfig]) ->build(); $extension->load([$config], $container); $this->assertTrue($container->hasAlias($expectedAliasName)); $alias = $container->getAlias($expectedAliasName); $this->assertEquals($expectedAliasTarget, (string) $alias); } public static function cacheConfigurationProvider() : array { return [ 'metadata_cache_default' => [ 'expectedAliasName' => 'doctrine.orm.default_metadata_cache', 'expectedAliasTarget' => 'doctrine.orm.cache.provider.cache.doctrine.orm.default.metadata', 'cacheName' => 'metadata_cache_driver', 'cacheConfig' => ['type' => null], ], 'query_cache_default' => [ 'expectedAliasName' => 'doctrine.orm.default_query_cache', 'expectedAliasTarget' => 'doctrine.orm.cache.provider.cache.doctrine.orm.default.query', 'cacheName' => 'query_cache_driver', 'cacheConfig' => ['type' => null], ], 'result_cache_default' => [ 'expectedAliasName' => 'doctrine.orm.default_result_cache', 'expectedAliasTarget' => 'doctrine.orm.cache.provider.cache.doctrine.orm.default.result', 'cacheName' => 'result_cache_driver', 'cacheConfig' => ['type' => null], ], 'metadata_cache_pool' => [ 'expectedAliasName' => 'doctrine.orm.default_metadata_cache', 'expectedAliasTarget' => 'doctrine.orm.cache.provider.metadata_cache_pool', 'cacheName' => 'metadata_cache_driver', 'cacheConfig' => ['type' => 'pool', 'pool' => 'metadata_cache_pool'], ], 'query_cache_pool' => [ 'expectedAliasName' => 'doctrine.orm.default_query_cache', 'expectedAliasTarget' => 'doctrine.orm.cache.provider.query_cache_pool', 'cacheName' => 'query_cache_driver', 'cacheConfig' => ['type' => 'pool', 'pool' => 'query_cache_pool'], ], 'result_cache_pool' => [ 'expectedAliasName' => 'doctrine.orm.default_result_cache', 'expectedAliasTarget' => 'doctrine.orm.cache.provider.result_cache_pool', 'cacheName' => 'result_cache_driver', 'cacheConfig' => ['type' => 'pool', 'pool' => 'result_cache_pool'], ], 'metadata_cache_service' => [ 'expectedAliasName' => 'doctrine.orm.default_metadata_cache', 'expectedAliasTarget' => 'service_target_metadata', 'cacheName' => 'metadata_cache_driver', 'cacheConfig' => ['type' => 'service', 'id' => 'service_target_metadata'], ], 'query_cache_service' => [ 'expectedAliasName' => 'doctrine.orm.default_query_cache', 'expectedAliasTarget' => 'service_target_query', 'cacheName' => 'query_cache_driver', 'cacheConfig' => ['type' => 'service', 'id' => 'service_target_query'], ], 'result_cache_service' => [ 'expectedAliasName' => 'doctrine.orm.default_result_cache', 'expectedAliasTarget' => 'service_target_result', 'cacheName' => 'result_cache_driver', 'cacheConfig' => ['type' => 'service', 'id' => 'service_target_result'], ], ]; } public function testShardManager() : void { $container = $this->getContainer(); $extension = new DoctrineExtension(); $config = BundleConfigurationBuilder::createBuilder() ->addConnection([ 'connections' => [ 'foo' => [ 'shards' => [ 'test' => ['id' => 1], ], ], 'bar' => [], ], ]) ->build(); $extension->load([$config], $container); $this->assertTrue($container->hasDefinition('doctrine.dbal.foo_shard_manager')); $this->assertFalse($container->hasDefinition('doctrine.dbal.bar_shard_manager')); } private function getContainer($bundles = 'YamlBundle', $vendor = null) : ContainerBuilder { $bundles = (array) $bundles; $map = []; foreach ($bundles as $bundle) { require_once __DIR__ . '/Fixtures/Bundles/' . ($vendor ? $vendor . '/' : '') . $bundle . '/' . $bundle . '.php'; $map[$bundle] = 'Fixtures\\Bundles\\' . ($vendor ? $vendor . '\\' : '') . $bundle . '\\' . $bundle; } $container = new ContainerBuilder(new ParameterBag([ 'kernel.name' => 'app', 'kernel.debug' => false, 'kernel.bundles' => $map, 'kernel.cache_dir' => sys_get_temp_dir(), 'kernel.environment' => 'test', 'kernel.root_dir' => __DIR__ . '/../../', // src dir ])); // Register dummy cache services so we don't have to load the FrameworkExtension $container->setDefinition('cache.system', (new Definition(ArrayAdapter::class))->setPublic(true)); $container->setDefinition('cache.app', (new Definition(ArrayAdapter::class))->setPublic(true)); $container->setDefinition('my_pool', (new Definition(ArrayAdapter::class))->setPublic(true)); return $container; } private function assertDICConstructorArguments(Definition $definition, array $args) : void { $this->assertEquals($args, $definition->getArguments(), "Expected and actual DIC Service constructor arguments of definition '" . $definition->getClass() . "' don't match."); } private function assertDICDefinitionMethodCallAt(int $pos, Definition $definition, string $methodName, array $params = null) : void { $calls = $definition->getMethodCalls(); if (! isset($calls[$pos][0])) { return; } $this->assertEquals($methodName, $calls[$pos][0], "Method '" . $methodName . "' is expected to be called at position " . $pos . '.'); if ($params === null) { return; } $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. */ private function assertDICDefinitionMethodCallOnce(Definition $definition, string $methodName, array $params = null) : void { $calls = $definition->getMethodCalls(); $called = false; foreach ($calls as $call) { if ($call[0] !== $methodName) { continue; } 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) { return; } $this->fail("Method '" . $methodName . "' is expected to be called once, definition does not contain a call though."); } private function compileContainer(ContainerBuilder $container) : void { $container->getCompilerPassConfig()->setOptimizationPasses([new ResolveChildDefinitionsPass()]); $container->getCompilerPassConfig()->setRemovingPasses([]); $container->compile(); } } class TestWrapperClass extends Connection { } php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/000077500000000000000000000000001361552055200242235ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/Bundles/000077500000000000000000000000001361552055200256175ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/Bundles/AnnotationsBundle/000077500000000000000000000000001361552055200312465ustar00rootroot00000000000000AnnotationsBundle.php000066400000000000000000000002221361552055200353230ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/Bundles/AnnotationsBundleresolver = $resolver; } /** * {@inheritdoc} */ public function clear($className = null) : void { $this->resolver->clear($className); } /** * {@inheritdoc} */ public function resolve($className) { return $this->resolver->resolve($className); } /** * {@inheritdoc} */ public function register($object) : void { $this->resolver->register($object); } /** * {@inheritdoc} */ public function registerService($className, $serviceId) : void { $this->resolver->registerService($className, $serviceId); } } php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/InvokableEntityListener.php000066400000000000000000000003451361552055200315530ustar00rootroot00000000000000load(static function (ContainerBuilder $container) { // @todo Setting the kernel.name parameter can be removed once the dependency on DoctrineCacheBundle has been dropped $container->setParameter('kernel.name', 'foo'); $container->loadFromExtension('framework', ['secret' => 'F00']); $container->loadFromExtension('doctrine', [ 'dbal' => ['driver' => 'pdo_sqlite'], 'orm' => [ 'mappings' => [ 'RepositoryServiceBundle' => [ 'type' => 'annotation', 'dir' => __DIR__ . '/Bundles/RepositoryServiceBundle/Entity', 'prefix' => 'Fixtures\Bundles\RepositoryServiceBundle\Entity', ], ], ], ]); // Register a NullLogger to avoid getting the stderr default logger of FrameworkBundle $container->register('logger', NullLogger::class); }); } public function getProjectDir() : string { if ($this->projectDir === null) { $this->projectDir = sys_get_temp_dir() . '/sf_kernel_' . md5(mt_rand()); } return $this->projectDir; } public function getRootDir() : string { return $this->getProjectDir(); } } php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/000077500000000000000000000000001361552055200254705ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml/000077500000000000000000000000001361552055200262705ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml/dbal_auto_commit.xml000066400000000000000000000010111361552055200323050ustar00rootroot00000000000000 php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml/dbal_logging.xml000066400000000000000000000025761361552055200314340ustar00rootroot00000000000000 dbal_oracle_connectstring.xml000066400000000000000000000011001361552055200341120ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml/dbal_oracle_instancename.xml000066400000000000000000000010421361552055200337630ustar00rootroot00000000000000 php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml/dbal_savepoints.xml000066400000000000000000000014741361552055200321750ustar00rootroot00000000000000 php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml/dbal_schema_filter.xml000066400000000000000000000013101361552055200325740ustar00rootroot00000000000000 dbal_service_multiple_connections.xml000066400000000000000000000053441361552055200357000ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml dbal_service_pool_sharding_connection.xml000066400000000000000000000017421361552055200365100ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml InnoDB dbal_service_single_connection.xml000066400000000000000000000011541361552055200351360ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml dbal_service_single_master_slave_connection.xml000066400000000000000000000015131361552055200377020ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml InnoDB php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml/dbal_types.xml000066400000000000000000000012611361552055200311400ustar00rootroot00000000000000 Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\TestType orm_attach_entity_listener.xml000066400000000000000000000032001361552055200343500ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml orm_attach_entity_listener_tag.xml000066400000000000000000000037141361552055200352150ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml orm_attach_entity_listeners_two_connections.xml000066400000000000000000000016631361552055200400410ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml orm_attach_lazy_entity_listener.xml000066400000000000000000000033421361552055200354160ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml orm_entity_listener_custom_resolver.xml000066400000000000000000000023071361552055200363460ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml orm_entity_listener_lazy_abstract.xml000066400000000000000000000017331361552055200357570ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml orm_entity_listener_lazy_private.xml000066400000000000000000000017321361552055200356250ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml orm_entity_listener_lazy_resolver_without_interface.xml000066400000000000000000000021321361552055200416120ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml orm_entity_listener_resolver.xml000066400000000000000000000024371361552055200347600ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml/orm_filters.xml000066400000000000000000000020361361552055200313400ustar00rootroot00000000000000 Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\TestFilter myValue mySecondValue php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml/orm_functions.xml000066400000000000000000000024051361552055200317000ustar00rootroot00000000000000 Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestNumericFunction Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestDatetimeFunction php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml/orm_hydration_mode.xml000066400000000000000000000016141361552055200326760ustar00rootroot00000000000000 Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestHydrator php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml/orm_imports.xml000066400000000000000000000011661361552055200313700ustar00rootroot00000000000000 php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml/orm_imports_import.xml000066400000000000000000000015221361552055200327560ustar00rootroot00000000000000 orm_multiple_em_bundle_mappings.xml000066400000000000000000000022661361552055200353610ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml/orm_namingstrategy.xml000066400000000000000000000017521361552055200327300ustar00rootroot00000000000000 php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml/orm_proxy.xml000066400000000000000000000010661361552055200310530ustar00rootroot00000000000000 php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml/orm_quotestrategy.xml000066400000000000000000000017401361552055200326110ustar00rootroot00000000000000 php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml/orm_repository_factory.xml000066400000000000000000000015141361552055200336360ustar00rootroot00000000000000 orm_resolve_target_entity.xml000066400000000000000000000014331361552055200342320ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml MyUserClass php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml/orm_second_level_cache.xml000066400000000000000000000046371361552055200334660ustar00rootroot00000000000000 3600 orm_service_multiple_entity_managers.xml000066400000000000000000000027321361552055200364400ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml Proxies orm_service_simple_single_entity_manager.xml000066400000000000000000000014151361552055200372510ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml orm_service_simple_single_entity_manager_without_dbname.xml000066400000000000000000000014001361552055200423340ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml orm_service_single_entity_manager.xml000066400000000000000000000023311361552055200356760ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml Proxies orm_single_em_bundle_mappings.xml000066400000000000000000000017651361552055200350120ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml orm_single_em_default_table_options.xml000066400000000000000000000024221361552055200362000ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml utf8mb4 utf8mb4_unicode_ci InnoDB orm_single_em_dql_functions.xml000066400000000000000000000014521361552055200345040ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction well_known_schema_filter_default_tables_cache.xml000066400000000000000000000017001361552055200401560ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml well_known_schema_filter_default_tables_lock.xml000066400000000000000000000016721361552055200400530ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml well_known_schema_filter_default_tables_messenger.xml000066400000000000000000000017231361552055200411100ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml well_known_schema_filter_default_tables_session.xml000066400000000000000000000017421361552055200406040ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml well_known_schema_filter_overridden_tables_cache.xml000066400000000000000000000022731361552055200407010ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml app_cache well_known_schema_filter_overridden_tables_lock.xml000066400000000000000000000021731361552055200405650ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml app_locks well_known_schema_filter_overridden_tables_messenger.xml000066400000000000000000000021741361552055200416260ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml app_messages well_known_schema_filter_overridden_tables_session.xml000066400000000000000000000022451361552055200413200ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/xml app_session php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/yml/000077500000000000000000000000001361552055200262715ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/yml/dbal_auto_commit.yml000066400000000000000000000000571361552055200323200ustar00rootroot00000000000000doctrine: dbal: auto_commit: false php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/yml/dbal_logging.yml000066400000000000000000000011551361552055200314260ustar00rootroot00000000000000doctrine: dbal: default_connection: mysql connections: log: logging: true profiling: false profile: logging: false profiling: true profile_with_backtrace: logging: false profiling: true profiling_collect_backtrace: true backtrace_without_profile: logging: false profiling: false profiling_collect_backtrace: true both: logging: true profiling: true dbal_oracle_connectstring.yml000066400000000000000000000001301361552055200341160ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: connectstring: scott@sales-server:1521/sales.us.example.com php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/yml/dbal_oracle_instancename.yml000066400000000000000000000000721361552055200337670ustar00rootroot00000000000000doctrine: dbal: instancename: mySuperInstance php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/yml/dbal_savepoints.yml000066400000000000000000000003741361552055200321750ustar00rootroot00000000000000doctrine: dbal: default_connection: savepoints connections: savepoints: use_savepoints: true nosavepoints: use_savepoints: false notset: user: root php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/yml/dbal_schema_filter.yml000066400000000000000000000003131361552055200326000ustar00rootroot00000000000000doctrine: dbal: default_connection: connection1 connections: connection1: schema_filter: ~^(?!t_)~ connection2: [] connection3: [] dbal_service_multiple_connections.yml000066400000000000000000000036571361552055200357070ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/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 options: userDefinedFunctions: asin: callback: 'asin' numArgs: 1 arbitraryValue: foo 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_schema user: pgsql_user password: pgsql_s3cr3t default_dbname: pgsql_db sslmode: require sslrootcert: postgresql-ca.pem sslcert: postgresql-cert.pem sslkey: postgresql-key.pem sslcrl: postgresql.crl 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.yml000066400000000000000000000010061361552055200365030ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/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 default_table_options: engine: InnoDB shards: - id: 1 user: shard_user dbname: shard_db password: shard_s3cr3t unix_socket: /path/to/mysqld_shard.sock services: foo.shard_choser: class: stdClass dbal_service_single_connection.yml000066400000000000000000000002561361552055200351420ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/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.yml000066400000000000000000000006471361552055200377130ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: dbname: mysql_db user: mysql_user password: mysql_s3cr3t unix_socket: /path/to/mysqld.sock keep_slave: true default_table_options: engine: InnoDB slaves: slave1: user: slave_user dbname: slave_db password: slave_s3cr3t unix_socket: /path/to/mysqld_slave.sock php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/yml/dbal_types.yml000066400000000000000000000003071361552055200311420ustar00rootroot00000000000000doctrine: dbal: default_connection: default types: test: Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\TestType connections: default: ~ orm_attach_entity_listener.yml000066400000000000000000000015261361552055200343630ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymldoctrine: 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.yml000066400000000000000000000024311361552055200352120ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/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 } invokable_entity_listener: class: Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\Fixtures\InvokableEntityListener tags: - { name: doctrine.orm.entity_listener, entity: My/Entity1, event: loadClassMetadata } - { name: doctrine.orm.entity_listener, entity: My/Entity1, event: postPersist } grand_parent_entity_listener: class: GrandParentEntityListener parent_entity_listener: parent: grand_parent_entity_listener class: ParentEntityListener children_entity_listener: parent: parent_entity_listener tags: - { name: doctrine.orm.entity_listener, entity: My/Entity3, event: postLoad } doctrine: dbal: default_connection: default connections: default: dbname: db orm: default_entity_manager: em1 entity_managers: em1: em2: orm_attach_entity_listeners_two_connections.yml000066400000000000000000000005401361552055200400340ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: default connections: default: dbname: db foobar: dbname: foobar orm: default_entity_manager: em1 entity_managers: em1: connection: default em2: connection: foobar orm_attach_lazy_entity_listener.yml000066400000000000000000000020101361552055200354070ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymlservices: custom_entity_listener_resolver: class: Doctrine\Bundle\DoctrineBundle\Mapping\ContainerEntityListenerResolver arguments: - '@service_container' entity_listener1: class: EntityListener1 tags: - { name: doctrine.orm.entity_listener, lazy: true } entity_listener2: class: EntityListener2 tags: - { name: doctrine.orm.entity_listener, entity_manager: em2, lazy: true } entity_listener3: class: EntityListener3 tags: - { name: doctrine.orm.entity_listener, lazy: false } entity_listener4: class: EntityListener4 tags: - { name: doctrine.orm.entity_listener } doctrine: dbal: default_connection: default connections: default: dbname: db orm: default_entity_manager: em1 entity_managers: em1: em2: entity_listener_resolver: custom_entity_listener_resolver orm_entity_listener_custom_resolver.yml000066400000000000000000000011471361552055200363510ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymlservices: custom_entity_listener_resolver: class: Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\Fixtures\CustomEntityListenerServiceResolver public: false entity_listener: class: EntityListener public: false tags: - { name: doctrine.orm.entity_listener } doctrine: dbal: default_connection: default connections: default: dbname: db orm: default_entity_manager: em1 entity_managers: em1: entity_listener_resolver: custom_entity_listener_resolver orm_entity_listener_lazy_abstract.yml000066400000000000000000000005711361552055200357600ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymlservices: entity_listener: abstract: true class: EntityListener tags: - { name: doctrine.orm.entity_listener, lazy: true } doctrine: dbal: default_connection: default connections: default: dbname: db orm: default_entity_manager: em1 entity_managers: em1: orm_entity_listener_lazy_private.yml000066400000000000000000000005701361552055200356260ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymlservices: entity_listener: public: false class: EntityListener tags: - { name: doctrine.orm.entity_listener, lazy: true } doctrine: dbal: default_connection: default connections: default: dbname: db orm: default_entity_manager: em1 entity_managers: em1: orm_entity_listener_lazy_resolver_without_interface.yml000066400000000000000000000007641361552055200416250ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymlservices: custom_resolver: class: Doctrine\ORM\Mapping\DefaultEntityListenerResolver entity_listener: class: EntityListener tags: - { name: doctrine.orm.entity_listener, lazy: true } doctrine: dbal: default_connection: default connections: default: dbname: db orm: default_entity_manager: em1 entity_managers: em1: entity_listener_resolver: custom_resolver orm_entity_listener_resolver.yml000066400000000000000000000012311361552055200347510ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymlservices: 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 php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/yml/orm_filters.yml000066400000000000000000000010631361552055200313410ustar00rootroot00000000000000doctrine: 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 php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/yml/orm_functions.yml000066400000000000000000000013211361552055200316760ustar00rootroot00000000000000doctrine: 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 php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/yml/orm_hydration_mode.yml000066400000000000000000000005641361552055200327030ustar00rootroot00000000000000doctrine: dbal: default_connection: default connections: default: dbname: db orm: entity_managers: default: hydrators: test_hydrator: Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestHydrator mappings: YamlBundle: ~ php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/yml/orm_imports.yml000066400000000000000000000001601361552055200313630ustar00rootroot00000000000000imports: - { resource: orm_imports_import.yml } doctrine: orm: auto_generate_proxy_classes: true php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/yml/orm_imports_import.yml000066400000000000000000000005041361552055200327570ustar00rootroot00000000000000doctrine: dbal: default_connection: default connections: default: dbname: db orm: auto_generate_proxy_classes: false default_entity_manager: default entity_managers: default: mappings: YamlBundle: ~ orm_multiple_em_bundle_mappings.yml000066400000000000000000000013371361552055200353610ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/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 php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/yml/orm_namingstrategy.yml000066400000000000000000000007551361552055200327340ustar00rootroot00000000000000doctrine: 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 php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/yml/orm_quotestrategy.yml000066400000000000000000000007431361552055200326150ustar00rootroot00000000000000doctrine: 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 php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/yml/orm_repository_factory.yml000066400000000000000000000004431361552055200336400ustar00rootroot00000000000000doctrine: dbal: default_connection: default connections: default: dbname: db orm: repository_factory: repository_factory services: repository_factory: class: Doctrine\Bundle\DoctrineBundle\Repository\RepositoryFactoryorm_resolve_target_entity.yml000066400000000000000000000003641361552055200342360ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: default connections: default: dbname: db orm: resolve_target_entities: Symfony\Component\Security\Core\User\UserInterface: MyUserClass php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/yml/orm_second_level_cache.yml000066400000000000000000000035371361552055200334660ustar00rootroot00000000000000services: 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: ~ 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: ~ type: filelock lock_path: "%kernel.cache_dir%/doctrine/orm/slc/filelock" my_entity_region: lifetime: 600 cache_driver: ~ orm_service_multiple_entity_managers.yml000066400000000000000000000015151361552055200364400ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/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: connection: conn1 mappings: YamlBundle: ~ em2: connection: conn2 mappings: YamlBundle: ~ orm_service_simple_single_entity_manager.yml000066400000000000000000000004311361552055200372500ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: default connections: default: dbname: db orm: default_entity_manager: default entity_managers: default: mappings: YamlBundle: ~ orm_service_simple_single_entity_manager_without_dbname.yml000066400000000000000000000003761361552055200423510ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: default connections: default: orm: default_entity_manager: default entity_managers: default: mappings: YamlBundle: ~ orm_service_single_entity_manager.yml000066400000000000000000000011301361552055200356740ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/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: ~ orm_single_em_bundle_mappings.yml000066400000000000000000000010261361552055200350020ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymldoctrine: 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.yml000066400000000000000000000012771361552055200362110ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/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 orm_single_em_dql_functions.yml000066400000000000000000000004321361552055200345030ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: default connections: default: dbname: db orm: dql: string_functions: test_string: Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction well_known_schema_filter_default_tables_cache.yml000066400000000000000000000006201361552055200401600ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: connection1 connections: connection1: schema_filter: ~^(?!t_)~ connection2: [] connection3: [] services: well_known_filter: alias: 'doctrine.dbal.well_known_schema_asset_filter' public: true symfony.cache: class: 'Symfony\Component\Cache\Adapter\PdoAdapter' well_known_schema_filter_default_tables_lock.yml000066400000000000000000000006121361552055200400460ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: connection1 connections: connection1: schema_filter: ~^(?!t_)~ connection2: [] connection3: [] services: well_known_filter: alias: 'doctrine.dbal.well_known_schema_asset_filter' public: true symfony.lock: class: 'Symfony\Component\Lock\Store\PdoStore' well_known_schema_filter_default_tables_messenger.yml000066400000000000000000000006431361552055200411120ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: connection1 connections: connection1: schema_filter: ~^(?!t_)~ connection2: [] connection3: [] services: well_known_filter: alias: 'doctrine.dbal.well_known_schema_asset_filter' public: true symfony.messenger: class: 'Symfony\Component\Messenger\Transport\Doctrine\Connection' well_known_schema_filter_default_tables_session.yml000066400000000000000000000006611361552055200406050ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: connection1 connections: connection1: schema_filter: ~^(?!t_)~ connection2: [] connection3: [] services: well_known_filter: alias: 'doctrine.dbal.well_known_schema_asset_filter' public: true symfony.session: class: 'Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler'well_known_schema_filter_overridden_tables_cache.yml000066400000000000000000000007641361552055200407060ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: connection1 connections: connection1: schema_filter: ~^(?!t_)~ connection2: [] connection3: [] services: well_known_filter: alias: 'doctrine.dbal.well_known_schema_asset_filter' public: true symfony.cache: class: 'Symfony\Component\Cache\Adapter\PdoAdapter' arguments: - ~ - ~ - ~ - db_table: app_cachewell_known_schema_filter_overridden_tables_lock.yml000066400000000000000000000007161361552055200405700ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: connection1 connections: connection1: schema_filter: ~^(?!t_)~ connection2: [] connection3: [] services: well_known_filter: alias: 'doctrine.dbal.well_known_schema_asset_filter' public: true symfony.lock: class: 'Symfony\Component\Lock\Store\PdoStore' arguments: - ~ - db_table: app_lockswell_known_schema_filter_overridden_tables_messenger.yml000066400000000000000000000007351361552055200416310ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: connection1 connections: connection1: schema_filter: ~^(?!t_)~ connection2: [] connection3: [] services: well_known_filter: alias: 'doctrine.dbal.well_known_schema_asset_filter' public: true symfony.messenger: class: 'Symfony\Component\Messenger\Transport\Doctrine\Connection' arguments: - table_name: app_messages well_known_schema_filter_overridden_tables_session.yml000066400000000000000000000007711361552055200413240ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/DependencyInjection/Fixtures/config/ymldoctrine: dbal: default_connection: connection1 connections: connection1: schema_filter: ~^(?!t_)~ connection2: [] connection3: [] services: well_known_filter: alias: 'doctrine.dbal.well_known_schema_asset_filter' public: true symfony.session: class: 'Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler' arguments: - ~ - db_table: app_session php-doctrine-bundle-2.0.7/Tests/DependencyInjection/TestDatetimeFunction.php000066400000000000000000000006341361552055200272300ustar00rootroot00000000000000isFile() || substr($element->getFilename(), -4) !== '.xml') { continue; } $schemaFiles[] = [$element->getPathname()]; } return $schemaFiles; } /** * @dataProvider dataValidateSchemaFiles */ public function testValidateSchema($file) : void { $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?'); } } php-doctrine-bundle-2.0.7/Tests/DependencyInjection/XmlDoctrineExtensionTest.php000066400000000000000000000010531361552055200301070ustar00rootroot00000000000000load($file . '.xml'); } } php-doctrine-bundle-2.0.7/Tests/DependencyInjection/YamlDoctrineExtensionTest.php000066400000000000000000000010601361552055200302470ustar00rootroot00000000000000load($file . '.yml'); } } php-doctrine-bundle-2.0.7/Tests/Mapping/000077500000000000000000000000001361552055200200645ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/Mapping/ContainerEntityListenerResolverTest.php000066400000000000000000000116371361552055200300140ustar00rootroot00000000000000container = $this->createMock(ContainerInterface::class); $this->resolver = new ContainerEntityListenerResolver($this->container); } public function testResolveClass() : void { $className = '\Doctrine\Bundle\DoctrineBundle\Tests\Mapping\EntityListener1'; $object = $this->resolver->resolve($className); $this->assertInstanceOf($className, $object); $this->assertSame($object, $this->resolver->resolve($className)); } public function testRegisterClassAndResolve() : void { $className = '\Doctrine\Bundle\DoctrineBundle\Tests\Mapping\EntityListener1'; $object = new $className(); $this->resolver->register($object); $this->assertSame($object, $this->resolver->resolve($className)); } public function testRegisterServiceAndResolve() : void { $className = '\Doctrine\Bundle\DoctrineBundle\Tests\Mapping\EntityListener1'; $serviceId = 'app.entity_listener'; $object = new $className(); $this->resolver->registerService($className, $serviceId); $this->container ->expects($this->any()) ->method('has') ->with($serviceId) ->will($this->returnValue(true)); $this->container ->expects($this->any()) ->method('get') ->with($serviceId) ->will($this->returnValue($object)); $this->assertInstanceOf($className, $this->resolver->resolve($className)); $this->assertSame($object, $this->resolver->resolve($className)); } /** * @expectedException \RuntimeException * @expectedExceptionMessage There is no service named */ public function testRegisterMissingServiceAndResolve() : void { $className = '\Doctrine\Bundle\DoctrineBundle\Tests\Mapping\EntityListener1'; $serviceId = 'app.entity_listener'; $this->resolver->registerService($className, $serviceId); $this->container ->expects($this->any()) ->method('has') ->with($serviceId) ->will($this->returnValue(false)); $this->resolver->resolve($className); } public function testClearOne() : void { $className1 = '\Doctrine\Bundle\DoctrineBundle\Tests\Mapping\EntityListener1'; $className2 = '\Doctrine\Bundle\DoctrineBundle\Tests\Mapping\EntityListener2'; $obj1 = $this->resolver->resolve($className1); $obj2 = $this->resolver->resolve($className2); $this->assertInstanceOf($className1, $obj1); $this->assertInstanceOf($className2, $obj2); $this->assertSame($obj1, $this->resolver->resolve($className1)); $this->assertSame($obj2, $this->resolver->resolve($className2)); $this->resolver->clear($className1); $this->assertInstanceOf($className1, $this->resolver->resolve($className1)); $this->assertInstanceOf($className2, $this->resolver->resolve($className2)); $this->assertNotSame($obj1, $this->resolver->resolve($className1)); $this->assertSame($obj2, $this->resolver->resolve($className2)); } public function testClearAll() : void { $className1 = '\Doctrine\Bundle\DoctrineBundle\Tests\Mapping\EntityListener1'; $className2 = '\Doctrine\Bundle\DoctrineBundle\Tests\Mapping\EntityListener2'; $obj1 = $this->resolver->resolve($className1); $obj2 = $this->resolver->resolve($className2); $this->assertInstanceOf($className1, $obj1); $this->assertInstanceOf($className2, $obj2); $this->assertSame($obj1, $this->resolver->resolve($className1)); $this->assertSame($obj2, $this->resolver->resolve($className2)); $this->resolver->clear(); $this->assertInstanceOf($className1, $this->resolver->resolve($className1)); $this->assertInstanceOf($className2, $this->resolver->resolve($className2)); $this->assertNotSame($obj1, $this->resolver->resolve($className1)); $this->assertNotSame($obj2, $this->resolver->resolve($className2)); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage An object was expected, but got "string". */ public function testRegisterStringException() : void { $this->resolver->register('CompanyContractListener'); } } class EntityListener1 { } class EntityListener2 { } php-doctrine-bundle-2.0.7/Tests/Mapping/DisconnectedMetadataFactoryTest.php000066400000000000000000000027451361552055200270400ustar00rootroot00000000000000getMockBuilder('Doctrine\Persistence\ManagerRegistry')->getMock(); $factory = new DisconnectedMetadataFactory($registry); $factory->findNamespaceAndPathForMetadata($collection); } public function testFindNamespaceAndPathForMetadata() : void { $class = new ClassMetadataInfo('\Vendor\Package\Class'); $collection = new ClassMetadataCollection([$class]); $registry = $this->getMockBuilder('Doctrine\Persistence\ManagerRegistry')->getMock(); $factory = new DisconnectedMetadataFactory($registry); $factory->findNamespaceAndPathForMetadata($collection, '/path/to/code'); $this->assertEquals('\Vendor\Package', $collection->getNamespace()); } } php-doctrine-bundle-2.0.7/Tests/ProfilerTest.php000066400000000000000000000072061361552055200216310ustar00rootroot00000000000000logger = new DebugStack(); $registry = $this->getMockBuilder(ManagerRegistry::class)->getMock(); $registry->expects($this->once())->method('getManagers')->willReturn([]); $this->collector = new DoctrineDataCollector($registry); $this->collector->addLogger('foo', $this->logger); $twigLoaderFilesystem = new FilesystemLoader(__DIR__ . '/../Resources/views/Collector'); $twigLoaderFilesystem->addPath(__DIR__ . '/../vendor/symfony/web-profiler-bundle/Resources/views', 'WebProfiler'); $this->twig = new Environment($twigLoaderFilesystem, ['debug' => true, 'strict_variables' => true]); $fragmentHandler = $this->getMockBuilder(FragmentHandler::class)->disableOriginalConstructor()->getMock(); $fragmentHandler->method('render')->willReturn(''); $kernelRuntime = new HttpKernelRuntime($fragmentHandler); $urlGenerator = $this->getMockBuilder(UrlGeneratorInterface::class)->getMock(); $urlGenerator->method('generate')->willReturn(''); $this->twig->addExtension(new CodeExtension('', '', '')); $this->twig->addExtension(new RoutingExtension($urlGenerator)); $this->twig->addExtension(new HttpKernelExtension($fragmentHandler)); $this->twig->addExtension(new WebProfilerExtension()); $this->twig->addExtension(new DoctrineExtension()); $loader = $this->getMockBuilder(RuntimeLoaderInterface::class)->getMock(); $loader->method('load')->willReturn($kernelRuntime); $this->twig->addRuntimeLoader($loader); } public function testRender() : void { $this->logger->queries = [ [ 'sql' => 'SELECT * FROM foo WHERE bar IN (?, ?)', 'params' => ['foo', 'bar'], 'types' => null, 'executionMS' => 1, ], ]; $this->collector->collect($request = new Request(['group' => '0']), $response = new Response()); $profile = new Profile('foo'); $output = $this->twig->render('db.html.twig', [ 'request' => $request, 'token' => 'foo', 'page' => 'foo', 'profile' => $profile, 'collector' => $this->collector, 'queries' => $this->logger->queries, ]); $output = str_replace(["\e[37m", "\e[0m", "\e[32;1m", "\e[34;1m"], '', $output); $this->assertContains("SELECT * FROM foo WHERE bar IN ('foo', 'bar');", $output); } } php-doctrine-bundle-2.0.7/Tests/RegistryTest.php000066400000000000000000000204051361552055200216530ustar00rootroot00000000000000getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); $registry = new Registry($container, [], [], 'default', 'default'); $this->assertEquals('default', $registry->getDefaultConnectionName()); } public function testGetDefaultEntityManagerName() : void { $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); $registry = new Registry($container, [], [], 'default', 'default'); $this->assertEquals('default', $registry->getDefaultManagerName()); } public function testGetDefaultConnection() : void { $conn = $this->getMockBuilder('Doctrine\DBAL\Connection')->disableOriginalConstructor()->getMock(); $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); $container->expects($this->once()) ->method('get') ->with($this->equalTo('doctrine.dbal.default_connection')) ->will($this->returnValue($conn)); $registry = new Registry($container, ['default' => 'doctrine.dbal.default_connection'], [], 'default', 'default'); $this->assertSame($conn, $registry->getConnection()); } public function testGetConnection() : void { $conn = $this->getMockBuilder('Doctrine\DBAL\Connection')->disableOriginalConstructor()->getMock(); $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); $container->expects($this->once()) ->method('get') ->with($this->equalTo('doctrine.dbal.default_connection')) ->will($this->returnValue($conn)); $registry = new Registry($container, ['default' => 'doctrine.dbal.default_connection'], [], 'default', 'default'); $this->assertSame($conn, $registry->getConnection('default')); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Doctrine ORM Connection named "default" does not exist. */ public function testGetUnknownConnection() : void { $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); $registry = new Registry($container, [], [], 'default', 'default'); $registry->getConnection('default'); } public function testGetConnectionNames() : void { $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); $registry = new Registry($container, ['default' => 'doctrine.dbal.default_connection'], [], 'default', 'default'); $this->assertEquals(['default' => 'doctrine.dbal.default_connection'], $registry->getConnectionNames()); } public function testGetDefaultEntityManager() : void { $em = new stdClass(); $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); $container->expects($this->once()) ->method('get') ->with($this->equalTo('doctrine.orm.default_entity_manager')) ->will($this->returnValue($em)); $registry = new Registry($container, [], ['default' => 'doctrine.orm.default_entity_manager'], 'default', 'default'); $this->assertSame($em, $registry->getManager()); } public function testGetEntityManager() : void { $em = new stdClass(); $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); $container->expects($this->once()) ->method('get') ->with($this->equalTo('doctrine.orm.default_entity_manager')) ->will($this->returnValue($em)); $registry = new Registry($container, [], ['default' => 'doctrine.orm.default_entity_manager'], 'default', 'default'); $this->assertSame($em, $registry->getManager('default')); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Doctrine ORM Manager named "default" does not exist. */ public function testGetUnknownEntityManager() : void { $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); $registry = new Registry($container, [], [], 'default', 'default'); $registry->getManager('default'); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Doctrine ORM Manager named "default" does not exist. */ public function testResetUnknownEntityManager() : void { $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); $registry = new Registry($container, [], [], 'default', 'default'); $registry->resetManager('default'); } public function testReset() : void { $noProxyManager = $this->getMockBuilder(EntityManagerInterface::class)->getMock(); $noProxyManager->expects($this->once()) ->method('clear'); $proxyManager = $this->getMockBuilder([LazyLoadingInterface::class, EntityManagerInterface::class])->getMock(); $proxyManager->expects($this->once()) ->method('setProxyInitializer') ->with($this->isInstanceOf(Closure::class)); $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); $container->expects($this->any()) ->method('initialized') ->withConsecutive(['doctrine.orm.uninitialized_entity_manager'], ['doctrine.orm.noproxy_entity_manager'], ['doctrine.orm.proxy_entity_manager']) ->willReturnOnConsecutiveCalls(false, true, true, true); $container->expects($this->any()) ->method('get') ->withConsecutive(['doctrine.orm.noproxy_entity_manager'], ['doctrine.orm.proxy_entity_manager'], ['doctrine.orm.proxy_entity_manager']) ->willReturnOnConsecutiveCalls($noProxyManager, $proxyManager, $proxyManager); $entityManagers = [ 'uninitialized' => 'doctrine.orm.uninitialized_entity_manager', 'noproxy' => 'doctrine.orm.noproxy_entity_manager', 'proxy' => 'doctrine.orm.proxy_entity_manager', ]; $registry = new Registry($container, [], $entityManagers, 'default', 'default'); $registry->reset(); } public function testIdentityMapsStayConsistentAfterReset() { $kernel = new TestKernel(); $kernel->boot(); $container = $kernel->getContainer(); $registry = $container->get('doctrine'); $entityManager = $container->get('doctrine.orm.default_entity_manager'); $repository = $entityManager->getRepository(TestCustomClassRepoEntity::class); $this->assertInstanceOf(ProxyInterface::class, $entityManager); assert($entityManager instanceof EntityManagerInterface); assert($registry instanceof Registry); assert($repository instanceof TestCustomClassRepoRepository); $entity = new TestCustomClassRepoEntity(); $repository->getEntityManager()->persist($entity); $this->assertTrue($entityManager->getUnitOfWork()->isEntityScheduled($entity)); $this->assertTrue($repository->getEntityManager()->getUnitOfWork()->isEntityScheduled($entity)); $registry->reset(); $this->assertFalse($entityManager->getUnitOfWork()->isEntityScheduled($entity)); $this->assertFalse($repository->getEntityManager()->getUnitOfWork()->isEntityScheduled($entity)); $entityManager->flush(); } } php-doctrine-bundle-2.0.7/Tests/Repository/000077500000000000000000000000001361552055200206505ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/Repository/ContainerRepositoryFactoryTest.php000066400000000000000000000160601361552055200275760ustar00rootroot00000000000000createEntityManager(['Foo\CoolEntity' => 'my_repo']); $repo = new StubRepository(); $container = $this->createContainer(['my_repo' => $repo]); $factory = new ContainerRepositoryFactory($container); $this->assertSame($repo, $factory->getRepository($em, 'Foo\CoolEntity')); } public function testGetRepositoryReturnsEntityRepository() : void { $container = $this->createContainer([]); $em = $this->createEntityManager(['Foo\BoringEntity' => null]); $factory = new ContainerRepositoryFactory($container); $actualRepo = $factory->getRepository($em, 'Foo\BoringEntity'); $this->assertInstanceOf(EntityRepository::class, $actualRepo); // test the same instance is returned $this->assertSame($actualRepo, $factory->getRepository($em, 'Foo\BoringEntity')); } public function testCustomRepositoryIsReturned() : void { $container = $this->createContainer([]); $em = $this->createEntityManager([ 'Foo\CustomNormalRepoEntity' => StubRepository::class, ]); $factory = new ContainerRepositoryFactory($container); $actualRepo = $factory->getRepository($em, 'Foo\CustomNormalRepoEntity'); $this->assertInstanceOf(StubRepository::class, $actualRepo); // test the same instance is returned $this->assertSame($actualRepo, $factory->getRepository($em, 'Foo\CustomNormalRepoEntity')); } /** * @expectedException \RuntimeException * @expectedExceptionMessage The service "my_repo" must implement ObjectRepository (or extend a base class, like ServiceEntityRepository). */ public function testServiceRepositoriesMustExtendObjectRepository() : void { $repo = new stdClass(); $container = $this->createContainer(['my_repo' => $repo]); $em = $this->createEntityManager(['Foo\CoolEntity' => 'my_repo']); $factory = new ContainerRepositoryFactory($container); $factory->getRepository($em, 'Foo\CoolEntity'); } public function testServiceRepositoriesCanNotExtendsEntityRepository() : void { $repo = $this->getMockBuilder(ObjectRepository::class)->getMock(); $container = $this->createContainer(['my_repo' => $repo]); $em = $this->createEntityManager(['Foo\CoolEntity' => 'my_repo']); $factory = new ContainerRepositoryFactory($container); $factory->getRepository($em, 'Foo\CoolEntity'); $actualRepo = $factory->getRepository($em, 'Foo\CoolEntity'); $this->assertSame($repo, $actualRepo); } /** * @expectedException \RuntimeException * @expectedExceptionMessage The "Doctrine\Bundle\DoctrineBundle\Tests\Repository\StubServiceRepository" entity repository implements "Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepositoryInterface", but its service could not be found. Make sure the service exists and is tagged with "doctrine.repository_service". */ public function testRepositoryMatchesServiceInterfaceButServiceNotFound() : void { $container = $this->createContainer([]); $em = $this->createEntityManager([ 'Foo\CoolEntity' => StubServiceRepository::class, ]); $factory = new ContainerRepositoryFactory($container); $factory->getRepository($em, 'Foo\CoolEntity'); } /** * @expectedException \RuntimeException * @expectedExceptionMessage The "Foo\CoolEntity" entity has a repositoryClass set to "not_a_real_class", but this is not a valid class. Check your class naming. If this is meant to be a service id, make sure this service exists and is tagged with "doctrine.repository_service". */ public function testCustomRepositoryIsNotAValidClass() : void { $container = $this->createContainer([]); $em = $this->createEntityManager(['Foo\CoolEntity' => 'not_a_real_class']); $factory = new ContainerRepositoryFactory($container); $factory->getRepository($em, 'Foo\CoolEntity'); } private function createContainer(array $services) : MockObject { $container = $this->getMockBuilder(ContainerInterface::class)->getMock(); $container->expects($this->any()) ->method('has') ->willReturnCallback(static function ($id) use ($services) { return isset($services[$id]); }); $container->expects($this->any()) ->method('get') ->willReturnCallback(static function ($id) use ($services) { return $services[$id]; }); return $container; } private function createEntityManager(array $entityRepositoryClasses) : MockObject { $classMetadatas = []; foreach ($entityRepositoryClasses as $entityClass => $entityRepositoryClass) { $metadata = new ClassMetadata($entityClass); $metadata->customRepositoryClassName = $entityRepositoryClass; $classMetadatas[$entityClass] = $metadata; } $em = $this->getMockBuilder(EntityManagerInterface::class)->getMock(); $em->expects($this->any()) ->method('getClassMetadata') ->willReturnCallback(static function ($class) use ($classMetadatas) { return $classMetadatas[$class]; }); $em->expects($this->any()) ->method('getConfiguration') ->willReturn(new Configuration()); return $em; } } /** * Repository implementing non-deprecated interface, as current interface implemented in ORM\EntityRepository * uses deprecated one and Composer autoload triggers deprecations that can't be silenced by @group legacy */ class NonDeprecatedRepository implements ObjectRepository { /** * {@inheritDoc} */ public function find($id) { return null; } public function findAll() : array { return []; } public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null) : array { return []; } /** * {@inheritDoc} */ public function findOneBy(array $criteria) { return null; } public function getClassName() : string { return ''; } } class StubRepository extends NonDeprecatedRepository { } class StubServiceRepository extends NonDeprecatedRepository implements ServiceEntityRepositoryInterface { } php-doctrine-bundle-2.0.7/Tests/Repository/ServiceEntityRepositoryTest.php000066400000000000000000000014361361552055200271220ustar00rootroot00000000000000getMockBuilder(ManagerRegistry::class)->getMock(); new ServiceEntityRepository($registry, TestEntity::class); } } php-doctrine-bundle-2.0.7/Tests/ServiceRepositoryTest.php000066400000000000000000000117351361552055200235510ustar00rootroot00000000000000 'app', 'kernel.debug' => false, 'kernel.bundles' => ['RepositoryServiceBundle' => RepositoryServiceBundle::class], 'kernel.cache_dir' => sys_get_temp_dir(), 'kernel.environment' => 'test', 'kernel.root_dir' => __DIR__ . '/../../../../', // src dir 'kernel.project_dir' => __DIR__ . '/../../../../', // src dir 'kernel.bundles_metadata' => [], 'kernel.charset' => 'UTF-8', 'kernel.container_class' => ContainerBuilder::class, 'kernel.secret' => 'test', 'container.build_id' => uniqid(), 'env(base64:default::SYMFONY_DECRYPTION_SECRET)' => 'foo', ])); $container->set('annotation_reader', new AnnotationReader()); $extension = new FrameworkExtension(); $container->registerExtension($extension); $extension->load(['framework' => []], $container); $extension = new DoctrineExtension(); $container->registerExtension($extension); $extension->load([[ 'dbal' => [ 'driver' => 'pdo_sqlite', 'charset' => 'UTF8', ], 'orm' => [ 'mappings' => [ 'RepositoryServiceBundle' => [ 'type' => 'annotation', 'dir' => __DIR__ . '/DependencyInjection/Fixtures/Bundles/RepositoryServiceBundle/Entity', 'prefix' => 'Fixtures\Bundles\RepositoryServiceBundle\Entity', ], ], ], ], ], $container); $def = $container->register(TestCustomServiceRepoRepository::class, TestCustomServiceRepoRepository::class) ->setPublic(false); // create a public alias so we can use it below for testing $container->setAlias('test_alias__' . TestCustomServiceRepoRepository::class, new Alias(TestCustomServiceRepoRepository::class, true)); $def->setAutowired(true); $def->setAutoconfigured(true); $container->addCompilerPass(new ServiceRepositoryCompilerPass()); $container->compile(); $em = $container->get('doctrine.orm.default_entity_manager'); // traditional custom class repository $customClassRepo = $em->getRepository(TestCustomClassRepoEntity::class); $this->assertInstanceOf(TestCustomClassRepoRepository::class, $customClassRepo); // a smoke test, trying some methods $this->assertSame(TestCustomClassRepoEntity::class, $customClassRepo->getClassName()); $this->assertInstanceOf(QueryBuilder::class, $customClassRepo->createQueryBuilder('tc')); // generic EntityRepository $genericRepository = $em->getRepository(TestDefaultRepoEntity::class); $this->assertInstanceOf(EntityRepository::class, $genericRepository); $this->assertSame($genericRepository, $genericRepository = $em->getRepository(TestDefaultRepoEntity::class)); // a smoke test, trying one of the methods $this->assertSame(TestDefaultRepoEntity::class, $genericRepository->getClassName()); // custom service repository $customServiceRepo = $em->getRepository(TestCustomServiceRepoEntity::class); $this->assertSame($customServiceRepo, $container->get('test_alias__' . TestCustomServiceRepoRepository::class)); // a smoke test, trying some methods $this->assertSame(TestCustomServiceRepoEntity::class, $customServiceRepo->getClassName()); $this->assertInstanceOf(QueryBuilder::class, $customServiceRepo->createQueryBuilder('tc')); } } php-doctrine-bundle-2.0.7/Tests/TestCase.php000066400000000000000000000102131361552055200207120ustar00rootroot00000000000000 'app', 'kernel.debug' => false, 'kernel.bundles' => ['XmlBundle' => 'Fixtures\Bundles\XmlBundle\XmlBundle'], 'kernel.cache_dir' => sys_get_temp_dir(), 'kernel.environment' => 'test', 'kernel.root_dir' => __DIR__ . '/../../../../', // src dir 'kernel.project_dir' => __DIR__ . '/../../../../', // src dir 'kernel.bundles_metadata' => [], 'container.build_id' => uniqid(), ])); $container->set('annotation_reader', new AnnotationReader()); $extension = new DoctrineExtension(); $container->registerExtension($extension); $extension->load([[ 'dbal' => [ 'connections' => [ 'default' => [ 'driver' => 'pdo_mysql', 'charset' => 'UTF8', 'platform-service' => 'my.platform', ], ], 'default_connection' => 'default', 'types' => [ 'test' => [ 'class' => TestType::class, ], ], ], 'orm' => [ 'default_entity_manager' => 'default', 'entity_managers' => [ 'default' => [ 'mappings' => [ 'XmlBundle' => [ 'type' => 'xml', 'dir' => __DIR__ . '/DependencyInjection/Fixtures/Bundles/XmlBundle/Resources/config/doctrine', 'prefix' => 'Fixtures\Bundles\XmlBundle\Entity', ], ], ], ], 'resolve_target_entities' => ['Symfony\Component\Security\Core\User\UserInterface' => 'stdClass'], ], ], ], $container); $container->setDefinition('my.platform', new Definition('Doctrine\DBAL\Platforms\MySqlPlatform'))->setPublic(true); // Register dummy cache services so we don't have to load the FrameworkExtension $container->setDefinition('cache.system', (new Definition(ArrayAdapter::class))->setPublic(true)); $container->setDefinition('cache.app', (new Definition(ArrayAdapter::class))->setPublic(true)); $container->getCompilerPassConfig()->setOptimizationPasses([new ResolveChildDefinitionsPass()]); $container->getCompilerPassConfig()->setRemovingPasses([]); // make all Doctrine services public, so we can fetch them in the test $container->getCompilerPassConfig()->addPass(new TestCaseAllPublicCompilerPass()); $container->compile(); return $container; } } class TestCaseAllPublicCompilerPass implements CompilerPassInterface { public function process(ContainerBuilder $container) : void { foreach ($container->getDefinitions() as $id => $definition) { if (strpos($id, 'doctrine') === false) { continue; } $definition->setPublic(true); } foreach ($container->getAliases() as $id => $alias) { if (strpos($id, 'doctrine') === false) { continue; } $alias->setPublic(true); } } } php-doctrine-bundle-2.0.7/Tests/Twig/000077500000000000000000000000001361552055200174035ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Tests/Twig/DoctrineExtensionTest.php000066400000000000000000000056501361552055200244260ustar00rootroot00000000000000replaceQueryParameters($query, $parameters); $this->assertEquals('a=1 OR (1)::string OR b=2', $result); } public function testReplaceQueryParametersWithStartingIndexAtOne() : void { $extension = new DoctrineExtension(); $query = 'a=? OR b=?'; $parameters = [ 1 => 1, 2 => 2, ]; $result = $extension->replaceQueryParameters($query, $parameters); $this->assertEquals('a=1 OR b=2', $result); } public function testReplaceQueryParameters() : void { $extension = new DoctrineExtension(); $query = 'a=? OR b=?'; $parameters = [ 1, 2, ]; $result = $extension->replaceQueryParameters($query, $parameters); $this->assertEquals('a=1 OR b=2', $result); } public function testReplaceQueryParametersWithNamedIndex() : void { $extension = new DoctrineExtension(); $query = 'a=:a OR b=:b'; $parameters = [ 'a' => 1, 'b' => 2, ]; $result = $extension->replaceQueryParameters($query, $parameters); $this->assertEquals('a=1 OR b=2', $result); } public function testEscapeBinaryParameter() : void { $binaryString = pack('H*', '9d40b8c1417f42d099af4782ec4b20b6'); $this->assertEquals('0x9D40B8C1417F42D099AF4782EC4B20B6', DoctrineExtension::escapeFunction($binaryString)); } public function testEscapeStringParameter() : void { $this->assertEquals("'test string'", DoctrineExtension::escapeFunction('test string')); } public function testEscapeArrayParameter() : void { $this->assertEquals("1, NULL, 'test', foo", DoctrineExtension::escapeFunction([1, null, 'test', new DummyClass('foo')])); } public function testEscapeObjectParameter() : void { $object = new DummyClass('bar'); $this->assertEquals('bar', DoctrineExtension::escapeFunction($object)); } public function testEscapeNullParameter() : void { $this->assertEquals('NULL', DoctrineExtension::escapeFunction(null)); } public function testEscapeBooleanParameter() : void { $this->assertEquals('1', DoctrineExtension::escapeFunction(true)); } } class DummyClass { /** @var string */ protected $str; public function __construct(string $str) { $this->str = $str; } public function __toString() : string { return $this->str; } } php-doctrine-bundle-2.0.7/Twig/000077500000000000000000000000001361552055200163015ustar00rootroot00000000000000php-doctrine-bundle-2.0.7/Twig/DoctrineExtension.php000066400000000000000000000134231361552055200224610ustar00rootroot00000000000000 ['html']]), new TwigFilter('doctrine_replace_query_parameters', [$this, 'replaceQueryParameters']), ]; } /** * Get the possible combinations of elements from the given array */ private function getPossibleCombinations(array $elements, int $combinationsLevel) : array { $baseCount = count($elements); $result = []; if ($combinationsLevel === 1) { foreach ($elements as $element) { $result[] = [$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) { continue; } $tmp = $nextLevelElement; $newCombination = array_slice($tmp, 0); $newCombination[] = $element; $result[] = array_slice($newCombination, 0); } } 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) { // Check if result is non-unicode string using PCRE_UTF8 modifier case is_string($result) && ! preg_match('//u', $result): $result = '0x' . strtoupper(bin2hex($result)); break; 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 $result === null: $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|Data $parameters * * @return string */ public function replaceQueryParameters($query, $parameters) { if ($parameters instanceof Data) { $parameters = $parameters->getValue(true); } $i = 0; if (! array_key_exists(0, $parameters) && array_key_exists(1, $parameters)) { $i = 1; } return 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'; } } php-doctrine-bundle-2.0.7/UPGRADE-1.11.md000066400000000000000000000021071361552055200173560ustar00rootroot00000000000000UPGRADE FROM 1.10 to 1.11 ========================= PHP and Symfony version support ------------------------------- * Support for PHP 5.5, 5.6 and 7.0 was dropped * Support for unsupported Symfony versions was dropped. The bundle now supports Symfony 3.4 LTS and 4.1 or newer. * Support for Twig 1.34 and below as well as 2.4 and below (for 2.x) releases was dropped. Commands -------- * Deprecated instantiating `Doctrine\Bundle\DoctrineBundle\Command` without a `ManagerRegistry` instance. * Deprecated `setContainer` and `getContainer` in `Doctrine\Bundle\DoctrineBundle\Command`. * `Doctrine\Bundle\DoctrineBundle\Command` no longer implements `ContainerAwareInterface`. Mapping ------- * Renamed `ContainerAwareEntityListenerResolver` to `ContainerEntityListenerResolver`. Types ----- * Marking types as commented in the configuration is deprecated. Instead, mark them commented using the `requiresSQLCommentHint()` method of the type. * The `commented` configuration option for types will be dropped in a future release. You should avoid using it. php-doctrine-bundle-2.0.7/UPGRADE-1.12.md000066400000000000000000000015201361552055200173550ustar00rootroot00000000000000UPGRADE FROM 1.11 to 1.12 ========================= Deprecation of DoctrineCacheBundle ---------------------------------- With DoctrineCacheBundle [being deprecated](https://github.com/doctrine/DoctrineCacheBundle/issues/156), configuring caches through it has been deprecated. If you are using anything other than the `pool` or `id` cache types, please update your configuration to either use symfony/cache through the `pool` type or configure your cache services manually and use the `service` type. Service aliases --------------- * Deprecated the `Symfony\Bridge\Doctrine\RegistryInterface` and `Doctrine\Bundle\DoctrineBundle\Registry` service alias, use `Doctrine\Common\Persistence\ManagerRegistry` instead. * Deprecated the `Doctrine\Common\Persistence\ObjectManager` service alias, use `Doctrine\ORM\EntityManagerInterface` instead. php-doctrine-bundle-2.0.7/UPGRADE-2.0.md000066400000000000000000000042121361552055200172740ustar00rootroot00000000000000UPGRADE FROM 1.x to 2.0 ======================= PHP and Symfony version support ------------------------------- * Support for PHP 5.5, 5.6 and 7.0 was dropped * Support for unsupported Symfony versions was dropped. The bundle now supports Symfony 3.4 LTS and 4.1 or newer. * Support for Twig 1.34 and below as well as 2.4 and below (for 2.x) releases was dropped. * When no charset parameter is defined, it now defaults to `utf8mb4` on the MySQL platform and to `utf8` on all other platforms. Commands -------- * `Doctrine\Bundle\DoctrineBundle\Command` requires a `ManagerRegistry` instance when instantiating. * Dropped `setContainer` and `getContainer` in `Doctrine\Bundle\DoctrineBundle\Command`. * `Doctrine\Bundle\DoctrineBundle\Command` no longer implements `ContainerAwareInterface`. * `Doctrine\Bundle\DoctrineBundle\Command\GenerateEntitiesDoctrineCommand` was dropped in favour of the MakerBundle. Deprecation of DoctrineCacheBundle ---------------------------------- Configuring caches through DoctrineCacheBundle is no longer possible. Please use symfony/cache through the `pool` type or configure your cache services manually and use the `service` type. Mapping ------- * Dropped `ContainerAwareEntityListenerResolver`, use `ContainerEntityListenerResolver` instead. Registry -------- * `Registry` no longer implements `Symfony\Bridge\Doctrine\RegistryInterface`. * Removed all deprecated entity manager specific methods from the registry. Service aliases --------------- * The `Symfony\Bridge\Doctrine\RegistryInterface` interface is no longer aliased to the `doctrine` service, use `Doctrine\Common\Persistence\ManagerRegistry` instead. * The `Doctrine\Common\Persistence\ObjectManager` interface is no longer aliased to the `doctrine.orm.entity_manager` service, use `Doctrine\ORM\EntityManagerInterface` instead. Types ----- * Marking types as commented in the configuration is no longer supported. Instead, mark them commented using the `requiresSQLCommentHint()` method of the type. * The `commented` configuration option for types will be dropped in a future release. You should not use it. php-doctrine-bundle-2.0.7/UPGRADE-3.0.md000066400000000000000000000002301361552055200172710ustar00rootroot00000000000000UPGRADE FROM 2.x to 3.0 ======================= Types ----- * The `commented` configuration option for types is no longer supported and deprecated. php-doctrine-bundle-2.0.7/composer.json000066400000000000000000000046041361552055200201150ustar00rootroot00000000000000{ "name": "doctrine/doctrine-bundle", "type": "symfony-bundle", "description": "Symfony DoctrineBundle", "keywords": ["DBAL", "ORM", "Database", "Persistence"], "homepage": "http://www.doctrine-project.org", "license": "MIT", "minimum-stability": "dev", "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": "^7.1", "doctrine/dbal": "^2.9.0", "doctrine/persistence": "^1.3.3", "jdorn/sql-formatter": "^1.2.16", "symfony/cache": "^4.3.3|^5.0", "symfony/config": "^4.3.3|^5.0", "symfony/console": "^3.4.30|^4.3.3|^5.0", "symfony/dependency-injection": "^4.3.3|^5.0", "symfony/doctrine-bridge": "^4.3.7|^5.0", "symfony/framework-bundle": "^3.4.30|^4.3.3|^5.0", "symfony/service-contracts": "^1.1.1|^2.0" }, "require-dev": { "doctrine/coding-standard": "^6.0", "doctrine/orm": "^2.6", "ocramius/proxy-manager": "^2.1", "phpunit/phpunit": "^7.5", "symfony/phpunit-bridge": "^4.2", "symfony/property-info": "^4.3.3|^5.0", "symfony/proxy-manager-bridge": "^3.4|^4.3.3|^5.0", "symfony/twig-bridge": "^3.4.30|^4.3.3|^5.0", "symfony/validator": "^3.4.30|^4.3.3|^5.0", "symfony/web-profiler-bundle": "^3.4.30|^4.3.3|^5.0", "symfony/yaml": "^3.4.30|^4.3.3|^5.0", "twig/twig": "^1.34|^2.12" }, "config": { "sort-packages": true }, "conflict": { "doctrine/orm": "<2.6", "twig/twig": "<1.34|>=2.0,<2.4" }, "suggest": { "doctrine/orm": "The Doctrine ORM integration is optional in the bundle.", "symfony/web-profiler-bundle": "To use the data collector." }, "autoload": { "psr-4": { "Doctrine\\Bundle\\DoctrineBundle\\": "" } }, "autoload-dev": { "psr-4": { "": "Tests/DependencyInjection" } }, "extra": { "branch-alias": { "dev-master": "2.0.x-dev" } } } php-doctrine-bundle-2.0.7/phpcs.xml.dist000066400000000000000000000055071361552055200201770ustar00rootroot00000000000000 . vendor/* Tests/* Tests/* Tests/DependencyInjection/Fixtures/* DependencyInjection/* Twig/DoctrineExtension.php Tests/* DependencyInjection/* Twig/DoctrineExtension.php Tests/* DependencyInjection/* Twig/DoctrineExtension.php Tests/* php-doctrine-bundle-2.0.7/phpunit.xml.dist000066400000000000000000000012461361552055200205450ustar00rootroot00000000000000 ./Tests . ./Resources ./Tests ./vendor