From ba57bec932a10089f8a778208ed1b17f430ffc3a Mon Sep 17 00:00:00 2001 From: prisis Date: Mon, 26 Nov 2018 11:02:14 +0100 Subject: [PATCH 1/4] fixes #429 --- composer.json | 11 + phpunit.xml.dist | 16 + .../Migration/Exception/Exception.php | 10 + ...ExecutedUnavailableMigrationsException.php | 35 ++ .../Exception/InvalidArgumentException.php | 9 + .../Exception/MigrationVersionException.php | 7 + .../Contract/Migration/NamingStrategy.php | 27 ++ .../DBAL/.github/PULL_REQUEST_TEMPLATE.md | 5 + .../Bridge/Doctrine/DBAL/Connection.php | 39 ++ .../Doctrine/DBAL/ConnectionManager.php | 234 ++++++++++ src/Viserio/Bridge/Doctrine/DBAL/LICENSE | 21 + .../ConsoleCommandsServiceProvider.php | 59 +++ .../Provider/DoctrineDBALServiceProvider.php | 93 ++++ .../Bridge/Doctrine/DBAL/Proxy/DBAL.php | 19 + src/Viserio/Bridge/Doctrine/DBAL/README.md | 33 ++ .../Bridge/Doctrine/DBAL/Statement.php | 75 +++ .../DBAL/Tests/ConnectionManagerTest.php | 75 +++ .../ConsoleCommandsServiceProviderTest.php | 41 ++ ...LServiceProviderDatabaseConnectionTest.php | 71 +++ .../DoctrineDBALServiceProviderTest.php | 37 ++ .../Doctrine/DBAL/Tests/Stub/database.sqlite | Bin 0 -> 2048 bytes .../Bridge/Doctrine/DBAL/composer.json | 56 +++ .../Bridge/Doctrine/DBAL/phpunit.xml.dist | 40 ++ .../.github/PULL_REQUEST_TEMPLATE.md | 5 + .../Bridge/Doctrine/Extensions/LICENSE | 21 + .../Provider/ExtensionsServiceProvider.php | 139 ++++++ .../Bridge/Doctrine/Extensions/README.md | 33 ++ .../Extensions/Types/ChronosDateTimeType.php | 3 + .../Types/ChronosDateTimeTzType.php | 3 + .../Extensions/Types/ChronosDateType.php | 3 + .../Extensions/Types/ChronosTimeType.php | 3 + .../Bridge/Doctrine/Extensions/composer.json | 57 +++ .../Doctrine/Extensions/phpunit.xml.dist | 40 ++ .../.github/PULL_REQUEST_TEMPLATE.md | 5 + .../Migration/Commands/AbstractCommand.php | 107 +++++ .../Migration/Commands/DiffCommand.php | 3 + .../Migration/Commands/ExecuteCommand.php | 3 + .../Migration/Commands/GenerateCommand.php | 34 ++ .../Commands/Helper/ConfigurationHelper.php | 186 ++++++++ .../Migration/Commands/LatestCommand.php | 3 + .../Migration/Commands/MigrateCommand.php | 20 + .../Migration/Commands/RefreshCommand.php | 3 + .../Migration/Commands/ResetCommand.php | 3 + .../Migration/Commands/RollbackCommand.php | 3 + .../Migration/Commands/StatusCommand.php | 3 + .../Migration/Commands/UpToDateCommand.php | 3 + .../Migration/Commands/VersionCommand.php | 36 ++ .../Migration/Configuration/Configuration.php | 38 ++ src/Viserio/Bridge/Doctrine/Migration/LICENSE | 21 + .../Naming/DefaultNamingStrategy.php | 38 ++ .../ConsoleCommandsServiceProvider.php | 68 +++ .../Bridge/Doctrine/Migration/README.md | 33 ++ .../ConsoleCommandsServiceProviderTest.php | 68 +++ .../Migration/Tests/Stub/database.sqlite | Bin 0 -> 2048 bytes .../Bridge/Doctrine/Migration/composer.json | 52 +++ .../Doctrine/Migration/phpunit.xml.dist | 40 ++ .../ORM/.github/PULL_REQUEST_TEMPLATE.md | 5 + .../Bridge/Doctrine/ORM/AbstractTable.php | 86 ++++ .../ORM/Commands/AbstractDoctrineCommand.php | 66 +++ .../CreateDatabaseDoctrineCommand.php | 0 .../Commands/DropDatabaseDoctrineCommand.php | 0 .../GenerateEntitiesDoctrineCommand.php | 0 .../Commands/ImportMappingDoctrineCommand.php | 0 .../ClearMetadataCacheDoctrineCommand.php | 0 .../ORM/Configuration/CacheManager.php | 32 ++ .../ORM/Configuration/MetaDataManager.php | 200 ++++++++ .../Bridge/Doctrine/ORM/ConnectionFactory.php | 105 +++++ .../DataCollector/DoctrineDataCollector.php | 365 +++++++++++++++ .../Doctrine/ORM/EntityManagerFactory.php | 408 ++++++++++++++++ .../Exceptions/ExtensionNotFoundException.php | 9 + .../NoEntityManagerFoundException.php | 9 + .../Doctrine/ORM/Exceptions/TypeNotFound.php | 9 + src/Viserio/Bridge/Doctrine/ORM/LICENSE | 21 + .../Bridge/Doctrine/ORM/Logger/Logger.php | 7 + .../Bridge/Doctrine/ORM/ManagerRegistry.php | 388 ++++++++++++++++ .../ORM/Middleware/SubstituteBindings.php | 0 .../ORM/Pagination/PaginatorAdapter.php | 46 ++ .../ConsoleCommandsServiceProvider.php | 88 ++++ .../DoctrineORMQueueJobServiceProvider.php | 17 + .../Provider/DoctrineORMServiceProvicer.php | 47 ++ .../Bridge/Doctrine/ORM/Proxy/Doctrine.php | 19 + .../Doctrine/ORM/Proxy/EntityManager.php | 19 + .../Bridge/Doctrine/ORM/Proxy/Registry.php | 19 + .../Doctrine/ORM/Queue/FailedJobTable.php | 31 ++ src/Viserio/Bridge/Doctrine/ORM/README.md | 33 ++ .../ORM/Resolvers/EntityListenerResolver.php | 68 +++ .../Doctrine/ORM/Serializers/ArrayEncoder.php | 43 ++ .../ORM/Serializers/Traits/ArrayableTrait.php | 27 ++ .../Doctrine/ORM/Tests/ClassAliasesTest.php | 18 + .../Tests/Configuration/CacheManagerTest.php | 32 ++ .../Configuration/MetaDataManagerTest.php | 83 ++++ .../ORM/Tests/EntityManagerFactoryTest.php | 0 .../Tests/Fixtures/ArrayableEntityFixture.php | 23 + .../ORM/Tests/ManagerRegistryTest.php | 48 ++ .../ConsoleCommandsServiceProviderTest.php | 66 +++ .../DoctrineORMServiceProviderTest.php | 16 + .../Resolvers/EntityListenerResolverTest.php | 128 +++++ .../Tests/Serializers/ArrayEncoderTest.php | 45 ++ .../Doctrine/ORM/Tests/Stub/database.sqlite | Bin 0 -> 2048 bytes src/Viserio/Bridge/Doctrine/ORM/alias.php | 18 + src/Viserio/Bridge/Doctrine/ORM/composer.json | 64 +++ .../Bridge/Doctrine/ORM/phpunit.xml.dist | 40 ++ .../Testing/.github/PULL_REQUEST_TEMPLATE.md | 5 + .../Testing/Cache/StaticArrayCache.php | 120 +++++ .../LoadDataFixturesDoctrineCommand.php | 13 + .../Concerns/DoctrineEntitiesTestCase.php | 10 + .../Concerns/InteractsWithEntities.php | 115 +++++ .../Testing/DBAL/StaticConnection.php | 123 +++++ .../Testing/DBAL/StaticConnectionManager.php | 39 ++ .../Doctrine/Testing/DBAL/StaticDriver.php | 187 ++++++++ .../Bridge/Doctrine/Testing/Factory.php | 227 +++++++++ .../Doctrine/Testing/FactoryBuilder.php | 154 ++++++ src/Viserio/Bridge/Doctrine/Testing/LICENSE | 21 + .../Testing/PHPUnit/PHPUnitListener.php | 37 ++ .../ConsoleCommandsServiceProvider.php | 48 ++ .../DoctrineORMTestingServiceProvider.php | 80 ++++ .../DoctrineTestingServiceProvier.php | 51 ++ src/Viserio/Bridge/Doctrine/Testing/README.md | 33 ++ .../Doctrine/Testing/SimpleHydrator.php | 32 ++ .../Tests/Cache/StaticArrayCacheTest.php | 438 ++++++++++++++++++ .../Concerns/DoctrineEntitiesTestCaseTest.php | 3 + .../Testing/Tests/DBAL/StaticDriverTest.php | 52 +++ .../Testing/Tests/FactoryBuilderTest.php | 9 + .../Doctrine/Testing/Tests/FactoryTest.php | 9 + .../Testing/Tests/Fixtures/MockDriver.php | 68 +++ .../ConsoleCommandsServiceProviderTest.php | 47 ++ .../DoctrineORMTestingServiceProviderTest.php | 0 .../Testing/Tests/Stub/database.sqlite | Bin 0 -> 2048 bytes .../Bridge/Doctrine/Testing/composer.json | 57 +++ .../Bridge/Doctrine/Testing/phpunit.xml.dist | 40 ++ 130 files changed, 6856 insertions(+) create mode 100644 src/Viserio/Bridge/Doctrine/Contract/Migration/Exception/Exception.php create mode 100644 src/Viserio/Bridge/Doctrine/Contract/Migration/Exception/ExecutedUnavailableMigrationsException.php create mode 100644 src/Viserio/Bridge/Doctrine/Contract/Migration/Exception/InvalidArgumentException.php create mode 100644 src/Viserio/Bridge/Doctrine/Contract/Migration/Exception/MigrationVersionException.php create mode 100644 src/Viserio/Bridge/Doctrine/Contract/Migration/NamingStrategy.php create mode 100644 src/Viserio/Bridge/Doctrine/DBAL/.github/PULL_REQUEST_TEMPLATE.md create mode 100644 src/Viserio/Bridge/Doctrine/DBAL/Connection.php create mode 100644 src/Viserio/Bridge/Doctrine/DBAL/ConnectionManager.php create mode 100644 src/Viserio/Bridge/Doctrine/DBAL/LICENSE create mode 100644 src/Viserio/Bridge/Doctrine/DBAL/Provider/ConsoleCommandsServiceProvider.php create mode 100644 src/Viserio/Bridge/Doctrine/DBAL/Provider/DoctrineDBALServiceProvider.php create mode 100644 src/Viserio/Bridge/Doctrine/DBAL/Proxy/DBAL.php create mode 100644 src/Viserio/Bridge/Doctrine/DBAL/README.md create mode 100644 src/Viserio/Bridge/Doctrine/DBAL/Statement.php create mode 100644 src/Viserio/Bridge/Doctrine/DBAL/Tests/ConnectionManagerTest.php create mode 100644 src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/ConsoleCommandsServiceProviderTest.php create mode 100644 src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/DoctrineDBALServiceProviderDatabaseConnectionTest.php create mode 100644 src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/DoctrineDBALServiceProviderTest.php create mode 100644 src/Viserio/Bridge/Doctrine/DBAL/Tests/Stub/database.sqlite create mode 100644 src/Viserio/Bridge/Doctrine/DBAL/composer.json create mode 100644 src/Viserio/Bridge/Doctrine/DBAL/phpunit.xml.dist create mode 100644 src/Viserio/Bridge/Doctrine/Extensions/.github/PULL_REQUEST_TEMPLATE.md create mode 100644 src/Viserio/Bridge/Doctrine/Extensions/LICENSE create mode 100644 src/Viserio/Bridge/Doctrine/Extensions/Provider/ExtensionsServiceProvider.php create mode 100644 src/Viserio/Bridge/Doctrine/Extensions/README.md create mode 100644 src/Viserio/Bridge/Doctrine/Extensions/Types/ChronosDateTimeType.php create mode 100644 src/Viserio/Bridge/Doctrine/Extensions/Types/ChronosDateTimeTzType.php create mode 100644 src/Viserio/Bridge/Doctrine/Extensions/Types/ChronosDateType.php create mode 100644 src/Viserio/Bridge/Doctrine/Extensions/Types/ChronosTimeType.php create mode 100644 src/Viserio/Bridge/Doctrine/Extensions/composer.json create mode 100644 src/Viserio/Bridge/Doctrine/Extensions/phpunit.xml.dist create mode 100644 src/Viserio/Bridge/Doctrine/Migration/.github/PULL_REQUEST_TEMPLATE.md create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/AbstractCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/DiffCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/ExecuteCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/GenerateCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/Helper/ConfigurationHelper.php create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/LatestCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/MigrateCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/RefreshCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/ResetCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/RollbackCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/StatusCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/UpToDateCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/VersionCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Configuration/Configuration.php create mode 100644 src/Viserio/Bridge/Doctrine/Migration/LICENSE create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Naming/DefaultNamingStrategy.php create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Provider/ConsoleCommandsServiceProvider.php create mode 100644 src/Viserio/Bridge/Doctrine/Migration/README.md create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Tests/Provider/ConsoleCommandsServiceProviderTest.php create mode 100644 src/Viserio/Bridge/Doctrine/Migration/Tests/Stub/database.sqlite create mode 100644 src/Viserio/Bridge/Doctrine/Migration/composer.json create mode 100644 src/Viserio/Bridge/Doctrine/Migration/phpunit.xml.dist create mode 100644 src/Viserio/Bridge/Doctrine/ORM/.github/PULL_REQUEST_TEMPLATE.md create mode 100644 src/Viserio/Bridge/Doctrine/ORM/AbstractTable.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Commands/AbstractDoctrineCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Commands/CreateDatabaseDoctrineCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Commands/DropDatabaseDoctrineCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Commands/GenerateEntitiesDoctrineCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Commands/ImportMappingDoctrineCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Commands/Proxies/ClearMetadataCacheDoctrineCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Configuration/CacheManager.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Configuration/MetaDataManager.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/ConnectionFactory.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/DataCollector/DoctrineDataCollector.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/EntityManagerFactory.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Exceptions/ExtensionNotFoundException.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Exceptions/NoEntityManagerFoundException.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Exceptions/TypeNotFound.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/LICENSE create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Logger/Logger.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/ManagerRegistry.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Middleware/SubstituteBindings.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Pagination/PaginatorAdapter.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Provider/ConsoleCommandsServiceProvider.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Provider/DoctrineORMQueueJobServiceProvider.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Provider/DoctrineORMServiceProvicer.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Proxy/Doctrine.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Proxy/EntityManager.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Proxy/Registry.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Queue/FailedJobTable.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/README.md create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Resolvers/EntityListenerResolver.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Serializers/ArrayEncoder.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Serializers/Traits/ArrayableTrait.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Tests/ClassAliasesTest.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Tests/Configuration/CacheManagerTest.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Tests/Configuration/MetaDataManagerTest.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Tests/EntityManagerFactoryTest.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Tests/Fixtures/ArrayableEntityFixture.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Tests/ManagerRegistryTest.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Tests/Provider/ConsoleCommandsServiceProviderTest.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Tests/Provider/DoctrineORMServiceProviderTest.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Tests/Resolvers/EntityListenerResolverTest.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Tests/Serializers/ArrayEncoderTest.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/Tests/Stub/database.sqlite create mode 100644 src/Viserio/Bridge/Doctrine/ORM/alias.php create mode 100644 src/Viserio/Bridge/Doctrine/ORM/composer.json create mode 100644 src/Viserio/Bridge/Doctrine/ORM/phpunit.xml.dist create mode 100644 src/Viserio/Bridge/Doctrine/Testing/.github/PULL_REQUEST_TEMPLATE.md create mode 100644 src/Viserio/Bridge/Doctrine/Testing/Cache/StaticArrayCache.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/Commands/LoadDataFixturesDoctrineCommand.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/Concerns/DoctrineEntitiesTestCase.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/Concerns/InteractsWithEntities.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticConnection.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticConnectionManager.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticDriver.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/Factory.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/FactoryBuilder.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/LICENSE create mode 100644 src/Viserio/Bridge/Doctrine/Testing/PHPUnit/PHPUnitListener.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/Provider/ConsoleCommandsServiceProvider.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/Provider/DoctrineORMTestingServiceProvider.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/Provider/DoctrineTestingServiceProvier.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/README.md create mode 100644 src/Viserio/Bridge/Doctrine/Testing/SimpleHydrator.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/Tests/Cache/StaticArrayCacheTest.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/Tests/Concerns/DoctrineEntitiesTestCaseTest.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/Tests/DBAL/StaticDriverTest.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/Tests/FactoryBuilderTest.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/Tests/FactoryTest.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/Tests/Fixtures/MockDriver.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/Tests/Provider/ConsoleCommandsServiceProviderTest.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/Tests/Provider/DoctrineORMTestingServiceProviderTest.php create mode 100644 src/Viserio/Bridge/Doctrine/Testing/Tests/Stub/database.sqlite create mode 100644 src/Viserio/Bridge/Doctrine/Testing/composer.json create mode 100644 src/Viserio/Bridge/Doctrine/Testing/phpunit.xml.dist diff --git a/composer.json b/composer.json index 47c32fda9..9826160fd 100644 --- a/composer.json +++ b/composer.json @@ -89,6 +89,11 @@ "viserio/contract": "self.version", "viserio/cookie": "self.version", "viserio/cron": "self.version", + "viserio/doctrine-dbal-bridge": "self.version", + "viserio/doctrine-extensions-bridge": "self.version", + "viserio/doctrine-migration-bridge": "self.version", + "viserio/doctrine-orm-bridge": "self.version", + "viserio/doctrine-testing-bridge": "self.version", "viserio/events": "self.version", "viserio/exception": "self.version", "viserio/filesystem": "self.version", @@ -131,6 +136,9 @@ "cache/namespaced-cache": "^1.0", "cache/session-handler": "^1.0", "doctrine/dbal": "^2.5", + "doctrine/data-fixtures": "^1.3.1", + "doctrine/migrations": "^2.0.0-beta2", + "doctrine/orm": "^2.6.3", "enqueue/dbal": "^0.8", "enqueue/fs": "^0.8", "enqueue/pheanstalk": "^0.8", @@ -139,6 +147,8 @@ "erusev/parsedown": "^1.7", "erusev/parsedown-extra": "^0.7", "filp/whoops": "^2.2.0", + "fzaninotto/faker": "^1.8.0", + "gedmo/doctrine-extensions": "^2.4.36", "guzzlehttp/guzzle": "^6.3.0", "league/flysystem-aws-s3-v3": "^1.0.19", "league/flysystem-cached-adapter": "^1.0.6", @@ -160,6 +170,7 @@ "predis/predis": "^1.0", "roave/security-advisories": "dev-master", "spatie/flysystem-dropbox": "^1.0", + "ocramius/proxy-manager": "^2.2.2", "symfony/phpunit-bridge": "^4.2.0", "symfony/var-dumper": "^4.2.0", "symfony/yaml": "^4.2.0", diff --git a/phpunit.xml.dist b/phpunit.xml.dist index d3de61c06..bfe21235c 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -26,6 +26,22 @@ + + ./src/Viserio/Bridge/Doctrine/DBAL/Tests + + + ./src/Viserio/Bridge/Doctrine/Extensions/Tests + + + ./src/Viserio/Bridge/Doctrine/Migration/Tests + + + ./src/Viserio/Bridge/Doctrine/ORM/Tests + + + ./src/Viserio/Bridge/Doctrine/Testing/Tests + + ./src/Viserio/Bridge/Monolog/Tests diff --git a/src/Viserio/Bridge/Doctrine/Contract/Migration/Exception/Exception.php b/src/Viserio/Bridge/Doctrine/Contract/Migration/Exception/Exception.php new file mode 100644 index 000000000..1af8119e5 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Contract/Migration/Exception/Exception.php @@ -0,0 +1,10 @@ +migrations = $migrations; + } + + /** + * Get all unavailable migrations. + * + * @return array + */ + public function getMigrations(): array + { + return $this->migrations; + } +} diff --git a/src/Viserio/Bridge/Doctrine/Contract/Migration/Exception/InvalidArgumentException.php b/src/Viserio/Bridge/Doctrine/Contract/Migration/Exception/InvalidArgumentException.php new file mode 100644 index 000000000..9b4ab15ba --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Contract/Migration/Exception/InvalidArgumentException.php @@ -0,0 +1,9 @@ + [ + 'mysql' => [ + 'driver' => 'pdo_mysql', + 'host' => 'DB_HOST', + 'port' => 'DB_PORT', + 'database' => 'DB_DATABASE_NAME', + 'username' => 'DB_DATABASE_USER', + 'password' => 'DB_DATABASE_PASSWORD', + 'charset' => 'utf8mb4', + 'collation' => 'utf8mb4_unicode_ci', + 'strict' => true, + 'driverOptions' => [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'utf8mb4\''], + ], + 'sqlite' => [ + 'driver' => 'pdo_sqlite', + 'database' => 'DB_PATH', + ], + 'pgsql' => [ + 'driver' => 'pdo_pgsql', + 'host' => 'DB_HOST', + 'port' => 'DB_PORT', + 'database' => 'DB_DATABASE_NAME', + 'username' => 'DB_DATABASE_USER', + 'password' => 'DB_DATABASE_PASSWORD', + 'charset' => 'utf8mb4', + 'sslmode' => 'prefer', + ], + 'sqlsrv' => [ + 'driver' => 'pdo_sqlsrv', + 'host' => 'DB_HOST', + 'port' => 'DB_PORT', + 'database' => 'DB_DATABASE_NAME', + 'username' => 'DB_DATABASE_USER', + 'password' => 'DB_DATABASE_PASSWORD', + 'charset' => 'utf8mb4', + ], + ], + ]; + } + + /** + * Set a doctrine event manager instance. + * + * @param \Doctrine\Common\EventManager $doctrineEventManager + * + * @return void + */ + public function setDoctrineEventManager(EventManager $doctrineEventManager): void + { + $this->doctrineEventManager = $doctrineEventManager; + } + + /** + * Get a doctrine event manager instance or null. + * + * @return null|\Doctrine\Common\EventManager + */ + public function getDoctrineEventManager(): ?EventManager + { + return $this->doctrineEventManager; + } + + /** + * Set a doctrine event manager instance. + * + * @param \Doctrine\DBAL\Configuration $doctrineConfiguration + * + * @return void + */ + public function setDoctrineConfiguration(Configuration $doctrineConfiguration): void + { + $this->doctrineConfiguration = $doctrineConfiguration; + } + + /** + * Get a doctrine event manager instance or null. + * + * @return null|\Doctrine\DBAL\Configuration + */ + public function getDoctrineConfiguration(): ?Configuration + { + return $this->doctrineConfiguration; + } + + /** + * {@inheritdoc} + */ + public function getConnectionConfig(string $name): array + { + return self::parseConfig(parent::getConnectionConfig($name)); + } + + /** + * Create a new mysql doctrine connection. + * + * @param array $config + * + * @throws \Doctrine\DBAL\DBALException + * + * @return \Doctrine\DBAL\Connection|\Viserio\Bridge\Doctrine\DBAL\Connection + */ + protected function createMysqlConnection(array $config): Connection + { + return DriverManager::getConnection($config, $this->getDoctrineConfiguration(), $this->getDoctrineEventManager()); + } + + /** + * Create a new sqlite doctrine connection. + * + * @param array $config + * + * @throws \Doctrine\DBAL\DBALException + * + * @return \Doctrine\DBAL\Connection|\Viserio\Bridge\Doctrine\DBAL\Connection + */ + protected function createSqliteConnection(array $config): Connection + { + return DriverManager::getConnection($config, $this->getDoctrineConfiguration(), $this->getDoctrineEventManager()); + } + + /** + * Create a new pgsql doctrine connection. + * + * @param array $config + * + * @throws \Doctrine\DBAL\DBALException + * + * @return \Doctrine\DBAL\Connection|\Viserio\Bridge\Doctrine\DBAL\Connection + */ + protected function createPgsqlConnection(array $config): Connection + { + return DriverManager::getConnection($config, $this->getDoctrineConfiguration(), $this->getDoctrineEventManager()); + } + + /** + * Create a new sqlsrv doctrine connection. + * + * @param array $config + * + * @throws \Doctrine\DBAL\DBALException + * + * @return \Doctrine\DBAL\Connection|\Viserio\Bridge\Doctrine\DBAL\Connection + */ + protected function createSqlsrvConnection(array $config): Connection + { + return DriverManager::getConnection($config, $this->getDoctrineConfiguration(), $this->getDoctrineEventManager()); + } + + /** + * {@inheritdoc} + */ + protected static function getConfigName(): string + { + return 'dbal'; + } + + /** + * Map our config style to doctrine config. + * + * @param array $config + * + * @return array + */ + private static function parseConfig(array $config): array + { + $doctrineConfig = []; + + $doctrineConfig['wrapperClass'] = $config['wrapper_class'] ?? Connection::class; + + if (\mb_strpos($config['name'], 'sqlite') === false) { + $doctrineConfig['user'] = $config['username']; + $doctrineConfig['dbname'] = $config['database']; + } else { + if (isset($config['username'])) { + $doctrineConfig['user'] = $config['username']; + } + + $doctrineConfig['path'] = $config['database']; + } + + unset($config['username'], $config['database']); + + return \array_merge($config, $doctrineConfig); + } +} diff --git a/src/Viserio/Bridge/Doctrine/DBAL/LICENSE b/src/Viserio/Bridge/Doctrine/DBAL/LICENSE new file mode 100644 index 000000000..9941d8719 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/DBAL/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 - 2017 Narrowspark + +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. diff --git a/src/Viserio/Bridge/Doctrine/DBAL/Provider/ConsoleCommandsServiceProvider.php b/src/Viserio/Bridge/Doctrine/DBAL/Provider/ConsoleCommandsServiceProvider.php new file mode 100644 index 000000000..a8878a36d --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/DBAL/Provider/ConsoleCommandsServiceProvider.php @@ -0,0 +1,59 @@ + [self::class, 'extendConsole'], + ]; + } + + /** + * Extend viserio console with commands. + * + * @param \Psr\Container\ContainerInterface $container + * @param null|\Viserio\Component\Console\Application $console + * + * @return null|\Viserio\Component\Console\Application + */ + public static function extendConsole( + ContainerInterface $container, + ?Application $console = null + ): ?Application { + if ($console !== null) { + $console->getHelperSet() + ->set(new ConnectionHelper($container->get(Connection::class)), 'db'); + + $console->addCommands([ + new RunSqlCommand(), + new ImportCommand(), + new ReservedWordsCommand(), + ]); + } + + return $console; + } +} diff --git a/src/Viserio/Bridge/Doctrine/DBAL/Provider/DoctrineDBALServiceProvider.php b/src/Viserio/Bridge/Doctrine/DBAL/Provider/DoctrineDBALServiceProvider.php new file mode 100644 index 000000000..4ac8043f9 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/DBAL/Provider/DoctrineDBALServiceProvider.php @@ -0,0 +1,93 @@ + [self::class, 'createConnectionManager'], + Connection::class => [self::class, 'createConnection'], + DoctrineConnection::class => function (ContainerInterface $container) { + return $container->get(Connection::class); + }, + 'db' => function (ContainerInterface $container) { + return $container->get(Connection::class); + }, + 'database' => function (ContainerInterface $container) { + return $container->get(Connection::class); + }, + Configuration::class => [self::class, 'createConfiguration'], + EventManager::class => [self::class, 'createEventManager'], + ]; + } + + /** + * {@inheritdoc} + */ + public function getExtensions(): array + { + return []; + } + + /** + * Create a new doctrine configuration. + * + * @return \Doctrine\DBAL\Configuration + */ + public static function createConfiguration(): Configuration + { + return new Configuration(); + } + + /** + * Create a new doctrine event manager. + * + * @return \Doctrine\Common\EventManager + */ + public static function createEventManager(): EventManager + { + return new EventManager(); + } + + /** + * Create a new doctrine connection. + * + * @param \Psr\Container\ContainerInterface $container + * + * @return \Viserio\Bridge\Doctrine\DBAL\ConnectionManager + */ + public static function createConnectionManager(ContainerInterface $container): ConnectionManager + { + $manager = new ConnectionManager($container); + + $manager->setDoctrineConfiguration($container->get(Configuration::class)); + $manager->setDoctrineEventManager($container->get(EventManager::class)); + + return $manager; + } + + /** + * Create a new doctrine connection. + * + * @param \Psr\Container\ContainerInterface $container + * + * @return \Doctrine\DBAL\Connection + */ + public static function createConnection(ContainerInterface $container): DoctrineConnection + { + return $container->get(ConnectionManager::class)->getConnection(); + } +} diff --git a/src/Viserio/Bridge/Doctrine/DBAL/Proxy/DBAL.php b/src/Viserio/Bridge/Doctrine/DBAL/Proxy/DBAL.php new file mode 100644 index 000000000..18e930871 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/DBAL/Proxy/DBAL.php @@ -0,0 +1,19 @@ + **Note:** If you want to build an application using Narrowspark, visit the main [![Source Code](http://img.shields.io/badge/source-narrowspark/narrowspark-blue.svg?style=flat-square)](https://github.com/narrowspark/narrowspark). + +## Contributing + +Issues for this package shall be posted on [Narrowspark framework issues](http://github.com/narrowspark/framework/issues). +Thank you for considering contributing to the Narrowspark framework! The contribution guide can be found in the [Narrowspark documentation](http://narrowspark.de/docs/contributions). + +## Installation + +Use [Composer](https://getcomposer.org/) to install this package: + +```sh +composer require viserio/bridge/doctrine +``` + +## Official Documentation + +Documentation for the framework can be found on the [Narrowspark website](http://narrowspark.de/docs). + +### License + +The Narrowspark framework is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT). diff --git a/src/Viserio/Bridge/Doctrine/DBAL/Statement.php b/src/Viserio/Bridge/Doctrine/DBAL/Statement.php new file mode 100644 index 000000000..e35d80263 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/DBAL/Statement.php @@ -0,0 +1,75 @@ +statement = $statement; + } + + /** + * Invoke doctrine statement functions. + * + * @param string $name + * @param array $args + * + * @return mixed + */ + public function __call($name, $args) + { + return \call_user_func_array([$this->statement, $name], $args); + } + + /** + * Returns the next row of a result set. + * + * @param null|int $fetchMode Controls how the next row will be returned to the caller. + * The value must be one of the PDO::FETCH_* constants, + * defaulting to PDO::FETCH_BOTH. + * + * @return null|bool|float|int|object|string The return value of this method on + * success depends on the fetch mode. + * In all cases, FALSE is returned on failure. + */ + public function fetch(int $fetchMode = null) + { + $stmt = $this->statement->fetch($fetchMode); + + if (\is_array($stmt)) { + return new Collection($stmt); + } + + return $stmt; + } + + /** + * Returns an array containing all of the result set rows. + * + * @param null|int $fetchMode Controls how the next row will be returned to the caller. + * The value must be one of the PDO::FETCH_* constants, + * defaulting to PDO::FETCH_BOTH. + * + * @return \Narrowspark\Collection\Collection + */ + public function fetchAll(int $fetchMode = null): Collection + { + return new Collection($this->statement->fetch($fetchMode)); + } +} diff --git a/src/Viserio/Bridge/Doctrine/DBAL/Tests/ConnectionManagerTest.php b/src/Viserio/Bridge/Doctrine/DBAL/Tests/ConnectionManagerTest.php new file mode 100644 index 000000000..c3bbb0739 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/DBAL/Tests/ConnectionManagerTest.php @@ -0,0 +1,75 @@ +manager = new ConnectionManager([ + 'viserio' => [ + 'doctrine' => [ + 'dbal' => [ + 'default' => 'mysql', + ], + ], + ], + ]); + } + + public function testDefaultConnection(): void + { + self::assertInstanceOf(Connection::class, $this->manager->getConnection()); + } + + public function testMysqlConnection(): void + { + self::assertInstanceOf(Connection::class, $this->manager->getConnection('mysql')); + } + + public function testSqliteConnection(): void + { + self::assertInstanceOf(Connection::class, $this->manager->getConnection('sqlite')); + } + + public function testPgsqlConnection(): void + { + self::assertInstanceOf(Connection::class, $this->manager->getConnection('pgsql')); + } + + public function testSqlsrvConnection(): void + { + self::assertInstanceOf(Connection::class, $this->manager->getConnection('sqlsrv')); + } + + public function testSetAndGetDoctrineEventManager(): void + { + self::assertNull($this->manager->getDoctrineEventManager()); + + $this->manager->setDoctrineEventManager($this->mock(EventManager::class)); + + self::assertInstanceOf(EventManager::class, $this->manager->getDoctrineEventManager()); + } + + public function testSetAndGetDoctrineConfiguration(): void + { + self::assertNull($this->manager->getDoctrineConfiguration()); + + $this->manager->setDoctrineConfiguration($this->mock(Configuration::class)); + + self::assertInstanceOf(Configuration::class, $this->manager->getDoctrineConfiguration()); + } +} diff --git a/src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/ConsoleCommandsServiceProviderTest.php b/src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/ConsoleCommandsServiceProviderTest.php new file mode 100644 index 000000000..d837313ee --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/ConsoleCommandsServiceProviderTest.php @@ -0,0 +1,41 @@ +register(new ConsoleServiceProvider()); + $container->register(new DoctrineDBALServiceProvider()); + $container->register(new ConsoleCommandsServiceProvider()); + + $container->instance('config', [ + 'viserio' => [ + 'doctrine' => [ + 'dbal' => [ + 'default' => 'mysql', + ], + ], + ], + ]); + + $console = $container->get(Application::class); + $commands = $console->all(); + + self::assertInstanceOf(ImportCommand::class, $commands['dbal:import']); + self::assertInstanceOf(ReservedWordsCommand::class, $commands['dbal:reserved-words']); + self::assertInstanceOf(RunSqlCommand::class, $commands['dbal:run-sql']); + } +} diff --git a/src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/DoctrineDBALServiceProviderDatabaseConnectionTest.php b/src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/DoctrineDBALServiceProviderDatabaseConnectionTest.php new file mode 100644 index 000000000..47ff53f68 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/DoctrineDBALServiceProviderDatabaseConnectionTest.php @@ -0,0 +1,71 @@ +register(new DoctrineDBALServiceProvider()); + + $container->instance('config', [ + 'viserio' => [ + 'doctrine' => [ + 'dbal' => [ + 'default' => 'sqlite', + 'connections' => [ + 'sqlite' => [ + 'driver' => 'pdo_sqlite', + 'database' => \dirname(__DIR__) . '/Stub/database.sqlite', + 'memory' => true, + ], + ], + ], + ], + ], + ]); + + $conn = $container->get(Connection::class); + $sql = 'SELECT name FROM text WHERE id = 1'; + + $collection = $conn->fetchArray($sql); + + self::assertInstanceOf(Collection::class, $collection); + self::assertSame([0 => 'narrowspark'], $collection->all()); + + $collection = $conn->fetchAll($sql); + + self::assertInstanceOf(Collection::class, $collection); + self::assertSame(['name' => 'narrowspark'], $collection->all()); + + $collection = $conn->fetchAssoc($sql); + + self::assertInstanceOf(Collection::class, $collection); + self::assertSame(['name' => 'narrowspark'], $collection->all()); + + $stmt = $conn->prepare($sql); + $stmt->execute(); + + $collection = $stmt->fetchAll(); + + self::assertInstanceOf(Collection::class, $collection); + self::assertSame(['name' => 'narrowspark'], $collection->all()); + + $stmt = $conn->query($sql); + $collection = $stmt->fetch(); + + self::assertInstanceOf(Collection::class, $collection); + self::assertSame(['name' => 'narrowspark'], $collection->all()); + + $stmt = $conn->query('SELECT name FROM text WHERE id = 2'); + + self::assertFalse($stmt->fetch()); + } +} diff --git a/src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/DoctrineDBALServiceProviderTest.php b/src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/DoctrineDBALServiceProviderTest.php new file mode 100644 index 000000000..a1013021c --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/DoctrineDBALServiceProviderTest.php @@ -0,0 +1,37 @@ +register(new DoctrineDBALServiceProvider()); + + $container->instance('config', [ + 'viserio' => [ + 'doctrine' => [ + 'dbal' => [ + 'default' => 'mysql', + ], + ], + ], + ]); + + self::assertInstanceOf(Configuration::class, $container->get(Configuration::class)); + self::assertInstanceOf(EventManager::class, $container->get(EventManager::class)); + self::assertInstanceOf(ConnectionManager::class, $container->get(ConnectionManager::class)); + self::assertInstanceOf(Connection::class, $container->get(Connection::class)); + self::assertInstanceOf(Connection::class, $container->get('db')); + self::assertInstanceOf(Connection::class, $container->get('database')); + } +} diff --git a/src/Viserio/Bridge/Doctrine/DBAL/Tests/Stub/database.sqlite b/src/Viserio/Bridge/Doctrine/DBAL/Tests/Stub/database.sqlite new file mode 100644 index 0000000000000000000000000000000000000000..ccbe3558eaa96c68890b860c5019aa03c9347b3f GIT binary patch literal 2048 zcmWFz^vNtqRY=P(%1ta$FlJz3U}R))P*7lCU|@n`AO!}DKoW#u0GSOFL#LS-bRWs_ z0!0~_w=e+FC>RZa(GZ|81iTp8#6?9JD@ziSa#BlDD@s6^$vMc?F~n6N#L>yeRY3_P zq@6 + + + + + + + + + + + ./Tests/ + + + + + + ./ + + ./vendor + ./Tests + + + + + diff --git a/src/Viserio/Bridge/Doctrine/Extensions/.github/PULL_REQUEST_TEMPLATE.md b/src/Viserio/Bridge/Doctrine/Extensions/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..3a1c85818 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Extensions/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,5 @@ +This is a READ ONLY repository. + +Please make your pull request to https://github.com/narrowspark/framework + +Thank you for contributing. diff --git a/src/Viserio/Bridge/Doctrine/Extensions/LICENSE b/src/Viserio/Bridge/Doctrine/Extensions/LICENSE new file mode 100644 index 000000000..9941d8719 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Extensions/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 - 2017 Narrowspark + +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. diff --git a/src/Viserio/Bridge/Doctrine/Extensions/Provider/ExtensionsServiceProvider.php b/src/Viserio/Bridge/Doctrine/Extensions/Provider/ExtensionsServiceProvider.php new file mode 100644 index 000000000..4c4116048 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Extensions/Provider/ExtensionsServiceProvider.php @@ -0,0 +1,139 @@ + false, + ]; + } + + /** + * Check if a annotations driver exists. + * + * @param \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain $chain + * + * @return bool + */ + private static function hasAnnotationReader(MappingDriverChain $chain): bool + { + foreach ($chain->getDrivers() as $driver) { + if ($driver instanceof AnnotationDriver) { + return true; + } + } + + return false; + } + + /** + * Register gedmo for annotations. + * + * @param \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain $chain + * + * @return void + */ + private static function registerGedmoForAnnotations(MappingDriverChain $chain): void + { + if (self::needsAllMappings()) { + DoctrineExtensions::registerMappingIntoDriverChainORM( + $chain, + $chain->getReader() + ); + } else { + DoctrineExtensions::registerAbstractMappingIntoDriverChainORM( + $chain, + $chain->getReader() + ); + } + } + + /** + * Check if a fluent driver exists. + * + * @param \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain $chain + * + * @return bool + */ + private static function hasFluentDriver(MappingDriverChain $chain): bool + { + foreach ($chain->getDrivers() as $driver) { + if ($driver instanceof FluentDriver) { + return true; + } + } + + return false; + } + + /** + * Register gedmo for fluent. + * + * @param \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain $chain + * + * @return void + */ + private static function registerGedmoForFluent(MappingDriverChain $chain): void + { + if (self::needsAllMappings()) { + GedmoExtensions::registerAll($chain); + } else { + GedmoExtensions::registerAbstract($chain); + } + } + + /** + * Check if all mappings are needed. + * + * @return bool + */ + private static function needsAllMappings(): bool + { + return self::$options['all_mappings'] === true; + } +} diff --git a/src/Viserio/Bridge/Doctrine/Extensions/README.md b/src/Viserio/Bridge/Doctrine/Extensions/README.md new file mode 100644 index 000000000..a880132af --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Extensions/README.md @@ -0,0 +1,33 @@ +# Viserio Doctrine Extensions package + +This package is part of the [Narrowspark framework](http://github.com/narrowspark/framework). + +[![Author](http://img.shields.io/badge/author-@anolilab-blue.svg?style=flat-square)](https://twitter.com/anolilab) +[![Quality Score](https://img.shields.io/scrutinizer/g/narrowspark/framework.svg?style=flat-square)](https://scrutinizer-ci.com/g/narrowspark/framework/code-structure/master) +[![Build Status](https://api.travis-ci.org/narrowspark/framework.svg?branch=master&style=flat-square)](https://travis-ci.org/narrowspark/framework) +[![Latest Version](https://img.shields.io/packagist/v/narrowspark/framework.svg?style=flat-square)](https://github.com/narrowspark/framework/releases) +[![Minimum PHP Version](https://img.shields.io/badge/php-%5E7.1.0-8892BF.svg?style=flat-square)](https://php.net/) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE) + +> **Note:** If you want to build an application using Narrowspark, visit the main [![Source Code](http://img.shields.io/badge/source-narrowspark/narrowspark-blue.svg?style=flat-square)](https://github.com/narrowspark/narrowspark). + +## Contributing + +Issues for this package shall be posted on [Narrowspark framework issues](http://github.com/narrowspark/framework/issues). +Thank you for considering contributing to the Narrowspark framework! The contribution guide can be found in the [Narrowspark documentation](http://narrowspark.de/docs/contributions). + +## Installation + +Use [Composer](https://getcomposer.org/) to install this package: + +```sh +composer require viserio/bridge-doctrine-extensions +``` + +## Official Documentation + +Documentation for the framework can be found on the [Narrowspark website](http://narrowspark.de/docs). + +### License + +The Narrowspark framework is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT). diff --git a/src/Viserio/Bridge/Doctrine/Extensions/Types/ChronosDateTimeType.php b/src/Viserio/Bridge/Doctrine/Extensions/Types/ChronosDateTimeType.php new file mode 100644 index 000000000..c43bcb27c --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Extensions/Types/ChronosDateTimeType.php @@ -0,0 +1,3 @@ + + + + + + + + + + + + ./Tests/ + + + + + + ./ + + ./vendor + ./Tests + + + + + diff --git a/src/Viserio/Bridge/Doctrine/Migration/.github/PULL_REQUEST_TEMPLATE.md b/src/Viserio/Bridge/Doctrine/Migration/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..3a1c85818 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Migration/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,5 @@ +This is a READ ONLY repository. + +Please make your pull request to https://github.com/narrowspark/framework + +Thank you for contributing. diff --git a/src/Viserio/Bridge/Doctrine/Migration/Commands/AbstractCommand.php b/src/Viserio/Bridge/Doctrine/Migration/Commands/AbstractCommand.php new file mode 100644 index 000000000..b5e81deae --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Migration/Commands/AbstractCommand.php @@ -0,0 +1,107 @@ +migrationConfiguration) { + if ($this->getHelperSet()->has('migration_configuration')) { + $configHelper = $this->getHelperSet()->get('migration_configuration'); + + if (! $configHelper instanceof ConfigurationHelper) { + throw new RuntimeException(''); + } + } else { + $configHelper = new ConfigurationHelper($this->configuration, $this->getConnection($input)); + } + + $configHelper->setContainer($this->container); + + $this->migrationConfiguration = $configHelper->getMigrationConfig($input, $this->getOutputWriter($output)); + } + + return $this->migrationConfiguration; + } + + /** + * @param \Symfony\Component\Console\Input\InputInterface $input + * + * @throws \Doctrine\DBAL\DBALException + * + * @return \Doctrine\DBAL\Connection + */ + private function getConnection(InputInterface $input) + { + if ($this->connection) { + return $this->connection; + } + + $chainLoader = new ConnectionConfigurationChainLoader( + [ + new ArrayConnectionConfigurationLoader($input->getOption('db-configuration')), + new ArrayConnectionConfigurationLoader('migrations-db.php'), + new ConnectionHelperLoader($this->getHelperSet(), 'connection'), + new ConnectionConfigurationLoader($this->configuration), + ] + ); + + if ($connection = $chainLoader->chosen()) { + return $this->connection = $connection; + } + + throw new \InvalidArgumentException('You have to specify a --db-configuration file or pass a Database Connection as a dependency to the Migrations.'); + } + + /** + * @param \Symfony\Component\Console\Output\OutputInterface $output + * + * @return \Doctrine\DBAL\Migrations\OutputWriter + */ + private function getOutputWriter(OutputInterface $output) + { + if (! $this->outputWriter) { + $this->outputWriter = new OutputWriter(function ($message) use ($output) { + return $output->writeln($message); + }); + } + + return $this->outputWriter; + } +} diff --git a/src/Viserio/Bridge/Doctrine/Migration/Commands/DiffCommand.php b/src/Viserio/Bridge/Doctrine/Migration/Commands/DiffCommand.php new file mode 100644 index 000000000..e4d6cc991 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Migration/Commands/DiffCommand.php @@ -0,0 +1,3 @@ +getMigrationsDirectory(); + $dir = $dir ?? getcwd(); + $dir = rtrim($dir, '/'); + + if (! file_exists($dir)) { + throw new InvalidArgumentException(sprintf('Migrations directory [%s] does not exist.', $dir)); + } + + if ($configuration->areMigrationsOrganizedByYear()) { + $dir .= DIRECTORY_SEPARATOR . date('Y'); + } + + if ($configuration->areMigrationsOrganizedByYearAndMonth()) { + $dir .= DIRECTORY_SEPARATOR . date('m'); + } + + if (! file_exists($dir)) { + mkdir($dir, 0755, true); + } + + return $dir; + } +} diff --git a/src/Viserio/Bridge/Doctrine/Migration/Commands/Helper/ConfigurationHelper.php b/src/Viserio/Bridge/Doctrine/Migration/Commands/Helper/ConfigurationHelper.php new file mode 100644 index 000000000..8c7da1882 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Migration/Commands/Helper/ConfigurationHelper.php @@ -0,0 +1,186 @@ +options = $options; + $this->connection = $connection; + } + + /** + * {@inheritdoc} + */ + public static function getDimensions(): iterable + { + return ['viserio', 'doctrine', 'migration']; + } + + /** + * {@inheritdoc} + */ + public static function getDefaultOptions(): iterable + { + return [ + 'default' => 'mysql', + 'connections' => [ + 'mysql' => [ + 'name' => 'Doctrine Migrations', + 'namespace' => 'Database\\Migration', + 'table' => 'migrations', + 'schema_filter' => '/^(?).*$/', + 'naming_strategy' => null, + 'custom_template' => null, + 'organize_migrations' => null, + ], + ], + ]; + } + + /** + * {@inheritdoc} + */ + public static function getMandatoryOptions(): iterable + { + return ['directory']; + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return 'migration_configuration'; + } + + /** + * Get a viserio migration configuration object. + * + * @param \Symfony\Component\Console\Input\InputInterface $input + * @param \Doctrine\DBAL\Migrations\OutputWriter $outputWriter + * + * @return \Viserio\Bridge\Doctrine\Migration\Configuration\Configuration + */ + public function getMigrationConfig(InputInterface $input, OutputWriter $outputWriter): Configuration + { + $options = self::resolveOptions($this->options); + + try { + $name = $input->getOption('connection'); + } catch (SymfonyInvalidArgumentException $exception) { + $name = $options['default']; + } + + $configuration = new Configuration($this->connection, $outputWriter); + $config = $options['connections'][$name]; + + $configuration->setName($config['name']); + $configuration->setMigrationsNamespace($config['namespace']); + $configuration->setMigrationsTableName($config['table']); + $configuration->getConnection()->getConfiguration()->setFilterSchemaAssetsExpression($config['schema_filter']); + + $strategy = $this->getStrategy($config); + + $configuration->setNamingStrategy($strategy); + $configuration->setMigrationsFinder($strategy->getFinder()); + + $configuration->setMigrationsDirectory($config['directory']); + $configuration->registerMigrationsFromDirectory($config['directory']); + $configuration->setCustomTemplate($config['custom_template']); + + return $this->configureOrganizeMigrations($config, $configuration); + } + + /** + * Get a naming strategy. + * + * @param array $config + * + * @return \Viserio\Bridge\Doctrine\Contract\Migration\NamingStrategy + */ + private function getStrategy(array $config): NamingStrategyContract + { + if (\is_object($config['naming_strategy'])) { + return $config['naming_strategy']; + } + + if ($this->container !== null && $this->container->has($config['naming_strategy'])) { + return $this->container->get($config['naming_strategy']); + } + + return new DefaultNamingStrategy(); + } + + /** + * Configures the migration organize. + * + * @param iterable $config + * @param \Viserio\Bridge\Doctrine\Migration\Configuration\Configuration $configuration + * + * @throws \Viserio\Bridge\Doctrine\Contract\Migration\Exception\InvalidArgumentException + * + * @return \Viserio\Bridge\Doctrine\Migration\Configuration\Configuration + */ + private function configureOrganizeMigrations(iterable $config, Configuration $configuration): Configuration + { + switch ($config['organize_migrations']) { + case Configuration::VERSIONS_ORGANIZATION_BY_YEAR: + $configuration->setMigrationsAreOrganizedByYear(true); + + break; + case Configuration::VERSIONS_ORGANIZATION_BY_YEAR_AND_MONTH: + $configuration->setMigrationsAreOrganizedByYearAndMonth(true); + + break; + case null: + break; + default: + throw new InvalidArgumentException('Invalid value for [organize_migrations].'); + } + + return $configuration; + } +} diff --git a/src/Viserio/Bridge/Doctrine/Migration/Commands/LatestCommand.php b/src/Viserio/Bridge/Doctrine/Migration/Commands/LatestCommand.php new file mode 100644 index 000000000..e4d6cc991 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Migration/Commands/LatestCommand.php @@ -0,0 +1,3 @@ +getName(); + $name = $name ? $name : 'Doctrine Database Migrations'; + $name = str_repeat(' ', 20) . $name . str_repeat(' ', 20); + + $this->line(str_repeat(' ', mb_strlen($name)), 'question'); + $this->line($name, 'question'); + $this->line(str_repeat(' ', mb_strlen($name)), 'question'); + $this->line(''); + } +} diff --git a/src/Viserio/Bridge/Doctrine/Migration/Commands/RefreshCommand.php b/src/Viserio/Bridge/Doctrine/Migration/Commands/RefreshCommand.php new file mode 100644 index 000000000..e4d6cc991 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Migration/Commands/RefreshCommand.php @@ -0,0 +1,3 @@ +namingStrategy = $namingStrategy; + } + + /** + * Get a naming strategy. + * + * @return \Viserio\Bridge\Doctrine\Contract\Migration\NamingStrategy + */ + public function getNamingStrategy(): NamingStrategyContract + { + return $this->namingStrategy; + } +} diff --git a/src/Viserio/Bridge/Doctrine/Migration/LICENSE b/src/Viserio/Bridge/Doctrine/Migration/LICENSE new file mode 100644 index 000000000..9941d8719 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Migration/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 - 2017 Narrowspark + +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. diff --git a/src/Viserio/Bridge/Doctrine/Migration/Naming/DefaultNamingStrategy.php b/src/Viserio/Bridge/Doctrine/Migration/Naming/DefaultNamingStrategy.php new file mode 100644 index 000000000..b5ae9030e --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Migration/Naming/DefaultNamingStrategy.php @@ -0,0 +1,38 @@ + [self::class, 'extendConsole'], + ]; + } + + /** + * Extend viserio console with commands. + * + * @param \Psr\Container\ContainerInterface $container + * @param null|\Viserio\Component\Console\Application $console + * + * @return null|\Viserio\Component\Console\Application + */ + public static function extendConsole( + ContainerInterface $container, + ?Application $console = null + ): ?Application { + if ($console !== null) { + $console->getHelperSet() + ->set(new ConfigurationHelper($container), 'connection'); + + $console->addCommands([ + new DiffCommand(), + new ExecuteCommand(), + new GenerateCommand(), + new MigrateCommand(), + new StatusCommand(), + new VersionCommand(), + ]); + } + + return $console; + } +} diff --git a/src/Viserio/Bridge/Doctrine/Migration/README.md b/src/Viserio/Bridge/Doctrine/Migration/README.md new file mode 100644 index 000000000..502a77dfb --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Migration/README.md @@ -0,0 +1,33 @@ +# Viserio Doctrine Migration package + +This package is part of the [Narrowspark framework](http://github.com/narrowspark/framework). + +[![Author](http://img.shields.io/badge/author-@anolilab-blue.svg?style=flat-square)](https://twitter.com/anolilab) +[![Quality Score](https://img.shields.io/scrutinizer/g/narrowspark/framework.svg?style=flat-square)](https://scrutinizer-ci.com/g/narrowspark/framework/code-structure/master) +[![Build Status](https://api.travis-ci.org/narrowspark/framework.svg?branch=master&style=flat-square)](https://travis-ci.org/narrowspark/framework) +[![Latest Version](https://img.shields.io/packagist/v/narrowspark/framework.svg?style=flat-square)](https://github.com/narrowspark/framework/releases) +[![Minimum PHP Version](https://img.shields.io/badge/php-%5E7.1.0-8892BF.svg?style=flat-square)](https://php.net/) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE) + +> **Note:** If you want to build an application using Narrowspark, visit the main [![Source Code](http://img.shields.io/badge/source-narrowspark/narrowspark-blue.svg?style=flat-square)](https://github.com/narrowspark/narrowspark). + +## Contributing + +Issues for this package shall be posted on [Narrowspark framework issues](http://github.com/narrowspark/framework/issues). +Thank you for considering contributing to the Narrowspark framework! The contribution guide can be found in the [Narrowspark documentation](http://narrowspark.de/docs/contributions). + +## Installation + +Use [Composer](https://getcomposer.org/) to install this package: + +```sh +composer require viserio/bridge/doctrine +``` + +## Official Documentation + +Documentation for the framework can be found on the [Narrowspark website](http://narrowspark.de/docs). + +### License + +The Narrowspark framework is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT). diff --git a/src/Viserio/Bridge/Doctrine/Migration/Tests/Provider/ConsoleCommandsServiceProviderTest.php b/src/Viserio/Bridge/Doctrine/Migration/Tests/Provider/ConsoleCommandsServiceProviderTest.php new file mode 100644 index 000000000..6ecac4a7f --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Migration/Tests/Provider/ConsoleCommandsServiceProviderTest.php @@ -0,0 +1,68 @@ +register(new ConsoleServiceProvider()); + $container->register(new DoctrineDBALServiceProvider()); + $container->register(new ConsoleCommandsServiceProvider()); + + $container->instance('config', [ + 'viserio' => [ + 'console' => [ + 'version' => '1', + ], + 'doctrine' => [ + 'dbal' => [ + 'default' => 'mysql', + 'connections' => [ + 'mysql' => [ + 'driver' => 'pdo_mysql', + 'host' => 'DB_HOST', + 'port' => 'DB_PORT', + 'database' => 'DB_DATABASE_NAME', + 'username' => 'DB_DATABASE_USER', + 'password' => 'DB_DATABASE_PASSWORD', + 'charset' => 'DB_CHARSET', 'UTF8', + 'driverOptions' => [1002 => 'SET NAMES utf8'], + ], + ], + ], + 'migrations' => [ + 'path' => __DIR__ . '/../Stub/', + 'namespace' => 'Database\\Migrations', + 'name' => 'migration', + 'table_name' => 'migration', + ], + ], + ], + ]); + + $console = $container->get(Application::class); + $commands = $console->all(); + + self::assertInstanceOf(DiffCommand::class, $commands['migrations:diff']); + self::assertInstanceOf(ExecuteCommand::class, $commands['migrations:execute']); + self::assertInstanceOf(GenerateCommand::class, $commands['migrations:generate']); + self::assertInstanceOf(MigrateCommand::class, $commands['migrations:migrate']); + self::assertInstanceOf(StatusCommand::class, $commands['migrations:status']); + self::assertInstanceOf(VersionCommand::class, $commands['migrations:version']); + } +} diff --git a/src/Viserio/Bridge/Doctrine/Migration/Tests/Stub/database.sqlite b/src/Viserio/Bridge/Doctrine/Migration/Tests/Stub/database.sqlite new file mode 100644 index 0000000000000000000000000000000000000000..ccbe3558eaa96c68890b860c5019aa03c9347b3f GIT binary patch literal 2048 zcmWFz^vNtqRY=P(%1ta$FlJz3U}R))P*7lCU|@n`AO!}DKoW#u0GSOFL#LS-bRWs_ z0!0~_w=e+FC>RZa(GZ|81iTp8#6?9JD@ziSa#BlDD@s6^$vMc?F~n6N#L>yeRY3_P zq@6 + + + + + + + + + + + ./Tests/ + + + + + + ./ + + ./vendor + ./Tests + + + + + diff --git a/src/Viserio/Bridge/Doctrine/ORM/.github/PULL_REQUEST_TEMPLATE.md b/src/Viserio/Bridge/Doctrine/ORM/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..3a1c85818 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,5 @@ +This is a READ ONLY repository. + +Please make your pull request to https://github.com/narrowspark/framework + +Thank you for contributing. diff --git a/src/Viserio/Bridge/Doctrine/ORM/AbstractTable.php b/src/Viserio/Bridge/Doctrine/ORM/AbstractTable.php new file mode 100644 index 000000000..f5f06dc2c --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/AbstractTable.php @@ -0,0 +1,86 @@ +table = $table; + } + + /** + * Build a new table. + * + * @return \Doctrine\DBAL\Schema\Table + */ + public function build(): Table + { + return new Table( + $this->table, + $this->getColumns(), + $this->getIndices() + ); + } + + /** + * Create a new table column. + * + * @param string $name + * @param string $type + * @param bool $autoincrement + * + * @return \Doctrine\DBAL\Schema\Column + */ + protected function createColumn(string $name, string $type, bool $autoincrement = false): Column + { + $column = new Column($name, Type::getType($type)); + $column->setAutoincrement($autoincrement); + + return $column; + } + + /** + * @param string $name + * @param array $columns + * @param bool $unique + * @param bool $primary + * + * @return \Doctrine\DBAL\Schema\Index + */ + protected function index( + string $name, + array $columns, + bool $unique = false, + bool $primary = false + ): Index { + return new Index($name, $columns, $unique, $primary); + } + + /** + * @return \Doctrine\DBAL\Schema\Column[] + */ + abstract protected function getColumns(): array; + + /** + * @return \Doctrine\DBAL\Schema\Index[] + */ + abstract protected function getIndices(): array; +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/Commands/AbstractDoctrineCommand.php b/src/Viserio/Bridge/Doctrine/ORM/Commands/AbstractDoctrineCommand.php new file mode 100644 index 000000000..291dcc437 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/Commands/AbstractDoctrineCommand.php @@ -0,0 +1,66 @@ +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 null|int $shardId + * + * @return \Doctrine\ORM\EntityManager + */ + protected function getEntityManager(string $name, ?int $shardId = null): EntityManager + { + $manager = $this->container->get('doctrine')->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 \Doctrine\DBAL\Connection + */ + protected function getDoctrineConnection(string $name): Connection + { + return $this->container->get('doctrine')->getConnection($name); + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/Commands/CreateDatabaseDoctrineCommand.php b/src/Viserio/Bridge/Doctrine/ORM/Commands/CreateDatabaseDoctrineCommand.php new file mode 100644 index 000000000..e69de29bb diff --git a/src/Viserio/Bridge/Doctrine/ORM/Commands/DropDatabaseDoctrineCommand.php b/src/Viserio/Bridge/Doctrine/ORM/Commands/DropDatabaseDoctrineCommand.php new file mode 100644 index 000000000..e69de29bb diff --git a/src/Viserio/Bridge/Doctrine/ORM/Commands/GenerateEntitiesDoctrineCommand.php b/src/Viserio/Bridge/Doctrine/ORM/Commands/GenerateEntitiesDoctrineCommand.php new file mode 100644 index 000000000..e69de29bb diff --git a/src/Viserio/Bridge/Doctrine/ORM/Commands/ImportMappingDoctrineCommand.php b/src/Viserio/Bridge/Doctrine/ORM/Commands/ImportMappingDoctrineCommand.php new file mode 100644 index 000000000..e69de29bb diff --git a/src/Viserio/Bridge/Doctrine/ORM/Commands/Proxies/ClearMetadataCacheDoctrineCommand.php b/src/Viserio/Bridge/Doctrine/ORM/Commands/Proxies/ClearMetadataCacheDoctrineCommand.php new file mode 100644 index 000000000..e69de29bb diff --git a/src/Viserio/Bridge/Doctrine/ORM/Configuration/CacheManager.php b/src/Viserio/Bridge/Doctrine/ORM/Configuration/CacheManager.php new file mode 100644 index 000000000..44caad266 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/Configuration/CacheManager.php @@ -0,0 +1,32 @@ + 'annotations', + 'drivers' => [ + 'fluent' => [ + 'mappings' => [], + ], + 'annotations' => [ + 'simple' => false, + 'paths' => [], + ], + ], + ]; + } + + /** + * {@inheritdoc} + */ + public static function getDimensions(): iterable + { + return ['viserio', 'doctrine', self::getConfigName()]; + } + + /** + * Create an instance of the annotation meta driver. + * + * @param array $config + * + * @return \Doctrine\ORM\Mapping\Driver\AnnotationDriver + */ + protected function createAnnotationsDriver(array $config): array + { + $configuration = new Configuration(); + + return [ + 'driver' => $configuration->newDefaultAnnotationDriver( + $config['paths'], + $config['simple'] + ), + 'meta_factory' => ClassMetadataFactory::class, + ]; + } + + /** + * Create an instance of the xml meta driver. + * + * @param array $config + * + * @return \Doctrine\ORM\Mapping\Driver\XmlDriver + */ + protected function createXmlDriver(array $config): array + { + return [ + 'driver' => new XmlDriver( + $config['paths'], + $config['extension'] ?? XmlDriver::DEFAULT_FILE_EXTENSION + ), + 'meta_factory' => ClassMetadataFactory::class, + ]; + } + + /** + * Create an instance of the yaml meta driver. + * + * @param array $config + * + * @return \Doctrine\ORM\Mapping\Driver\YamlDriver + */ + protected function createYamlDriver(array $config): array + { + return [ + 'driver' => new YamlDriver( + $config['paths'], + $config['extension'] ?? YamlDriver::DEFAULT_FILE_EXTENSION + ), + 'meta_factory' => ClassMetadataFactory::class, + ]; + } + + /** + * Create an instance of the simplified yaml meta driver. + * + * @param array $config + * + * @return \Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver + */ + protected function createSimplifiedYamlDriver(array $config): array + { + return [ + 'driver' => new SimplifiedYamlDriver( + $config['paths'], + $config['extension'] ?? SimplifiedYamlDriver::DEFAULT_FILE_EXTENSION + ), + 'meta_factory' => ClassMetadataFactory::class, + ]; + } + + /** + * Create an instance of the simplified xml meta driver. + * + * @param array $config + * + * @return \Doctrine\ORM\Mapping\Driver\SimplifiedXmlDriver + */ + protected function createSimplifiedXmlDriver(array $config): array + { + return [ + 'driver' => new SimplifiedXmlDriver( + $config['paths'], + $config['extension'] ?? SimplifiedXmlDriver::DEFAULT_FILE_EXTENSION + ), + 'meta_factory' => ClassMetadataFactory::class, + ]; + } + + /** + * Create an instance of the static php meta driver. + * + * @param array $config + * + * @return \Doctrine\Common\Persistence\Mapping\Driver\StaticPHPDriver + */ + protected function createStaticPhpDriver(array $config): array + { + return [ + 'driver' => new StaticPHPDriver($config['paths']), + 'meta_factory' => ClassMetadataFactory::class, + ]; + } + + /** + * Create an instance of the php meta driver. + * + * @param array $config + * + * @return \Doctrine\Common\Persistence\Mapping\Driver\PHPDriver + */ + protected function createPhpDriver(array $config): array + { + return [ + 'driver' => new PHPDriver($config['paths']), + 'meta_factory' => ClassMetadataFactory::class, + ]; + } + + /** + * Create an instance of the fluent meta driver. + * + * @param array $config + * + * @return \LaravelDoctrine\Fluent\FluentDriver + */ + protected function createFluentDriver(array $config): array + { + $driver = new FluentDriver($config['mappings']); + + $driver->setFluentFactory(function (ClassMetadataInfo $meta) { + return new Builder(new ClassMetadataBuilder($meta)); + }); + + return [ + 'driver' => $driver, + 'meta_factory' => ExtensibleClassMetadataFactory::class, + ]; + } + + /** + * {@inheritdoc} + */ + protected static function getConfigName(): string + { + return 'metadata'; + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/ConnectionFactory.php b/src/Viserio/Bridge/Doctrine/ORM/ConnectionFactory.php new file mode 100644 index 000000000..dfb012016 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/ConnectionFactory.php @@ -0,0 +1,105 @@ +typesConfig = $typesConfig; + } + + /** + * Create a connection by name. + * + * @param array $params + * @param \Doctrine\DBAL\Configuration $config + * @param \Doctrine\Common\EventManager $eventManager + * @param array $mappingTypes + * + * @return \Doctrine\DBAL\Connection + */ + public function createConnection( + array $params, + Configuration $config = null, + EventManager $eventManager = null, + array $mappingTypes = [] + ): Connection { + if (! $this->initialized) { + $this->initializeTypes(); + } + + $connection = DriverManager::getConnection($params, $config, $eventManager); + + if (! empty($mappingTypes)) { + $platform = $connection->getDatabasePlatform(); + + foreach ($mappingTypes as $dbType => $doctrineType) { + $platform->registerDoctrineTypeMapping($dbType, $doctrineType); + } + } + + if (! empty($this->commentedTypes)) { + $platform = $connection->getDatabasePlatform(); + + foreach ($this->commentedTypes as $type) { + $platform->markDoctrineTypeCommented(Type::getType($type)); + } + } + + return $connection; + } + + /** + * Initialize the types. + * + * @return void + */ + private function initializeTypes(): void + { + foreach ($this->typesConfig as $type => $typeConfig) { + if (Type::hasType($type)) { + Type::overrideType($type, $typeConfig['class']); + } else { + Type::addType($type, $typeConfig['class']); + } + + if ($typeConfig['commented']) { + $this->commentedTypes[] = $type; + } + } + + $this->initialized = true; + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/DataCollector/DoctrineDataCollector.php b/src/Viserio/Bridge/Doctrine/ORM/DataCollector/DoctrineDataCollector.php new file mode 100644 index 000000000..ec9fe8513 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/DataCollector/DoctrineDataCollector.php @@ -0,0 +1,365 @@ +registry = $registry; + $this->connections = $registry->getConnectionNames(); + $this->managers = $registry->getManagerNames(); + } + + /** + * {@inheritdoc} + */ + public function collect(ServerRequestInterface $serverRequest, ResponseInterface $response): void + { + $queries = []; + $errors = []; + $entities = []; + $caches = [ + 'enabled' => false, + 'log_enabled' => false, + 'counts' => [ + 'puts' => 0, + 'hits' => 0, + 'misses' => 0, + ], + 'regions' => [ + 'puts' => [], + 'hits' => [], + 'misses' => [], + ], + ]; + + foreach ($this->loggers as $name => $logger) { + $queries[$name] = $this->sanitizeQueries($name, $logger->queries); + } + + foreach ($this->registry->getManagers() as $name => $em) { + $entities[$name] = []; + + /** @var $factory \Doctrine\ORM\Mapping\ClassMetadataFactory */ + $factory = $em->getMetadataFactory(); + $validator = new SchemaValidator($em); + + /** @var $class \Doctrine\ORM\Mapping\ClassMetadataInfo */ + foreach ($factory->getLoadedMetadata() as $class) { + if (! isset($entities[$name][$class->getName()])) { + $classErrors = $validator->validateClass($class); + $entities[$name][$class->getName()] = $class->getName(); + + if (! empty($classErrors)) { + $errors[$name][$class->getName()] = $classErrors; + } + } + } + + /** @var $emConfig \Doctrine\ORM\Configuration */ + $emConfig = $em->getConfiguration(); + $slcEnabled = $emConfig->isSecondLevelCacheEnabled(); + + if (! $slcEnabled) { + continue; + } + + $caches['enabled'] = true; + + /** @var $cacheConfiguration \Doctrine\ORM\Cache\CacheConfiguration */ + /** @var $cacheLoggerChain \Doctrine\ORM\Cache\Logging\CacheLoggerChain */ + $cacheConfiguration = $emConfig->getSecondLevelCacheConfiguration(); + $cacheLoggerChain = $cacheConfiguration->getCacheLogger(); + + if (! $cacheLoggerChain || ! $cacheLoggerChain->getLogger('statistics')) { + continue; + } + + /** @var $cacheLoggerStats \Doctrine\ORM\Cache\Logging\StatisticsCacheLogger */ + $cacheLoggerStats = $cacheLoggerChain->getLogger('statistics'); + $caches['log_enabled'] = true; + $caches['counts']['puts'] += $cacheLoggerStats->getPutCount(); + $caches['counts']['hits'] += $cacheLoggerStats->getHitCount(); + $caches['counts']['misses'] += $cacheLoggerStats->getMissCount(); + + foreach ($cacheLoggerStats->getRegionsPut() as $key => $value) { + if (! isset($caches['regions']['puts'][$key])) { + $caches['regions']['puts'][$key] = 0; + } + + $caches['regions']['puts'][$key] += $value; + } + + foreach ($cacheLoggerStats->getRegionsHit() as $key => $value) { + if (! isset($caches['regions']['hits'][$key])) { + $caches['regions']['hits'][$key] = 0; + } + + $caches['regions']['hits'][$key] += $value; + } + + foreach ($cacheLoggerStats->getRegionsMiss() as $key => $value) { + if (! isset($caches['regions']['misses'][$key])) { + $caches['regions']['misses'][$key] = 0; + } + + $caches['regions']['misses'][$key] += $value; + } + } + + $this->data = [ + 'queries' => $queries, + 'connections' => $this->connections, + 'managers' => $this->managers, + 'entities' => $entities, + 'errors' => $errors, + 'caches' => $caches, + ]; + } + + /** + * Adds the stack logger for a connection. + * + * @param string $name + * @param \Doctrine\DBAL\Logging\DebugStack $logger + */ + public function addLogger(string $name, DebugStack $logger): void + { + $this->loggers[$name] = $logger; + } + + public function getInvalidEntityCount() + { + if (null === $this->invalidEntityCount) { + $this->invalidEntityCount = \array_sum(\array_map('\count', $this->data['errors'])); + } + + return $this->invalidEntityCount; + } + + /** + * {@inheritdoc} + */ + public function getMenu(): array + { + return []; + } + + /** + * {@inheritdoc} + */ + public function getTooltip(): string + { + return ''; + } + + /** + * {@inheritdoc} + */ + public function getPanel(): string + { + return ''; + } + + private function getQueryCount() + { + return array_sum(array_map('count', $this->data['queries'])); + } + + private function getTime() + { + $time = 0; + + foreach ($this->data['queries'] as $queries) { + foreach ($queries as $query) { + $time += $query['executionMS']; + } + } + + return $time; + } + + private function getGroupedQueryCount() + { + $count = 0; + + foreach ($this->getGroupedQueries() as $connectionGroupedQueries) { + $count += count($connectionGroupedQueries); + } + + return $count; + } + + private function getGroupedQueries() + { + static $groupedQueries = null; + + if ($groupedQueries !== null) { + return $groupedQueries; + } + + $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, function ($a, $b) { + if ($a['executionMS'] === $b['executionMS']) { + return 0; + } + + return ($a['executionMS'] < $b['executionMS']) ? 1 : -1; + }); + + $groupedQueries[$connection] = $connectionGroupedQueries; + } + + foreach ($groupedQueries as $connection => $queries) { + foreach ($queries as $i => $query) { + $groupedQueries[$connection][$i]['executionPercent'] = $this->executionTimePercentage($query['executionMS'], $totalExecutionMS); + } + } + + return $groupedQueries; + } + + private function sanitizeQueries(string $connectionName, array $queries): array + { + foreach ($queries as $i => $query) { + $queries[$i] = $this->sanitizeQuery($connectionName, $query); + } + + return $queries; + } + + private function sanitizeQuery(string $connectionName, array $query): array + { + $query['explainable'] = true; + + if (null === $query['params']) { + $query['params'] = []; + } + + if (! is_array($query['params'])) { + $query['params'] = [$query['params']]; + } + + foreach ($query['params'] as $j => $param) { + if (isset($query['types'][$j])) { + // Transform the param according to the type + $type = $query['types'][$j]; + + if (is_string($type)) { + $type = Type::getType($type); + } + + if ($type instanceof Type) { + $query['types'][$j] = $type->getBindingType(); + $param = $type->convertToDatabaseValue($param, $this->registry->getConnection($connectionName)->getDatabasePlatform()); + } + } + + [$query['params'][$j], $explainable] = $this->sanitizeParam($param); + + if (! $explainable) { + $query['explainable'] = false; + } + } + + return $query; + } + + /** + * Sanitizes a param. + * + * The return value is an array with the sanitized value and a boolean + * indicating if the original value was kept (allowing to use the sanitized + * value to explain the query). + * + * @param mixed $var + * + * @return array + */ + private function sanitizeParam($var): array + { + if (is_object($var)) { + $className = get_class($var); + + return method_exists($var, '__toString') ? + [sprintf('Object(%s): "%s"', $className, $var->__toString()), false] : + [sprintf('Object(%s)', $className), false]; + } + + if (is_array($var)) { + $a = []; + $original = true; + + foreach ($var as $k => $v) { + [$value, $orig] = $this->sanitizeParam($v); + $original = $original && $orig; + $a[$k] = $value; + } + + return [$a, $original]; + } + + if (is_resource($var)) { + return [sprintf('Resource(%s)', get_resource_type($var)), false]; + } + + return [$var, true]; + } + + private function executionTimePercentage($executionTimeMS, $totalExecutionTimeMS) + { + if ($totalExecutionTimeMS === 0.0 || $totalExecutionTimeMS === 0) { + return 0; + } + + return $executionTimeMS / $totalExecutionTimeMS * 100; + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/EntityManagerFactory.php b/src/Viserio/Bridge/Doctrine/ORM/EntityManagerFactory.php new file mode 100644 index 000000000..436915be4 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/EntityManagerFactory.php @@ -0,0 +1,408 @@ +container = $container; + $this->setup = $setup; + $this->meta = $meta; + $this->cache = $cache; + $this->resolver = $resolver; + } + + /** + * {@inheritdoc} + */ + public static function getDimensions(): iterable + { + return ['viserio', 'doctrine', 'orm']; + } + + /** + * {@inheritdoc} + */ + public static function getDefaultOptions(): iterable + { + return [ + 'logger' => false, + 'cache' => [ + 'default' => 'array', + ], + 'events' => [ + 'listners' => false, + 'subscribers' => false, + ], + 'proxies' => [ + // Auto generate mode possible values are: "NEVER", "ALWAYS", "FILE_NOT_EXISTS", "FILE_OUTDATED", "EVAL" + 'auto_generate' => false, + 'namespace' => false, + ], + 'second_level_cache' => false, + 'repository' => EntityRepository::class, + 'dql' => [ + 'datetime_functions' => [], + 'numeric_functions' => [], + 'string_functions' => [], + ], + 'filters' => false, + 'mapping_types' => [], + ]; + } + + /** + * {@inheritdoc} + */ + public static function getMandatoryOptions(): iterable + { + return [ + 'connections' => [ + 'default', + ], + 'proxies' => [ + 'path', + ], + ]; + } + + /** + * Create a new entity manager. + * + * @param string $id + * + * @return \Doctrine\ORM\EntityManagerInterface + */ + public function create(string $id): EntityManagerInterface + { + $this->configureOptions($this->container, $id); + + $configuration = $this->setup->createConfiguration( + $this->options['env'] === 'develop', + $this->options['proxies']['path'], + $this->cache->getDriver($this->options['cache']['default']) + ); + + $configuration = $this->setMetadataDriver($configuration); + $configuration = $this->configureCustomFunctions($configuration); + $configuration = $this->configureFirstLevelCacheSettings($configuration); + $configuration = $this->configureProxy($configuration); + + $configuration->setDefaultRepositoryClassName($this->options['repository']); + $configuration->setEntityListenerResolver($this->resolver); + $connection = new ConnectionFactory($this->options['']); + + $manager = EntityManager::create( + $connection->createConnection( + $this->mapConnectionKey($this->options['connections']['default']), + $configuration, + null, + $this->options['mapping_types'] + ), + $configuration + ); + + $this->registerLogger($manager, $configuration); + $this->registerListeners($manager); + $this->registerSubscribers($manager); + $this->registerFilters($configuration, $manager); + + return $manager; + } + + /** + * Register a logger. + * + * @param \Doctrine\ORM\EntityManagerInterface $em + * @param \Doctrine\ORM\Configuration $configuration + */ + protected function registerLogger(EntityManagerInterface $em, Configuration $configuration): void + { + if (($loggerClass = $this->options['logger']) !== false) { + $logger = $this->container->get($loggerClass); + $logger->register($em, $configuration); + } + } + + /** + * Configure custom functions. + * + * @param \Doctrine\ORM\Configuration $configuration + * + * @return \Doctrine\ORM\Configuration + */ + protected function configureCustomFunctions(Configuration $configuration): Configuration + { + $configuration->setCustomDatetimeFunctions($this->options['dql']['datetime_functions']); + $configuration->setCustomNumericFunctions($this->options['dql']['numeric_functions']); + $configuration->setCustomStringFunctions($this->options['dql']['string_functions']); + + return $configuration; + } + + /** + * Configure first level cache. + * + * @param \Doctrine\ORM\Configuration $configuration + * + * @return \Doctrine\ORM\Configuration + */ + protected function configureFirstLevelCacheSettings(Configuration $configuration): Configuration + { + $cache = $this->cache; + + $configuration->setQueryCacheImpl($cache->getDriver($this->options['query_cache_driver'])); + $configuration->setResultCacheImpl($cache->getDriver($this->options['result_cache_driver'])); + $configuration->setMetadataCacheImpl($cache->getDriver($this->options['metadata_cache_driver'])); + + $configuration = $this->setSecondLevelCaching($configuration); + + return $configuration; + } + + /** + * Configure second level cache. + * + * @param \Doctrine\ORM\Configuration $configuration + * + * @return \Doctrine\ORM\Configuration + */ + protected function setSecondLevelCaching(Configuration $configuration): Configuration + { + $secondCacheSetting = $this->options['second_level_cache']; + + if (is_array($secondCacheSetting)) { + $configuration->setSecondLevelCacheEnabled(); + + $cacheConfig = $configuration->getSecondLevelCacheConfiguration(); + // $cacheConfig->setCacheLogger($logger); + $cacheConfig->setCacheFactory( + new DefaultCacheFactory( + $cacheConfig->getRegionsConfiguration(), + $this->cache->getDriver($secondCacheSetting['region_cache_driver'] ?? null) + ) + ); + } + + return $configuration; + } + + /** + * Configure proxies. + * + * @param \Doctrine\ORM\Configuration $configuration + * + * @return \Doctrine\ORM\Configuration + */ + protected function configureProxy(Configuration $configuration): Configuration + { + $configuration->setProxyDir( + $this->options['proxies']['path'] + ); + + $configuration->setAutoGenerateProxyClasses( + $this->options['proxies']['auto_generate'] + ); + + if ($namespace = $this->options['proxies']['namespace']) { + $configuration->setProxyNamespace($namespace); + } + } + + /** + * Decorate a entity manager. + * + * @param \Doctrine\ORM\EntityManagerInterface $manager + * + * @return \Doctrine\ORM\EntityManagerInterface + */ + protected function decorateManager(EntityManagerInterface $manager): EntityManagerInterface + { + if ($decorator = $this->options['decorator']) { + if (! class_exists($decorator)) { + throw new InvalidArgumentException(sprintf('EntityManagerDecorator [%s] does not exist', $decorator)); + } + + $manager = new $decorator($manager); + } + + return $manager; + } + + /** + * Register event listeners. + * + * @param \Doctrine\ORM\EntityManagerInterface $manager + * + * @return void + */ + protected function registerListeners(EntityManagerInterface $manager): void + { + $eventManager = $manager->getEventManager(); + + if ($listeners = $this->options['events']['listeners'] !== false) { + foreach ($listeners as $event => $listener) { + if (is_array($listener)) { + foreach ($listener as $individualListener) { + $resolvedListener = $this->container->get($listener); + + $eventManager->addEventListener($event, $resolvedListener); + } + } else { + $resolvedListener = $this->container->get($listener); + + $eventManager->addEventListener($event, $resolvedListener); + } + } + } + } + + /** + * Register event subscribers. + * + * @param \Doctrine\ORM\EntityManagerInterface $manager + * + * @return void + */ + protected function registerSubscribers(EntityManagerInterface $manager): void + { + if ($subscribers = $settings['events']['subscribers'] !== false) { + foreach ($subscribers as $subscriber) { + $resolvedSubscriber = $this->container->get($subscriber); + $manager->getEventManager()->addEventSubscriber($resolvedSubscriber); + } + } + } + + /** + * Set a metadata driver to doctrine. + * + * @param \Doctrine\ORM\Configuration $configuration + * + * @return \Doctrine\ORM\Configuration + */ + protected function setMetadataDriver(Configuration $configuration): Configuration + { + $metadata = $this->meta->getDriver($this->options['metadata']['default']); + + $configuration->setMetadataDriverImpl($metadata['driver']); + $configuration->setClassMetadataFactoryName($metadata['meta_factory']); + + return $configuration; + } + + /** + * Register filters. + * + * @param \Doctrine\ORM\Configuration $configuration + * @param \Doctrine\ORM\EntityManagerInterface $manager + */ + protected function registerFilters(Configuration $configuration, EntityManagerInterface $manager): void + { + if ($filters = $this->options['filters'] !== false) { + foreach ($filters as $name => $filter) { + $configuration->addFilter($name, $filter); + $manager->getFilters()->enable($name); + } + } + } + + /** + * {@inheritdoc} + */ + protected function getConfigClass(): RequiresConfigContract + { + return $this; + } + + /** + * Map our config style to the dortrine config style. + * + * @param array $configs + * + * @return array + */ + private static function mapConnectionKey(array $configs): array + { + $mapList = [ + 'dbname' => 'database', + 'user' => 'username', + ]; + + foreach ($mapList as $newKey => $oldKey) { + if ($configs[$oldKey]) { + $arr[$newKey] = $arr[$oldKey]; + unset($arr[$oldKey]); + } + } + + return $configs; + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/Exceptions/ExtensionNotFoundException.php b/src/Viserio/Bridge/Doctrine/ORM/Exceptions/ExtensionNotFoundException.php new file mode 100644 index 000000000..efa353144 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/Exceptions/ExtensionNotFoundException.php @@ -0,0 +1,9 @@ +container = $container; + $this->factory = $factory; + } + + /** + * Set a default manager. + * + * @param string $defaultManager + * + * @return void + */ + public function setDefaultManager(string $defaultManager): void + { + $this->defaultManager = $defaultManager; + } + + /** + * Add a new manager instance. + * + * @param string $manager + * @param array $settings + * + * @return void + */ + public function addManager(string $manager, array $settings = []): void + { + $this->container->singleton($this->getManagerBindingName($manager), function () use ($settings) { + return $this->factory->create($settings); + }); + + $this->managers[$manager] = $manager; + + $this->addConnection($manager, $settings); + } + + /** + * {@inheritdoc} + */ + public function getDefaultManagerName(): string + { + if (isset($this->managers[$this->defaultManager])) { + return $this->defaultManager; + } + + return head($this->managers); + } + + /** + * {@inheritdoc} + */ + public function getManager($name = null): ObjectManager + { + $name = $name ?? $this->getDefaultManagerName(); + + if (! $this->hasManager($name)) { + throw new InvalidArgumentException(sprintf('Doctrine Manager named [%s] does not exist.', $name)); + } + + if (isset($this->managersMap[$name])) { + return $this->managersMap[$name]; + } + + return $this->managersMap[$name] = $this->getService( + $this->getManagerBindingName($this->managers[$name]) + ); + } + + /** + * Check if a manager exists. + * + * @param string $name + * + * @return bool + */ + public function hasManager(string $name): bool + { + return isset($this->managers[$name]); + } + + /** + * {@inheritdoc} + */ + public function getManagerNames(): array + { + return $this->managers; + } + + /** + * {@inheritdoc} + */ + public function getManagers(): array + { + $managers = []; + + foreach ($this->getManagerNames() as $name) { + $managers[$name] = $this->getManager($name); + } + + return $managers; + } + + /** + * {@inheritdoc} + */ + public function resetManager($name = null): ObjectManager + { + $name = $name ?? $this->getDefaultManagerName(); + + if (! $this->hasManager($name)) { + throw new InvalidArgumentException(sprintf('Doctrine Manager named [%s] does not exist.', $name)); + } + + // force the creation of a new document manager + // if the current one is closed + $this->resetService( + $this->getManagerBindingName($this->managers[$name]) + ); + + $this->resetService( + $this->getConnectionBindingName($this->connections[$name]) + ); + + unset($this->managersMap[$name], $this->connectionsMap[$name]); + } + + /** + * {@inheritdoc} + */ + public function getAliasNamespace($alias): string + { + foreach ($this->getManagerNames() as $name) { + try { + return $this->getManager($name)->getConfiguration()->getEntityNamespace($alias); + } catch (ORMException $e) { + } + } + + throw ORMException::unknownEntityNamespace($alias); + } + + /** + * {@inheritdoc} + */ + public function getRepository($persistentObject, $persistentManagerName = null): ObjectRepository + { + return $this->getManager($persistentManagerName)->getRepository($persistentObject); + } + + /** + * {@inheritdoc} + */ + public function getManagerForClass($class): ?ObjectManager + { + // Check for namespace alias + if (mb_strpos($class, ':') !== false) { + [$namespaceAlias, $simpleClassName] = explode(':', $class, 2); + $class = $this->getAliasNamespace($namespaceAlias) . '\\' . $simpleClassName; + } + + $proxyClass = new ReflectionClass($class); + + if ($proxyClass->implementsInterface(Proxy::class)) { + $class = $proxyClass->getParentClass()->getName(); + } + + foreach ($this->getManagerNames() as $name) { + $manager = $this->getManager($name); + + if (! $manager->getMetadataFactory()->isTransient($class)) { + foreach ($manager->getMetadataFactory()->getAllMetadata() as $metadata) { + if ($metadata->getName() === $class) { + return $manager; + } + } + } + } + } + + /** + * Set a default connection. + * + * @param string $defaultConnection + * + * @return void + */ + public function setDefaultConnection(string $defaultConnection): void + { + $this->defaultConnection = $defaultConnection; + } + + /** + * Add a new connection. + * + * @param object|string $connection + * @param array $settings + * + * @return void + */ + public function addConnection($connection, array $settings = []): void + { + $this->container->singleton($this->getConnectionBindingName($connection), function () use ($connection) { + return $this->getManager($connection)->getConnection(); + }); + + $this->connections[$connection] = $connection; + } + + /** + * {@inheritdoc} + */ + public function getDefaultConnectionName(): string + { + if (isset($this->connections[$this->defaultConnection])) { + return $this->defaultConnection; + } + + return reset($this->connections); + } + + /** + * {@inheritdoc} + */ + public function getConnection($name = null) + { + $name = $name ?? $this->getDefaultConnectionName(); + + if (! $this->hasConnection($name)) { + throw new InvalidArgumentException(sprintf('Doctrine Connection named [%s] does not exist.', $name)); + } + + if (isset($this->connectionsMap[$name])) { + return $this->connectionsMap[$name]; + } + + return $this->connectionsMap[$name] = $this->getService( + $this->getConnectionBindingName($this->connections[$name]) + ); + } + + /** + * Check if a connection exists. + * + * @param string $name + * + * @return bool + */ + public function hasConnection(string $name): bool + { + return isset($this->connections[$name]); + } + + /** + * {@inheritdoc} + */ + public function getConnections(): array + { + $connections = []; + + foreach ($this->connections as $name) { + $connections[$name] = $this->getConnection($name); + } + + return $connections; + } + + /** + * {@inheritdoc} + */ + public function getConnectionNames(): array + { + return $this->connections; + } + + /** + * Prefix a manager name. + * + * @param string $manager + * + * @return string + */ + protected function getManagerBindingName(string $manager): string + { + return self::MANAGER_BINDING_PREFIX . $manager; + } + + /** + * Prefix a connection name. + * + * @param $connection + * + * @return string + */ + protected function getConnectionBindingName(string $connection): string + { + return self::CONNECTION_BINDING_PREFIX . $connection; + } + + /** + * {@inheritdoc} + */ + protected function getService($name) + { + return $this->container->get($name); + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/Middleware/SubstituteBindings.php b/src/Viserio/Bridge/Doctrine/ORM/Middleware/SubstituteBindings.php new file mode 100644 index 000000000..e69de29bb diff --git a/src/Viserio/Bridge/Doctrine/ORM/Pagination/PaginatorAdapter.php b/src/Viserio/Bridge/Doctrine/ORM/Pagination/PaginatorAdapter.php new file mode 100644 index 000000000..caa0fe624 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/Pagination/PaginatorAdapter.php @@ -0,0 +1,46 @@ +query = $query; + $this->perPage = $perPage; + $this->pageResolver = $pageResolver; + $this->fetchJoinCollection = $fetchJoinCollection; + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/Provider/ConsoleCommandsServiceProvider.php b/src/Viserio/Bridge/Doctrine/ORM/Provider/ConsoleCommandsServiceProvider.php new file mode 100644 index 000000000..42ae86e81 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/Provider/ConsoleCommandsServiceProvider.php @@ -0,0 +1,88 @@ + [self::class, 'extendConsole'], + ]; + } + + /** + * Extend viserio console with commands. + * + * @param \Psr\Container\ContainerInterface $container + * @param null|\Viserio\Component\Console\Application $console + * + * @return null|\Viserio\Component\Console\Application + */ + public static function extendConsole( + ContainerInterface $container, + ?Application $console = null + ): ?Application { + if ($console !== null) { + $manager = $container->get(EntityManagerInterface::class); + + $console->getHelperSet()->set(new ConnectionHelper($manager->getConnection()), 'db'); + $console->getHelperSet()->set(new EntityManagerHelper($manager), 'em'); + + $console->addCommands([ + new MetadataCommand(), + new ResultCommand(), + new QueryCommand(), + new CreateCommand(), + new UpdateCommand(), + new DropCommand(), + new EnsureProductionSettingsCommand(), + new ConvertDoctrine1SchemaCommand(), + new GenerateRepositoriesCommand(), + new GenerateEntitiesCommand(), + new ConvertMappingCommand(), + new RunDqlCommand(), + new ValidateSchemaCommand(), + new InfoCommand(), + new MappingDescribeCommand(), + ]); + + return $console; + } + + return null; + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/Provider/DoctrineORMQueueJobServiceProvider.php b/src/Viserio/Bridge/Doctrine/ORM/Provider/DoctrineORMQueueJobServiceProvider.php new file mode 100644 index 000000000..2a2c412c4 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/Provider/DoctrineORMQueueJobServiceProvider.php @@ -0,0 +1,17 @@ + [self::class, 'createManagerRegistry'], + ManagerRegistry::class => function (ContainerInterface $container) { + return $container->get(DoctrineManagerRegistry::class); + }, + 'registry' => function (ContainerInterface $container) { + return $container->get(DoctrineManagerRegistry::class); + }, + EntityManagerInterface::class => [self::class, 'createEntityManager'], + EntityManager::class => function (ContainerInterface $container) { + return $container->get(EntityManagerInterface::class); + }, + 'em' => function (ContainerInterface $container) { + return $container->get(EntityManagerInterface::class); + }, + ]; + } + + public static function createManagerRegistry(ContainerInterface $container): DoctrineManagerRegistry + { + $registery = new ManagerRegistry($container, $container->get(EntityManagerFactory::class)); + + return $registery; + } + + public static function createEntityManager(ContainerInterface $container): EntityManagerInterface + { + return $container->get(DoctrineManagerRegistry::class)->getManager(); + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/Proxy/Doctrine.php b/src/Viserio/Bridge/Doctrine/ORM/Proxy/Doctrine.php new file mode 100644 index 000000000..e0c9e5fce --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/Proxy/Doctrine.php @@ -0,0 +1,19 @@ +createColumn('id', 'integer', true), + $this->createColumn('connection', 'string'), + $this->createColumn('queue', 'string'), + $this->createColumn('payload', 'text'), + $this->createColumn('failed_at', 'datetime'), + $this->createColumn('exception', 'text')->setNotnull(false), + ]; + } + + /** + * {@inheritdoc} + */ + protected function getIndices(): array + { + return [ + $this->index('pk', ['id'], true, true), + ]; + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/README.md b/src/Viserio/Bridge/Doctrine/ORM/README.md new file mode 100644 index 000000000..38cc24f0d --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/README.md @@ -0,0 +1,33 @@ +# Viserio Doctrine ORM package + +This package is part of the [Narrowspark framework](http://github.com/narrowspark/framework). + +[![Author](http://img.shields.io/badge/author-@anolilab-blue.svg?style=flat-square)](https://twitter.com/anolilab) +[![Quality Score](https://img.shields.io/scrutinizer/g/narrowspark/framework.svg?style=flat-square)](https://scrutinizer-ci.com/g/narrowspark/framework/code-structure/master) +[![Build Status](https://api.travis-ci.org/narrowspark/framework.svg?branch=master&style=flat-square)](https://travis-ci.org/narrowspark/framework) +[![Latest Version](https://img.shields.io/packagist/v/narrowspark/framework.svg?style=flat-square)](https://github.com/narrowspark/framework/releases) +[![Minimum PHP Version](https://img.shields.io/badge/php-%5E7.1.0-8892BF.svg?style=flat-square)](https://php.net/) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE) + +> **Note:** If you want to build an application using Narrowspark, visit the main [![Source Code](http://img.shields.io/badge/source-narrowspark/narrowspark-blue.svg?style=flat-square)](https://github.com/narrowspark/narrowspark). + +## Contributing + +Issues for this package shall be posted on [Narrowspark framework issues](http://github.com/narrowspark/framework/issues). +Thank you for considering contributing to the Narrowspark framework! The contribution guide can be found in the [Narrowspark documentation](http://narrowspark.de/docs/contributions). + +## Installation + +Use [Composer](https://getcomposer.org/) to install this package: + +```sh +composer require viserio/bridge/doctrine +``` + +## Official Documentation + +Documentation for the framework can be found on the [Narrowspark website](http://narrowspark.de/docs). + +### License + +The Narrowspark framework is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT). diff --git a/src/Viserio/Bridge/Doctrine/ORM/Resolvers/EntityListenerResolver.php b/src/Viserio/Bridge/Doctrine/ORM/Resolvers/EntityListenerResolver.php new file mode 100644 index 000000000..6066551f3 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/Resolvers/EntityListenerResolver.php @@ -0,0 +1,68 @@ +container = $container; + } + + /** + * {@inheritdoc} + */ + public function clear($className = null): void + { + if ($className) { + unset($this->instances[$className = trim($className, '\\')]); + + return; + } + + $this->instances = []; + } + + /** + * {@inheritdoc} + */ + public function resolve($className) + { + if (isset($this->instances[$className = trim($className, '\\')])) { + return $this->instances[$className]; + } + + return $this->instances[$className] = $this->container->get($className); + } + + /** + * {@inheritdoc} + */ + public function register($object): void + { + if (! is_object($object)) { + throw new InvalidArgumentException(sprintf('An object was expected, but got "%s".', gettype($object))); + } + + $this->instances[get_class($object)] = $object; + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/Serializers/ArrayEncoder.php b/src/Viserio/Bridge/Doctrine/ORM/Serializers/ArrayEncoder.php new file mode 100644 index 000000000..9f0865f07 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/Serializers/ArrayEncoder.php @@ -0,0 +1,43 @@ + new ArrayEncoder(), + ] + ); + + return $serializer->serialize($this, 'array'); + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/ClassAliasesTest.php b/src/Viserio/Bridge/Doctrine/ORM/Tests/ClassAliasesTest.php new file mode 100644 index 000000000..2d6c371a7 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/Tests/ClassAliasesTest.php @@ -0,0 +1,18 @@ + [ + 'viserio' => [ + 'doctrine' => [ + 'cache' => [ + 'drivers' => [], + 'namespace' => false, + ], + ], + ], + ], + ]) + ); + + self::assertInstanceOf(DoctrineCacheBridge::class, $manager->getDriver('array')); + self::assertInstanceOf(DoctrineCacheBridge::class, $manager->getDriver()); + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/Configuration/MetaDataManagerTest.php b/src/Viserio/Bridge/Doctrine/ORM/Tests/Configuration/MetaDataManagerTest.php new file mode 100644 index 000000000..ccac98ea2 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/Tests/Configuration/MetaDataManagerTest.php @@ -0,0 +1,83 @@ + [ + 'doctrine' => [ + 'metadata' => [ + 'drivers' => [ + ], + ], + ], + ], + ] + ); + + $driver = $manager->getDriver(); + self::assertInstanceOf(AnnotationDriver::class, $driver['driver']); + self::assertSame(ClassMetadataFactory::class, $driver['meta_factory']); + + $driver = $manager->getDriver('annotations'); + + self::assertInstanceOf(AnnotationDriver::class, $driver['driver']); + self::assertSame(ClassMetadataFactory::class, $driver['meta_factory']); + } + + /** + * @dataProvider metaDriverProvider + * + * @param mixed $driverClass + * @param mixed $driverName + * @param mixed $driverInfos + * @param array $config + */ + public function testMetaDataDriver(array $config, $driverInfos, $driverName): void + { + $manager = new MetaDataManager( + [ + 'viserio' => [ + 'doctrine' => [ + 'metadata' => $config, + ], + ], + ] + ); + + $driver = $manager->getDriver($driverName); + + self::assertInstanceOf($driverInfos['driver'], $driver['driver']); + self::assertSame($driverInfos['meta_factory'], $driver['meta_factory']); + } + + public function metaDriverProvider() + { + return [ + [['default' => 'xml', 'drivers' => ['xml' => ['paths' => [__DIR__]]]], ['driver' => XmlDriver::class, 'meta_factory' => ClassMetadataFactory::class], 'xml'], + [['default' => 'yaml', 'drivers' => ['yaml' => ['paths' => [__DIR__]]]], ['driver' => YamlDriver::class, 'meta_factory' => ClassMetadataFactory::class], 'yaml'], + [['default' => 'simplified_yaml', 'drivers' => ['simplified_yaml' => ['paths' => [__DIR__]]]], ['driver' => SimplifiedYamlDriver::class, 'meta_factory' => ClassMetadataFactory::class], 'simplified_yaml'], + [['default' => 'simplified_xml', 'drivers' => ['simplified_xml' => ['paths' => [__DIR__]]]], ['driver' => SimplifiedXmlDriver::class, 'meta_factory' => ClassMetadataFactory::class], 'simplified_xml'], + [['default' => 'static_php', 'drivers' => ['static_php' => ['paths' => [__DIR__]]]], ['driver' => StaticPHPDriver::class, 'meta_factory' => ClassMetadataFactory::class], 'static_php'], + [['default' => 'php', 'drivers' => ['php' => ['paths' => [__DIR__]]]], ['driver' => PHPDriver::class, 'meta_factory' => ClassMetadataFactory::class], 'php'], + [['default' => 'fluent', 'drivers' => ['fluent' => ['paths' => [__DIR__]]]], ['driver' => FluentDriver::class, 'meta_factory' => ExtensibleClassMetadataFactory::class], 'fluent'], + ]; + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/EntityManagerFactoryTest.php b/src/Viserio/Bridge/Doctrine/ORM/Tests/EntityManagerFactoryTest.php new file mode 100644 index 000000000..e69de29bb diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/Fixtures/ArrayableEntityFixture.php b/src/Viserio/Bridge/Doctrine/ORM/Tests/Fixtures/ArrayableEntityFixture.php new file mode 100644 index 000000000..b288949a1 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/Tests/Fixtures/ArrayableEntityFixture.php @@ -0,0 +1,23 @@ +id; + } + + public function getName() + { + return $this->name; + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/ManagerRegistryTest.php b/src/Viserio/Bridge/Doctrine/ORM/Tests/ManagerRegistryTest.php new file mode 100644 index 000000000..a400551be --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/Tests/ManagerRegistryTest.php @@ -0,0 +1,48 @@ +container = $this->mock(ContainerInterface::class); + $this->factory = $this->mock(EntityManagerFactory::class); + + $this->registry = new ManagerRegistry( + $this->container, + $this->factory + ); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Doctrine Connection named [non-existing] does not exist. + */ + public function testCannotNonExistingConnection(): void + { + $this->registry->getConnection('non-existing'); + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/Provider/ConsoleCommandsServiceProviderTest.php b/src/Viserio/Bridge/Doctrine/ORM/Tests/Provider/ConsoleCommandsServiceProviderTest.php new file mode 100644 index 000000000..b8761d3dd --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/Tests/Provider/ConsoleCommandsServiceProviderTest.php @@ -0,0 +1,66 @@ +mock(EntityManagerInterface::class); + $entityManager->shouldReceive('getConnection') + ->once() + ->andReturn($this->mock(Connection::class)); + $container = new Container(); + $container->instance(EntityManagerInterface::class, $entityManager); + $container->register(new ConsoleServiceProvider()); + $container->register(new ConsoleCommandsServiceProvider()); + + $container->instance('config', [ + 'viserio' => [ + 'console' => [ + 'version' => '1', + ], + ], + ]); + + $console = $container->get(Application::class); + $commands = $console->all(); + + self::assertInstanceOf(MetadataCommand::class, $commands['orm:clear-cache:metadata']); + self::assertInstanceOf(QueryCommand::class, $commands['orm:clear-cache:query']); + self::assertInstanceOf(ResultCommand::class, $commands['orm:clear-cache:result']); + self::assertInstanceOf(ConvertDoctrine1SchemaCommand::class, $commands['orm:convert-d1-schema']); + self::assertInstanceOf(ConvertMappingCommand::class, $commands['orm:convert-mapping']); + self::assertInstanceOf(EnsureProductionSettingsCommand::class, $commands['orm:ensure-production-settings']); + self::assertInstanceOf(GenerateRepositoriesCommand::class, $commands['orm:generate-repositories']); + self::assertInstanceOf(InfoCommand::class, $commands['orm:info']); + self::assertInstanceOf(MappingDescribeCommand::class, $commands['orm:mapping:describe']); + self::assertInstanceOf(RunDqlCommand::class, $commands['orm:run-dql']); + self::assertInstanceOf(CreateCommand::class, $commands['orm:schema-tool:create']); + self::assertInstanceOf(DropCommand::class, $commands['orm:schema-tool:drop']); + self::assertInstanceOf(UpdateCommand::class, $commands['orm:schema-tool:update']); + self::assertInstanceOf(ValidateSchemaCommand::class, $commands['orm:validate-schema']); + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/Provider/DoctrineORMServiceProviderTest.php b/src/Viserio/Bridge/Doctrine/ORM/Tests/Provider/DoctrineORMServiceProviderTest.php new file mode 100644 index 000000000..05dad5c49 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/Tests/Provider/DoctrineORMServiceProviderTest.php @@ -0,0 +1,16 @@ +register(new OptionsResolverServiceProvider()); +// } +// } diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/Resolvers/EntityListenerResolverTest.php b/src/Viserio/Bridge/Doctrine/ORM/Tests/Resolvers/EntityListenerResolverTest.php new file mode 100644 index 000000000..2dc4bd101 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/Tests/Resolvers/EntityListenerResolverTest.php @@ -0,0 +1,128 @@ +assertInstanceOf( + ResolverContract::class, + new EntityListenerResolver($this->mock(ContainerInterface::class)) + ); + } + + public function testResolvesFromContainer(): void + { + $object = new stdClass(); + + $container = $this->mock(ContainerInterface::class); + $container->shouldReceive('get') + ->with('class') + ->andReturn($object); + $resolver = new EntityListenerResolver($container); + + $resolvedObject = $resolver->resolve('class'); + + $this->assertSame($object, $resolvedObject, 'Resolver should retrieve the object from the container.'); + } + + public function testHoldsReferenceAfterResolve(): void + { + $object = new stdClass(); + $anotherObject = new stdClass(); + + $container = $this->mock(ContainerInterface::class); + $container->shouldReceive('get') + ->with('class') + ->once() + ->andReturn($object, $anotherObject); + + $resolver = new EntityListenerResolver($container); + + $resolvedObject = $resolver->resolve('class'); + $resolvedObjectAgain = $resolver->resolve('class'); + + $this->assertSame($object, $resolvedObject, 'Resolver should retrieve the object from the container.'); + $this->assertSame($object, $resolvedObjectAgain, 'Resolver should retrieve the object from its own reference.'); + } + + public function testClearsHeldReference(): void + { + $object = new stdClass(); + $anotherObject = new stdClass(); + + $container = $this->mock(ContainerInterface::class); + $container->shouldReceive('get') + ->with('class') + ->twice() + ->andReturn($object, $anotherObject); + + $resolver = new EntityListenerResolver($container); + $resolver->resolve('class'); + $resolver->clear('class'); + + $resolvedObjectAgain = $resolver->resolve('class'); + + $this->assertSame($anotherObject, $resolvedObjectAgain, 'Resolver should got back to container after clear'); + } + + public function testClearsAllHeldReferences(): void + { + $object = new stdClass(); + $anotherObject = new stdClass(); + $oneMoreObject = new stdClass(); + $yetAnotherObject = new stdClass(); + + $container = $this->mock(ContainerInterface::class); + $container->shouldReceive('get') + ->with('class') + ->twice() + ->andReturn($object, $anotherObject); + $container->shouldReceive('get') + ->with('class2') + ->twice() + ->andReturn($oneMoreObject, $yetAnotherObject); + + $resolver = new EntityListenerResolver($container); + $resolver->resolve('class'); + $resolver->resolve('class2'); + $resolver->clear(); + + $resolvedAnotherObject = $resolver->resolve('class'); + $resolvedYetAnotherObject = $resolver->resolve('class2'); + + $this->assertSame($anotherObject, $resolvedAnotherObject, 'Resolver should retrieve the object from the container.'); + $this->assertSame($yetAnotherObject, $resolvedYetAnotherObject, 'Resolver should retrieve the object from the container.'); + } + + public function testAllowsDirectlyRegisteringListeners(): void + { + $object = new stdClass(); + + $container = $this->mock(ContainerInterface::class); + $resolver = new EntityListenerResolver($container); + $resolver->register($object); + + $resolvedObject = $resolver->resolve(get_class($object)); + + $this->assertSame($object, $resolvedObject, 'Resolver should not use container when directly registering'); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage An object was expected, but got "string". + */ + public function testDoesNotAllowRegisteringNonObjects(): void + { + $container = $this->mock(ContainerInterface::class); + $resolver = new EntityListenerResolver($container); + $resolver->register('foo'); + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/Serializers/ArrayEncoderTest.php b/src/Viserio/Bridge/Doctrine/ORM/Tests/Serializers/ArrayEncoderTest.php new file mode 100644 index 000000000..0e416aae2 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/ORM/Tests/Serializers/ArrayEncoderTest.php @@ -0,0 +1,45 @@ +serialize(new ArrayableEntityFixture()); + + $this->assertEquals( + [ + 'id' => 'IDVALUE', + 'name' => 'NAMEVALUE', + ], + $array + ); + } + + public function testEntityCanSerializeToArrayWithArrayableTrait(): void + { + $this->assertEquals( + [ + 'id' => 'IDVALUE', + 'name' => 'NAMEVALUE', + ], + (new ArrayableEntityFixture())->toArray() + ); + } + + private function serialize($entity) + { + $serializer = new Serializer([new GetSetMethodNormalizer()], [ + 'array' => new ArrayEncoder(), + ]); + + return $serializer->serialize($entity, 'array'); + } +} diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/Stub/database.sqlite b/src/Viserio/Bridge/Doctrine/ORM/Tests/Stub/database.sqlite new file mode 100644 index 0000000000000000000000000000000000000000..ccbe3558eaa96c68890b860c5019aa03c9347b3f GIT binary patch literal 2048 zcmWFz^vNtqRY=P(%1ta$FlJz3U}R))P*7lCU|@n`AO!}DKoW#u0GSOFL#LS-bRWs_ z0!0~_w=e+FC>RZa(GZ|81iTp8#6?9JD@ziSa#BlDD@s6^$vMc?F~n6N#L>yeRY3_P zq@6 + + + + + + + + + + + ./Tests/ + + + + + + ./ + + ./vendor + ./Tests + + + + + diff --git a/src/Viserio/Bridge/Doctrine/Testing/.github/PULL_REQUEST_TEMPLATE.md b/src/Viserio/Bridge/Doctrine/Testing/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..3a1c85818 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,5 @@ +This is a READ ONLY repository. + +Please make your pull request to https://github.com/narrowspark/framework + +Thank you for contributing. diff --git a/src/Viserio/Bridge/Doctrine/Testing/Cache/StaticArrayCache.php b/src/Viserio/Bridge/Doctrine/Testing/Cache/StaticArrayCache.php new file mode 100644 index 000000000..ad3e82377 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/Cache/StaticArrayCache.php @@ -0,0 +1,120 @@ +upTime = time(); + } + + /** + * {@inheritdoc} + */ + protected function doFetch($id) + { + if (! $this->doContains($id)) { + $this->missesCount++; + + return false; + } + + $this->hitsCount++; + + return self::$data[$id][0]; + } + + /** + * {@inheritdoc} + */ + protected function doContains($id): bool + { + if (! isset(self::$data[$id])) { + return false; + } + + $expiration = self::$data[$id][1]; + + if ($expiration && $expiration < time()) { + $this->doDelete($id); + + return false; + } + + return true; + } + + /** + * {@inheritdoc} + */ + protected function doSave($id, $data, $lifeTime = 0): bool + { + self::$data[$id] = [$data, $lifeTime ? time() + $lifeTime : false]; + + return true; + } + + /** + * {@inheritdoc} + */ + protected function doDelete($id): bool + { + unset(self::$data[$id]); + + return true; + } + + /** + * {@inheritdoc} + */ + protected function doFlush(): bool + { + self::$data = []; + + return true; + } + + /** + * {@inheritdoc} + */ + protected function doGetStats(): ?array + { + return [ + Cache::STATS_HITS => $this->hitsCount, + Cache::STATS_MISSES => $this->missesCount, + Cache::STATS_UPTIME => $this->upTime, + Cache::STATS_MEMORY_USAGE => null, + Cache::STATS_MEMORY_AVAILABLE => null, + ]; + } +} diff --git a/src/Viserio/Bridge/Doctrine/Testing/Commands/LoadDataFixturesDoctrineCommand.php b/src/Viserio/Bridge/Doctrine/Testing/Commands/LoadDataFixturesDoctrineCommand.php new file mode 100644 index 000000000..f2a93dc70 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/Commands/LoadDataFixturesDoctrineCommand.php @@ -0,0 +1,13 @@ +find($class, $id); + + Assert::assertNotNull( + $entity, + sprintf( + 'A [%s] entity was not found by id: %s', + $class, + print_r($id, true) + ) + ); + + return $entity; + } + + /** + * Check if a entitie dont exists. + * + * @param string $class + * @param mixed $id + * + * @return void + */ + public static function entityDoesNotExist(string $class, $id): void + { + Assert::assertNull( + self::entityManager()->find($class, $id), + sprintf( + 'A [%s] entity was found by id: %s', + $class, + print_r($id, true) + ) + ); + } + + /** + * Check if entities match. + * + * @param string $class + * @param array $criteria + * @param null|int $count + * + * @return object[] + */ + public static function entitiesMatch(string $class, array $criteria, ?int $count = null): array + { + $entities = self::entityManager()->getRepository($class)->findBy($criteria); + + Assert::assertNotEmpty( + $entities, + sprintf( + 'No [%s] entities were found with the given criteria: %s', + $class, + print_r($criteria, true) + ) + ); + + if ($count !== null) { + Assert::assertCount( + $count, + $entities, + sprintf( + 'Expected to find %s [%s] entities, but found %s with the given criteria: %s', + $count, + $class, + count($entities), + print_r($criteria, true) + ) + ); + } + + return $entities; + } + + /** + * Check if entities does not match. + * + * @param string $class + * @param array $criteria + * + * @return void + */ + public static function noEntitiesMatch(string $class, array $criteria): void + { + Assert::assertEmpty( + self::entityManager()->getRepository($class)->findBy($criteria), + "Some [$class] entities were found with the given criteria: " . print_r($criteria, true) + ); + } + + /** + * Create a new EntityManager class. + * + * @return \Doctrine\ORM\EntityManager + */ + abstract protected static function entityManager(): EntityManager; +} diff --git a/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticConnection.php b/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticConnection.php new file mode 100644 index 000000000..073f7d10b --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticConnection.php @@ -0,0 +1,123 @@ +connection = $connection; + } + + /** + * {@inheritdoc} + */ + public function prepare($prepareString) + { + return $this->connection->prepare($prepareString); + } + + /** + * {@inheritdoc} + */ + public function query() + { + return \call_user_func_array([$this->connection, 'query'], \func_get_args()); + } + + /** + * {@inheritdoc} + */ + public function quote($input, $type = \PDO::PARAM_STR) + { + return $this->connection->quote($input, $type); + } + + /** + * {@inheritdoc} + */ + public function exec($statement) + { + return $this->connection->exec($statement); + } + + /** + * {@inheritdoc} + */ + public function lastInsertId($name = null) + { + return $this->connection->lastInsertId($name); + } + + /** + * {@inheritdoc} + */ + public function beginTransaction() + { + if ($this->transactionStarted) { + return $this->connection->beginTransaction(); + } + + return $this->transactionStarted = true; + } + + /** + * {@inheritdoc} + */ + public function commit() + { + return $this->connection->commit(); + } + + /** + * {@inheritdoc} + */ + public function rollBack() + { + return $this->connection->rollBack(); + } + + /** + * {@inheritdoc} + */ + public function errorCode() + { + return $this->connection->errorCode(); + } + + /** + * {@inheritdoc} + */ + public function errorInfo() + { + return $this->connection->errorInfo(); + } + + /** + * @return Connection + */ + public function getWrappedConnection() + { + return $this->connection; + } +} diff --git a/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticConnectionManager.php b/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticConnectionManager.php new file mode 100644 index 000000000..5db6a0b98 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticConnectionManager.php @@ -0,0 +1,39 @@ +getParams(), + new StaticDriver($connectionOriginalDriver->getDriver(), $connectionOriginalDriver->getDatabasePlatform()), + $connectionOriginalDriver->getConfiguration(), + $connectionOriginalDriver->getEventManager() + ); + + if (StaticDriver::isKeepStaticConnections()) { + // The underlying connection already has a transaction started. + // Make sure we use savepoints to be able to easily roll-back nested transactions + if ($connection->getDriver()->getDatabasePlatform()->supportsSavepoints()) { + $connection->setNestTransactionsWithSavepoints(true); + } + + // We start a transaction on the connection as well + // so the internal state ($_transactionNestingLevel) is in sync with the underlying connection. + $connection->beginTransaction(); + } + + return $connection; + } +} diff --git a/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticDriver.php b/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticDriver.php new file mode 100644 index 000000000..0cd4aa509 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticDriver.php @@ -0,0 +1,187 @@ +underlyingDriver = $underlyingDriver; + $this->platform = $platform; + } + + /** + * {@inheritdoc} + */ + public function connect(array $params, $username = null, $password = null, array $driverOptions = []) + { + if (self::$keepStaticConnections) { + $key = sha1(serialize($params) . $username . $password); + + if (! isset(self::$connections[$key])) { + self::$connections[$key] = $this->underlyingDriver->connect($params, $username, $password, $driverOptions); + self::$connections[$key]->beginTransaction(); + } + + return new StaticConnection(self::$connections[$key]); + } + + return $this->underlyingDriver->connect($params, $username, $password, $driverOptions); + } + + /** + * {@inheritdoc} + */ + public function getDatabasePlatform() + { + return $this->platform; + } + + /** + * {@inheritdoc} + */ + public function getSchemaManager(Connection $conn) + { + return $this->underlyingDriver->getSchemaManager($conn); + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return $this->underlyingDriver->getName(); + } + + /** + * {@inheritdoc} + */ + public function getDatabase(Connection $conn) + { + return $this->underlyingDriver->getDatabase($conn); + } + + /** + * {@inheritdoc} + */ + public function convertException($message, DriverException $exception) + { + if ($this->underlyingDriver instanceof ExceptionConverterDriver) { + return $this->underlyingDriver->convertException($message, $exception); + } + + return $exception; + } + + /** + * {@inheritdoc} + */ + public function createDatabasePlatformForVersion($version) + { + return $this->platform; + } + + /** + * Should the connection be kept? + * + * @param bool $keepStaticConnections + * + * @return void + */ + public static function setKeepStaticConnections(bool $keepStaticConnections): void + { + self::$keepStaticConnections = $keepStaticConnections; + } + + /** + * Is the connection held. + * + * @return bool + */ + public static function isKeepStaticConnections(): bool + { + return self::$keepStaticConnections; + } + + /** + * Begins a transaction. + * + * @return void + */ + public static function beginTransaction(): void + { + foreach (self::$connections as $connection) { + try { + $connection->beginTransaction(); + } catch (PDOException $exception) { + // transaction could be started already + } + } + } + + /** + * Rolls back a transaction. + * + * @return void + */ + public static function rollBack(): void + { + foreach (self::$connections as $connection) { + $connection->rollBack(); + } + } + + /** + * Commits a transaction. + * + * @return void + */ + public static function commit(): void + { + foreach (self::$connections as $connection) { + $connection->commit(); + } + } +} diff --git a/src/Viserio/Bridge/Doctrine/Testing/Factory.php b/src/Viserio/Bridge/Doctrine/Testing/Factory.php new file mode 100644 index 000000000..6b0416b8b --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/Factory.php @@ -0,0 +1,227 @@ +faker = $faker; + $this->registry = $registry; + + if (! is_dir($pathToFactories)) { + throw new RuntimeException(sprintf('[%s] is not a directory.', $pathToFactories)); + } + + foreach (Finder::create()->files()->name('*.php')->in($pathToFactories) as $file) { + require $file->getRealPath(); + } + } + + /** + * Define a class with a given short-name. + * + * @param string $class + * @param string $name + * @param callable $attributes + * + * @return void + */ + public function defineAs(string $class, string $name, callable $attributes): void + { + $this->define($class, $attributes, $name); + } + + /** + * Define a class with a given set of attributes. + * + * @param string $class + * @param callable $attributes + * @param string $name + * + * @return void + */ + public function define(string $class, callable $attributes, string $name = 'default'): void + { + $this->definitions[$class][$name] = $attributes; + } + + /** + * Create an instance of the given model and persist it to the database. + * + * @param string $class + * @param array $attributes + * + * @return mixed + */ + public function create(string $class, array $attributes = []) + { + return $this->of($class)->create($attributes); + } + + /** + * Create an instance of the given model and type and persist it to the database. + * + * @param string $class + * @param string $name + * @param array $attributes + * + * @return mixed + */ + public function createAs(string $class, string $name, array $attributes = []) + { + return $this->of($class, $name)->create($attributes); + } + + /** + * Create an instance of the given model. + * + * @param string $class + * @param array $attributes + * + * @return mixed + */ + public function make(string $class, array $attributes = []) + { + return $this->of($class)->make($attributes); + } + + /** + * Create an instance of the given model and type. + * + * @param string $class + * @param string $name + * @param array $attributes + * + * @return mixed + */ + public function makeAs(string $class, string $name, array $attributes = []) + { + return $this->of($class, $name)->make($attributes); + } + + /** + * Get the raw attribute array for a given named model. + * + * @param string $class + * @param string $name + * @param array $attributes + * + * @return array + */ + public function rawOf(string $class, string $name, array $attributes = []) + { + return $this->raw($class, $attributes, $name); + } + + /** + * Get the raw attribute array for a given model. + * + * @param string $class + * @param array $attributes + * @param string $name + * + * @return array + */ + public function raw(string $class, array $attributes = [], string $name = 'default'): array + { + $raw = call_user_func($this->definitions[$class][$name], $this->faker); + + return array_merge($raw, $attributes); + } + + /** + * Create a builder for the given model. + * + * @param string $class + * @param string $name + * + * @return \Viserio\Bridge\Doctrine\Testing\FactoryBuilder + */ + public function of(string $class, string $name = 'default'): FactoryBuilder + { + return new FactoryBuilder($this->registry, $class, $name, $this->definitions, $this->faker); + } + + /** + * Determine if the given offset exists. + * + * @param string $offset + * + * @return bool + */ + public function offsetExists($offset) + { + return isset($this->definitions[$offset]); + } + + /** + * Get the value of the given offset. + * + * @param string $offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return $this->make($offset); + } + + /** + * Set the given offset to the given value. + * + * @param string $offset + * @param callable $value + * + * @return void + */ + public function offsetSet($offset, $value) + { + return $this->define($offset, $value); + } + + /** + * Unset the value at the given offset. + * + * @param string $offset + * + * @return void + */ + public function offsetUnset($offset): void + { + unset($this->definitions[$offset]); + } +} diff --git a/src/Viserio/Bridge/Doctrine/Testing/FactoryBuilder.php b/src/Viserio/Bridge/Doctrine/Testing/FactoryBuilder.php new file mode 100644 index 000000000..bf9127597 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/FactoryBuilder.php @@ -0,0 +1,154 @@ +name = $name; + $this->class = $class; + $this->faker = $faker; + $this->registry = $registry; + $this->definitions = $definitions; + } + + /** + * Set the amount of models you wish to create / make. + * + * @param int $amount + * + * @return $this + */ + public function times(int $amount): self + { + $this->amount = $amount; + + return $this; + } + + /** + * Create a collection of models and persist them to the database. + * + * @param array $attributes + * + * @return mixed + */ + public function create(array $attributes = []) + { + $results = $this->make($attributes); + $manager = $this->registry->getManagerForClass($this->class); + + if ($this->amount === 1) { + $manager->persist($results); + } else { + foreach ($results as $result) { + $manager->persist($result); + } + } + + $manager->flush(); + + return $results; + } + + /** + * Create a collection of models. + * + * @param array $attributes + * + * @return mixed + */ + public function make(array $attributes = []) + { + if ($this->amount === 1) { + return $this->makeInstance($attributes); + } + + $results = []; + + for ($i = 0; $i < $this->amount; $i++) { + $results[] = $this->makeInstance($attributes); + } + + return new Collection($results); + } + + /** + * Make an instance of the model with the given attributes. + * + * @param array $attributes + * + * @return mixed + */ + protected function makeInstance(array $attributes = []) + { + if (! isset($this->definitions[$this->class][$this->name])) { + throw new InvalidArgumentException("Unable to locate factory with name [{$this->name}]."); + } + + $definition = call_user_func($this->definitions[$this->class][$this->name], $this->faker, $attributes); + + if ($definition instanceof $this->class) { + return $definition; + } + + return SimpleHydrator::hydrate($this->class, array_merge($definition, $attributes)); + } +} diff --git a/src/Viserio/Bridge/Doctrine/Testing/LICENSE b/src/Viserio/Bridge/Doctrine/Testing/LICENSE new file mode 100644 index 000000000..9941d8719 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 - 2017 Narrowspark + +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. diff --git a/src/Viserio/Bridge/Doctrine/Testing/PHPUnit/PHPUnitListener.php b/src/Viserio/Bridge/Doctrine/Testing/PHPUnit/PHPUnitListener.php new file mode 100644 index 000000000..0fc55ba74 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/PHPUnit/PHPUnitListener.php @@ -0,0 +1,37 @@ + [self::class, 'extendConsole'], + ]; + } + + /** + * Extend viserio console with commands. + * + * @param \Psr\Container\ContainerInterface $container + * @param null|\Viserio\Component\Console\Application $console + * + * @return null|\Viserio\Component\Console\Application + */ + public static function extendConsole( + ContainerInterface $container, + ?Application $console = null + ): ?Application { + if ($console !== null) { + $console->add(new LoadDataFixturesDoctrineCommand()); + } + + return $console; + } +} diff --git a/src/Viserio/Bridge/Doctrine/Testing/Provider/DoctrineORMTestingServiceProvider.php b/src/Viserio/Bridge/Doctrine/Testing/Provider/DoctrineORMTestingServiceProvider.php new file mode 100644 index 000000000..f4e05f1ce --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/Provider/DoctrineORMTestingServiceProvider.php @@ -0,0 +1,80 @@ + [self::class, 'createEntityFactory'], + FakerGenerator::class => [self::class, 'createFakerGenerator'], + ]; + } + + /** + * {@inheritdoc} + */ + public function getExtensions(): array + { + return []; + } + + /** + * {@inheritdoc} + */ + public static function getDimensions(): iterable + { + return ['viserio', 'doctrine']; + } + + /** + * {@inheritdoc} + */ + public static function getDefaultOptions(): iterable + { + return [ + 'locale' => FakerFactory::DEFAULT_LOCALE, + ]; + } + + /** + * @param \Psr\Container\ContainerInterface $container + * + * @return EntityFactory + */ + public static function createEntityFactory(ContainerInterface $container): EntityFactory + { + return new EntityFactory( + $container->get(FakerGenerator::class), + $container->get(ManagerRegistry::class) + ); + } + + /** + * Create a new instance of faker generator. + * + * @param \Psr\Container\ContainerInterface $container + * + * @return \Faker\Generator + */ + public static function createFakerGenerator(ContainerInterface $container): FakerGenerator + { + return FakerFactory::create(); + } +} diff --git a/src/Viserio/Bridge/Doctrine/Testing/Provider/DoctrineTestingServiceProvier.php b/src/Viserio/Bridge/Doctrine/Testing/Provider/DoctrineTestingServiceProvier.php new file mode 100644 index 000000000..63f902803 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/Provider/DoctrineTestingServiceProvier.php @@ -0,0 +1,51 @@ + [self::class, 'createStaticConnectionManager'], + ]; + } + + /** + * Create a new instance of faker generator. + * + * @param \Psr\Container\ContainerInterface $container + * @param null|\Viserio\Bridge\Doctrine\DBAL\ConnectionManager $connectionManager + * + * @return \Viserio\Bridge\Doctrine\Testing\DBAL\StaticConnectionManager + */ + public static function createStaticConnectionManager( + ContainerInterface $container, + ?ConnectionManager $connectionManager + ): StaticConnectionManager { + $manager = new StaticConnectionManager($container); + + if ($connectionManager !== null) { + $manager->setDoctrineConfiguration($manager->getDoctrineConfiguration()); + $manager->setDoctrineEventManager($manager->getDoctrineEventManager()); + } + + return $manager; + } +} diff --git a/src/Viserio/Bridge/Doctrine/Testing/README.md b/src/Viserio/Bridge/Doctrine/Testing/README.md new file mode 100644 index 000000000..959090bb3 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/README.md @@ -0,0 +1,33 @@ +# Viserio Doctrine Testing package + +This package is part of the [Narrowspark framework](http://github.com/narrowspark/framework). + +[![Author](http://img.shields.io/badge/author-@anolilab-blue.svg?style=flat-square)](https://twitter.com/anolilab) +[![Quality Score](https://img.shields.io/scrutinizer/g/narrowspark/framework.svg?style=flat-square)](https://scrutinizer-ci.com/g/narrowspark/framework/code-structure/master) +[![Build Status](https://api.travis-ci.org/narrowspark/framework.svg?branch=master&style=flat-square)](https://travis-ci.org/narrowspark/framework) +[![Latest Version](https://img.shields.io/packagist/v/narrowspark/framework.svg?style=flat-square)](https://github.com/narrowspark/framework/releases) +[![Minimum PHP Version](https://img.shields.io/badge/php-%5E7.1.0-8892BF.svg?style=flat-square)](https://php.net/) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE) + +> **Note:** If you want to build an application using Narrowspark, visit the main [![Source Code](http://img.shields.io/badge/source-narrowspark/narrowspark-blue.svg?style=flat-square)](https://github.com/narrowspark/narrowspark). + +## Contributing + +Issues for this package shall be posted on [Narrowspark framework issues](http://github.com/narrowspark/framework/issues). +Thank you for considering contributing to the Narrowspark framework! The contribution guide can be found in the [Narrowspark documentation](http://narrowspark.de/docs/contributions). + +## Installation + +Use [Composer](https://getcomposer.org/) to install this package: + +```sh +composer require viserio/bridge/doctrine +``` + +## Official Documentation + +Documentation for the framework can be found on the [Narrowspark website](http://narrowspark.de/docs). + +### License + +The Narrowspark framework is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT). diff --git a/src/Viserio/Bridge/Doctrine/Testing/SimpleHydrator.php b/src/Viserio/Bridge/Doctrine/Testing/SimpleHydrator.php new file mode 100644 index 000000000..890e6b706 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/SimpleHydrator.php @@ -0,0 +1,32 @@ +newInstanceWithoutConstructor(); + + foreach ($attributes as $field => $value) { + if ($reflection->hasProperty($field)) { + $property = $reflection->getProperty($field); + $property->setAccessible(true); + $property->setValue($instance, $value); + } + } + + return $instance; + } +} diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/Cache/StaticArrayCacheTest.php b/src/Viserio/Bridge/Doctrine/Testing/Tests/Cache/StaticArrayCacheTest.php new file mode 100644 index 000000000..9b5a51ccb --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/Tests/Cache/StaticArrayCacheTest.php @@ -0,0 +1,438 @@ +getCacheDriver(); + // Test saving a value, checking if it exists, and fetching it back + self::assertTrue($cache->save('key', $value)); + self::assertTrue($cache->contains('key')); + + if (is_object($value)) { + self::assertEquals($value, $cache->fetch('key'), 'Objects retrieved from the cache must be equal but not necessarily the same reference'); + } else { + self::assertSame($value, $cache->fetch('key'), 'Scalar and array data retrieved from the cache must be the same as the original, e.g. same type'); + } + + // Test deleting a value + self::assertTrue($cache->delete('key')); + self::assertFalse($cache->contains('key')); + self::assertFalse($cache->fetch('key')); + } + + /** + * @dataProvider provideDataToCache + * + * @param mixed $value + */ + public function testUpdateExistingEntry($value): void + { + $cache = $this->getCacheDriver(); + + self::assertTrue($cache->save('key', 'old-value')); + self::assertTrue($cache->contains('key')); + self::assertTrue($cache->save('key', $value)); + self::assertTrue($cache->contains('key')); + + if (is_object($value)) { + self::assertEquals($value, $cache->fetch('key'), 'Objects retrieved from the cache must be equal but not necessarily the same reference'); + } else { + self::assertSame($value, $cache->fetch('key'), 'Scalar and array data retrieved from the cache must be the same as the original, e.g. same type'); + } + } + + public function testCacheKeyIsCaseSensitive(): void + { + $cache = $this->getCacheDriver(); + + self::assertTrue($cache->save('key', 'value')); + self::assertTrue($cache->contains('key')); + self::assertSame('value', $cache->fetch('key')); + self::assertFalse($cache->contains('KEY')); + self::assertFalse($cache->fetch('KEY')); + + $cache->delete('KEY'); + + self::assertTrue($cache->contains('key'), 'Deleting cache item with different case must not affect other cache item'); + } + + public function testFetchMultiple(): void + { + $cache = $this->getCacheDriver(); + $values = $this->provideDataToCache(); + $saved = []; + + foreach ($values as $key => $value) { + $cache->save($key, $value[0]); + $saved[$key] = $value[0]; + } + + $keys = array_keys($saved); + + self::assertEquals( + $saved, + $cache->fetchMultiple($keys), + 'Testing fetchMultiple with different data types' + ); + self::assertEquals( + array_slice($saved, 0, 1), + $cache->fetchMultiple(array_slice($keys, 0, 1)), + 'Testing fetchMultiple with a single key' + ); + + $keysWithNonExisting = []; + $keysWithNonExisting[] = 'non_existing1'; + $keysWithNonExisting[] = $keys[0]; + $keysWithNonExisting[] = 'non_existing2'; + $keysWithNonExisting[] = $keys[1]; + $keysWithNonExisting[] = 'non_existing3'; + + self::assertEquals( + array_slice($saved, 0, 2), + $cache->fetchMultiple($keysWithNonExisting), + 'Testing fetchMultiple with a subset of keys and mixed with non-existing ones' + ); + } + + public function testFetchMultipleWithNoKeys(): void + { + $cache = $this->getCacheDriver(); + + self::assertSame([], $cache->fetchMultiple([])); + } + + public function testSaveMultiple(): void + { + $cache = $this->getCacheDriver(); + $cache->deleteAll(); + $data = array_map(function ($value) { + return $value[0]; + }, $this->provideDataToCache()); + + self::assertTrue($cache->saveMultiple($data)); + + $keys = array_keys($data); + + self::assertEquals($data, $cache->fetchMultiple($keys)); + } + + public function provideDataToCache(): array + { + $obj = new \stdClass(); + $obj->foo = 'bar'; + $obj2 = new \stdClass(); + $obj2->bar = 'foo'; + $obj2->obj = $obj; + $obj->obj2 = $obj2; + + return [ + 'array' => [['one', 2, 3.01]], + 'string' => ['value'], + 'string_invalid_utf8' => ["\xc3\x28"], + 'string_null_byte' => ['with' . "\0" . 'null char'], + 'integer' => [1], + 'float' => [1.5], + 'object' => [new ArrayObject(['one', 2, 3.01])], + 'object_recursive' => [$obj], + 'true' => [true], + // the following are considered FALSE in boolean context, but caches should still recognize their existence + 'null' => [null], + 'false' => [false], + 'array_empty' => [[]], + 'string_zero' => ['0'], + 'integer_zero' => [0], + 'float_zero' => [0.0], + 'string_empty' => [''], + ]; + } + + public function testDeleteIsSuccessfulWhenKeyDoesNotExist(): void + { + $cache = $this->getCacheDriver(); + $cache->delete('key'); + + self::assertFalse($cache->contains('key')); + self::assertTrue($cache->delete('key')); + } + + public function testDeleteAll(): void + { + $cache = $this->getCacheDriver(); + + self::assertTrue($cache->save('key1', 1)); + self::assertTrue($cache->save('key2', 2)); + self::assertTrue($cache->deleteAll()); + self::assertFalse($cache->contains('key1')); + self::assertFalse($cache->contains('key2')); + } + + public function testDeleteMulti(): void + { + $cache = $this->getCacheDriver(); + + self::assertTrue($cache->save('key1', 1)); + self::assertTrue($cache->save('key2', 1)); + self::assertTrue($cache->deleteMultiple(['key1', 'key2', 'key3'])); + self::assertFalse($cache->contains('key1')); + self::assertFalse($cache->contains('key2')); + self::assertFalse($cache->contains('key3')); + } + + /** + * @dataProvider provideCacheIds + * + * @param mixed $id + */ + public function testCanHandleSpecialCacheIds($id): void + { + $cache = $this->getCacheDriver(); + + self::assertTrue($cache->save($id, 'value')); + self::assertTrue($cache->contains($id)); + self::assertEquals('value', $cache->fetch($id)); + self::assertTrue($cache->delete($id)); + self::assertFalse($cache->contains($id)); + self::assertFalse($cache->fetch($id)); + } + + public function testNoCacheIdCollisions(): void + { + $cache = $this->getCacheDriver(); + $ids = $this->provideCacheIds(); + // fill cache with each id having a different value + foreach ($ids as $index => $id) { + $cache->save($id[0], $index); + } + // then check value of each cache id + foreach ($ids as $index => $id) { + $value = $cache->fetch($id[0]); + self::assertNotFalse($value, sprintf('Failed to retrieve data for cache id "%s".', $id[0])); + if ($index !== $value) { + $this->fail(sprintf('Cache id "%s" collides with id "%s".', $id[0], $ids[$value][0])); + } + } + } + + /** + * Returns cache ids with special characters that should still work. + * + * For example, the characters :\/<>"*?| are not valid in Windows filenames. So they must be encoded properly. + * Each cache id should be considered different from the others. + */ + public function provideCacheIds(): array + { + return [ + [':'], + ['\\'], + ['/'], + ['<'], + ['>'], + ['"'], + ['*'], + ['?'], + ['|'], + ['['], + [']'], + ['ä'], + ['a'], + ['é'], + ['e'], + ['.'], // directory traversal + ['..'], // directory traversal + ['-'], + ['_'], + ['$'], + ['%'], + [' '], + ["\0"], + [''], + [str_repeat('a', 300)], // long key + [str_repeat('a', 113)], + ]; + } + + public function testLifetime(): void + { + $cache = $this->getCacheDriver(); + $cache->save('expire', 'value', 1); + + self::assertTrue($cache->contains('expire'), 'Data should not be expired yet'); + + // @TODO should more TTL-based tests pop up, so then we should mock the `time` API instead + sleep(2); + + self::assertFalse($cache->contains('expire'), 'Data should be expired'); + } + + public function testNoExpire(): void + { + $cache = $this->getCacheDriver(); + $cache->save('noexpire', 'value', 0); + + // @TODO should more TTL-based tests pop up, so then we should mock the `time` API instead + sleep(1); + + self::assertTrue($cache->contains('noexpire'), 'Data with lifetime of zero should not expire'); + } + + public function testLongLifetime(): void + { + $cache = $this->getCacheDriver(); + $cache->save('longlifetime', 'value', 30 * 24 * 3600 + 1); + + self::assertTrue($cache->contains('longlifetime'), 'Data with lifetime > 30 days should be accepted'); + } + + public function testFlushAll(): void + { + $cache = $this->getCacheDriver(); + + self::assertTrue($cache->save('key1', 1)); + self::assertTrue($cache->save('key2', 2)); + self::assertTrue($cache->flushAll()); + self::assertFalse($cache->contains('key1')); + self::assertFalse($cache->contains('key2')); + } + + public function testNamespace(): void + { + $cache = $this->getCacheDriver(); + $cache->setNamespace('ns1_'); + + self::assertTrue($cache->save('key1', 1)); + self::assertTrue($cache->contains('key1')); + + $cache->setNamespace('ns2_'); + + self::assertFalse($cache->contains('key1')); + } + + public function testDeleteAllNamespace(): void + { + $cache = $this->getCacheDriver(); + $cache->setNamespace('ns1'); + + self::assertFalse($cache->contains('key1')); + + $cache->save('key1', 'test'); + + self::assertTrue($cache->contains('key1')); + + $cache->setNamespace('ns2'); + + self::assertFalse($cache->contains('key1')); + + $cache->save('key1', 'test'); + + self::assertTrue($cache->contains('key1')); + + $cache->setNamespace('ns1'); + + self::assertTrue($cache->contains('key1')); + + $cache->deleteAll(); + + self::assertFalse($cache->contains('key1')); + + $cache->setNamespace('ns2'); + + self::assertTrue($cache->contains('key1')); + + $cache->deleteAll(); + + self::assertFalse($cache->contains('key1')); + } + + public function testSaveReturnsTrueWithAndWithoutTTlSet(): void + { + $cache = $this->getCacheDriver(); + $cache->deleteAll(); + + self::assertTrue($cache->save('without_ttl', 'without_ttl')); + self::assertTrue($cache->save('with_ttl', 'with_ttl', 3600)); + } + + public function testValueThatIsFalseBooleanIsProperlyRetrieved(): void + { + $cache = $this->getCacheDriver(); + $cache->deleteAll(); + + self::assertTrue($cache->save('key1', false)); + self::assertTrue($cache->contains('key1')); + self::assertFalse($cache->fetch('key1')); + } + + /** + * @group 147 + * @group 152 + */ + public function testFetchingANonExistingKeyShouldNeverCauseANoticeOrWarning(): void + { + $cache = $this->getCacheDriver(); + $errorHandler = function (): void { + restore_error_handler(); + $this->fail('include failure captured'); + }; + set_error_handler($errorHandler); + $cache->fetch('key'); + + self::assertSame( + $errorHandler, + set_error_handler(function (): void { + }), + 'The error handler is the one set by this test, and wasn\'t replaced' + ); + + restore_error_handler(); + restore_error_handler(); + } + + public function testGetStats(): void + { + $cache = $this->getCacheDriver(); + $cache->fetch('test1'); + $cache->fetch('test2'); + $cache->fetch('test3'); + $cache->save('test1', 123); + $cache->save('test2', 123); + $cache->fetch('test1'); + $cache->fetch('test2'); + $cache->fetch('test3'); + $stats = $cache->getStats(); + + self::assertEquals(2, $stats[Cache::STATS_HITS]); + self::assertEquals(5, $stats[Cache::STATS_MISSES]); // +1 for internal call to DoctrineNamespaceCacheKey + self::assertNotNull($stats[Cache::STATS_UPTIME]); + self::assertNull($stats[Cache::STATS_MEMORY_USAGE]); + self::assertNull($stats[Cache::STATS_MEMORY_AVAILABLE]); + + $cache->delete('test1'); + $cache->delete('test2'); + $cache->fetch('test1'); + $cache->fetch('test2'); + $cache->fetch('test3'); + $stats = $cache->getStats(); + + self::assertEquals(2, $stats[Cache::STATS_HITS]); + self::assertEquals(8, $stats[Cache::STATS_MISSES]); // +1 for internal call to DoctrineNamespaceCacheKey + } + + private function getCacheDriver(): CacheProvider + { + return new StaticArrayCache(); + } +} diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/Concerns/DoctrineEntitiesTestCaseTest.php b/src/Viserio/Bridge/Doctrine/Testing/Tests/Concerns/DoctrineEntitiesTestCaseTest.php new file mode 100644 index 000000000..bc05404dc --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/Tests/Concerns/DoctrineEntitiesTestCaseTest.php @@ -0,0 +1,3 @@ +platform = $this->createMock(AbstractPlatform::class); + } + + public function testReturnCorrectPlatform(): void + { + $driver = new StaticDriver(new MockDriver(), $this->platform); + + self::assertSame($this->platform, $driver->getDatabasePlatform()); + self::assertSame($this->platform, $driver->createDatabasePlatformForVersion(1)); + } + + public function testConnect(): void + { + $driver = new StaticDriver(new MockDriver(), $this->platform); + $driver::setKeepStaticConnections(true); + + $connection1 = $driver->connect(['database_name' => 1], 'user1', 'pw1'); + $connection2 = $driver->connect(['database_name' => 2], 'user1', 'pw2'); + + self::assertInstanceOf(StaticConnection::class, $connection1); + self::assertNotSame($connection1->getWrappedConnection(), $connection2->getWrappedConnection()); + + $driver = new StaticDriver(new MockDriver(), $this->platform); + $connectionNew1 = $driver->connect(['database_name' => 1], 'user1', 'pw1'); + $connectionNew2 = $driver->connect(['database_name' => 2], 'user1', 'pw2'); + + self::assertSame($connection1->getWrappedConnection(), $connectionNew1->getWrappedConnection()); + self::assertSame($connection2->getWrappedConnection(), $connectionNew2->getWrappedConnection()); + } +} diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/FactoryBuilderTest.php b/src/Viserio/Bridge/Doctrine/Testing/Tests/FactoryBuilderTest.php new file mode 100644 index 000000000..e2dd7e0e0 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/Tests/FactoryBuilderTest.php @@ -0,0 +1,9 @@ +getMock(DriverConnection::class); + } + + /** + * {@inheritdoc} + */ + public function getDatabasePlatform() + { + return $this->getMock(AbstractPlatform::class); + } + + /** + * {@inheritdoc} + */ + public function getSchemaManager(Connection $conn) + { + return $this->getMock(AbstractSchemaManager::class); + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return 'mock'; + } + + /** + * {@inheritdoc} + */ + public function getDatabase(Connection $conn) + { + return 'mock'; + } + + /** + * Create a new phpunit mock. + * + * @param string $className + * + * @return \PHPUnit_Framework_MockObject_MockObject + */ + private function getMock(string $className): PHPUnit_Framework_MockObject_MockObject + { + $generator = new PHPUnit_Framework_MockObject_Generator(); + + return $generator->getMock($className, [], [], '', false); + } +} diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/Provider/ConsoleCommandsServiceProviderTest.php b/src/Viserio/Bridge/Doctrine/Testing/Tests/Provider/ConsoleCommandsServiceProviderTest.php new file mode 100644 index 000000000..5b148c8d0 --- /dev/null +++ b/src/Viserio/Bridge/Doctrine/Testing/Tests/Provider/ConsoleCommandsServiceProviderTest.php @@ -0,0 +1,47 @@ +register(new ConsoleServiceProvider()); + $container->register(new DoctrineDBALServiceProvider()); + $container->register(new ConsoleCommandsServiceProvider()); + + $container->instance('config', [ + 'viserio' => [ + 'console' => [ + 'version' => '1', + ], + 'doctrine' => [ + 'default' => 'mysql', + 'connections' => [ + 'mysql' => [ + 'driver' => 'pdo_mysql', + 'host' => 'DB_HOST', + 'port' => 'DB_PORT', + 'database' => 'DB_DATABASE_NAME', + 'username' => 'DB_DATABASE_USER', + 'password' => 'DB_DATABASE_PASSWORD', + 'charset' => 'DB_CHARSET', 'UTF8', + 'driverOptions' => [1002 => 'SET NAMES utf8'], + ], + ], + ], + ], + ]); + + $console = $container->get(Application::class); + $commands = $console->all(); + } +} diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/Provider/DoctrineORMTestingServiceProviderTest.php b/src/Viserio/Bridge/Doctrine/Testing/Tests/Provider/DoctrineORMTestingServiceProviderTest.php new file mode 100644 index 000000000..e69de29bb diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/Stub/database.sqlite b/src/Viserio/Bridge/Doctrine/Testing/Tests/Stub/database.sqlite new file mode 100644 index 0000000000000000000000000000000000000000..ccbe3558eaa96c68890b860c5019aa03c9347b3f GIT binary patch literal 2048 zcmWFz^vNtqRY=P(%1ta$FlJz3U}R))P*7lCU|@n`AO!}DKoW#u0GSOFL#LS-bRWs_ z0!0~_w=e+FC>RZa(GZ|81iTp8#6?9JD@ziSa#BlDD@s6^$vMc?F~n6N#L>yeRY3_P zq@6 + + + + + + + + + + + ./Tests/ + + + + + + ./ + + ./vendor + ./Tests + + + + + From 15007065efd87b775fc9c21b9e9608acb43fcf06 Mon Sep 17 00:00:00 2001 From: prisis Date: Mon, 26 Nov 2018 11:34:27 +0100 Subject: [PATCH 2/4] moved some packages --- composer.json | 16 +- .../DoctrineDBALServiceProviderTest.php | 37 ---- .../Bridge/Doctrine/DBAL/composer.json | 56 ----- .../Provider/ExtensionsServiceProvider.php | 4 +- .../Bridge/Doctrine/Extensions/composer.json | 89 ++++---- .../Migration/Commands/DiffCommand.php | 3 - .../Migration/Commands/ExecuteCommand.php | 3 - .../Migration/Commands/GenerateCommand.php | 34 --- .../Migration/Commands/LatestCommand.php | 3 - .../Migration/Commands/RefreshCommand.php | 3 - .../Migration/Commands/ResetCommand.php | 3 - .../Migration/Commands/RollbackCommand.php | 3 - .../Migration/Commands/StatusCommand.php | 3 - .../Migration/Commands/UpToDateCommand.php | 3 - .../Bridge/Doctrine/Migration/composer.json | 52 ----- .../Bridge/Doctrine/ORM/AbstractTable.php | 8 +- .../ORM/Commands/AbstractDoctrineCommand.php | 2 +- .../ORM/Configuration/CacheManager.php | 2 +- .../ORM/Configuration/MetaDataManager.php | 4 +- .../Bridge/Doctrine/ORM/ConnectionFactory.php | 4 +- .../DataCollector/DoctrineDataCollector.php | 48 ++--- .../Doctrine/ORM/EntityManagerFactory.php | 16 +- .../Bridge/Doctrine/ORM/ManagerRegistry.php | 92 ++++---- .../ConsoleCommandsServiceProvider.php | 6 +- .../Provider/DoctrineORMServiceProvicer.php | 4 +- .../ORM/Resolvers/EntityListenerResolver.php | 10 +- .../ORM/Serializers/Traits/ArrayableTrait.php | 4 +- .../Doctrine/ORM/Tests/ClassAliasesTest.php | 11 +- .../Tests/Configuration/CacheManagerTest.php | 9 +- .../Configuration/MetaDataManagerTest.php | 17 +- .../Tests/Fixtures/ArrayableEntityFixture.php | 1 + .../ORM/Tests/ManagerRegistryTest.php | 14 +- .../ConsoleCommandsServiceProviderTest.php | 33 +-- .../Resolvers/EntityListenerResolverTest.php | 14 +- .../Tests/Serializers/ArrayEncoderTest.php | 5 +- src/Viserio/Bridge/Doctrine/ORM/alias.php | 8 +- src/Viserio/Bridge/Doctrine/ORM/composer.json | 104 +++++---- .../Testing/Cache/StaticArrayCache.php | 6 +- .../Concerns/DoctrineEntitiesTestCase.php | 3 + .../Concerns/InteractsWithEntities.php | 22 +- .../Testing/DBAL/StaticConnection.php | 2 +- .../Doctrine/Testing/DBAL/StaticDriver.php | 46 ++-- .../Bridge/Doctrine/Testing/Factory.php | 16 +- .../Doctrine/Testing/FactoryBuilder.php | 13 +- .../ConsoleCommandsServiceProvider.php | 6 +- .../DoctrineORMTestingServiceProvider.php | 4 +- .../Doctrine/Testing/SimpleHydrator.php | 2 +- .../Tests/Cache/StaticArrayCacheTest.php | 199 +++++++++--------- .../Testing/Tests/DBAL/StaticDriverTest.php | 19 +- .../Testing/Tests/Fixtures/MockDriver.php | 8 +- .../ConsoleCommandsServiceProviderTest.php | 5 +- .../Bridge/Doctrine/Testing/composer.json | 87 ++++---- .../.github/PULL_REQUEST_TEMPLATE.md | 0 .../DBAL => Provider/Doctrine}/Connection.php | 8 +- .../Doctrine}/ConnectionManager.php | 106 +++++----- .../DBAL => Provider/Doctrine}/LICENSE | 0 .../ConsoleCommandsServiceProvider.php | 13 +- .../Provider/DoctrineDBALServiceProvider.php | 10 +- .../DBAL => Provider/Doctrine}/Proxy/DBAL.php | 4 +- .../DBAL => Provider/Doctrine}/README.md | 0 .../DBAL => Provider/Doctrine}/Statement.php | 2 +- .../Doctrine}/Tests/ConnectionManagerTest.php | 31 +-- .../ConsoleCommandsServiceProviderTest.php | 17 +- ...LServiceProviderDatabaseConnectionTest.php | 33 +-- .../DoctrineDBALServiceProviderTest.php | 40 ++++ .../Doctrine}/Tests/Stub/database.sqlite | Bin src/Viserio/Provider/Doctrine/composer.json | 66 ++++++ .../Doctrine}/phpunit.xml.dist | 0 .../.github/PULL_REQUEST_TEMPLATE.md | 0 .../Commands/AbstractCommand.php | 21 +- .../Commands/DiffCommand.php | 3 + .../Commands/ExecuteCommand.php | 3 + .../Commands/GenerateCommand.php | 34 +++ .../Commands/Helper/ConfigurationHelper.php | 28 +-- .../Commands/LatestCommand.php | 3 + .../Commands/MigrateCommand.php | 8 +- .../Commands/RefreshCommand.php | 3 + .../Commands/ResetCommand.php | 3 + .../Commands/RollbackCommand.php | 3 + .../Commands/StatusCommand.php | 3 + .../Commands/UpToDateCommand.php | 3 + .../Commands/VersionCommand.php | 2 +- .../Configuration/Configuration.php | 26 +-- .../DoctrineMigration}/LICENSE | 0 .../Naming/DefaultNamingStrategy.php | 4 +- .../ConsoleCommandsServiceProvider.php | 11 +- .../DoctrineMigration}/README.md | 0 .../ConsoleCommandsServiceProviderTest.php | 23 +- .../Tests/Stub/database.sqlite | Bin .../Provider/DoctrineMigration/composer.json | 61 ++++++ .../DoctrineMigration}/phpunit.xml.dist | 0 .../Provider/Twig/Command/LintCommand.php | 2 +- .../ConsoleCommandsServiceProvider.php | 2 +- .../Twig/Tests/Engine/TwigEngineTest.php | 4 +- 94 files changed, 917 insertions(+), 829 deletions(-) delete mode 100644 src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/DoctrineDBALServiceProviderTest.php delete mode 100644 src/Viserio/Bridge/Doctrine/DBAL/composer.json delete mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/DiffCommand.php delete mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/ExecuteCommand.php delete mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/GenerateCommand.php delete mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/LatestCommand.php delete mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/RefreshCommand.php delete mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/ResetCommand.php delete mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/RollbackCommand.php delete mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/StatusCommand.php delete mode 100644 src/Viserio/Bridge/Doctrine/Migration/Commands/UpToDateCommand.php delete mode 100644 src/Viserio/Bridge/Doctrine/Migration/composer.json rename src/Viserio/{Bridge/Doctrine/DBAL => Provider/Doctrine}/.github/PULL_REQUEST_TEMPLATE.md (100%) rename src/Viserio/{Bridge/Doctrine/DBAL => Provider/Doctrine}/Connection.php (78%) rename src/Viserio/{Bridge/Doctrine/DBAL => Provider/Doctrine}/ConnectionManager.php (91%) rename src/Viserio/{Bridge/Doctrine/DBAL => Provider/Doctrine}/LICENSE (100%) rename src/Viserio/{Bridge/Doctrine/DBAL => Provider/Doctrine}/Provider/ConsoleCommandsServiceProvider.php (78%) rename src/Viserio/{Bridge/Doctrine/DBAL => Provider/Doctrine}/Provider/DoctrineDBALServiceProvider.php (90%) rename src/Viserio/{Bridge/Doctrine/DBAL => Provider/Doctrine}/Proxy/DBAL.php (77%) rename src/Viserio/{Bridge/Doctrine/DBAL => Provider/Doctrine}/README.md (100%) rename src/Viserio/{Bridge/Doctrine/DBAL => Provider/Doctrine}/Statement.php (98%) rename src/Viserio/{Bridge/Doctrine/DBAL => Provider/Doctrine}/Tests/ConnectionManagerTest.php (52%) rename src/Viserio/{Bridge/Doctrine/DBAL => Provider/Doctrine}/Tests/Provider/ConsoleCommandsServiceProviderTest.php (66%) rename src/Viserio/{Bridge/Doctrine/DBAL => Provider/Doctrine}/Tests/Provider/DoctrineDBALServiceProviderDatabaseConnectionTest.php (58%) create mode 100644 src/Viserio/Provider/Doctrine/Tests/Provider/DoctrineDBALServiceProviderTest.php rename src/Viserio/{Bridge/Doctrine/DBAL => Provider/Doctrine}/Tests/Stub/database.sqlite (100%) create mode 100644 src/Viserio/Provider/Doctrine/composer.json rename src/Viserio/{Bridge/Doctrine/DBAL => Provider/Doctrine}/phpunit.xml.dist (100%) rename src/Viserio/{Bridge/Doctrine/Migration => Provider/DoctrineMigration}/.github/PULL_REQUEST_TEMPLATE.md (100%) rename src/Viserio/{Bridge/Doctrine/Migration => Provider/DoctrineMigration}/Commands/AbstractCommand.php (82%) create mode 100644 src/Viserio/Provider/DoctrineMigration/Commands/DiffCommand.php create mode 100644 src/Viserio/Provider/DoctrineMigration/Commands/ExecuteCommand.php create mode 100644 src/Viserio/Provider/DoctrineMigration/Commands/GenerateCommand.php rename src/Viserio/{Bridge/Doctrine/Migration => Provider/DoctrineMigration}/Commands/Helper/ConfigurationHelper.php (84%) create mode 100644 src/Viserio/Provider/DoctrineMigration/Commands/LatestCommand.php rename src/Viserio/{Bridge/Doctrine/Migration => Provider/DoctrineMigration}/Commands/MigrateCommand.php (59%) create mode 100644 src/Viserio/Provider/DoctrineMigration/Commands/RefreshCommand.php create mode 100644 src/Viserio/Provider/DoctrineMigration/Commands/ResetCommand.php create mode 100644 src/Viserio/Provider/DoctrineMigration/Commands/RollbackCommand.php create mode 100644 src/Viserio/Provider/DoctrineMigration/Commands/StatusCommand.php create mode 100644 src/Viserio/Provider/DoctrineMigration/Commands/UpToDateCommand.php rename src/Viserio/{Bridge/Doctrine/Migration => Provider/DoctrineMigration}/Commands/VersionCommand.php (93%) rename src/Viserio/{Bridge/Doctrine/Migration => Provider/DoctrineMigration}/Configuration/Configuration.php (62%) rename src/Viserio/{Bridge/Doctrine/Migration => Provider/DoctrineMigration}/LICENSE (100%) rename src/Viserio/{Bridge/Doctrine/Migration => Provider/DoctrineMigration}/Naming/DefaultNamingStrategy.php (84%) rename src/Viserio/{Bridge/Doctrine/Migration => Provider/DoctrineMigration}/Provider/ConsoleCommandsServiceProvider.php (84%) rename src/Viserio/{Bridge/Doctrine/Migration => Provider/DoctrineMigration}/README.md (100%) rename src/Viserio/{Bridge/Doctrine/Migration => Provider/DoctrineMigration}/Tests/Provider/ConsoleCommandsServiceProviderTest.php (73%) rename src/Viserio/{Bridge/Doctrine/Migration => Provider/DoctrineMigration}/Tests/Stub/database.sqlite (100%) create mode 100644 src/Viserio/Provider/DoctrineMigration/composer.json rename src/Viserio/{Bridge/Doctrine/Migration => Provider/DoctrineMigration}/phpunit.xml.dist (100%) diff --git a/composer.json b/composer.json index 9826160fd..02030cb97 100644 --- a/composer.json +++ b/composer.json @@ -40,15 +40,16 @@ "ext-tokenizer": "*", "ext-ctype": "*", "ext-mbstring": "*", - "container-interop/service-provider": "^0.4", "cache/array-adapter": "^1.0.0", "cache/void-adapter": "^1.0.0", "cakephp/chronos": "^1.1.4", + "container-interop/service-provider": "^0.4", "danielstjules/stringy": "^3.0.0", "doctrine/inflector": "^1.3.0", "dragonmantank/cron-expression": "^2.1.0", "egulias/email-validator": "^2.1.0", "enqueue/null": "^0.8.0", + "jdorn/sql-formatter": "^1.2.17", "league/flysystem": "^1.0.44", "monolog/monolog": "^1.24.0", "narrowspark/arr": "^2.1.0", @@ -89,10 +90,9 @@ "viserio/contract": "self.version", "viserio/cookie": "self.version", "viserio/cron": "self.version", - "viserio/doctrine-dbal-bridge": "self.version", + "viserio/doctrine-doctrine-provider": "self.version", "viserio/doctrine-extensions-bridge": "self.version", "viserio/doctrine-migration-bridge": "self.version", - "viserio/doctrine-orm-bridge": "self.version", "viserio/doctrine-testing-bridge": "self.version", "viserio/events": "self.version", "viserio/exception": "self.version", @@ -150,6 +150,7 @@ "fzaninotto/faker": "^1.8.0", "gedmo/doctrine-extensions": "^2.4.36", "guzzlehttp/guzzle": "^6.3.0", + "http-interop/http-factory-tests": "^0.5.0", "league/flysystem-aws-s3-v3": "^1.0.19", "league/flysystem-cached-adapter": "^1.0.6", "league/flysystem-sftp": "^1.0", @@ -160,15 +161,14 @@ "mockery/mockery": "^1.2.0", "mouf/picotainer": "^1.1.0", "narrowspark/automatic-common": "^0.9.0", + "narrowspark/coding-standard": "^1.4.0", "narrowspark/testing-helper": "^7.0.0", "nyholm/nsa": "^1.1", "pda/pheanstalk": "^3.1", "php-amqplib/php-amqplib": "^2.6", "phpstan/phpstan-php-parser": "^0.10.0", "phpunit/phpunit": "^7.5.0", - "http-interop/http-factory-tests": "^0.5.0", "predis/predis": "^1.0", - "roave/security-advisories": "dev-master", "spatie/flysystem-dropbox": "^1.0", "ocramius/proxy-manager": "^2.2.2", "symfony/phpunit-bridge": "^4.2.0", @@ -190,7 +190,7 @@ "Viserio\\Provider\\": "src/Viserio/Provider/" }, "files": [ - "src/Viserio/Component/Support/helper.php" + "src/Viserio/Component/Support/helper.php" ], "exclude-from-classmap": [ "src/Viserio/Component/**/Tests/", @@ -207,11 +207,11 @@ "minimum-stability": "dev", "prefer-stable": true, "scripts": { + "changelog": "./build/changelog.sh", "coverage": "phpunit --coverage-html=\"build/logs\"", "cs": "php-cs-fixer fix", "phpstan": "phpstan analyse -c phpstan.neon -l 7 src/Viserio --memory-limit=-1", - "test": "phpunit", - "changelog": "./build/changelog.sh" + "test": "phpunit" }, "support": { "issues": "https://github.com/narrowspark/framework/issues", diff --git a/src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/DoctrineDBALServiceProviderTest.php b/src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/DoctrineDBALServiceProviderTest.php deleted file mode 100644 index a1013021c..000000000 --- a/src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/DoctrineDBALServiceProviderTest.php +++ /dev/null @@ -1,37 +0,0 @@ -register(new DoctrineDBALServiceProvider()); - - $container->instance('config', [ - 'viserio' => [ - 'doctrine' => [ - 'dbal' => [ - 'default' => 'mysql', - ], - ], - ], - ]); - - self::assertInstanceOf(Configuration::class, $container->get(Configuration::class)); - self::assertInstanceOf(EventManager::class, $container->get(EventManager::class)); - self::assertInstanceOf(ConnectionManager::class, $container->get(ConnectionManager::class)); - self::assertInstanceOf(Connection::class, $container->get(Connection::class)); - self::assertInstanceOf(Connection::class, $container->get('db')); - self::assertInstanceOf(Connection::class, $container->get('database')); - } -} diff --git a/src/Viserio/Bridge/Doctrine/DBAL/composer.json b/src/Viserio/Bridge/Doctrine/DBAL/composer.json deleted file mode 100644 index 03a3cd3fb..000000000 --- a/src/Viserio/Bridge/Doctrine/DBAL/composer.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name" : "viserio/doctrine-dbal-bridge", - "type" : "viserio-bridge", - "description": "The Viserio Doctrine bridge.", - "keywords" : ["narrowspark", "viserio", "database", "doctrine", "dbal", "bridge"], - "license" : "MIT", - "homepage" : "http://narrowspark.com", - "support" : { - "issues": "https://github.com/narrowspark/framework/issues", - "source": "https://github.com/narrowspark/framework" - }, - "authors" : [ - { - "name" : "Daniel Bannert", - "email" : "d.bannert@anolilab.de", - "homepage": "http://www.anolilab.de", - "role" : "Developer" - } - ], - "require": { - "php" : "^7.1", - "ext-pdo" : "*", - "ext-mbstring" : "*", - "doctrine/dbal" : "^2.5", - "narrowspark/collection" : "^0.1", - "viserio/support" : "self.version" - }, - "require-dev": { - "container-interop/service-provider" : "^0.3", - "narrowspark/testing-helper" : "^4.0", - "phpunit/phpunit" : "^6.0", - "viserio/container" : "self.version" - }, - "autoload": { - "psr-4": { - "Viserio\\Bridge\\Doctrine\\DBAL\\" : "" - }, - "exclude-from-classmap" : ["/Tests/"] - }, - "autoload-dev": { - "psr-4": { - "Viserio\\Bridge\\Doctrine\\DBAL\\Tests\\" : "Tests/" - } - }, - "suggest": { - "container-interop/service-provider" : "Required to use service-provider (^0.3).", - "viserio/statical-proxy" : "Required to use the proxy instances (self.version)." - }, - "extra": { - "branch-alias": { - "dev-master" : "1.0-dev" - } - }, - "minimum-stability" : "dev", - "prefer-stable" : true -} diff --git a/src/Viserio/Bridge/Doctrine/Extensions/Provider/ExtensionsServiceProvider.php b/src/Viserio/Bridge/Doctrine/Extensions/Provider/ExtensionsServiceProvider.php index 4c4116048..d9cde53fe 100644 --- a/src/Viserio/Bridge/Doctrine/Extensions/Provider/ExtensionsServiceProvider.php +++ b/src/Viserio/Bridge/Doctrine/Extensions/Provider/ExtensionsServiceProvider.php @@ -38,7 +38,7 @@ public function getExtensions(): array /** * {@inheritdoc} */ - public static function getDimensions(): iterable + public static function getDimensions(): array { return ['viserio', 'doctrine', 'extensions']; } @@ -46,7 +46,7 @@ public static function getDimensions(): iterable /** * {@inheritdoc} */ - public static function getDefaultOptions(): iterable + public static function getDefaultOptions(): array { return [ 'all_mappings' => false, diff --git a/src/Viserio/Bridge/Doctrine/Extensions/composer.json b/src/Viserio/Bridge/Doctrine/Extensions/composer.json index 2338f72c2..cc78f7d68 100644 --- a/src/Viserio/Bridge/Doctrine/Extensions/composer.json +++ b/src/Viserio/Bridge/Doctrine/Extensions/composer.json @@ -1,57 +1,68 @@ { - "name" : "viserio/doctrine-extensions-bridge", - "type" : "viserio-bridge", + "name": "viserio/doctrine-extensions-bridge", + "type": "viserio-bridge", "description": "The Viserio Doctrine Extensions bridge.", - "keywords" : ["narrowspark", "viserio", "extensions", "doctrine", "bridge", "gedmo", "beberlei", "data mapper"], - "license" : "MIT", - "homepage" : "http://narrowspark.com", - "support" : { - "issues": "https://github.com/narrowspark/framework/issues", - "source": "https://github.com/narrowspark/framework" - }, - "authors" : [ + "keywords": [ + "narrowspark", + "viserio", + "extensions", + "doctrine", + "bridge", + "gedmo", + "beberlei", + "data mapper" + ], + "homepage": "http://narrowspark.com", + "license": "MIT", + "authors": [ { - "name" : "Daniel Bannert", - "email" : "d.bannert@anolilab.de", - "homepage": "http://www.anolilab.de", - "role" : "Developer" + "name": "Daniel Bannert", + "email": "d.bannert@anolilab.de", + "homepage": "http://www.anolilab.de", + "role": "Developer" } ], "require": { - "php" : "^7.1", - "doctrine/common" : "^2.7" + "php": "^7.1", + "doctrine/common": "^2.7" }, "require-dev": { - "beberlei/DoctrineExtensions" : "^1.0", - "cakephp/chronos" : "^1.0", - "container-interop/service-provider" : "^0.3", - "gedmo/doctrine-extensions" : "^2.4", - "laravel-doctrine/fluent" : "^1.1", - "phpunit/phpunit" : "^6.0", - "viserio/container" : "self.version" + "beberlei/DoctrineExtensions": "^1.0", + "cakephp/chronos": "^1.0", + "container-interop/service-provider": "^0.3", + "gedmo/doctrine-extensions": "^2.4", + "laravel-doctrine/fluent": "^1.1", + "phpunit/phpunit": "^7.2.0", + "viserio/container": "self.version" + }, + "suggest": { + "beberlei/DoctrineExtensions": "Query/Type Doctrine2 extensions (^1.0)", + "cakephp/chronos": "Required to use Chronos types (Alternative to DateTime) (^1.0)", + "container-interop/service-provider": "Required to use service-provider (^0.3).", + "gedmo/doctrine-extensions": "Behavioral Doctrine2 extensions (^2.4)" + }, + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } }, "autoload": { "psr-4": { - "Viserio\\Bridge\\Doctrine\\Extensions\\" : "" + "Viserio\\Bridge\\Doctrine\\Extensions\\": "" }, - "exclude-from-classmap" : ["/Tests/"] + "exclude-from-classmap": [ + "/Tests/" + ] }, "autoload-dev": { "psr-4": { - "Viserio\\Bridge\\Doctrine\\Extensions\\Tests\\" : "Tests/" + "Viserio\\Bridge\\Doctrine\\Extensions\\Tests\\": "Tests/" } }, - "suggest": { - "cakephp/chronos" : "Required to use Chronos types (Alternative to DateTime) (^1.0)", - "container-interop/service-provider" : "Required to use service-provider (^0.3).", - "gedmo/doctrine-extensions" : "Behavioral Doctrine2 extensions (^2.4)", - "beberlei/DoctrineExtensions" : "Query/Type Doctrine2 extensions (^1.0)" - }, - "extra": { - "branch-alias": { - "dev-master" : "1.0-dev" - } - }, - "minimum-stability" : "dev", - "prefer-stable" : true + "minimum-stability": "dev", + "prefer-stable": true, + "support": { + "issues": "https://github.com/narrowspark/framework/issues", + "source": "https://github.com/narrowspark/framework" + } } diff --git a/src/Viserio/Bridge/Doctrine/Migration/Commands/DiffCommand.php b/src/Viserio/Bridge/Doctrine/Migration/Commands/DiffCommand.php deleted file mode 100644 index e4d6cc991..000000000 --- a/src/Viserio/Bridge/Doctrine/Migration/Commands/DiffCommand.php +++ /dev/null @@ -1,3 +0,0 @@ -getMigrationsDirectory(); - $dir = $dir ?? getcwd(); - $dir = rtrim($dir, '/'); - - if (! file_exists($dir)) { - throw new InvalidArgumentException(sprintf('Migrations directory [%s] does not exist.', $dir)); - } - - if ($configuration->areMigrationsOrganizedByYear()) { - $dir .= DIRECTORY_SEPARATOR . date('Y'); - } - - if ($configuration->areMigrationsOrganizedByYearAndMonth()) { - $dir .= DIRECTORY_SEPARATOR . date('m'); - } - - if (! file_exists($dir)) { - mkdir($dir, 0755, true); - } - - return $dir; - } -} diff --git a/src/Viserio/Bridge/Doctrine/Migration/Commands/LatestCommand.php b/src/Viserio/Bridge/Doctrine/Migration/Commands/LatestCommand.php deleted file mode 100644 index e4d6cc991..000000000 --- a/src/Viserio/Bridge/Doctrine/Migration/Commands/LatestCommand.php +++ /dev/null @@ -1,3 +0,0 @@ -getConnection() instanceof PoolingShardConnection) { - throw new LogicException(sprintf("Connection of EntityManager '%s' must implement shards configuration.", $name)); + throw new LogicException(\sprintf("Connection of EntityManager '%s' must implement shards configuration.", $name)); } $manager->getConnection()->connect($shardId); diff --git a/src/Viserio/Bridge/Doctrine/ORM/Configuration/CacheManager.php b/src/Viserio/Bridge/Doctrine/ORM/Configuration/CacheManager.php index 44caad266..0fdb96a03 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/Configuration/CacheManager.php +++ b/src/Viserio/Bridge/Doctrine/ORM/Configuration/CacheManager.php @@ -11,7 +11,7 @@ class CacheManager extends BaseCacheManager /** * {@inheritdoc} */ - public static function getDimensions(): iterable + public static function getDimensions(): array { return ['viserio', 'doctrine', self::getConfigName()]; } diff --git a/src/Viserio/Bridge/Doctrine/ORM/Configuration/MetaDataManager.php b/src/Viserio/Bridge/Doctrine/ORM/Configuration/MetaDataManager.php index 4d828538d..4df1338b5 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/Configuration/MetaDataManager.php +++ b/src/Viserio/Bridge/Doctrine/ORM/Configuration/MetaDataManager.php @@ -23,7 +23,7 @@ class MetaDataManager extends AbstractManager implements ProvidesDefaultOptionsC /** * {@inheritdoc} */ - public static function getDefaultOptions(): iterable + public static function getDefaultOptions(): array { return [ 'default' => 'annotations', @@ -42,7 +42,7 @@ public static function getDefaultOptions(): iterable /** * {@inheritdoc} */ - public static function getDimensions(): iterable + public static function getDimensions(): array { return ['viserio', 'doctrine', self::getConfigName()]; } diff --git a/src/Viserio/Bridge/Doctrine/ORM/ConnectionFactory.php b/src/Viserio/Bridge/Doctrine/ORM/ConnectionFactory.php index dfb012016..2f26a4bb8 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/ConnectionFactory.php +++ b/src/Viserio/Bridge/Doctrine/ORM/ConnectionFactory.php @@ -52,9 +52,9 @@ public function __construct(array $typesConfig) */ public function createConnection( array $params, - Configuration $config = null, + Configuration $config = null, EventManager $eventManager = null, - array $mappingTypes = [] + array $mappingTypes = [] ): Connection { if (! $this->initialized) { $this->initializeTypes(); diff --git a/src/Viserio/Bridge/Doctrine/ORM/DataCollector/DoctrineDataCollector.php b/src/Viserio/Bridge/Doctrine/ORM/DataCollector/DoctrineDataCollector.php index ec9fe8513..35174950c 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/DataCollector/DoctrineDataCollector.php +++ b/src/Viserio/Bridge/Doctrine/ORM/DataCollector/DoctrineDataCollector.php @@ -38,6 +38,15 @@ public function __construct(ManagerRegistry $registry) $this->managers = $registry->getManagerNames(); } + public function getInvalidEntityCount() + { + if (null === $this->invalidEntityCount) { + $this->invalidEntityCount = \array_sum(\array_map('\count', $this->data['errors'])); + } + + return $this->invalidEntityCount; + } + /** * {@inheritdoc} */ @@ -106,8 +115,8 @@ public function collect(ServerRequestInterface $serverRequest, ResponseInterface /** @var $cacheLoggerStats \Doctrine\ORM\Cache\Logging\StatisticsCacheLogger */ $cacheLoggerStats = $cacheLoggerChain->getLogger('statistics'); $caches['log_enabled'] = true; - $caches['counts']['puts'] += $cacheLoggerStats->getPutCount(); - $caches['counts']['hits'] += $cacheLoggerStats->getHitCount(); + $caches['counts']['puts'] += $cacheLoggerStats->getPutCount(); + $caches['counts']['hits'] += $cacheLoggerStats->getHitCount(); $caches['counts']['misses'] += $cacheLoggerStats->getMissCount(); foreach ($cacheLoggerStats->getRegionsPut() as $key => $value) { @@ -156,15 +165,6 @@ public function addLogger(string $name, DebugStack $logger): void $this->loggers[$name] = $logger; } - public function getInvalidEntityCount() - { - if (null === $this->invalidEntityCount) { - $this->invalidEntityCount = \array_sum(\array_map('\count', $this->data['errors'])); - } - - return $this->invalidEntityCount; - } - /** * {@inheritdoc} */ @@ -191,7 +191,7 @@ public function getPanel(): string private function getQueryCount() { - return array_sum(array_map('count', $this->data['queries'])); + return \array_sum(\array_map('count', $this->data['queries'])); } private function getTime() @@ -212,7 +212,7 @@ private function getGroupedQueryCount() $count = 0; foreach ($this->getGroupedQueries() as $connectionGroupedQueries) { - $count += count($connectionGroupedQueries); + $count += \count($connectionGroupedQueries); } return $count; @@ -247,7 +247,7 @@ private function getGroupedQueries() $totalExecutionMS += $query['executionMS']; } - usort($connectionGroupedQueries, function ($a, $b) { + \usort($connectionGroupedQueries, function ($a, $b) { if ($a['executionMS'] === $b['executionMS']) { return 0; } @@ -284,7 +284,7 @@ private function sanitizeQuery(string $connectionName, array $query): array $query['params'] = []; } - if (! is_array($query['params'])) { + if (! \is_array($query['params'])) { $query['params'] = [$query['params']]; } @@ -293,7 +293,7 @@ private function sanitizeQuery(string $connectionName, array $query): array // Transform the param according to the type $type = $query['types'][$j]; - if (is_string($type)) { + if (\is_string($type)) { $type = Type::getType($type); } @@ -326,15 +326,15 @@ private function sanitizeQuery(string $connectionName, array $query): array */ private function sanitizeParam($var): array { - if (is_object($var)) { - $className = get_class($var); + if (\is_object($var)) { + $className = \get_class($var); - return method_exists($var, '__toString') ? - [sprintf('Object(%s): "%s"', $className, $var->__toString()), false] : - [sprintf('Object(%s)', $className), false]; + return \method_exists($var, '__toString') ? + [\sprintf('Object(%s): "%s"', $className, $var->__toString()), false] : + [\sprintf('Object(%s)', $className), false]; } - if (is_array($var)) { + if (\is_array($var)) { $a = []; $original = true; @@ -347,8 +347,8 @@ private function sanitizeParam($var): array return [$a, $original]; } - if (is_resource($var)) { - return [sprintf('Resource(%s)', get_resource_type($var)), false]; + if (\is_resource($var)) { + return [\sprintf('Resource(%s)', \get_resource_type($var)), false]; } return [$var, true]; diff --git a/src/Viserio/Bridge/Doctrine/ORM/EntityManagerFactory.php b/src/Viserio/Bridge/Doctrine/ORM/EntityManagerFactory.php index 436915be4..8031ebf24 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/EntityManagerFactory.php +++ b/src/Viserio/Bridge/Doctrine/ORM/EntityManagerFactory.php @@ -82,7 +82,7 @@ public function __construct( /** * {@inheritdoc} */ - public static function getDimensions(): iterable + public static function getDimensions(): array { return ['viserio', 'doctrine', 'orm']; } @@ -90,7 +90,7 @@ public static function getDimensions(): iterable /** * {@inheritdoc} */ - public static function getDefaultOptions(): iterable + public static function getDefaultOptions(): array { return [ 'logger' => false, @@ -121,7 +121,7 @@ public static function getDefaultOptions(): iterable /** * {@inheritdoc} */ - public static function getMandatoryOptions(): iterable + public static function getMandatoryOptions(): array { return [ 'connections' => [ @@ -222,9 +222,7 @@ protected function configureFirstLevelCacheSettings(Configuration $configuration $configuration->setResultCacheImpl($cache->getDriver($this->options['result_cache_driver'])); $configuration->setMetadataCacheImpl($cache->getDriver($this->options['metadata_cache_driver'])); - $configuration = $this->setSecondLevelCaching($configuration); - - return $configuration; + return $this->setSecondLevelCaching($configuration); } /** @@ -238,7 +236,7 @@ protected function setSecondLevelCaching(Configuration $configuration): Configur { $secondCacheSetting = $this->options['second_level_cache']; - if (is_array($secondCacheSetting)) { + if (\is_array($secondCacheSetting)) { $configuration->setSecondLevelCacheEnabled(); $cacheConfig = $configuration->getSecondLevelCacheConfiguration(); @@ -287,7 +285,7 @@ protected function decorateManager(EntityManagerInterface $manager): EntityManag { if ($decorator = $this->options['decorator']) { if (! class_exists($decorator)) { - throw new InvalidArgumentException(sprintf('EntityManagerDecorator [%s] does not exist', $decorator)); + throw new InvalidArgumentException(\sprintf('EntityManagerDecorator [%s] does not exist', $decorator)); } $manager = new $decorator($manager); @@ -309,7 +307,7 @@ protected function registerListeners(EntityManagerInterface $manager): void if ($listeners = $this->options['events']['listeners'] !== false) { foreach ($listeners as $event => $listener) { - if (is_array($listener)) { + if (\is_array($listener)) { foreach ($listener as $individualListener) { $resolvedListener = $this->container->get($listener); diff --git a/src/Viserio/Bridge/Doctrine/ORM/ManagerRegistry.php b/src/Viserio/Bridge/Doctrine/ORM/ManagerRegistry.php index 05337eb18..4174a7323 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/ManagerRegistry.php +++ b/src/Viserio/Bridge/Doctrine/ORM/ManagerRegistry.php @@ -97,6 +97,46 @@ public function setDefaultManager(string $defaultManager): void $this->defaultManager = $defaultManager; } + /** + * Set a default connection. + * + * @param string $defaultConnection + * + * @return void + */ + public function setDefaultConnection(string $defaultConnection): void + { + $this->defaultConnection = $defaultConnection; + } + + /** + * {@inheritdoc} + */ + public function getManagers(): array + { + $managers = []; + + foreach ($this->getManagerNames() as $name) { + $managers[$name] = $this->getManager($name); + } + + return $managers; + } + + /** + * {@inheritdoc} + */ + public function getConnections(): array + { + $connections = []; + + foreach ($this->connections as $name) { + $connections[$name] = $this->getConnection($name); + } + + return $connections; + } + /** * Add a new manager instance. * @@ -136,7 +176,7 @@ public function getManager($name = null): ObjectManager $name = $name ?? $this->getDefaultManagerName(); if (! $this->hasManager($name)) { - throw new InvalidArgumentException(sprintf('Doctrine Manager named [%s] does not exist.', $name)); + throw new InvalidArgumentException(\sprintf('Doctrine Manager named [%s] does not exist.', $name)); } if (isset($this->managersMap[$name])) { @@ -168,20 +208,6 @@ public function getManagerNames(): array return $this->managers; } - /** - * {@inheritdoc} - */ - public function getManagers(): array - { - $managers = []; - - foreach ($this->getManagerNames() as $name) { - $managers[$name] = $this->getManager($name); - } - - return $managers; - } - /** * {@inheritdoc} */ @@ -190,7 +216,7 @@ public function resetManager($name = null): ObjectManager $name = $name ?? $this->getDefaultManagerName(); if (! $this->hasManager($name)) { - throw new InvalidArgumentException(sprintf('Doctrine Manager named [%s] does not exist.', $name)); + throw new InvalidArgumentException(\sprintf('Doctrine Manager named [%s] does not exist.', $name)); } // force the creation of a new document manager @@ -235,8 +261,8 @@ public function getRepository($persistentObject, $persistentManagerName = null): public function getManagerForClass($class): ?ObjectManager { // Check for namespace alias - if (mb_strpos($class, ':') !== false) { - [$namespaceAlias, $simpleClassName] = explode(':', $class, 2); + if (\mb_strpos($class, ':') !== false) { + [$namespaceAlias, $simpleClassName] = \explode(':', $class, 2); $class = $this->getAliasNamespace($namespaceAlias) . '\\' . $simpleClassName; } @@ -259,18 +285,6 @@ public function getManagerForClass($class): ?ObjectManager } } - /** - * Set a default connection. - * - * @param string $defaultConnection - * - * @return void - */ - public function setDefaultConnection(string $defaultConnection): void - { - $this->defaultConnection = $defaultConnection; - } - /** * Add a new connection. * @@ -297,7 +311,7 @@ public function getDefaultConnectionName(): string return $this->defaultConnection; } - return reset($this->connections); + return \reset($this->connections); } /** @@ -308,7 +322,7 @@ public function getConnection($name = null) $name = $name ?? $this->getDefaultConnectionName(); if (! $this->hasConnection($name)) { - throw new InvalidArgumentException(sprintf('Doctrine Connection named [%s] does not exist.', $name)); + throw new InvalidArgumentException(\sprintf('Doctrine Connection named [%s] does not exist.', $name)); } if (isset($this->connectionsMap[$name])) { @@ -332,20 +346,6 @@ public function hasConnection(string $name): bool return isset($this->connections[$name]); } - /** - * {@inheritdoc} - */ - public function getConnections(): array - { - $connections = []; - - foreach ($this->connections as $name) { - $connections[$name] = $this->getConnection($name); - } - - return $connections; - } - /** * {@inheritdoc} */ diff --git a/src/Viserio/Bridge/Doctrine/ORM/Provider/ConsoleCommandsServiceProvider.php b/src/Viserio/Bridge/Doctrine/ORM/Provider/ConsoleCommandsServiceProvider.php index 42ae86e81..3726e205b 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/Provider/ConsoleCommandsServiceProvider.php +++ b/src/Viserio/Bridge/Doctrine/ORM/Provider/ConsoleCommandsServiceProvider.php @@ -52,10 +52,8 @@ public function getExtensions() * * @return null|\Viserio\Component\Console\Application */ - public static function extendConsole( - ContainerInterface $container, - ?Application $console = null - ): ?Application { + public static function extendConsole(ContainerInterface $container, ?Application $console = null): ?Application + { if ($console !== null) { $manager = $container->get(EntityManagerInterface::class); diff --git a/src/Viserio/Bridge/Doctrine/ORM/Provider/DoctrineORMServiceProvicer.php b/src/Viserio/Bridge/Doctrine/ORM/Provider/DoctrineORMServiceProvicer.php index 6cb51b668..d038fe1f4 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/Provider/DoctrineORMServiceProvicer.php +++ b/src/Viserio/Bridge/Doctrine/ORM/Provider/DoctrineORMServiceProvicer.php @@ -35,9 +35,7 @@ public function getServices() public static function createManagerRegistry(ContainerInterface $container): DoctrineManagerRegistry { - $registery = new ManagerRegistry($container, $container->get(EntityManagerFactory::class)); - - return $registery; + return new ManagerRegistry($container, $container->get(EntityManagerFactory::class)); } public static function createEntityManager(ContainerInterface $container): EntityManagerInterface diff --git a/src/Viserio/Bridge/Doctrine/ORM/Resolvers/EntityListenerResolver.php b/src/Viserio/Bridge/Doctrine/ORM/Resolvers/EntityListenerResolver.php index 6066551f3..8bedfa1d2 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/Resolvers/EntityListenerResolver.php +++ b/src/Viserio/Bridge/Doctrine/ORM/Resolvers/EntityListenerResolver.php @@ -34,7 +34,7 @@ public function __construct(ContainerInterface $container) public function clear($className = null): void { if ($className) { - unset($this->instances[$className = trim($className, '\\')]); + unset($this->instances[$className = \trim($className, '\\')]); return; } @@ -47,7 +47,7 @@ public function clear($className = null): void */ public function resolve($className) { - if (isset($this->instances[$className = trim($className, '\\')])) { + if (isset($this->instances[$className = \trim($className, '\\')])) { return $this->instances[$className]; } @@ -59,10 +59,10 @@ public function resolve($className) */ public function register($object): void { - if (! is_object($object)) { - throw new InvalidArgumentException(sprintf('An object was expected, but got "%s".', gettype($object))); + if (! \is_object($object)) { + throw new InvalidArgumentException(\sprintf('An object was expected, but got "%s".', \gettype($object))); } - $this->instances[get_class($object)] = $object; + $this->instances[\get_class($object)] = $object; } } diff --git a/src/Viserio/Bridge/Doctrine/ORM/Serializers/Traits/ArrayableTrait.php b/src/Viserio/Bridge/Doctrine/ORM/Serializers/Traits/ArrayableTrait.php index 301c4b19c..7780abe74 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/Serializers/Traits/ArrayableTrait.php +++ b/src/Viserio/Bridge/Doctrine/ORM/Serializers/Traits/ArrayableTrait.php @@ -11,14 +11,14 @@ trait ArrayableTrait /** * @return string */ - public function toArray() + public function toArray(): string { $serializer = new Serializer( [ new GetSetMethodNormalizer(), ], [ - 'array' => new ArrayEncoder(), + 'array' => new ArrayEncoder(), ] ); diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/ClassAliasesTest.php b/src/Viserio/Bridge/Doctrine/ORM/Tests/ClassAliasesTest.php index 2d6c371a7..8682f0abf 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/Tests/ClassAliasesTest.php +++ b/src/Viserio/Bridge/Doctrine/ORM/Tests/ClassAliasesTest.php @@ -7,12 +7,15 @@ use Viserio\Bridge\Doctrine\ORM\Fluent as ViserioFluent; use Viserio\Bridge\Doctrine\ORM\FluentDriver as ViserioFluentDriver; -class ClassAliasesTest extends TestCase +/** + * @internal + */ +final class ClassAliasesTest extends TestCase { public function testAlias(): void { - self::assertTrue(interface_exists(ViserioFluent::class)); - self::assertTrue(class_exists(ViserioEntityMapping::class)); - self::assertTrue(class_exists(ViserioFluentDriver::class)); + $this->assertTrue(\interface_exists(ViserioFluent::class)); + $this->assertTrue(class_exists(ViserioEntityMapping::class)); + $this->assertTrue(class_exists(ViserioFluentDriver::class)); } } diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/Configuration/CacheManagerTest.php b/src/Viserio/Bridge/Doctrine/ORM/Tests/Configuration/CacheManagerTest.php index 8d2316399..ed130babe 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/Tests/Configuration/CacheManagerTest.php +++ b/src/Viserio/Bridge/Doctrine/ORM/Tests/Configuration/CacheManagerTest.php @@ -7,7 +7,10 @@ use PHPUnit\Framework\TestCase; use Viserio\Bridge\Doctrine\ORM\Configuration\CacheManager; -class CacheManagerTest extends TestCase +/** + * @internal + */ +final class CacheManagerTest extends TestCase { public function testGetDriverWithDoctrineWrapper(): void { @@ -26,7 +29,7 @@ public function testGetDriverWithDoctrineWrapper(): void ]) ); - self::assertInstanceOf(DoctrineCacheBridge::class, $manager->getDriver('array')); - self::assertInstanceOf(DoctrineCacheBridge::class, $manager->getDriver()); + $this->assertInstanceOf(DoctrineCacheBridge::class, $manager->getDriver('array')); + $this->assertInstanceOf(DoctrineCacheBridge::class, $manager->getDriver()); } } diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/Configuration/MetaDataManagerTest.php b/src/Viserio/Bridge/Doctrine/ORM/Tests/Configuration/MetaDataManagerTest.php index ccac98ea2..3a68ff46e 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/Tests/Configuration/MetaDataManagerTest.php +++ b/src/Viserio/Bridge/Doctrine/ORM/Tests/Configuration/MetaDataManagerTest.php @@ -15,7 +15,10 @@ use PHPUnit\Framework\TestCase; use Viserio\Bridge\Doctrine\ORM\Configuration\MetaDataManager; -class MetaDataManagerTest extends TestCase +/** + * @internal + */ +final class MetaDataManagerTest extends TestCase { public function testGetDriverWithAnnotations(): void { @@ -33,13 +36,13 @@ public function testGetDriverWithAnnotations(): void ); $driver = $manager->getDriver(); - self::assertInstanceOf(AnnotationDriver::class, $driver['driver']); - self::assertSame(ClassMetadataFactory::class, $driver['meta_factory']); + $this->assertInstanceOf(AnnotationDriver::class, $driver['driver']); + $this->assertSame(ClassMetadataFactory::class, $driver['meta_factory']); $driver = $manager->getDriver('annotations'); - self::assertInstanceOf(AnnotationDriver::class, $driver['driver']); - self::assertSame(ClassMetadataFactory::class, $driver['meta_factory']); + $this->assertInstanceOf(AnnotationDriver::class, $driver['driver']); + $this->assertSame(ClassMetadataFactory::class, $driver['meta_factory']); } /** @@ -64,8 +67,8 @@ public function testMetaDataDriver(array $config, $driverInfos, $driverName): vo $driver = $manager->getDriver($driverName); - self::assertInstanceOf($driverInfos['driver'], $driver['driver']); - self::assertSame($driverInfos['meta_factory'], $driver['meta_factory']); + $this->assertInstanceOf($driverInfos['driver'], $driver['driver']); + $this->assertSame($driverInfos['meta_factory'], $driver['meta_factory']); } public function metaDriverProvider() diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/Fixtures/ArrayableEntityFixture.php b/src/Viserio/Bridge/Doctrine/ORM/Tests/Fixtures/ArrayableEntityFixture.php index b288949a1..391572a79 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/Tests/Fixtures/ArrayableEntityFixture.php +++ b/src/Viserio/Bridge/Doctrine/ORM/Tests/Fixtures/ArrayableEntityFixture.php @@ -9,6 +9,7 @@ class ArrayableEntityFixture use ArrayableTrait; protected $id = 'IDVALUE'; + protected $name = 'NAMEVALUE'; public function getId() diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/ManagerRegistryTest.php b/src/Viserio/Bridge/Doctrine/ORM/Tests/ManagerRegistryTest.php index a400551be..4c18261ab 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/Tests/ManagerRegistryTest.php +++ b/src/Viserio/Bridge/Doctrine/ORM/Tests/ManagerRegistryTest.php @@ -7,7 +7,10 @@ use Viserio\Bridge\Doctrine\ORM\EntityManagerFactory; use Viserio\Bridge\Doctrine\ORM\ManagerRegistry; -class ManagerRegistryTest extends MockeryTestCase +/** + * @internal + */ +final class ManagerRegistryTest extends MockeryTestCase { /** * @var Mock @@ -24,7 +27,7 @@ class ManagerRegistryTest extends MockeryTestCase */ protected $registry; - public function setUp(): void + protected function setUp(): void { parent::setUp(); @@ -37,12 +40,11 @@ public function setUp(): void ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Doctrine Connection named [non-existing] does not exist. - */ public function testCannotNonExistingConnection(): void { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Doctrine Connection named [non-existing] does not exist.'); + $this->registry->getConnection('non-existing'); } } diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/Provider/ConsoleCommandsServiceProviderTest.php b/src/Viserio/Bridge/Doctrine/ORM/Tests/Provider/ConsoleCommandsServiceProviderTest.php index b8761d3dd..599da46a1 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/Tests/Provider/ConsoleCommandsServiceProviderTest.php +++ b/src/Viserio/Bridge/Doctrine/ORM/Tests/Provider/ConsoleCommandsServiceProviderTest.php @@ -24,7 +24,10 @@ use Viserio\Component\Console\Provider\ConsoleServiceProvider; use Viserio\Component\Container\Container; -class ConsoleCommandsServiceProviderTest extends MockeryTestCase +/** + * @internal + */ +final class ConsoleCommandsServiceProviderTest extends MockeryTestCase { public function testProvider(): void { @@ -48,19 +51,19 @@ public function testProvider(): void $console = $container->get(Application::class); $commands = $console->all(); - self::assertInstanceOf(MetadataCommand::class, $commands['orm:clear-cache:metadata']); - self::assertInstanceOf(QueryCommand::class, $commands['orm:clear-cache:query']); - self::assertInstanceOf(ResultCommand::class, $commands['orm:clear-cache:result']); - self::assertInstanceOf(ConvertDoctrine1SchemaCommand::class, $commands['orm:convert-d1-schema']); - self::assertInstanceOf(ConvertMappingCommand::class, $commands['orm:convert-mapping']); - self::assertInstanceOf(EnsureProductionSettingsCommand::class, $commands['orm:ensure-production-settings']); - self::assertInstanceOf(GenerateRepositoriesCommand::class, $commands['orm:generate-repositories']); - self::assertInstanceOf(InfoCommand::class, $commands['orm:info']); - self::assertInstanceOf(MappingDescribeCommand::class, $commands['orm:mapping:describe']); - self::assertInstanceOf(RunDqlCommand::class, $commands['orm:run-dql']); - self::assertInstanceOf(CreateCommand::class, $commands['orm:schema-tool:create']); - self::assertInstanceOf(DropCommand::class, $commands['orm:schema-tool:drop']); - self::assertInstanceOf(UpdateCommand::class, $commands['orm:schema-tool:update']); - self::assertInstanceOf(ValidateSchemaCommand::class, $commands['orm:validate-schema']); + $this->assertInstanceOf(MetadataCommand::class, $commands['orm:clear-cache:metadata']); + $this->assertInstanceOf(QueryCommand::class, $commands['orm:clear-cache:query']); + $this->assertInstanceOf(ResultCommand::class, $commands['orm:clear-cache:result']); + $this->assertInstanceOf(ConvertDoctrine1SchemaCommand::class, $commands['orm:convert-d1-schema']); + $this->assertInstanceOf(ConvertMappingCommand::class, $commands['orm:convert-mapping']); + $this->assertInstanceOf(EnsureProductionSettingsCommand::class, $commands['orm:ensure-production-settings']); + $this->assertInstanceOf(GenerateRepositoriesCommand::class, $commands['orm:generate-repositories']); + $this->assertInstanceOf(InfoCommand::class, $commands['orm:info']); + $this->assertInstanceOf(MappingDescribeCommand::class, $commands['orm:mapping:describe']); + $this->assertInstanceOf(RunDqlCommand::class, $commands['orm:run-dql']); + $this->assertInstanceOf(CreateCommand::class, $commands['orm:schema-tool:create']); + $this->assertInstanceOf(DropCommand::class, $commands['orm:schema-tool:drop']); + $this->assertInstanceOf(UpdateCommand::class, $commands['orm:schema-tool:update']); + $this->assertInstanceOf(ValidateSchemaCommand::class, $commands['orm:validate-schema']); } } diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/Resolvers/EntityListenerResolverTest.php b/src/Viserio/Bridge/Doctrine/ORM/Tests/Resolvers/EntityListenerResolverTest.php index 2dc4bd101..8cc88bbf8 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/Tests/Resolvers/EntityListenerResolverTest.php +++ b/src/Viserio/Bridge/Doctrine/ORM/Tests/Resolvers/EntityListenerResolverTest.php @@ -8,7 +8,10 @@ use stdClass; use Viserio\Bridge\Doctrine\ORM\Resolvers\EntityListenerResolver; -class EntityListenerResolverTest extends MockeryTestCase +/** + * @internal + */ +final class EntityListenerResolverTest extends MockeryTestCase { public function testImplementsDoctrineInterface(): void { @@ -110,17 +113,16 @@ public function testAllowsDirectlyRegisteringListeners(): void $resolver = new EntityListenerResolver($container); $resolver->register($object); - $resolvedObject = $resolver->resolve(get_class($object)); + $resolvedObject = $resolver->resolve(\get_class($object)); $this->assertSame($object, $resolvedObject, 'Resolver should not use container when directly registering'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage An object was expected, but got "string". - */ public function testDoesNotAllowRegisteringNonObjects(): void { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('An object was expected, but got "string".'); + $container = $this->mock(ContainerInterface::class); $resolver = new EntityListenerResolver($container); $resolver->register('foo'); diff --git a/src/Viserio/Bridge/Doctrine/ORM/Tests/Serializers/ArrayEncoderTest.php b/src/Viserio/Bridge/Doctrine/ORM/Tests/Serializers/ArrayEncoderTest.php index 0e416aae2..6c2413b17 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/Tests/Serializers/ArrayEncoderTest.php +++ b/src/Viserio/Bridge/Doctrine/ORM/Tests/Serializers/ArrayEncoderTest.php @@ -8,7 +8,10 @@ use Viserio\Bridge\Doctrine\ORM\Serializers\ArrayEncoder; use Viserio\Bridge\Doctrine\ORM\Tests\Fixtures\ArrayableEntityFixture; -class ArrayEncoderTest extends TestCase +/** + * @internal + */ +final class ArrayEncoderTest extends TestCase { public function testCanSerializeToArray(): void { diff --git a/src/Viserio/Bridge/Doctrine/ORM/alias.php b/src/Viserio/Bridge/Doctrine/ORM/alias.php index 687f62b04..e667d2f40 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/alias.php +++ b/src/Viserio/Bridge/Doctrine/ORM/alias.php @@ -6,13 +6,13 @@ use LaravelDoctrine\Fluent\FluentDriver; if (class_exists(EntityMapping::class)) { - class_alias(EntityMapping::class, 'Viserio\Bridge\Doctrine\ORM\EntityMapping'); + \class_alias(EntityMapping::class, 'Viserio\Bridge\Doctrine\ORM\EntityMapping'); } -if (interface_exists(Fluent::class)) { - class_alias(Fluent::class, 'Viserio\Bridge\Doctrine\ORM\Fluent'); +if (\interface_exists(Fluent::class)) { + \class_alias(Fluent::class, 'Viserio\Bridge\Doctrine\ORM\Fluent'); } if (class_exists(FluentDriver::class)) { - class_alias(FluentDriver::class, 'Viserio\Bridge\Doctrine\ORM\FluentDriver'); + \class_alias(FluentDriver::class, 'Viserio\Bridge\Doctrine\ORM\FluentDriver'); } diff --git a/src/Viserio/Bridge/Doctrine/ORM/composer.json b/src/Viserio/Bridge/Doctrine/ORM/composer.json index 0ac0f1496..85c570577 100644 --- a/src/Viserio/Bridge/Doctrine/ORM/composer.json +++ b/src/Viserio/Bridge/Doctrine/ORM/composer.json @@ -1,64 +1,76 @@ { - "name" : "viserio/doctrine-orm-bridge", - "type" : "viserio-bridge", + "name": "viserio/doctrine-orm-bridge", + "type": "viserio-bridge", "description": "The Viserio Doctrine ORM bridge.", - "keywords" : ["narrowspark", "viserio", "database", "doctrine", "orm", "bridge", "fluent"], - "license" : "MIT", - "homepage" : "http://narrowspark.com", - "support" : { - "issues": "https://github.com/narrowspark/framework/issues", - "source": "https://github.com/narrowspark/framework" - }, - "authors" : [ + "keywords": [ + "narrowspark", + "viserio", + "database", + "doctrine", + "orm", + "bridge", + "fluent" + ], + "homepage": "http://narrowspark.com", + "license": "MIT", + "authors": [ { - "name" : "Daniel Bannert", - "email" : "d.bannert@anolilab.de", - "homepage": "http://www.anolilab.de", - "role" : "Developer" + "name": "Daniel Bannert", + "email": "d.bannert@anolilab.de", + "homepage": "http://www.anolilab.de", + "role": "Developer" } ], "require": { - "php" : "^7.1", - "ext-pdo" : "*", - "cache/psr-6-doctrine-bridge" : "^3.0", - "doctrine/orm" : "^2.5", - "ocramius/proxy-manager" : "^2.1", - "viserio/cache" : "self.version", - "viserio/bridge-doctrine-dbal" : "self.version", - "viserio/contracts" : "self.version", - "viserio/options-resolver" : "self.version", - "viserio/support" : "self.version" + "php": "^7.1", + "ext-pdo": "*", + "cache/psr-6-doctrine-bridge": "^3.0", + "doctrine/orm": "^2.5", + "ocramius/proxy-manager": "^2.1", + "viserio/bridge-doctrine-dbal": "self.version", + "viserio/cache": "self.version", + "viserio/contracts": "self.version", + "viserio/options-resolver": "self.version", + "viserio/support": "self.version" }, "require-dev": { - "container-interop/service-provider" : "^0.3", - "laravel-doctrine/fluent" : "^1.1", - "narrowspark/testing-helper" : "^2.0", - "phpunit/phpunit" : "^6.0", - "symfony/serializer" : "~3.3", - "viserio/console" : "self.version", - "viserio/pagination" : "self.version" + "container-interop/service-provider": "^0.3", + "laravel-doctrine/fluent": "^1.1", + "narrowspark/testing-helper": "^2.0", + "phpunit/phpunit": "^7.2.0", + "symfony/serializer": "~3.3", + "viserio/console": "self.version", + "viserio/pagination": "self.version" + }, + "suggest": { + "container-interop/service-provider": "Required to use service-provider (^0.3).", + "viserio/statical-proxy": "Required to use the proxy instances (self.version)." + }, + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } }, "autoload": { "psr-4": { - "Viserio\\Bridge\\Doctrine\\ORM\\" : "" + "Viserio\\Bridge\\Doctrine\\ORM\\": "" }, - "files" : ["alias.php"], - "exclude-from-classmap" : ["/Tests/"] + "files": [ + "alias.php" + ], + "exclude-from-classmap": [ + "/Tests/" + ] }, "autoload-dev": { "psr-4": { - "Viserio\\Bridge\\Doctrine\\ORM\\Tests\\" : "Tests/" + "Viserio\\Bridge\\Doctrine\\ORM\\Tests\\": "Tests/" } }, - "suggest": { - "container-interop/service-provider" : "Required to use service-provider (^0.3).", - "viserio/statical-proxy" : "Required to use the proxy instances (self.version)." - }, - "extra": { - "branch-alias": { - "dev-master" : "1.0-dev" - } - }, - "minimum-stability" : "dev", - "prefer-stable" : true + "minimum-stability": "dev", + "prefer-stable": true, + "support": { + "issues": "https://github.com/narrowspark/framework/issues", + "source": "https://github.com/narrowspark/framework" + } } diff --git a/src/Viserio/Bridge/Doctrine/Testing/Cache/StaticArrayCache.php b/src/Viserio/Bridge/Doctrine/Testing/Cache/StaticArrayCache.php index ad3e82377..76a2a265c 100644 --- a/src/Viserio/Bridge/Doctrine/Testing/Cache/StaticArrayCache.php +++ b/src/Viserio/Bridge/Doctrine/Testing/Cache/StaticArrayCache.php @@ -35,7 +35,7 @@ class StaticArrayCache extends CacheProvider */ public function __construct() { - $this->upTime = time(); + $this->upTime = \time(); } /** @@ -65,7 +65,7 @@ protected function doContains($id): bool $expiration = self::$data[$id][1]; - if ($expiration && $expiration < time()) { + if ($expiration && $expiration < \time()) { $this->doDelete($id); return false; @@ -79,7 +79,7 @@ protected function doContains($id): bool */ protected function doSave($id, $data, $lifeTime = 0): bool { - self::$data[$id] = [$data, $lifeTime ? time() + $lifeTime : false]; + self::$data[$id] = [$data, $lifeTime ? \time() + $lifeTime : false]; return true; } diff --git a/src/Viserio/Bridge/Doctrine/Testing/Concerns/DoctrineEntitiesTestCase.php b/src/Viserio/Bridge/Doctrine/Testing/Concerns/DoctrineEntitiesTestCase.php index b0b04acf9..4256054cd 100644 --- a/src/Viserio/Bridge/Doctrine/Testing/Concerns/DoctrineEntitiesTestCase.php +++ b/src/Viserio/Bridge/Doctrine/Testing/Concerns/DoctrineEntitiesTestCase.php @@ -4,6 +4,9 @@ use PHPUnit\Framework\TestCase; +/** + * @internal + */ abstract class DoctrineEntitiesTestCase extends TestCase { use InteractsWithEntities; diff --git a/src/Viserio/Bridge/Doctrine/Testing/Concerns/InteractsWithEntities.php b/src/Viserio/Bridge/Doctrine/Testing/Concerns/InteractsWithEntities.php index 61d367960..c52d141c4 100644 --- a/src/Viserio/Bridge/Doctrine/Testing/Concerns/InteractsWithEntities.php +++ b/src/Viserio/Bridge/Doctrine/Testing/Concerns/InteractsWithEntities.php @@ -15,16 +15,16 @@ trait InteractsWithEntities * * @return object */ - public static function entityExists(string $class, $id) + public static function entityExists(string $class, $id): object { $entity = self::entityManager()->find($class, $id); Assert::assertNotNull( $entity, - sprintf( + \sprintf( 'A [%s] entity was not found by id: %s', $class, - print_r($id, true) + \print_r($id, true) ) ); @@ -43,10 +43,10 @@ public static function entityDoesNotExist(string $class, $id): void { Assert::assertNull( self::entityManager()->find($class, $id), - sprintf( + \sprintf( 'A [%s] entity was found by id: %s', $class, - print_r($id, true) + \print_r($id, true) ) ); } @@ -66,10 +66,10 @@ public static function entitiesMatch(string $class, array $criteria, ?int $count Assert::assertNotEmpty( $entities, - sprintf( + \sprintf( 'No [%s] entities were found with the given criteria: %s', $class, - print_r($criteria, true) + \print_r($criteria, true) ) ); @@ -77,12 +77,12 @@ public static function entitiesMatch(string $class, array $criteria, ?int $count Assert::assertCount( $count, $entities, - sprintf( + \sprintf( 'Expected to find %s [%s] entities, but found %s with the given criteria: %s', $count, $class, - count($entities), - print_r($criteria, true) + \count($entities), + \print_r($criteria, true) ) ); } @@ -102,7 +102,7 @@ public static function noEntitiesMatch(string $class, array $criteria): void { Assert::assertEmpty( self::entityManager()->getRepository($class)->findBy($criteria), - "Some [$class] entities were found with the given criteria: " . print_r($criteria, true) + "Some [${class}] entities were found with the given criteria: " . \print_r($criteria, true) ); } diff --git a/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticConnection.php b/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticConnection.php index 073f7d10b..b50fc28dc 100644 --- a/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticConnection.php +++ b/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticConnection.php @@ -116,7 +116,7 @@ public function errorInfo() /** * @return Connection */ - public function getWrappedConnection() + public function getWrappedConnection(): Connection { return $this->connection; } diff --git a/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticDriver.php b/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticDriver.php index 0cd4aa509..d37f68e20 100644 --- a/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticDriver.php +++ b/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticDriver.php @@ -52,13 +52,35 @@ public function __construct(Driver $underlyingDriver, AbstractPlatform $platform $this->platform = $platform; } + /** + * Is the connection held. + * + * @return bool + */ + public static function isKeepStaticConnections(): bool + { + return self::$keepStaticConnections; + } + + /** + * Should the connection be kept? + * + * @param bool $keepStaticConnections + * + * @return void + */ + public static function setKeepStaticConnections(bool $keepStaticConnections): void + { + self::$keepStaticConnections = $keepStaticConnections; + } + /** * {@inheritdoc} */ public function connect(array $params, $username = null, $password = null, array $driverOptions = []) { if (self::$keepStaticConnections) { - $key = sha1(serialize($params) . $username . $password); + $key = \sha1(\serialize($params) . $username . $password); if (! isset(self::$connections[$key])) { self::$connections[$key] = $this->underlyingDriver->connect($params, $username, $password, $driverOptions); @@ -123,28 +145,6 @@ public function createDatabasePlatformForVersion($version) return $this->platform; } - /** - * Should the connection be kept? - * - * @param bool $keepStaticConnections - * - * @return void - */ - public static function setKeepStaticConnections(bool $keepStaticConnections): void - { - self::$keepStaticConnections = $keepStaticConnections; - } - - /** - * Is the connection held. - * - * @return bool - */ - public static function isKeepStaticConnections(): bool - { - return self::$keepStaticConnections; - } - /** * Begins a transaction. * diff --git a/src/Viserio/Bridge/Doctrine/Testing/Factory.php b/src/Viserio/Bridge/Doctrine/Testing/Factory.php index 6b0416b8b..c8bbb69a8 100644 --- a/src/Viserio/Bridge/Doctrine/Testing/Factory.php +++ b/src/Viserio/Bridge/Doctrine/Testing/Factory.php @@ -42,8 +42,8 @@ public function __construct(Faker $faker, ManagerRegistry $registry, string $pat $this->faker = $faker; $this->registry = $registry; - if (! is_dir($pathToFactories)) { - throw new RuntimeException(sprintf('[%s] is not a directory.', $pathToFactories)); + if (! \is_dir($pathToFactories)) { + throw new RuntimeException(\sprintf('[%s] is not a directory.', $pathToFactories)); } foreach (Finder::create()->files()->name('*.php')->in($pathToFactories) as $file) { @@ -142,7 +142,7 @@ public function makeAs(string $class, string $name, array $attributes = []) * * @return array */ - public function rawOf(string $class, string $name, array $attributes = []) + public function rawOf(string $class, string $name, array $attributes = []): array { return $this->raw($class, $attributes, $name); } @@ -158,9 +158,9 @@ public function rawOf(string $class, string $name, array $attributes = []) */ public function raw(string $class, array $attributes = [], string $name = 'default'): array { - $raw = call_user_func($this->definitions[$class][$name], $this->faker); + $raw = \call_user_func($this->definitions[$class][$name], $this->faker); - return array_merge($raw, $attributes); + return \array_merge($raw, $attributes); } /** @@ -183,7 +183,7 @@ public function of(string $class, string $name = 'default'): FactoryBuilder * * @return bool */ - public function offsetExists($offset) + public function offsetExists($offset): bool { return isset($this->definitions[$offset]); } @@ -208,9 +208,9 @@ public function offsetGet($offset) * * @return void */ - public function offsetSet($offset, $value) + public function offsetSet($offset, $value): void { - return $this->define($offset, $value); + $this->define($offset, $value); } /** diff --git a/src/Viserio/Bridge/Doctrine/Testing/FactoryBuilder.php b/src/Viserio/Bridge/Doctrine/Testing/FactoryBuilder.php index bf9127597..54037f41d 100644 --- a/src/Viserio/Bridge/Doctrine/Testing/FactoryBuilder.php +++ b/src/Viserio/Bridge/Doctrine/Testing/FactoryBuilder.php @@ -60,8 +60,13 @@ class FactoryBuilder * @param array $definitions * @param \Faker\Generator $faker */ - public function __construct(ManagerRegistry $registry, string $class, string $name, array $definitions, Faker $faker) - { + public function __construct( + ManagerRegistry $registry, + string $class, + string $name, + array $definitions, + Faker $faker + ) { $this->name = $name; $this->class = $class; $this->faker = $faker; @@ -143,12 +148,12 @@ protected function makeInstance(array $attributes = []) throw new InvalidArgumentException("Unable to locate factory with name [{$this->name}]."); } - $definition = call_user_func($this->definitions[$this->class][$this->name], $this->faker, $attributes); + $definition = \call_user_func($this->definitions[$this->class][$this->name], $this->faker, $attributes); if ($definition instanceof $this->class) { return $definition; } - return SimpleHydrator::hydrate($this->class, array_merge($definition, $attributes)); + return SimpleHydrator::hydrate($this->class, \array_merge($definition, $attributes)); } } diff --git a/src/Viserio/Bridge/Doctrine/Testing/Provider/ConsoleCommandsServiceProvider.php b/src/Viserio/Bridge/Doctrine/Testing/Provider/ConsoleCommandsServiceProvider.php index 7e7ec0f9f..1e49423f5 100644 --- a/src/Viserio/Bridge/Doctrine/Testing/Provider/ConsoleCommandsServiceProvider.php +++ b/src/Viserio/Bridge/Doctrine/Testing/Provider/ConsoleCommandsServiceProvider.php @@ -35,10 +35,8 @@ public function getExtensions(): array * * @return null|\Viserio\Component\Console\Application */ - public static function extendConsole( - ContainerInterface $container, - ?Application $console = null - ): ?Application { + public static function extendConsole(ContainerInterface $container, ?Application $console = null): ?Application + { if ($console !== null) { $console->add(new LoadDataFixturesDoctrineCommand()); } diff --git a/src/Viserio/Bridge/Doctrine/Testing/Provider/DoctrineORMTestingServiceProvider.php b/src/Viserio/Bridge/Doctrine/Testing/Provider/DoctrineORMTestingServiceProvider.php index f4e05f1ce..d089c9ffa 100644 --- a/src/Viserio/Bridge/Doctrine/Testing/Provider/DoctrineORMTestingServiceProvider.php +++ b/src/Viserio/Bridge/Doctrine/Testing/Provider/DoctrineORMTestingServiceProvider.php @@ -38,7 +38,7 @@ public function getExtensions(): array /** * {@inheritdoc} */ - public static function getDimensions(): iterable + public static function getDimensions(): array { return ['viserio', 'doctrine']; } @@ -46,7 +46,7 @@ public static function getDimensions(): iterable /** * {@inheritdoc} */ - public static function getDefaultOptions(): iterable + public static function getDefaultOptions(): array { return [ 'locale' => FakerFactory::DEFAULT_LOCALE, diff --git a/src/Viserio/Bridge/Doctrine/Testing/SimpleHydrator.php b/src/Viserio/Bridge/Doctrine/Testing/SimpleHydrator.php index 890e6b706..7db593ddd 100644 --- a/src/Viserio/Bridge/Doctrine/Testing/SimpleHydrator.php +++ b/src/Viserio/Bridge/Doctrine/Testing/SimpleHydrator.php @@ -14,7 +14,7 @@ class SimpleHydrator * * @return object */ - public static function hydrate($class, array $attributes = []) + public static function hydrate($class, array $attributes = []): object { $reflection = new ReflectionClass($class); $instance = $reflection->newInstanceWithoutConstructor(); diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/Cache/StaticArrayCacheTest.php b/src/Viserio/Bridge/Doctrine/Testing/Tests/Cache/StaticArrayCacheTest.php index 9b5a51ccb..e849248d9 100644 --- a/src/Viserio/Bridge/Doctrine/Testing/Tests/Cache/StaticArrayCacheTest.php +++ b/src/Viserio/Bridge/Doctrine/Testing/Tests/Cache/StaticArrayCacheTest.php @@ -8,7 +8,10 @@ use PHPUnit\Framework\TestCase; use Viserio\Bridge\Doctrine\Testing\Cache\StaticArrayCache; -class StaticArrayCacheTest extends TestCase +/** + * @internal + */ +final class StaticArrayCacheTest extends TestCase { /** * @dataProvider provideDataToCache @@ -19,19 +22,19 @@ public function testSetContainsFetchDelete($value): void { $cache = $this->getCacheDriver(); // Test saving a value, checking if it exists, and fetching it back - self::assertTrue($cache->save('key', $value)); - self::assertTrue($cache->contains('key')); + $this->assertTrue($cache->save('key', $value)); + $this->assertTrue($cache->contains('key')); - if (is_object($value)) { - self::assertEquals($value, $cache->fetch('key'), 'Objects retrieved from the cache must be equal but not necessarily the same reference'); + if (\is_object($value)) { + $this->assertEquals($value, $cache->fetch('key'), 'Objects retrieved from the cache must be equal but not necessarily the same reference'); } else { - self::assertSame($value, $cache->fetch('key'), 'Scalar and array data retrieved from the cache must be the same as the original, e.g. same type'); + $this->assertSame($value, $cache->fetch('key'), 'Scalar and array data retrieved from the cache must be the same as the original, e.g. same type'); } // Test deleting a value - self::assertTrue($cache->delete('key')); - self::assertFalse($cache->contains('key')); - self::assertFalse($cache->fetch('key')); + $this->assertTrue($cache->delete('key')); + $this->assertFalse($cache->contains('key')); + $this->assertFalse($cache->fetch('key')); } /** @@ -43,15 +46,15 @@ public function testUpdateExistingEntry($value): void { $cache = $this->getCacheDriver(); - self::assertTrue($cache->save('key', 'old-value')); - self::assertTrue($cache->contains('key')); - self::assertTrue($cache->save('key', $value)); - self::assertTrue($cache->contains('key')); + $this->assertTrue($cache->save('key', 'old-value')); + $this->assertTrue($cache->contains('key')); + $this->assertTrue($cache->save('key', $value)); + $this->assertTrue($cache->contains('key')); - if (is_object($value)) { - self::assertEquals($value, $cache->fetch('key'), 'Objects retrieved from the cache must be equal but not necessarily the same reference'); + if (\is_object($value)) { + $this->assertEquals($value, $cache->fetch('key'), 'Objects retrieved from the cache must be equal but not necessarily the same reference'); } else { - self::assertSame($value, $cache->fetch('key'), 'Scalar and array data retrieved from the cache must be the same as the original, e.g. same type'); + $this->assertSame($value, $cache->fetch('key'), 'Scalar and array data retrieved from the cache must be the same as the original, e.g. same type'); } } @@ -59,15 +62,15 @@ public function testCacheKeyIsCaseSensitive(): void { $cache = $this->getCacheDriver(); - self::assertTrue($cache->save('key', 'value')); - self::assertTrue($cache->contains('key')); - self::assertSame('value', $cache->fetch('key')); - self::assertFalse($cache->contains('KEY')); - self::assertFalse($cache->fetch('KEY')); + $this->assertTrue($cache->save('key', 'value')); + $this->assertTrue($cache->contains('key')); + $this->assertSame('value', $cache->fetch('key')); + $this->assertFalse($cache->contains('KEY')); + $this->assertFalse($cache->fetch('KEY')); $cache->delete('KEY'); - self::assertTrue($cache->contains('key'), 'Deleting cache item with different case must not affect other cache item'); + $this->assertTrue($cache->contains('key'), 'Deleting cache item with different case must not affect other cache item'); } public function testFetchMultiple(): void @@ -81,16 +84,16 @@ public function testFetchMultiple(): void $saved[$key] = $value[0]; } - $keys = array_keys($saved); + $keys = \array_keys($saved); - self::assertEquals( + $this->assertEquals( $saved, $cache->fetchMultiple($keys), 'Testing fetchMultiple with different data types' ); - self::assertEquals( - array_slice($saved, 0, 1), - $cache->fetchMultiple(array_slice($keys, 0, 1)), + $this->assertEquals( + \array_slice($saved, 0, 1), + $cache->fetchMultiple(\array_slice($keys, 0, 1)), 'Testing fetchMultiple with a single key' ); @@ -101,8 +104,8 @@ public function testFetchMultiple(): void $keysWithNonExisting[] = $keys[1]; $keysWithNonExisting[] = 'non_existing3'; - self::assertEquals( - array_slice($saved, 0, 2), + $this->assertEquals( + \array_slice($saved, 0, 2), $cache->fetchMultiple($keysWithNonExisting), 'Testing fetchMultiple with a subset of keys and mixed with non-existing ones' ); @@ -112,22 +115,22 @@ public function testFetchMultipleWithNoKeys(): void { $cache = $this->getCacheDriver(); - self::assertSame([], $cache->fetchMultiple([])); + $this->assertSame([], $cache->fetchMultiple([])); } public function testSaveMultiple(): void { $cache = $this->getCacheDriver(); $cache->deleteAll(); - $data = array_map(function ($value) { + $data = \array_map(function ($value) { return $value[0]; }, $this->provideDataToCache()); - self::assertTrue($cache->saveMultiple($data)); + $this->assertTrue($cache->saveMultiple($data)); - $keys = array_keys($data); + $keys = \array_keys($data); - self::assertEquals($data, $cache->fetchMultiple($keys)); + $this->assertEquals($data, $cache->fetchMultiple($keys)); } public function provideDataToCache(): array @@ -165,31 +168,31 @@ public function testDeleteIsSuccessfulWhenKeyDoesNotExist(): void $cache = $this->getCacheDriver(); $cache->delete('key'); - self::assertFalse($cache->contains('key')); - self::assertTrue($cache->delete('key')); + $this->assertFalse($cache->contains('key')); + $this->assertTrue($cache->delete('key')); } public function testDeleteAll(): void { $cache = $this->getCacheDriver(); - self::assertTrue($cache->save('key1', 1)); - self::assertTrue($cache->save('key2', 2)); - self::assertTrue($cache->deleteAll()); - self::assertFalse($cache->contains('key1')); - self::assertFalse($cache->contains('key2')); + $this->assertTrue($cache->save('key1', 1)); + $this->assertTrue($cache->save('key2', 2)); + $this->assertTrue($cache->deleteAll()); + $this->assertFalse($cache->contains('key1')); + $this->assertFalse($cache->contains('key2')); } public function testDeleteMulti(): void { $cache = $this->getCacheDriver(); - self::assertTrue($cache->save('key1', 1)); - self::assertTrue($cache->save('key2', 1)); - self::assertTrue($cache->deleteMultiple(['key1', 'key2', 'key3'])); - self::assertFalse($cache->contains('key1')); - self::assertFalse($cache->contains('key2')); - self::assertFalse($cache->contains('key3')); + $this->assertTrue($cache->save('key1', 1)); + $this->assertTrue($cache->save('key2', 1)); + $this->assertTrue($cache->deleteMultiple(['key1', 'key2', 'key3'])); + $this->assertFalse($cache->contains('key1')); + $this->assertFalse($cache->contains('key2')); + $this->assertFalse($cache->contains('key3')); } /** @@ -201,12 +204,12 @@ public function testCanHandleSpecialCacheIds($id): void { $cache = $this->getCacheDriver(); - self::assertTrue($cache->save($id, 'value')); - self::assertTrue($cache->contains($id)); - self::assertEquals('value', $cache->fetch($id)); - self::assertTrue($cache->delete($id)); - self::assertFalse($cache->contains($id)); - self::assertFalse($cache->fetch($id)); + $this->assertTrue($cache->save($id, 'value')); + $this->assertTrue($cache->contains($id)); + $this->assertEquals('value', $cache->fetch($id)); + $this->assertTrue($cache->delete($id)); + $this->assertFalse($cache->contains($id)); + $this->assertFalse($cache->fetch($id)); } public function testNoCacheIdCollisions(): void @@ -217,12 +220,14 @@ public function testNoCacheIdCollisions(): void foreach ($ids as $index => $id) { $cache->save($id[0], $index); } + // then check value of each cache id foreach ($ids as $index => $id) { $value = $cache->fetch($id[0]); - self::assertNotFalse($value, sprintf('Failed to retrieve data for cache id "%s".', $id[0])); + $this->assertNotFalse($value, \sprintf('Failed to retrieve data for cache id "%s".', $id[0])); + if ($index !== $value) { - $this->fail(sprintf('Cache id "%s" collides with id "%s".', $id[0], $ids[$value][0])); + $this->fail(\sprintf('Cache id "%s" collides with id "%s".', $id[0], $ids[$value][0])); } } } @@ -260,8 +265,8 @@ public function provideCacheIds(): array [' '], ["\0"], [''], - [str_repeat('a', 300)], // long key - [str_repeat('a', 113)], + [\str_repeat('a', 300)], // long key + [\str_repeat('a', 113)], ]; } @@ -270,12 +275,12 @@ public function testLifetime(): void $cache = $this->getCacheDriver(); $cache->save('expire', 'value', 1); - self::assertTrue($cache->contains('expire'), 'Data should not be expired yet'); + $this->assertTrue($cache->contains('expire'), 'Data should not be expired yet'); // @TODO should more TTL-based tests pop up, so then we should mock the `time` API instead - sleep(2); + \sleep(2); - self::assertFalse($cache->contains('expire'), 'Data should be expired'); + $this->assertFalse($cache->contains('expire'), 'Data should be expired'); } public function testNoExpire(): void @@ -284,9 +289,9 @@ public function testNoExpire(): void $cache->save('noexpire', 'value', 0); // @TODO should more TTL-based tests pop up, so then we should mock the `time` API instead - sleep(1); + \sleep(1); - self::assertTrue($cache->contains('noexpire'), 'Data with lifetime of zero should not expire'); + $this->assertTrue($cache->contains('noexpire'), 'Data with lifetime of zero should not expire'); } public function testLongLifetime(): void @@ -294,18 +299,18 @@ public function testLongLifetime(): void $cache = $this->getCacheDriver(); $cache->save('longlifetime', 'value', 30 * 24 * 3600 + 1); - self::assertTrue($cache->contains('longlifetime'), 'Data with lifetime > 30 days should be accepted'); + $this->assertTrue($cache->contains('longlifetime'), 'Data with lifetime > 30 days should be accepted'); } public function testFlushAll(): void { $cache = $this->getCacheDriver(); - self::assertTrue($cache->save('key1', 1)); - self::assertTrue($cache->save('key2', 2)); - self::assertTrue($cache->flushAll()); - self::assertFalse($cache->contains('key1')); - self::assertFalse($cache->contains('key2')); + $this->assertTrue($cache->save('key1', 1)); + $this->assertTrue($cache->save('key2', 2)); + $this->assertTrue($cache->flushAll()); + $this->assertFalse($cache->contains('key1')); + $this->assertFalse($cache->contains('key2')); } public function testNamespace(): void @@ -313,12 +318,12 @@ public function testNamespace(): void $cache = $this->getCacheDriver(); $cache->setNamespace('ns1_'); - self::assertTrue($cache->save('key1', 1)); - self::assertTrue($cache->contains('key1')); + $this->assertTrue($cache->save('key1', 1)); + $this->assertTrue($cache->contains('key1')); $cache->setNamespace('ns2_'); - self::assertFalse($cache->contains('key1')); + $this->assertFalse($cache->contains('key1')); } public function testDeleteAllNamespace(): void @@ -326,35 +331,35 @@ public function testDeleteAllNamespace(): void $cache = $this->getCacheDriver(); $cache->setNamespace('ns1'); - self::assertFalse($cache->contains('key1')); + $this->assertFalse($cache->contains('key1')); $cache->save('key1', 'test'); - self::assertTrue($cache->contains('key1')); + $this->assertTrue($cache->contains('key1')); $cache->setNamespace('ns2'); - self::assertFalse($cache->contains('key1')); + $this->assertFalse($cache->contains('key1')); $cache->save('key1', 'test'); - self::assertTrue($cache->contains('key1')); + $this->assertTrue($cache->contains('key1')); $cache->setNamespace('ns1'); - self::assertTrue($cache->contains('key1')); + $this->assertTrue($cache->contains('key1')); $cache->deleteAll(); - self::assertFalse($cache->contains('key1')); + $this->assertFalse($cache->contains('key1')); $cache->setNamespace('ns2'); - self::assertTrue($cache->contains('key1')); + $this->assertTrue($cache->contains('key1')); $cache->deleteAll(); - self::assertFalse($cache->contains('key1')); + $this->assertFalse($cache->contains('key1')); } public function testSaveReturnsTrueWithAndWithoutTTlSet(): void @@ -362,8 +367,8 @@ public function testSaveReturnsTrueWithAndWithoutTTlSet(): void $cache = $this->getCacheDriver(); $cache->deleteAll(); - self::assertTrue($cache->save('without_ttl', 'without_ttl')); - self::assertTrue($cache->save('with_ttl', 'with_ttl', 3600)); + $this->assertTrue($cache->save('without_ttl', 'without_ttl')); + $this->assertTrue($cache->save('with_ttl', 'with_ttl', 3600)); } public function testValueThatIsFalseBooleanIsProperlyRetrieved(): void @@ -371,9 +376,9 @@ public function testValueThatIsFalseBooleanIsProperlyRetrieved(): void $cache = $this->getCacheDriver(); $cache->deleteAll(); - self::assertTrue($cache->save('key1', false)); - self::assertTrue($cache->contains('key1')); - self::assertFalse($cache->fetch('key1')); + $this->assertTrue($cache->save('key1', false)); + $this->assertTrue($cache->contains('key1')); + $this->assertFalse($cache->fetch('key1')); } /** @@ -384,21 +389,21 @@ public function testFetchingANonExistingKeyShouldNeverCauseANoticeOrWarning(): v { $cache = $this->getCacheDriver(); $errorHandler = function (): void { - restore_error_handler(); + \restore_error_handler(); $this->fail('include failure captured'); }; - set_error_handler($errorHandler); + \set_error_handler($errorHandler); $cache->fetch('key'); - self::assertSame( + $this->assertSame( $errorHandler, - set_error_handler(function (): void { + \set_error_handler(function (): void { }), 'The error handler is the one set by this test, and wasn\'t replaced' ); - restore_error_handler(); - restore_error_handler(); + \restore_error_handler(); + \restore_error_handler(); } public function testGetStats(): void @@ -414,11 +419,11 @@ public function testGetStats(): void $cache->fetch('test3'); $stats = $cache->getStats(); - self::assertEquals(2, $stats[Cache::STATS_HITS]); - self::assertEquals(5, $stats[Cache::STATS_MISSES]); // +1 for internal call to DoctrineNamespaceCacheKey - self::assertNotNull($stats[Cache::STATS_UPTIME]); - self::assertNull($stats[Cache::STATS_MEMORY_USAGE]); - self::assertNull($stats[Cache::STATS_MEMORY_AVAILABLE]); + $this->assertEquals(2, $stats[Cache::STATS_HITS]); + $this->assertEquals(5, $stats[Cache::STATS_MISSES]); // +1 for internal call to DoctrineNamespaceCacheKey + $this->assertNotNull($stats[Cache::STATS_UPTIME]); + $this->assertNull($stats[Cache::STATS_MEMORY_USAGE]); + $this->assertNull($stats[Cache::STATS_MEMORY_AVAILABLE]); $cache->delete('test1'); $cache->delete('test2'); @@ -427,8 +432,8 @@ public function testGetStats(): void $cache->fetch('test3'); $stats = $cache->getStats(); - self::assertEquals(2, $stats[Cache::STATS_HITS]); - self::assertEquals(8, $stats[Cache::STATS_MISSES]); // +1 for internal call to DoctrineNamespaceCacheKey + $this->assertEquals(2, $stats[Cache::STATS_HITS]); + $this->assertEquals(8, $stats[Cache::STATS_MISSES]); // +1 for internal call to DoctrineNamespaceCacheKey } private function getCacheDriver(): CacheProvider diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/DBAL/StaticDriverTest.php b/src/Viserio/Bridge/Doctrine/Testing/Tests/DBAL/StaticDriverTest.php index 2c4ad5599..15e558615 100644 --- a/src/Viserio/Bridge/Doctrine/Testing/Tests/DBAL/StaticDriverTest.php +++ b/src/Viserio/Bridge/Doctrine/Testing/Tests/DBAL/StaticDriverTest.php @@ -8,7 +8,10 @@ use Viserio\Bridge\Doctrine\Testing\DBAL\StaticDriver; use Viserio\Bridge\Doctrine\Testing\Tests\Fixtures\MockDriver; -class StaticDriverTest extends TestCase +/** + * @internal + */ +final class StaticDriverTest extends TestCase { /** * @var AbstractPlatform|\PHPUnit_Framework_MockObject_MockObject @@ -18,7 +21,7 @@ class StaticDriverTest extends TestCase /** * {@inheritdoc} */ - public function setUp(): void + protected function setUp(): void { $this->platform = $this->createMock(AbstractPlatform::class); } @@ -27,8 +30,8 @@ public function testReturnCorrectPlatform(): void { $driver = new StaticDriver(new MockDriver(), $this->platform); - self::assertSame($this->platform, $driver->getDatabasePlatform()); - self::assertSame($this->platform, $driver->createDatabasePlatformForVersion(1)); + $this->assertSame($this->platform, $driver->getDatabasePlatform()); + $this->assertSame($this->platform, $driver->createDatabasePlatformForVersion(1)); } public function testConnect(): void @@ -39,14 +42,14 @@ public function testConnect(): void $connection1 = $driver->connect(['database_name' => 1], 'user1', 'pw1'); $connection2 = $driver->connect(['database_name' => 2], 'user1', 'pw2'); - self::assertInstanceOf(StaticConnection::class, $connection1); - self::assertNotSame($connection1->getWrappedConnection(), $connection2->getWrappedConnection()); + $this->assertInstanceOf(StaticConnection::class, $connection1); + $this->assertNotSame($connection1->getWrappedConnection(), $connection2->getWrappedConnection()); $driver = new StaticDriver(new MockDriver(), $this->platform); $connectionNew1 = $driver->connect(['database_name' => 1], 'user1', 'pw1'); $connectionNew2 = $driver->connect(['database_name' => 2], 'user1', 'pw2'); - self::assertSame($connection1->getWrappedConnection(), $connectionNew1->getWrappedConnection()); - self::assertSame($connection2->getWrappedConnection(), $connectionNew2->getWrappedConnection()); + $this->assertSame($connection1->getWrappedConnection(), $connectionNew1->getWrappedConnection()); + $this->assertSame($connection2->getWrappedConnection(), $connectionNew2->getWrappedConnection()); } } diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/Fixtures/MockDriver.php b/src/Viserio/Bridge/Doctrine/Testing/Tests/Fixtures/MockDriver.php index f450af0a9..9a9d51f93 100644 --- a/src/Viserio/Bridge/Doctrine/Testing/Tests/Fixtures/MockDriver.php +++ b/src/Viserio/Bridge/Doctrine/Testing/Tests/Fixtures/MockDriver.php @@ -7,8 +7,8 @@ use Doctrine\DBAL\Driver\Connection as DriverConnection; use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Schema\AbstractSchemaManager; -use PHPUnit_Framework_MockObject_Generator; -use PHPUnit_Framework_MockObject_MockObject; +use PHPUnit\Framework\MockObject\Generator; +use PHPUnit\Framework\MockObject\MockObject; class MockDriver implements Driver { @@ -59,9 +59,9 @@ public function getDatabase(Connection $conn) * * @return \PHPUnit_Framework_MockObject_MockObject */ - private function getMock(string $className): PHPUnit_Framework_MockObject_MockObject + private function getMock(string $className): MockObject { - $generator = new PHPUnit_Framework_MockObject_Generator(); + $generator = new Generator(); return $generator->getMock($className, [], [], '', false); } diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/Provider/ConsoleCommandsServiceProviderTest.php b/src/Viserio/Bridge/Doctrine/Testing/Tests/Provider/ConsoleCommandsServiceProviderTest.php index 5b148c8d0..aaab8788a 100644 --- a/src/Viserio/Bridge/Doctrine/Testing/Tests/Provider/ConsoleCommandsServiceProviderTest.php +++ b/src/Viserio/Bridge/Doctrine/Testing/Tests/Provider/ConsoleCommandsServiceProviderTest.php @@ -9,7 +9,10 @@ use Viserio\Component\Console\Provider\ConsoleServiceProvider; use Viserio\Component\Container\Container; -class ConsoleCommandsServiceProviderTest extends TestCase +/** + * @internal + */ +final class ConsoleCommandsServiceProviderTest extends TestCase { public function testProvider(): void { diff --git a/src/Viserio/Bridge/Doctrine/Testing/composer.json b/src/Viserio/Bridge/Doctrine/Testing/composer.json index a595fd2a7..b27e8fb24 100644 --- a/src/Viserio/Bridge/Doctrine/Testing/composer.json +++ b/src/Viserio/Bridge/Doctrine/Testing/composer.json @@ -1,57 +1,66 @@ { - "name" : "viserio/doctrine-testing-bridge", - "type" : "viserio-bridge", + "name": "viserio/doctrine-testing-bridge", + "type": "viserio-bridge", "description": "The Viserio Doctrine Testing bridge.", - "keywords" : ["narrowspark", "viserio", "database", "testing", "doctrine", "bridge"], - "license" : "MIT", - "homepage" : "http://narrowspark.com", - "support" : { - "issues": "https://github.com/narrowspark/framework/issues", - "source": "https://github.com/narrowspark/framework" - }, - "authors" : [ + "keywords": [ + "narrowspark", + "viserio", + "database", + "testing", + "doctrine", + "bridge" + ], + "homepage": "http://narrowspark.com", + "license": "MIT", + "authors": [ { - "name" : "Daniel Bannert", - "email" : "d.bannert@anolilab.de", - "homepage": "http://www.anolilab.de", - "role" : "Developer" + "name": "Daniel Bannert", + "email": "d.bannert@anolilab.de", + "homepage": "http://www.anolilab.de", + "role": "Developer" } ], "require": { - "php" : "^7.1", - "fzaninotto/faker" : "^1.6", - "narrowspark/collection" : "^0.1", - "viserio/doctrine-dbal-bridge" : "self.version" + "php": "^7.1", + "fzaninotto/faker": "^1.6", + "narrowspark/collection": "^0.1", + "viserio/doctrine-dbal-bridge": "self.version" }, "require-dev": { - "container-interop/service-provider" : "^0.3", - "doctrine/data-fixtures" : "^1.2", - "phpunit/phpunit" : "^6.0", - "viserio/container" : "self.version", - "viserio/doctrine-orm-bridge" : "self.version" + "container-interop/service-provider": "^0.3", + "doctrine/data-fixtures": "^1.2", + "phpunit/phpunit": "^7.2.0", + "viserio/container": "self.version", + "viserio/doctrine-orm-bridge": "self.version" + }, + "suggest": { + "container-interop/service-provider": "Required to use service-provider (^0.3).", + "doctrine/orm": "Required to use the concerns (self.version).", + "viserio/console": "Required to use the data-fixture command (self.version).", + "viserio/doctrine-orm-bridge": "Required to use the data-fixture command and concerns (self.version)." + }, + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } }, "autoload": { "psr-4": { - "Viserio\\Bridge\\Doctrine\\Testing\\" : "" + "Viserio\\Bridge\\Doctrine\\Testing\\": "" }, - "exclude-from-classmap" : ["/Tests/"] + "exclude-from-classmap": [ + "/Tests/" + ] }, "autoload-dev": { "psr-4": { - "Viserio\\Bridge\\Doctrine\\Testing\\Tests\\" : "Tests/" + "Viserio\\Bridge\\Doctrine\\Testing\\Tests\\": "Tests/" } }, - "suggest": { - "container-interop/service-provider" : "Required to use service-provider (^0.3).", - "doctrine/orm" : "Required to use the concerns (self.version).", - "viserio/console" : "Required to use the data-fixture command (self.version).", - "viserio/doctrine-orm-bridge" : "Required to use the data-fixture command and concerns (self.version)." - }, - "extra": { - "branch-alias": { - "dev-master" : "1.0-dev" - } - }, - "minimum-stability" : "dev", - "prefer-stable" : true + "minimum-stability": "dev", + "prefer-stable": true, + "support": { + "issues": "https://github.com/narrowspark/framework/issues", + "source": "https://github.com/narrowspark/framework" + } } diff --git a/src/Viserio/Bridge/Doctrine/DBAL/.github/PULL_REQUEST_TEMPLATE.md b/src/Viserio/Provider/Doctrine/.github/PULL_REQUEST_TEMPLATE.md similarity index 100% rename from src/Viserio/Bridge/Doctrine/DBAL/.github/PULL_REQUEST_TEMPLATE.md rename to src/Viserio/Provider/Doctrine/.github/PULL_REQUEST_TEMPLATE.md diff --git a/src/Viserio/Bridge/Doctrine/DBAL/Connection.php b/src/Viserio/Provider/Doctrine/Connection.php similarity index 78% rename from src/Viserio/Bridge/Doctrine/DBAL/Connection.php rename to src/Viserio/Provider/Doctrine/Connection.php index 5c5959d81..7827e9372 100644 --- a/src/Viserio/Bridge/Doctrine/DBAL/Connection.php +++ b/src/Viserio/Provider/Doctrine/Connection.php @@ -1,6 +1,6 @@ doctrineEventManager; + } + + /** + * Set a doctrine event manager instance. + * + * @param \Doctrine\Common\EventManager $doctrineEventManager + * + * @return void + */ + public function setDoctrineEventManager(EventManager $doctrineEventManager): void + { + $this->doctrineEventManager = $doctrineEventManager; + } + + /** + * Get a doctrine event manager instance or null. + * + * @return null|\Doctrine\DBAL\Configuration + */ + public function getDoctrineConfiguration(): ?Configuration + { + return $this->doctrineConfiguration; + } + + /** + * Set a doctrine event manager instance. + * + * @param \Doctrine\DBAL\Configuration $doctrineConfiguration + * + * @return void + */ + public function setDoctrineConfiguration(Configuration $doctrineConfiguration): void + { + $this->doctrineConfiguration = $doctrineConfiguration; + } + /** * {@inheritdoc} */ - public static function getDimensions(): iterable + public static function getDimensions(): array { return ['viserio', 'doctrine', static::getConfigName()]; } @@ -36,7 +80,7 @@ public static function getDimensions(): iterable /** * {@inheritdoc} */ - public static function getMandatoryOptions(): iterable + public static function getMandatoryOptions(): array { return ['default']; } @@ -44,7 +88,7 @@ public static function getMandatoryOptions(): iterable /** * {@inheritdoc} */ - public static function getDefaultOptions(): iterable + public static function getDefaultOptions(): array { return [ 'connections' => [ @@ -87,50 +131,6 @@ public static function getDefaultOptions(): iterable ]; } - /** - * Set a doctrine event manager instance. - * - * @param \Doctrine\Common\EventManager $doctrineEventManager - * - * @return void - */ - public function setDoctrineEventManager(EventManager $doctrineEventManager): void - { - $this->doctrineEventManager = $doctrineEventManager; - } - - /** - * Get a doctrine event manager instance or null. - * - * @return null|\Doctrine\Common\EventManager - */ - public function getDoctrineEventManager(): ?EventManager - { - return $this->doctrineEventManager; - } - - /** - * Set a doctrine event manager instance. - * - * @param \Doctrine\DBAL\Configuration $doctrineConfiguration - * - * @return void - */ - public function setDoctrineConfiguration(Configuration $doctrineConfiguration): void - { - $this->doctrineConfiguration = $doctrineConfiguration; - } - - /** - * Get a doctrine event manager instance or null. - * - * @return null|\Doctrine\DBAL\Configuration - */ - public function getDoctrineConfiguration(): ?Configuration - { - return $this->doctrineConfiguration; - } - /** * {@inheritdoc} */ @@ -146,7 +146,7 @@ public function getConnectionConfig(string $name): array * * @throws \Doctrine\DBAL\DBALException * - * @return \Doctrine\DBAL\Connection|\Viserio\Bridge\Doctrine\DBAL\Connection + * @return \Doctrine\DBAL\Connection|\Viserio\Provider\Doctrine\Connection */ protected function createMysqlConnection(array $config): Connection { @@ -160,7 +160,7 @@ protected function createMysqlConnection(array $config): Connection * * @throws \Doctrine\DBAL\DBALException * - * @return \Doctrine\DBAL\Connection|\Viserio\Bridge\Doctrine\DBAL\Connection + * @return \Doctrine\DBAL\Connection|\Viserio\Provider\Doctrine\Connection */ protected function createSqliteConnection(array $config): Connection { @@ -174,7 +174,7 @@ protected function createSqliteConnection(array $config): Connection * * @throws \Doctrine\DBAL\DBALException * - * @return \Doctrine\DBAL\Connection|\Viserio\Bridge\Doctrine\DBAL\Connection + * @return \Doctrine\DBAL\Connection|\Viserio\Provider\Doctrine\Connection */ protected function createPgsqlConnection(array $config): Connection { @@ -188,7 +188,7 @@ protected function createPgsqlConnection(array $config): Connection * * @throws \Doctrine\DBAL\DBALException * - * @return \Doctrine\DBAL\Connection|\Viserio\Bridge\Doctrine\DBAL\Connection + * @return \Doctrine\DBAL\Connection|\Viserio\Provider\Doctrine\Connection */ protected function createSqlsrvConnection(array $config): Connection { @@ -216,7 +216,7 @@ private static function parseConfig(array $config): array $doctrineConfig['wrapperClass'] = $config['wrapper_class'] ?? Connection::class; - if (\mb_strpos($config['name'], 'sqlite') === false) { + if (\strpos($config['name'], 'sqlite') === false) { $doctrineConfig['user'] = $config['username']; $doctrineConfig['dbname'] = $config['database']; } else { diff --git a/src/Viserio/Bridge/Doctrine/DBAL/LICENSE b/src/Viserio/Provider/Doctrine/LICENSE similarity index 100% rename from src/Viserio/Bridge/Doctrine/DBAL/LICENSE rename to src/Viserio/Provider/Doctrine/LICENSE diff --git a/src/Viserio/Bridge/Doctrine/DBAL/Provider/ConsoleCommandsServiceProvider.php b/src/Viserio/Provider/Doctrine/Provider/ConsoleCommandsServiceProvider.php similarity index 78% rename from src/Viserio/Bridge/Doctrine/DBAL/Provider/ConsoleCommandsServiceProvider.php rename to src/Viserio/Provider/Doctrine/Provider/ConsoleCommandsServiceProvider.php index a8878a36d..0206c1985 100644 --- a/src/Viserio/Bridge/Doctrine/DBAL/Provider/ConsoleCommandsServiceProvider.php +++ b/src/Viserio/Provider/Doctrine/Provider/ConsoleCommandsServiceProvider.php @@ -1,6 +1,6 @@ getHelperSet() - ->set(new ConnectionHelper($container->get(Connection::class)), 'db'); + $console->getHelperSet()->set(new ConnectionHelper($container->get(Connection::class)), 'db'); $console->addCommands([ new RunSqlCommand(), diff --git a/src/Viserio/Bridge/Doctrine/DBAL/Provider/DoctrineDBALServiceProvider.php b/src/Viserio/Provider/Doctrine/Provider/DoctrineDBALServiceProvider.php similarity index 90% rename from src/Viserio/Bridge/Doctrine/DBAL/Provider/DoctrineDBALServiceProvider.php rename to src/Viserio/Provider/Doctrine/Provider/DoctrineDBALServiceProvider.php index 4ac8043f9..0d04b7d83 100644 --- a/src/Viserio/Bridge/Doctrine/DBAL/Provider/DoctrineDBALServiceProvider.php +++ b/src/Viserio/Provider/Doctrine/Provider/DoctrineDBALServiceProvider.php @@ -1,14 +1,14 @@ get('config')); $manager->setDoctrineConfiguration($container->get(Configuration::class)); $manager->setDoctrineEventManager($container->get(EventManager::class)); diff --git a/src/Viserio/Bridge/Doctrine/DBAL/Proxy/DBAL.php b/src/Viserio/Provider/Doctrine/Proxy/DBAL.php similarity index 77% rename from src/Viserio/Bridge/Doctrine/DBAL/Proxy/DBAL.php rename to src/Viserio/Provider/Doctrine/Proxy/DBAL.php index 18e930871..feee98f03 100644 --- a/src/Viserio/Bridge/Doctrine/DBAL/Proxy/DBAL.php +++ b/src/Viserio/Provider/Doctrine/Proxy/DBAL.php @@ -1,9 +1,9 @@ manager->getConnection()); + $this->assertInstanceOf(Connection::class, $this->manager->getConnection()); } public function testMysqlConnection(): void { - self::assertInstanceOf(Connection::class, $this->manager->getConnection('mysql')); + $this->assertInstanceOf(Connection::class, $this->manager->getConnection('mysql')); } public function testSqliteConnection(): void { - self::assertInstanceOf(Connection::class, $this->manager->getConnection('sqlite')); + $this->assertInstanceOf(Connection::class, $this->manager->getConnection('sqlite')); } public function testPgsqlConnection(): void { - self::assertInstanceOf(Connection::class, $this->manager->getConnection('pgsql')); + $this->assertInstanceOf(Connection::class, $this->manager->getConnection('pgsql')); } public function testSqlsrvConnection(): void { - self::assertInstanceOf(Connection::class, $this->manager->getConnection('sqlsrv')); + $this->assertInstanceOf(Connection::class, $this->manager->getConnection('sqlsrv')); } public function testSetAndGetDoctrineEventManager(): void { - self::assertNull($this->manager->getDoctrineEventManager()); + $this->assertNull($this->manager->getDoctrineEventManager()); $this->manager->setDoctrineEventManager($this->mock(EventManager::class)); - self::assertInstanceOf(EventManager::class, $this->manager->getDoctrineEventManager()); + $this->assertInstanceOf(EventManager::class, $this->manager->getDoctrineEventManager()); } public function testSetAndGetDoctrineConfiguration(): void { - self::assertNull($this->manager->getDoctrineConfiguration()); + $this->assertNull($this->manager->getDoctrineConfiguration()); $this->manager->setDoctrineConfiguration($this->mock(Configuration::class)); - self::assertInstanceOf(Configuration::class, $this->manager->getDoctrineConfiguration()); + $this->assertInstanceOf(Configuration::class, $this->manager->getDoctrineConfiguration()); } } diff --git a/src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/ConsoleCommandsServiceProviderTest.php b/src/Viserio/Provider/Doctrine/Tests/Provider/ConsoleCommandsServiceProviderTest.php similarity index 66% rename from src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/ConsoleCommandsServiceProviderTest.php rename to src/Viserio/Provider/Doctrine/Tests/Provider/ConsoleCommandsServiceProviderTest.php index d837313ee..df8bbb370 100644 --- a/src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/ConsoleCommandsServiceProviderTest.php +++ b/src/Viserio/Provider/Doctrine/Tests/Provider/ConsoleCommandsServiceProviderTest.php @@ -1,18 +1,21 @@ get(Application::class); $commands = $console->all(); - self::assertInstanceOf(ImportCommand::class, $commands['dbal:import']); - self::assertInstanceOf(ReservedWordsCommand::class, $commands['dbal:reserved-words']); - self::assertInstanceOf(RunSqlCommand::class, $commands['dbal:run-sql']); + $this->assertInstanceOf(ImportCommand::class, $commands['dbal:import']); + $this->assertInstanceOf(ReservedWordsCommand::class, $commands['dbal:reserved-words']); + $this->assertInstanceOf(RunSqlCommand::class, $commands['dbal:run-sql']); } } diff --git a/src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/DoctrineDBALServiceProviderDatabaseConnectionTest.php b/src/Viserio/Provider/Doctrine/Tests/Provider/DoctrineDBALServiceProviderDatabaseConnectionTest.php similarity index 58% rename from src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/DoctrineDBALServiceProviderDatabaseConnectionTest.php rename to src/Viserio/Provider/Doctrine/Tests/Provider/DoctrineDBALServiceProviderDatabaseConnectionTest.php index 47ff53f68..a4120c468 100644 --- a/src/Viserio/Bridge/Doctrine/DBAL/Tests/Provider/DoctrineDBALServiceProviderDatabaseConnectionTest.php +++ b/src/Viserio/Provider/Doctrine/Tests/Provider/DoctrineDBALServiceProviderDatabaseConnectionTest.php @@ -1,14 +1,17 @@ fetchArray($sql); - self::assertInstanceOf(Collection::class, $collection); - self::assertSame([0 => 'narrowspark'], $collection->all()); + $this->assertInstanceOf(Collection::class, $collection); + $this->assertSame([0 => 'narrowspark'], $collection->all()); $collection = $conn->fetchAll($sql); - self::assertInstanceOf(Collection::class, $collection); - self::assertSame(['name' => 'narrowspark'], $collection->all()); + $this->assertInstanceOf(Collection::class, $collection); + $this->assertSame(['name' => 'narrowspark'], $collection->all()); $collection = $conn->fetchAssoc($sql); - self::assertInstanceOf(Collection::class, $collection); - self::assertSame(['name' => 'narrowspark'], $collection->all()); + $this->assertInstanceOf(Collection::class, $collection); + $this->assertSame(['name' => 'narrowspark'], $collection->all()); $stmt = $conn->prepare($sql); $stmt->execute(); $collection = $stmt->fetchAll(); - self::assertInstanceOf(Collection::class, $collection); - self::assertSame(['name' => 'narrowspark'], $collection->all()); + $this->assertInstanceOf(Collection::class, $collection); + $this->assertSame(['name' => 'narrowspark'], $collection->all()); $stmt = $conn->query($sql); $collection = $stmt->fetch(); - self::assertInstanceOf(Collection::class, $collection); - self::assertSame(['name' => 'narrowspark'], $collection->all()); + $this->assertInstanceOf(Collection::class, $collection); + $this->assertSame(['name' => 'narrowspark'], $collection->all()); $stmt = $conn->query('SELECT name FROM text WHERE id = 2'); - self::assertFalse($stmt->fetch()); + $this->assertFalse($stmt->fetch()); } } diff --git a/src/Viserio/Provider/Doctrine/Tests/Provider/DoctrineDBALServiceProviderTest.php b/src/Viserio/Provider/Doctrine/Tests/Provider/DoctrineDBALServiceProviderTest.php new file mode 100644 index 000000000..33b8ad743 --- /dev/null +++ b/src/Viserio/Provider/Doctrine/Tests/Provider/DoctrineDBALServiceProviderTest.php @@ -0,0 +1,40 @@ +register(new DoctrineDBALServiceProvider()); + + $container->instance('config', [ + 'viserio' => [ + 'doctrine' => [ + 'dbal' => [ + 'default' => 'mysql', + ], + ], + ], + ]); + + $this->assertInstanceOf(Configuration::class, $container->get(Configuration::class)); + $this->assertInstanceOf(EventManager::class, $container->get(EventManager::class)); + $this->assertInstanceOf(ConnectionManager::class, $container->get(ConnectionManager::class)); + $this->assertInstanceOf(Connection::class, $container->get(Connection::class)); + $this->assertInstanceOf(Connection::class, $container->get('db')); + $this->assertInstanceOf(Connection::class, $container->get('database')); + } +} diff --git a/src/Viserio/Bridge/Doctrine/DBAL/Tests/Stub/database.sqlite b/src/Viserio/Provider/Doctrine/Tests/Stub/database.sqlite similarity index 100% rename from src/Viserio/Bridge/Doctrine/DBAL/Tests/Stub/database.sqlite rename to src/Viserio/Provider/Doctrine/Tests/Stub/database.sqlite diff --git a/src/Viserio/Provider/Doctrine/composer.json b/src/Viserio/Provider/Doctrine/composer.json new file mode 100644 index 000000000..f618be402 --- /dev/null +++ b/src/Viserio/Provider/Doctrine/composer.json @@ -0,0 +1,66 @@ +{ + "name": "viserio/doctrine-provider", + "type": "viserio-bridge", + "description": "The Viserio Doctrine DBAL & ORM provider.", + "keywords": [ + "narrowspark", + "viserio", + "database", + "doctrine", + "dbal", + "orm", + "provider" + ], + "homepage": "http://narrowspark.com", + "license": "MIT", + "authors": [ + { + "name": "Daniel Bannert", + "email": "d.bannert@anolilab.de", + "homepage": "http://www.anolilab.de", + "role": "Developer" + } + ], + "require": { + "php": "^7.1", + "ext-pdo": "*", + "doctrine/dbal": "^2.5.13", + "jdorn/sql-formatter": "^1.2.17", + "narrowspark/collection": "^0.1", + "viserio/support": "self.version" + }, + "require-dev": { + "container-interop/service-provider": "^0.3", + "narrowspark/testing-helper": "^4.0", + "phpunit/phpunit": "^7.2.0", + "viserio/container": "self.version" + }, + "suggest": { + "container-interop/service-provider": "Required to use service-provider (^0.3).", + "viserio/statical-proxy": "Required to use the proxy instances (self.version)." + }, + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "psr-4": { + "Viserio\\Provider\\Doctrine\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "autoload-dev": { + "psr-4": { + "Viserio\\Provider\\Doctrine\\Tests\\": "Tests/" + } + }, + "minimum-stability": "dev", + "prefer-stable": true, + "support": { + "issues": "https://github.com/narrowspark/framework/issues", + "source": "https://github.com/narrowspark/framework" + } +} diff --git a/src/Viserio/Bridge/Doctrine/DBAL/phpunit.xml.dist b/src/Viserio/Provider/Doctrine/phpunit.xml.dist similarity index 100% rename from src/Viserio/Bridge/Doctrine/DBAL/phpunit.xml.dist rename to src/Viserio/Provider/Doctrine/phpunit.xml.dist diff --git a/src/Viserio/Bridge/Doctrine/Migration/.github/PULL_REQUEST_TEMPLATE.md b/src/Viserio/Provider/DoctrineMigration/.github/PULL_REQUEST_TEMPLATE.md similarity index 100% rename from src/Viserio/Bridge/Doctrine/Migration/.github/PULL_REQUEST_TEMPLATE.md rename to src/Viserio/Provider/DoctrineMigration/.github/PULL_REQUEST_TEMPLATE.md diff --git a/src/Viserio/Bridge/Doctrine/Migration/Commands/AbstractCommand.php b/src/Viserio/Provider/DoctrineMigration/Commands/AbstractCommand.php similarity index 82% rename from src/Viserio/Bridge/Doctrine/Migration/Commands/AbstractCommand.php rename to src/Viserio/Provider/DoctrineMigration/Commands/AbstractCommand.php index b5e81deae..3597c929a 100644 --- a/src/Viserio/Bridge/Doctrine/Migration/Commands/AbstractCommand.php +++ b/src/Viserio/Provider/DoctrineMigration/Commands/AbstractCommand.php @@ -1,6 +1,6 @@ getHelperSet()->get('migration_configuration'); if (! $configHelper instanceof ConfigurationHelper) { - throw new RuntimeException(''); + throw new RuntimeException('.'); } } else { $configHelper = new ConfigurationHelper($this->configuration, $this->getConnection($input)); @@ -67,7 +68,7 @@ protected function getMigrationConfiguration(InputInterface $input, OutputInterf * * @return \Doctrine\DBAL\Connection */ - private function getConnection(InputInterface $input) + private function getConnection(InputInterface $input): Connection { if ($this->connection) { return $this->connection; @@ -94,7 +95,7 @@ private function getConnection(InputInterface $input) * * @return \Doctrine\DBAL\Migrations\OutputWriter */ - private function getOutputWriter(OutputInterface $output) + private function getOutputWriter(OutputInterface $output): \Doctrine\DBAL\Migrations\OutputWriter { if (! $this->outputWriter) { $this->outputWriter = new OutputWriter(function ($message) use ($output) { diff --git a/src/Viserio/Provider/DoctrineMigration/Commands/DiffCommand.php b/src/Viserio/Provider/DoctrineMigration/Commands/DiffCommand.php new file mode 100644 index 000000000..310f046cd --- /dev/null +++ b/src/Viserio/Provider/DoctrineMigration/Commands/DiffCommand.php @@ -0,0 +1,3 @@ +getMigrationsDirectory(); + $dir = $dir ?? \getcwd(); + $dir = \rtrim($dir, '/'); + + if (! \file_exists($dir)) { + throw new InvalidArgumentException(\sprintf('Migrations directory [%s] does not exist.', $dir)); + } + + if ($configuration->areMigrationsOrganizedByYear()) { + $dir .= \DIRECTORY_SEPARATOR . \date('Y'); + } + + if ($configuration->areMigrationsOrganizedByYearAndMonth()) { + $dir .= \DIRECTORY_SEPARATOR . \date('m'); + } + + if (! \file_exists($dir)) { + \mkdir($dir, 0755, true); + } + + return $dir; + } +} diff --git a/src/Viserio/Bridge/Doctrine/Migration/Commands/Helper/ConfigurationHelper.php b/src/Viserio/Provider/DoctrineMigration/Commands/Helper/ConfigurationHelper.php similarity index 84% rename from src/Viserio/Bridge/Doctrine/Migration/Commands/Helper/ConfigurationHelper.php rename to src/Viserio/Provider/DoctrineMigration/Commands/Helper/ConfigurationHelper.php index 8c7da1882..43bdb1066 100644 --- a/src/Viserio/Bridge/Doctrine/Migration/Commands/Helper/ConfigurationHelper.php +++ b/src/Viserio/Provider/DoctrineMigration/Commands/Helper/ConfigurationHelper.php @@ -1,21 +1,21 @@ 'mysql', @@ -83,7 +83,7 @@ public static function getDefaultOptions(): iterable /** * {@inheritdoc} */ - public static function getMandatoryOptions(): iterable + public static function getMandatoryOptions(): array { return ['directory']; } @@ -102,7 +102,7 @@ public function getName() * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Doctrine\DBAL\Migrations\OutputWriter $outputWriter * - * @return \Viserio\Bridge\Doctrine\Migration\Configuration\Configuration + * @return \Viserio\Provider\Doctrine\Migration\Configuration\Configuration */ public function getMigrationConfig(InputInterface $input, OutputWriter $outputWriter): Configuration { @@ -139,7 +139,7 @@ public function getMigrationConfig(InputInterface $input, OutputWriter $outputWr * * @param array $config * - * @return \Viserio\Bridge\Doctrine\Contract\Migration\NamingStrategy + * @return \Viserio\Provider\Doctrine\Contract\Migration\NamingStrategy */ private function getStrategy(array $config): NamingStrategyContract { @@ -157,12 +157,12 @@ private function getStrategy(array $config): NamingStrategyContract /** * Configures the migration organize. * - * @param iterable $config - * @param \Viserio\Bridge\Doctrine\Migration\Configuration\Configuration $configuration + * @param iterable $config + * @param \Viserio\Provider\Doctrine\Migration\Configuration\Configuration $configuration * - * @throws \Viserio\Bridge\Doctrine\Contract\Migration\Exception\InvalidArgumentException + * @throws \Viserio\Provider\Doctrine\Contract\Migration\Exception\InvalidArgumentException * - * @return \Viserio\Bridge\Doctrine\Migration\Configuration\Configuration + * @return \Viserio\Provider\Doctrine\Migration\Configuration\Configuration */ private function configureOrganizeMigrations(iterable $config, Configuration $configuration): Configuration { diff --git a/src/Viserio/Provider/DoctrineMigration/Commands/LatestCommand.php b/src/Viserio/Provider/DoctrineMigration/Commands/LatestCommand.php new file mode 100644 index 000000000..310f046cd --- /dev/null +++ b/src/Viserio/Provider/DoctrineMigration/Commands/LatestCommand.php @@ -0,0 +1,3 @@ +getName(); $name = $name ? $name : 'Doctrine Database Migrations'; - $name = str_repeat(' ', 20) . $name . str_repeat(' ', 20); + $name = \str_repeat(' ', 20) . $name . \str_repeat(' ', 20); - $this->line(str_repeat(' ', mb_strlen($name)), 'question'); + $this->line(\str_repeat(' ', \mb_strlen($name)), 'question'); $this->line($name, 'question'); - $this->line(str_repeat(' ', mb_strlen($name)), 'question'); + $this->line(\str_repeat(' ', \mb_strlen($name)), 'question'); $this->line(''); } } diff --git a/src/Viserio/Provider/DoctrineMigration/Commands/RefreshCommand.php b/src/Viserio/Provider/DoctrineMigration/Commands/RefreshCommand.php new file mode 100644 index 000000000..310f046cd --- /dev/null +++ b/src/Viserio/Provider/DoctrineMigration/Commands/RefreshCommand.php @@ -0,0 +1,3 @@ +namingStrategy = $namingStrategy; + return $this->namingStrategy; } /** - * Get a naming strategy. + * Set a naming strategy object. * - * @return \Viserio\Bridge\Doctrine\Contract\Migration\NamingStrategy + * @param \Viserio\Provider\Doctrine\Contract\Migration\NamingStrategy $namingStrategy + * + * @return void */ - public function getNamingStrategy(): NamingStrategyContract + public function setNamingStrategy(NamingStrategyContract $namingStrategy): void { - return $this->namingStrategy; + $this->namingStrategy = $namingStrategy; } } diff --git a/src/Viserio/Bridge/Doctrine/Migration/LICENSE b/src/Viserio/Provider/DoctrineMigration/LICENSE similarity index 100% rename from src/Viserio/Bridge/Doctrine/Migration/LICENSE rename to src/Viserio/Provider/DoctrineMigration/LICENSE diff --git a/src/Viserio/Bridge/Doctrine/Migration/Naming/DefaultNamingStrategy.php b/src/Viserio/Provider/DoctrineMigration/Naming/DefaultNamingStrategy.php similarity index 84% rename from src/Viserio/Bridge/Doctrine/Migration/Naming/DefaultNamingStrategy.php rename to src/Viserio/Provider/DoctrineMigration/Naming/DefaultNamingStrategy.php index b5ae9030e..8b70e2c22 100644 --- a/src/Viserio/Bridge/Doctrine/Migration/Naming/DefaultNamingStrategy.php +++ b/src/Viserio/Provider/DoctrineMigration/Naming/DefaultNamingStrategy.php @@ -1,10 +1,10 @@ getHelperSet() ->set(new ConfigurationHelper($container), 'connection'); diff --git a/src/Viserio/Bridge/Doctrine/Migration/README.md b/src/Viserio/Provider/DoctrineMigration/README.md similarity index 100% rename from src/Viserio/Bridge/Doctrine/Migration/README.md rename to src/Viserio/Provider/DoctrineMigration/README.md diff --git a/src/Viserio/Bridge/Doctrine/Migration/Tests/Provider/ConsoleCommandsServiceProviderTest.php b/src/Viserio/Provider/DoctrineMigration/Tests/Provider/ConsoleCommandsServiceProviderTest.php similarity index 73% rename from src/Viserio/Bridge/Doctrine/Migration/Tests/Provider/ConsoleCommandsServiceProviderTest.php rename to src/Viserio/Provider/DoctrineMigration/Tests/Provider/ConsoleCommandsServiceProviderTest.php index 6ecac4a7f..028a9fd11 100644 --- a/src/Viserio/Bridge/Doctrine/Migration/Tests/Provider/ConsoleCommandsServiceProviderTest.php +++ b/src/Viserio/Provider/DoctrineMigration/Tests/Provider/ConsoleCommandsServiceProviderTest.php @@ -1,6 +1,6 @@ get(Application::class); $commands = $console->all(); - self::assertInstanceOf(DiffCommand::class, $commands['migrations:diff']); - self::assertInstanceOf(ExecuteCommand::class, $commands['migrations:execute']); - self::assertInstanceOf(GenerateCommand::class, $commands['migrations:generate']); - self::assertInstanceOf(MigrateCommand::class, $commands['migrations:migrate']); - self::assertInstanceOf(StatusCommand::class, $commands['migrations:status']); - self::assertInstanceOf(VersionCommand::class, $commands['migrations:version']); + $this->assertInstanceOf(DiffCommand::class, $commands['migrations:diff']); + $this->assertInstanceOf(ExecuteCommand::class, $commands['migrations:execute']); + $this->assertInstanceOf(GenerateCommand::class, $commands['migrations:generate']); + $this->assertInstanceOf(MigrateCommand::class, $commands['migrations:migrate']); + $this->assertInstanceOf(StatusCommand::class, $commands['migrations:status']); + $this->assertInstanceOf(VersionCommand::class, $commands['migrations:version']); } } diff --git a/src/Viserio/Bridge/Doctrine/Migration/Tests/Stub/database.sqlite b/src/Viserio/Provider/DoctrineMigration/Tests/Stub/database.sqlite similarity index 100% rename from src/Viserio/Bridge/Doctrine/Migration/Tests/Stub/database.sqlite rename to src/Viserio/Provider/DoctrineMigration/Tests/Stub/database.sqlite diff --git a/src/Viserio/Provider/DoctrineMigration/composer.json b/src/Viserio/Provider/DoctrineMigration/composer.json new file mode 100644 index 000000000..201706622 --- /dev/null +++ b/src/Viserio/Provider/DoctrineMigration/composer.json @@ -0,0 +1,61 @@ +{ + "name": "viserio/doctrine-migration-provider", + "type": "viserio-bridge", + "description": "The Viserio Doctrine provider.", + "keywords": [ + "narrowspark", + "viserio", + "database", + "doctrine", + "migrations", + "provider" + ], + "homepage": "http://narrowspark.com", + "license": "MIT", + "authors": [ + { + "name": "Daniel Bannert", + "email": "d.bannert@anolilab.de", + "homepage": "http://www.anolilab.de", + "role": "Developer" + } + ], + "require": { + "php": "^7.2", + "doctrine/migrations": "^2.0@beta", + "viserio/console": "self.version", + "viserio/options-resolver": "self.version" + }, + "require-dev": { + "container-interop/service-provider": "^0.4", + "phpunit/phpunit": "^7.2.0", + "viserio/container": "self.version" + }, + "suggest": { + "container-interop/service-provider": "Required to use service-provider (^0.4)." + }, + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "psr-4": { + "Viserio\\Provider\\Doctrine\\Migration\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "autoload-dev": { + "psr-4": { + "Viserio\\Provider\\Doctrine\\Migration\\Tests\\": "Tests/" + } + }, + "minimum-stability": "dev", + "prefer-stable": true, + "support": { + "issues": "https://github.com/narrowspark/framework/issues", + "source": "https://github.com/narrowspark/framework" + } +} diff --git a/src/Viserio/Bridge/Doctrine/Migration/phpunit.xml.dist b/src/Viserio/Provider/DoctrineMigration/phpunit.xml.dist similarity index 100% rename from src/Viserio/Bridge/Doctrine/Migration/phpunit.xml.dist rename to src/Viserio/Provider/DoctrineMigration/phpunit.xml.dist diff --git a/src/Viserio/Provider/Twig/Command/LintCommand.php b/src/Viserio/Provider/Twig/Command/LintCommand.php index 5fab717e7..9c32c142e 100644 --- a/src/Viserio/Provider/Twig/Command/LintCommand.php +++ b/src/Viserio/Provider/Twig/Command/LintCommand.php @@ -4,11 +4,11 @@ use Symfony\Component\Finder\Finder; use Twig\Environment; -use Viserio\Bridge\Twig\Command\LintCommand as BaseLintCommand; use Viserio\Component\Contract\OptionsResolver\ProvidesDefaultOptions as ProvidesDefaultOptionsContract; use Viserio\Component\Contract\OptionsResolver\RequiresComponentConfig as RequiresComponentConfigContract; use Viserio\Component\Contract\View\Finder as FinderContract; use Viserio\Component\OptionsResolver\Traits\OptionsResolverTrait; +use Viserio\Provider\Twig\Command\LintCommand as BaseLintCommand; class LintCommand extends BaseLintCommand implements RequiresComponentConfigContract, ProvidesDefaultOptionsContract { diff --git a/src/Viserio/Provider/Twig/Provider/ConsoleCommandsServiceProvider.php b/src/Viserio/Provider/Twig/Provider/ConsoleCommandsServiceProvider.php index 7818f18ef..fb9733e7e 100644 --- a/src/Viserio/Provider/Twig/Provider/ConsoleCommandsServiceProvider.php +++ b/src/Viserio/Provider/Twig/Provider/ConsoleCommandsServiceProvider.php @@ -5,12 +5,12 @@ use Interop\Container\ServiceProviderInterface; use Psr\Container\ContainerInterface; use Twig\Environment; -use Viserio\Bridge\Twig\Command\DebugCommand; use Viserio\Component\Console\Application; use Viserio\Component\Contract\OptionsResolver\ProvidesDefaultOptions as ProvidesDefaultOptionsContract; use Viserio\Component\Contract\OptionsResolver\RequiresComponentConfig as RequiresComponentConfigContract; use Viserio\Component\Contract\View\Finder as FinderContract; use Viserio\Provider\Twig\Command\CleanCommand; +use Viserio\Provider\Twig\Command\DebugCommand; use Viserio\Provider\Twig\Command\LintCommand; class ConsoleCommandsServiceProvider implements diff --git a/src/Viserio/Provider/Twig/Tests/Engine/TwigEngineTest.php b/src/Viserio/Provider/Twig/Tests/Engine/TwigEngineTest.php index 8beb61342..fe1377d73 100644 --- a/src/Viserio/Provider/Twig/Tests/Engine/TwigEngineTest.php +++ b/src/Viserio/Provider/Twig/Tests/Engine/TwigEngineTest.php @@ -7,11 +7,11 @@ use Symfony\Component\Filesystem\Filesystem; use Twig\Environment; use Twig\Loader\FilesystemLoader; -use Viserio\Bridge\Twig\Extension\ConfigExtension; -use Viserio\Bridge\Twig\Extension\StrExtension; use Viserio\Component\Contract\Config\Repository as RepositoryContract; use Viserio\Component\Contract\View\Exception\RuntimeException; use Viserio\Provider\Twig\Engine\TwigEngine; +use Viserio\Provider\Twig\Extension\ConfigExtension; +use Viserio\Provider\Twig\Extension\StrExtension; /** * @internal From 424fe9239ec0ad1bb17983b1886fbfc99e8e62a7 Mon Sep 17 00:00:00 2001 From: prisis Date: Wed, 28 Nov 2018 13:08:22 +0100 Subject: [PATCH 3/4] moved more files --- .../.github/PULL_REQUEST_TEMPLATE.md | 0 .../Extensions => DoctrineExtensions}/LICENSE | 0 .../Provider/ExtensionsServiceProvider.php | 0 .../Extensions => DoctrineExtensions}/README.md | 0 .../Types/ChronosDateTimeType.php | 0 .../Types/ChronosDateTimeTzType.php | 0 .../Types/ChronosDateType.php | 0 .../Types/ChronosTimeType.php | 0 .../Extensions => DoctrineExtensions}/composer.json | 0 .../phpunit.xml.dist | 0 .../.github/PULL_REQUEST_TEMPLATE.md | 0 .../Cache/StaticArrayCache.php | 0 .../Commands/LoadDataFixturesDoctrineCommand.php | 0 .../Concerns/DoctrineEntitiesTestCase.php | 0 .../Concerns/InteractsWithEntities.php | 0 .../DBAL/StaticConnection.php | 0 .../DBAL/StaticConnectionManager.php | 0 .../DBAL/StaticDriver.php | 0 .../Testing => DoctrineTesting}/Factory.php | 0 .../Testing => DoctrineTesting}/FactoryBuilder.php | 0 .../{Doctrine/Testing => DoctrineTesting}/LICENSE | 0 .../PHPUnit/PHPUnitListener.php | 0 .../Provider/ConsoleCommandsServiceProvider.php | 0 .../Provider/DoctrineORMTestingServiceProvider.php | 0 .../Provider/DoctrineTestingServiceProvier.php | 0 .../{Doctrine/Testing => DoctrineTesting}/README.md | 0 .../Testing => DoctrineTesting}/SimpleHydrator.php | 0 .../Tests/Cache/StaticArrayCacheTest.php | 0 .../Tests/Concerns/DoctrineEntitiesTestCaseTest.php | 0 .../Tests/DBAL/StaticDriverTest.php | 0 .../Tests/FactoryBuilderTest.php | 0 .../Tests/FactoryTest.php | 0 .../Tests/Fixtures/MockDriver.php | 0 .../Provider/ConsoleCommandsServiceProviderTest.php | 0 .../DoctrineORMTestingServiceProviderTest.php | 0 .../Tests/Stub/database.sqlite | Bin .../Testing => DoctrineTesting}/composer.json | 6 ++---- .../Testing => DoctrineTesting}/phpunit.xml.dist | 0 38 files changed, 2 insertions(+), 4 deletions(-) rename src/Viserio/Bridge/{Doctrine/Extensions => DoctrineExtensions}/.github/PULL_REQUEST_TEMPLATE.md (100%) rename src/Viserio/Bridge/{Doctrine/Extensions => DoctrineExtensions}/LICENSE (100%) rename src/Viserio/Bridge/{Doctrine/Extensions => DoctrineExtensions}/Provider/ExtensionsServiceProvider.php (100%) rename src/Viserio/Bridge/{Doctrine/Extensions => DoctrineExtensions}/README.md (100%) rename src/Viserio/Bridge/{Doctrine/Extensions => DoctrineExtensions}/Types/ChronosDateTimeType.php (100%) rename src/Viserio/Bridge/{Doctrine/Extensions => DoctrineExtensions}/Types/ChronosDateTimeTzType.php (100%) rename src/Viserio/Bridge/{Doctrine/Extensions => DoctrineExtensions}/Types/ChronosDateType.php (100%) rename src/Viserio/Bridge/{Doctrine/Extensions => DoctrineExtensions}/Types/ChronosTimeType.php (100%) rename src/Viserio/Bridge/{Doctrine/Extensions => DoctrineExtensions}/composer.json (100%) rename src/Viserio/Bridge/{Doctrine/Extensions => DoctrineExtensions}/phpunit.xml.dist (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/.github/PULL_REQUEST_TEMPLATE.md (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/Cache/StaticArrayCache.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/Commands/LoadDataFixturesDoctrineCommand.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/Concerns/DoctrineEntitiesTestCase.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/Concerns/InteractsWithEntities.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/DBAL/StaticConnection.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/DBAL/StaticConnectionManager.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/DBAL/StaticDriver.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/Factory.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/FactoryBuilder.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/LICENSE (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/PHPUnit/PHPUnitListener.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/Provider/ConsoleCommandsServiceProvider.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/Provider/DoctrineORMTestingServiceProvider.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/Provider/DoctrineTestingServiceProvier.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/README.md (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/SimpleHydrator.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/Tests/Cache/StaticArrayCacheTest.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/Tests/Concerns/DoctrineEntitiesTestCaseTest.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/Tests/DBAL/StaticDriverTest.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/Tests/FactoryBuilderTest.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/Tests/FactoryTest.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/Tests/Fixtures/MockDriver.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/Tests/Provider/ConsoleCommandsServiceProviderTest.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/Tests/Provider/DoctrineORMTestingServiceProviderTest.php (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/Tests/Stub/database.sqlite (100%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/composer.json (88%) rename src/Viserio/Bridge/{Doctrine/Testing => DoctrineTesting}/phpunit.xml.dist (100%) diff --git a/src/Viserio/Bridge/Doctrine/Extensions/.github/PULL_REQUEST_TEMPLATE.md b/src/Viserio/Bridge/DoctrineExtensions/.github/PULL_REQUEST_TEMPLATE.md similarity index 100% rename from src/Viserio/Bridge/Doctrine/Extensions/.github/PULL_REQUEST_TEMPLATE.md rename to src/Viserio/Bridge/DoctrineExtensions/.github/PULL_REQUEST_TEMPLATE.md diff --git a/src/Viserio/Bridge/Doctrine/Extensions/LICENSE b/src/Viserio/Bridge/DoctrineExtensions/LICENSE similarity index 100% rename from src/Viserio/Bridge/Doctrine/Extensions/LICENSE rename to src/Viserio/Bridge/DoctrineExtensions/LICENSE diff --git a/src/Viserio/Bridge/Doctrine/Extensions/Provider/ExtensionsServiceProvider.php b/src/Viserio/Bridge/DoctrineExtensions/Provider/ExtensionsServiceProvider.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Extensions/Provider/ExtensionsServiceProvider.php rename to src/Viserio/Bridge/DoctrineExtensions/Provider/ExtensionsServiceProvider.php diff --git a/src/Viserio/Bridge/Doctrine/Extensions/README.md b/src/Viserio/Bridge/DoctrineExtensions/README.md similarity index 100% rename from src/Viserio/Bridge/Doctrine/Extensions/README.md rename to src/Viserio/Bridge/DoctrineExtensions/README.md diff --git a/src/Viserio/Bridge/Doctrine/Extensions/Types/ChronosDateTimeType.php b/src/Viserio/Bridge/DoctrineExtensions/Types/ChronosDateTimeType.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Extensions/Types/ChronosDateTimeType.php rename to src/Viserio/Bridge/DoctrineExtensions/Types/ChronosDateTimeType.php diff --git a/src/Viserio/Bridge/Doctrine/Extensions/Types/ChronosDateTimeTzType.php b/src/Viserio/Bridge/DoctrineExtensions/Types/ChronosDateTimeTzType.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Extensions/Types/ChronosDateTimeTzType.php rename to src/Viserio/Bridge/DoctrineExtensions/Types/ChronosDateTimeTzType.php diff --git a/src/Viserio/Bridge/Doctrine/Extensions/Types/ChronosDateType.php b/src/Viserio/Bridge/DoctrineExtensions/Types/ChronosDateType.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Extensions/Types/ChronosDateType.php rename to src/Viserio/Bridge/DoctrineExtensions/Types/ChronosDateType.php diff --git a/src/Viserio/Bridge/Doctrine/Extensions/Types/ChronosTimeType.php b/src/Viserio/Bridge/DoctrineExtensions/Types/ChronosTimeType.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Extensions/Types/ChronosTimeType.php rename to src/Viserio/Bridge/DoctrineExtensions/Types/ChronosTimeType.php diff --git a/src/Viserio/Bridge/Doctrine/Extensions/composer.json b/src/Viserio/Bridge/DoctrineExtensions/composer.json similarity index 100% rename from src/Viserio/Bridge/Doctrine/Extensions/composer.json rename to src/Viserio/Bridge/DoctrineExtensions/composer.json diff --git a/src/Viserio/Bridge/Doctrine/Extensions/phpunit.xml.dist b/src/Viserio/Bridge/DoctrineExtensions/phpunit.xml.dist similarity index 100% rename from src/Viserio/Bridge/Doctrine/Extensions/phpunit.xml.dist rename to src/Viserio/Bridge/DoctrineExtensions/phpunit.xml.dist diff --git a/src/Viserio/Bridge/Doctrine/Testing/.github/PULL_REQUEST_TEMPLATE.md b/src/Viserio/Bridge/DoctrineTesting/.github/PULL_REQUEST_TEMPLATE.md similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/.github/PULL_REQUEST_TEMPLATE.md rename to src/Viserio/Bridge/DoctrineTesting/.github/PULL_REQUEST_TEMPLATE.md diff --git a/src/Viserio/Bridge/Doctrine/Testing/Cache/StaticArrayCache.php b/src/Viserio/Bridge/DoctrineTesting/Cache/StaticArrayCache.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/Cache/StaticArrayCache.php rename to src/Viserio/Bridge/DoctrineTesting/Cache/StaticArrayCache.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/Commands/LoadDataFixturesDoctrineCommand.php b/src/Viserio/Bridge/DoctrineTesting/Commands/LoadDataFixturesDoctrineCommand.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/Commands/LoadDataFixturesDoctrineCommand.php rename to src/Viserio/Bridge/DoctrineTesting/Commands/LoadDataFixturesDoctrineCommand.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/Concerns/DoctrineEntitiesTestCase.php b/src/Viserio/Bridge/DoctrineTesting/Concerns/DoctrineEntitiesTestCase.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/Concerns/DoctrineEntitiesTestCase.php rename to src/Viserio/Bridge/DoctrineTesting/Concerns/DoctrineEntitiesTestCase.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/Concerns/InteractsWithEntities.php b/src/Viserio/Bridge/DoctrineTesting/Concerns/InteractsWithEntities.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/Concerns/InteractsWithEntities.php rename to src/Viserio/Bridge/DoctrineTesting/Concerns/InteractsWithEntities.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticConnection.php b/src/Viserio/Bridge/DoctrineTesting/DBAL/StaticConnection.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticConnection.php rename to src/Viserio/Bridge/DoctrineTesting/DBAL/StaticConnection.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticConnectionManager.php b/src/Viserio/Bridge/DoctrineTesting/DBAL/StaticConnectionManager.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticConnectionManager.php rename to src/Viserio/Bridge/DoctrineTesting/DBAL/StaticConnectionManager.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticDriver.php b/src/Viserio/Bridge/DoctrineTesting/DBAL/StaticDriver.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/DBAL/StaticDriver.php rename to src/Viserio/Bridge/DoctrineTesting/DBAL/StaticDriver.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/Factory.php b/src/Viserio/Bridge/DoctrineTesting/Factory.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/Factory.php rename to src/Viserio/Bridge/DoctrineTesting/Factory.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/FactoryBuilder.php b/src/Viserio/Bridge/DoctrineTesting/FactoryBuilder.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/FactoryBuilder.php rename to src/Viserio/Bridge/DoctrineTesting/FactoryBuilder.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/LICENSE b/src/Viserio/Bridge/DoctrineTesting/LICENSE similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/LICENSE rename to src/Viserio/Bridge/DoctrineTesting/LICENSE diff --git a/src/Viserio/Bridge/Doctrine/Testing/PHPUnit/PHPUnitListener.php b/src/Viserio/Bridge/DoctrineTesting/PHPUnit/PHPUnitListener.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/PHPUnit/PHPUnitListener.php rename to src/Viserio/Bridge/DoctrineTesting/PHPUnit/PHPUnitListener.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/Provider/ConsoleCommandsServiceProvider.php b/src/Viserio/Bridge/DoctrineTesting/Provider/ConsoleCommandsServiceProvider.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/Provider/ConsoleCommandsServiceProvider.php rename to src/Viserio/Bridge/DoctrineTesting/Provider/ConsoleCommandsServiceProvider.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/Provider/DoctrineORMTestingServiceProvider.php b/src/Viserio/Bridge/DoctrineTesting/Provider/DoctrineORMTestingServiceProvider.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/Provider/DoctrineORMTestingServiceProvider.php rename to src/Viserio/Bridge/DoctrineTesting/Provider/DoctrineORMTestingServiceProvider.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/Provider/DoctrineTestingServiceProvier.php b/src/Viserio/Bridge/DoctrineTesting/Provider/DoctrineTestingServiceProvier.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/Provider/DoctrineTestingServiceProvier.php rename to src/Viserio/Bridge/DoctrineTesting/Provider/DoctrineTestingServiceProvier.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/README.md b/src/Viserio/Bridge/DoctrineTesting/README.md similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/README.md rename to src/Viserio/Bridge/DoctrineTesting/README.md diff --git a/src/Viserio/Bridge/Doctrine/Testing/SimpleHydrator.php b/src/Viserio/Bridge/DoctrineTesting/SimpleHydrator.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/SimpleHydrator.php rename to src/Viserio/Bridge/DoctrineTesting/SimpleHydrator.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/Cache/StaticArrayCacheTest.php b/src/Viserio/Bridge/DoctrineTesting/Tests/Cache/StaticArrayCacheTest.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/Tests/Cache/StaticArrayCacheTest.php rename to src/Viserio/Bridge/DoctrineTesting/Tests/Cache/StaticArrayCacheTest.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/Concerns/DoctrineEntitiesTestCaseTest.php b/src/Viserio/Bridge/DoctrineTesting/Tests/Concerns/DoctrineEntitiesTestCaseTest.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/Tests/Concerns/DoctrineEntitiesTestCaseTest.php rename to src/Viserio/Bridge/DoctrineTesting/Tests/Concerns/DoctrineEntitiesTestCaseTest.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/DBAL/StaticDriverTest.php b/src/Viserio/Bridge/DoctrineTesting/Tests/DBAL/StaticDriverTest.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/Tests/DBAL/StaticDriverTest.php rename to src/Viserio/Bridge/DoctrineTesting/Tests/DBAL/StaticDriverTest.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/FactoryBuilderTest.php b/src/Viserio/Bridge/DoctrineTesting/Tests/FactoryBuilderTest.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/Tests/FactoryBuilderTest.php rename to src/Viserio/Bridge/DoctrineTesting/Tests/FactoryBuilderTest.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/FactoryTest.php b/src/Viserio/Bridge/DoctrineTesting/Tests/FactoryTest.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/Tests/FactoryTest.php rename to src/Viserio/Bridge/DoctrineTesting/Tests/FactoryTest.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/Fixtures/MockDriver.php b/src/Viserio/Bridge/DoctrineTesting/Tests/Fixtures/MockDriver.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/Tests/Fixtures/MockDriver.php rename to src/Viserio/Bridge/DoctrineTesting/Tests/Fixtures/MockDriver.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/Provider/ConsoleCommandsServiceProviderTest.php b/src/Viserio/Bridge/DoctrineTesting/Tests/Provider/ConsoleCommandsServiceProviderTest.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/Tests/Provider/ConsoleCommandsServiceProviderTest.php rename to src/Viserio/Bridge/DoctrineTesting/Tests/Provider/ConsoleCommandsServiceProviderTest.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/Provider/DoctrineORMTestingServiceProviderTest.php b/src/Viserio/Bridge/DoctrineTesting/Tests/Provider/DoctrineORMTestingServiceProviderTest.php similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/Tests/Provider/DoctrineORMTestingServiceProviderTest.php rename to src/Viserio/Bridge/DoctrineTesting/Tests/Provider/DoctrineORMTestingServiceProviderTest.php diff --git a/src/Viserio/Bridge/Doctrine/Testing/Tests/Stub/database.sqlite b/src/Viserio/Bridge/DoctrineTesting/Tests/Stub/database.sqlite similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/Tests/Stub/database.sqlite rename to src/Viserio/Bridge/DoctrineTesting/Tests/Stub/database.sqlite diff --git a/src/Viserio/Bridge/Doctrine/Testing/composer.json b/src/Viserio/Bridge/DoctrineTesting/composer.json similarity index 88% rename from src/Viserio/Bridge/Doctrine/Testing/composer.json rename to src/Viserio/Bridge/DoctrineTesting/composer.json index b27e8fb24..fea4496e7 100644 --- a/src/Viserio/Bridge/Doctrine/Testing/composer.json +++ b/src/Viserio/Bridge/DoctrineTesting/composer.json @@ -24,20 +24,18 @@ "php": "^7.1", "fzaninotto/faker": "^1.6", "narrowspark/collection": "^0.1", - "viserio/doctrine-dbal-bridge": "self.version" + "phpunit/phpunit": "^7.2.0" }, "require-dev": { "container-interop/service-provider": "^0.3", "doctrine/data-fixtures": "^1.2", - "phpunit/phpunit": "^7.2.0", "viserio/container": "self.version", "viserio/doctrine-orm-bridge": "self.version" }, "suggest": { "container-interop/service-provider": "Required to use service-provider (^0.3).", "doctrine/orm": "Required to use the concerns (self.version).", - "viserio/console": "Required to use the data-fixture command (self.version).", - "viserio/doctrine-orm-bridge": "Required to use the data-fixture command and concerns (self.version)." + "viserio/console": "Required to use the data-fixture command (self.version)." }, "extra": { "branch-alias": { diff --git a/src/Viserio/Bridge/Doctrine/Testing/phpunit.xml.dist b/src/Viserio/Bridge/DoctrineTesting/phpunit.xml.dist similarity index 100% rename from src/Viserio/Bridge/Doctrine/Testing/phpunit.xml.dist rename to src/Viserio/Bridge/DoctrineTesting/phpunit.xml.dist From a1baaaf981e444c7e8a1444f87b6b8764a39abd7 Mon Sep 17 00:00:00 2001 From: prisis Date: Thu, 10 Jan 2019 17:31:23 +0100 Subject: [PATCH 4/4] added new test --- .../Tests/Fixtures/BaseHydrateableClass.php | 13 ++++++++ .../Tests/Fixtures/ChildHydrateableClass.php | 13 ++++++++ .../Tests/SimpleHydratorTest.php | 33 +++++++++++++++++++ 3 files changed, 59 insertions(+) create mode 100644 src/Viserio/Bridge/DoctrineTesting/Tests/Fixtures/BaseHydrateableClass.php create mode 100644 src/Viserio/Bridge/DoctrineTesting/Tests/Fixtures/ChildHydrateableClass.php create mode 100644 src/Viserio/Bridge/DoctrineTesting/Tests/SimpleHydratorTest.php diff --git a/src/Viserio/Bridge/DoctrineTesting/Tests/Fixtures/BaseHydrateableClass.php b/src/Viserio/Bridge/DoctrineTesting/Tests/Fixtures/BaseHydrateableClass.php new file mode 100644 index 000000000..812a33614 --- /dev/null +++ b/src/Viserio/Bridge/DoctrineTesting/Tests/Fixtures/BaseHydrateableClass.php @@ -0,0 +1,13 @@ +name; + } +} diff --git a/src/Viserio/Bridge/DoctrineTesting/Tests/Fixtures/ChildHydrateableClass.php b/src/Viserio/Bridge/DoctrineTesting/Tests/Fixtures/ChildHydrateableClass.php new file mode 100644 index 000000000..dab139861 --- /dev/null +++ b/src/Viserio/Bridge/DoctrineTesting/Tests/Fixtures/ChildHydrateableClass.php @@ -0,0 +1,13 @@ +description; + } +} diff --git a/src/Viserio/Bridge/DoctrineTesting/Tests/SimpleHydratorTest.php b/src/Viserio/Bridge/DoctrineTesting/Tests/SimpleHydratorTest.php new file mode 100644 index 000000000..2c2009700 --- /dev/null +++ b/src/Viserio/Bridge/DoctrineTesting/Tests/SimpleHydratorTest.php @@ -0,0 +1,33 @@ + 'Ghost', + ]); + + $this->assertInstanceOf(BaseHydrateableClass::class, $entity); + $this->assertEquals('Ghost', $entity->getName()); + } + + public function testCanHydrateWithExtensionOfPrivateProperties(): void + { + $entity = SimpleHydrator::hydrate(ChildHydrateableClass::class, [ + 'name' => 'Ghost', + 'description' => 'Hello World', + ]); + + $this->assertInstanceOf(ChildHydrateableClass::class, $entity); + $this->assertEquals('Ghost', $entity->getName()); + $this->assertEquals('Hello World', $entity->getDescription()); + } +}