diff --git a/.gitignore b/.gitignore index d2f5f690158..a7e9f0bfc0b 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ lib/api/ lib/Doctrine/Common lib/Doctrine/DBAL /.settings/ +*.iml .buildpath .project .idea diff --git a/UPGRADE.md b/UPGRADE.md index 3132aef9805..ca618a2a0cf 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -1,3 +1,159 @@ +# Upgrade to 3.0 + +## BC Break: Removed `Doctrine\ORM\Version` + +The `Doctrine\ORM\Version` class is no longer available: please refrain from checking the ORM version at runtime. + +## BC Break: Removed `EntityManager#merge()` and `EntityManager#detach()` methods + +Merge and detach semantics were a poor fit for the PHP "share-nothing" architecture. +In addition to that, merging/detaching caused multiple issues with data integrity +in the managed entity graph, which was constantly spawning more edge-case bugs/scenarios. + +The following API methods were therefore removed: + +* `EntityManager#merge()` +* `EntityManager#detach()` +* `UnitOfWork#merge()` +* `UnitOfWork#detach()` + +Users are encouraged to migrate `EntityManager#detach()` calls to `EntityManager#clear()`. + +In order to maintain performance on batch processing jobs, it is endorsed to enable +the second level cache (http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/second-level-cache.html) +on entities that are frequently reused across multiple `EntityManager#clear()` calls. + +An alternative to `EntityManager#merge()` is not provided by ORM 3.0, since the merging +semantics should be part of the business domain rather than the persistence domain of an +application. If your application relies heavily on CRUD-alike interactions and/or `PATCH` +restful operations, you should look at alternatives such as [JMSSerializer](https://github.com/schmittjoh/serializer). + +## BC Break: Added the final keyword for `EntityManager` + +Final keyword has been added to the ``EntityManager::class`` in order to ensure that EntityManager is not used as valid extension point. Valid extension point should be EntityManagerInterface. + +## BC Break: ``EntityManagerInterface`` is now used instead of ``EntityManager`` in typehints + +`Sequencing\Generator#generate()` now takes ``EntityManagerInterface`` as its first argument instead of ``EntityManager``. If you have any custom generators, please update your code accordingly. + +## BC Break: Removed `EntityManager#flush($entity)` and `EntityManager#flush($entities)` + +If your code relies on single entity flushing optimisations via +`EntityManager#flush($entity)`, the signature has been changed to +`EntityManager#flush()`. + +Said API was affected by multiple data integrity bugs due to the fact +that change tracking was being restricted upon a subset of the managed +entities. The ORM cannot support committing subsets of the managed +entities while also guaranteeing data integrity, therefore this +utility was removed. + +The `flush()` semantics remain the same, but the change tracking will be performed +on all entities managed by the unit of work, and not just on the provided +`$entity` or `$entities`, as the parameter is now completely ignored. + +The same applies to `UnitOfWork#commit($entity)`, which now is simply +`UnitOfWork#commit()`. + +If you would still like to perform batching operations over small `UnitOfWork` +instances, it is suggested to follow these paths instead: + + * eagerly use `EntityManager#clear()` in conjunction with a specific second level + cache configuration (see http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/second-level-cache.html) + * use an explicit change tracking policy (see http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/change-tracking-policies.html) + +## BC Break: Removed ``YAML`` mapping drivers. + +If your code relies on ``YamlDriver`` or ``SimpleYamlDriver``, you **MUST** change to +annotation or XML drivers instead. + +## BC Break: Changed methods in ``ClassMetadata`` + +* ``ClassMetadata::addInheritedProperty`` +* ``ClassMetadata::setDiscriminatorColumn`` + +## BC Break: Removed methods in ``ClassMetadata`` + +* ``ClassMetadata::getTypeOfField`` (to be removed, part of Common API) + +## BC Break: Removed methods in ``ClassMetadata`` + +* ``ClassMetadata::setTableName`` => Use ``ClassMetadata::setPrimaryTable(['name' => ...])`` +* ``ClassMetadata::getFieldMapping`` => Use ``ClassMetadata::getProperty()`` and its methods +* ``ClassMetadata::getQuotedColumnName`` => Use ``ClassMetadata::getProperty()::getQuotedColumnName()`` +* ``ClassMetadata::getQuotedTableName`` +* ``ClassMetadata::getQuotedJoinTableName`` +* ``ClassMetadata::getQuotedIdentifierColumnNames`` +* ``ClassMetadata::getIdentifierColumnNames`` => Use ``ClassMetadata::getIdentifierColumns($entityManager)`` +* ``ClassMetadata::setVersionMetadata`` +* ``ClassMetadata::setVersioned`` +* ``ClassMetadata::invokeLifecycleCallbacks`` +* ``ClassMetadata::isInheritedField`` => Use ``ClassMetadata::getProperty()::isInherited()`` +* ``ClassMetadata::isUniqueField`` => Use ``ClassMetadata::getProperty()::isUnique()`` +* ``ClassMetadata::isNullable`` => Use ``ClassMetadata::getProperty()::isNullable()`` +* ``ClassMetadata::getTypeOfColumn()`` => Use ``PersisterHelper::getTypeOfColumn()`` + +## BC Break: Removed ``quoted`` index from table, field and sequence mappings + +Quoting is now always called. Implement your own ``Doctrine\ORM\Mapping\NamingStrategy`` to manipulate +your schema, tables and column names to your custom desired naming convention. + +## BC Break: Removed ``ClassMetadata::$fieldMappings[$fieldName]['requireSQLConversion']`` + +ORM Type SQL conversion is now always being applied, minimizing the risks of error prone code in ORM internals + +## BC Break: Removed ``ClassMetadata::$columnNames`` + +If your code relies on this property, you should search/replace from this: + + $metadata->columnNames[$fieldName] + +To this: + + $metadata->getProperty($fieldName)->getColumnName() + +## BC Break: Renamed ``ClassMetadata::setIdentifierValues()`` to ``ClassMetadata::assignIdentifier()`` + +Provides a more meaningful name to method. + +## BC Break: Removed ``ClassMetadata::$namespace`` + +The namespace property in ClassMetadata was only used when using association +classes in the same namespace and it was used to speedup ClassMetadata +creation purposes. Namespace could be easily inferred by asking ``\ReflectionClass`` +which was already stored internally. + +### BC Break: Removed ``ClassMetadata::$isVersioned`` + +Switched to a method alternative: ``ClassMetadata::isVersioned()`` + +## BC Break: Removed ``Doctrine\ORM\Mapping\ClassMetadataInfo`` + +There was no reason to keep a blank class. All references are now pointing +to ``Doctrine\ORM\Mapping\ClassMetadata``. + +## BC Break: Annotations classes namespace change + +All Annotations classes got moved from ``Doctrine\ORM\Mapping`` into a more +pertinent namespace ``Doctrine\ORM\Annotation``. This change was done to add +room for Metadata namespace refactoring. + +## Minor BC break: Mappings now store DBAL\Type instances instead of strings + +This lead to manual ``ResultSetMapping`` building instances to also hold Types in meta results. +Example: + + $rsm->addMetaResult('e ', 'e_discr', 'discr', false, Type::getType('string')); + +## Enhancement: Mappings now store their declaring ClassMetadata + +Every field, association or embedded now contains a pointer to its declaring ClassMetadata. + +## Enhancement: Mappings now store their corresponding table name + +Every field, association join column or inline embedded field/association holds a reference to its owning table name. + + # Upgrade to 2.6 ## Minor BC BREAK: `Doctrine\ORM\Tools\Console\ConsoleRunner` is now final @@ -21,6 +177,7 @@ Method `Doctrine\ORM\Query\Parser#overwriteInternalDQLFunctionNotAllowed` was removed because of the choice to allow users to overwrite internal functions, ie `AVG`, `SUM`, `COUNT`, `MIN` and `MAX`. [#6500](https://github.com/doctrine/doctrine2/pull/6500) + # Upgrade to 2.5 ## Minor BC BREAK: removed `Doctrine\ORM\Query\SqlWalker#walkCaseExpression()` @@ -180,6 +337,7 @@ From now on, the resultset will look like this: Added way to access the underlying QueryBuilder#from() method's 'indexBy' parameter when using EntityRepository#createQueryBuilder() + # Upgrade to 2.4 ## BC BREAK: Compatibility Bugfix in PersistentCollection#matching() @@ -224,6 +382,7 @@ Now parenthesis are considered, the previous DQL will generate: SELECT 100 / (2 * 2) FROM my_entity + # Upgrade to 2.3 ## Auto Discriminator Map breaks userland implementations with Listener @@ -293,6 +452,7 @@ Also, following mapping drivers have been deprecated, please use their replaceme * `Doctrine\ORM\Mapping\Driver\PHPDriver` => `Doctrine\Common\Persistence\Mapping\Driver\PHPDriver` * `Doctrine\ORM\Mapping\Driver\StaticPHPDriver` => `Doctrine\Common\Persistence\Mapping\Driver\StaticPHPDriver` + # Upgrade to 2.2 ## ResultCache implementation rewritten @@ -376,6 +536,7 @@ Also, Doctrine 2.2 now is around 10-15% faster than 2.1. Previously EntityManager#find(null) returned null. It now throws an exception. + # Upgrade to 2.1 ## Interface for EntityRepository @@ -400,6 +561,7 @@ The annotation reader was heavily refactored between 2.0 and 2.1-RC1. In theory This is already done inside the ``$config->newDefaultAnnotationDriver``, so everything should automatically work if you are using this method. You can verify if everything still works by executing a console command such as schema-validate that loads all metadata into memory. + # Update from 2.0-BETA3 to 2.0-BETA4 ## XML Driver element demoted to attribute @@ -408,6 +570,7 @@ We changed how the XML Driver allows to define the change-tracking-policy. The w + # Update from 2.0-BETA2 to 2.0-BETA3 ## Serialization of Uninitialized Proxies @@ -470,10 +633,12 @@ don't loose anything through this. The default allocation size for sequences has been changed from 10 to 1. This step was made to not cause confusion with users and also because it is partly some kind of premature optimization. + # Update from 2.0-BETA1 to 2.0-BETA2 There are no backwards incompatible changes in this release. + # Upgrade from 2.0-ALPHA4 to 2.0-BETA1 ## EntityRepository deprecates access to protected variables @@ -544,7 +709,6 @@ access all entities. Xml and Yaml Drivers work as before! - ## New inversedBy attribute It is now *mandatory* that the owning side of a bidirectional association specifies the @@ -608,7 +772,7 @@ you need to use the following, explicit syntax: ## XML Mapping Driver The 'inheritance-type' attribute changed to take last bit of ClassMetadata constant names, i.e. -NONE, SINGLE_TABLE, INHERITANCE_TYPE_JOINED +NONE, SINGLE_TABLE, JOINED ## YAML Mapping Driver @@ -640,6 +804,7 @@ The Collection interface in the Common package has been updated with some missin that were present only on the default implementation, ArrayCollection. Custom collection implementations need to be updated to adhere to the updated interface. + # Upgrade from 2.0-ALPHA3 to 2.0-ALPHA4 ## CLI Controller changes @@ -676,6 +841,8 @@ With new required method AbstractTask::buildDocumentation, its implementation de database schema without deleting any unused tables, sequences or foreign keys. * Use "doctrine schema-tool --complete-update" to do a full incremental update of your schema. + + # Upgrade from 2.0-ALPHA2 to 2.0-ALPHA3 This section details the changes made to Doctrine 2.0-ALPHA3 to make it easier for you diff --git a/bin/doctrine b/bin/doctrine index c359ca7d83e..16c8477c5f0 100755 --- a/bin/doctrine +++ b/bin/doctrine @@ -1,4 +1,6 @@ #!/usr/bin/env php . - */ + + +declare(strict_types=1); require_once 'Doctrine/Common/ClassLoader.php'; diff --git a/bin/doctrine.php b/bin/doctrine.php index 81d4e7bf279..f46d5a856ea 100644 --- a/bin/doctrine.php +++ b/bin/doctrine.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); use Symfony\Component\Console\Helper\HelperSet; use Doctrine\ORM\Tools\Console\ConsoleRunner; diff --git a/build.properties b/build.properties index 4b4c921a556..e69de29bb2d 100644 --- a/build.properties +++ b/build.properties @@ -1,3 +0,0 @@ -# Version class and file -project.version_class = Doctrine\\ORM\\Version -project.version_file = lib/Doctrine/ORM/Version.php diff --git a/build.xml b/build.xml index 26132d19ca9..50cbcaa2649 100644 --- a/build.xml +++ b/build.xml @@ -38,29 +38,6 @@ - - - - - - - - - - - - - - - - - diff --git a/composer.json b/composer.json index d632c89919d..7a5d02f7142 100644 --- a/composer.json +++ b/composer.json @@ -17,20 +17,17 @@ "php": "^7.1", "ext-pdo": "*", "doctrine/collections": "^1.4", - "doctrine/dbal": ">=2.5-dev,<2.7-dev", + "doctrine/dbal": "dev-develop as 3.x-dev", "doctrine/instantiator": "~1.1", "doctrine/common": "^2.7.1", "doctrine/cache": "~1.6", "doctrine/annotations": "~1.4", + "ocramius/package-versions": "^1.1.2", "symfony/console": "~3.0|~4.0" }, "require-dev": { - "symfony/yaml": "~3.0|~4.0", "phpunit/phpunit": "^6.0" }, - "suggest": { - "symfony/yaml": "If you want to use YAML Metadata Mapping Driver" - }, "autoload": { "psr-4": { "Doctrine\\ORM\\": "lib/Doctrine/ORM" } }, @@ -43,7 +40,7 @@ "bin": ["bin/doctrine"], "extra": { "branch-alias": { - "dev-master": "2.6.x-dev" + "dev-master": "3.0.x-dev" } }, "archive": { diff --git a/docs/en/changelog/migration_2_5.rst b/docs/en/changelog/migration_2_5.rst index 408776d03c3..4d4ac1622d4 100644 --- a/docs/en/changelog/migration_2_5.rst +++ b/docs/en/changelog/migration_2_5.rst @@ -16,7 +16,7 @@ New Features and Improvements Events: PostLoad now triggered after associations are loaded ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Before Doctrine 2.5 if you had an entity with a ``@PostLoad`` event +Before Doctrine 2.5 if you had an entity with a ``@ORM\PostLoad`` event defined then Doctrine would trigger listeners after the fields were loaded, but before assocations are available. @@ -62,9 +62,9 @@ Embeddable Objects ~~~~~~~~~~~~~~~~~~ Doctrine now supports creating multiple PHP objects from one database table -implementing a feature called "Embeddable Objects". Next to an ``@Entity`` +implementing a feature called "Embeddable Objects". Next to an ``@ORM\Entity`` class you can now define a class that is embeddable into a database table of an -entity using the ``@Embeddable`` annotation. Embeddable objects can never be +entity using the ``@ORM\Embeddable`` annotation. Embeddable objects can never be saved, updated or deleted on their own, only as part of an entity (called "root-entity" or "aggregate"). Consequently embeddables don't have a primary key, they are identified only by their values. @@ -75,23 +75,25 @@ Example of defining and using embeddables classes: reflClass->implementsInterface('LocaleAware')) { + if (!$targetEntity->getReflectionClass()->implementsInterface('LocaleAware')) { return ""; } @@ -289,9 +302,14 @@ EXTRA_LAZY Improvements merge($user); - } - -.. note:: - - A frequent mistake is not to get the merged user object from the return - value of ``EntityManager#merge()``. The entity object passed to merge is - not necessarily the same object that is returned from the method. + if (isset($_SESSION['user'])) { + $user = $em->find(User::class, $_SESSION['user']); -Serializing entity into the session ------------------------------------ - -Entities that are serialized into the session normally contain references to -other entities as well. Think of the user entity has a reference to his -articles, groups, photos or many other different entities. If you serialize -this object into the session then you don't want to serialize the related -entities as well. This is why you should call ``EntityManager#detach()`` on this -object or implement the __sleep() magic method on your entity. - -.. code-block:: php - - find("User", 1); - $em->detach($user); - $_SESSION['user'] = $user; + if (! $user instanceof User) { + // user not found in the database + $_SESSION['user'] = null; + } + } -.. note:: +Serializing entities into the session +------------------------------------- - When you called detach on your objects they get "unmanaged" with that - entity manager. This means you cannot use them as part of write operations - during ``EntityManager#flush()`` anymore in this request. +Serializing entities in the session means serializing also all associated +entities and collections. While this might look like a quick solution in +simple applications, you will encounter problems due to the fact that the +data in the session is stale. +In order to prevent working with stale data, try saving only minimal +information about your entities in your session, without storing entire +entity objects. Should you need the full information of an object, so it +is suggested to re-query the database, which is usually the most +authoritative source of information in typical PHP applications. diff --git a/docs/en/cookbook/mysql-enums.rst b/docs/en/cookbook/mysql-enums.rst index 1765ecc90e8..b81b3419f28 100644 --- a/docs/en/cookbook/mysql-enums.rst +++ b/docs/en/cookbook/mysql-enums.rst @@ -43,13 +43,16 @@ entities: .. code-block:: php getClassMetadata(); - if (!$classMetadata->isInheritanceTypeSingleTable() || $classMetadata->getName() === $classMetadata->rootEntityName) { + if ($classMetadata->inheritanceType !== Mapping\InheritanceType::SINGLE_TABLE || + $classMetadata->getName() === $classMetadata->rootEntityName) { $classMetadata->setTableName($this->prefix . $classMetadata->getTableName()); } - foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) { - if ($mapping['type'] == \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_MANY && $mapping['isOwningSide']) { + foreach ($classMetadata->associationMappings as $fieldName => $mapping) { + if ($mapping['type'] == Mapping\ClassMetadata::MANY_TO_MANY && $mapping['isOwningSide']) { $mappedTableName = $mapping['joinTable']['name']; $classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->prefix . $mappedTableName; } diff --git a/docs/en/cookbook/strategy-cookbook-introduction.rst b/docs/en/cookbook/strategy-cookbook-introduction.rst index d9934f577de..7acb2d52fd8 100644 --- a/docs/en/cookbook/strategy-cookbook-introduction.rst +++ b/docs/en/cookbook/strategy-cookbook-introduction.rst @@ -213,8 +213,8 @@ This might look like this: .. code-block:: php _em->detach($row[0]); + // detach all entities from Doctrine, so that Garbage-Collection can kick in immediately + $this->_em->clear(); } .. note:: @@ -183,5 +183,9 @@ problems using the following approach: fetch-join a collection-valued association. The nature of such SQL result sets is not suitable for incremental hydration. +Packages for easing Batch Processing +------------------------------------ - +You can implement batch processing yourself, or use an existing +package such as `DoctrineBatchUtils `_, +which already provides the logic described above in an encapsulated format. diff --git a/docs/en/reference/best-practices.rst b/docs/en/reference/best-practices.rst index 256ee533961..fb6c6bb1a33 100644 --- a/docs/en/reference/best-practices.rst +++ b/docs/en/reference/best-practices.rst @@ -43,7 +43,7 @@ should use events judiciously. Use cascades judiciously ------------------------ -Automatic cascades of the persist/remove/merge/etc. operations are +Automatic cascades of the persist/remove/refresh/etc. operations are very handy but should be used wisely. Do NOT simply add all cascades to all associations. Think about which cascades actually do make sense for you for a particular association, given the diff --git a/docs/en/reference/dql-doctrine-query-language.rst b/docs/en/reference/dql-doctrine-query-language.rst index b0d19e8e089..c114a159eeb 100644 --- a/docs/en/reference/dql-doctrine-query-language.rst +++ b/docs/en/reference/dql-doctrine-query-language.rst @@ -1369,7 +1369,7 @@ can mark a many-to-one or one-to-one association as fetched temporarily to batch createQuery("SELECT u FROM MyProject\User u"); - $query->setFetchMode("MyProject\User", "address", \Doctrine\ORM\Mapping\ClassMetadata::FETCH_EAGER); + $query->setFetchMode("MyProject\User", "address", \Doctrine\ORM\Mapping\FetchMode::EAGER); $query->execute(); Given that there are 10 users and corresponding addresses in the database the executed queries will look something like: diff --git a/docs/en/reference/events.rst b/docs/en/reference/events.rst index 7922d3dfd1d..6dfde28d388 100644 --- a/docs/en/reference/events.rst +++ b/docs/en/reference/events.rst @@ -960,7 +960,7 @@ Load ClassMetadata Event ------------------------ When the mapping information for an entity is read, it is populated -in to a ``ClassMetadataInfo`` instance. You can hook in to this +in to a ``ClassMetadata`` instance. You can hook in to this process and manipulate the instance. .. code-block:: php diff --git a/docs/en/reference/filters.rst b/docs/en/reference/filters.rst index a5c0ee4cf14..881169e989f 100644 --- a/docs/en/reference/filters.rst +++ b/docs/en/reference/filters.rst @@ -47,7 +47,7 @@ proper quoting of parameters. public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) { // Check if the entity implements the LocalAware interface - if (!$targetEntity->reflClass->implementsInterface('LocaleAware')) { + if (!$targetEntity->getReflectionClass()->implementsInterface('LocaleAware')) { return ""; } diff --git a/docs/en/reference/inheritance-mapping.rst b/docs/en/reference/inheritance-mapping.rst index 2063624fe91..6d807fe346e 100644 --- a/docs/en/reference/inheritance-mapping.rst +++ b/docs/en/reference/inheritance-mapping.rst @@ -365,8 +365,7 @@ Example: - - + @@ -414,7 +413,7 @@ Example: joinColumn: name: address_id referencedColumnName: id - cascade: [ persist, merge ] + cascade: [ persist, refresh ] manyToMany: groups: targetEntity: Group @@ -426,7 +425,7 @@ Example: inverseJoinColumns: group_id: referencedColumnName: id - cascade: [ persist, merge, detach ] + cascade: [ persist, refresh ] # admin mapping MyProject\Model\Admin: @@ -522,7 +521,7 @@ Could be used by an entity that extends a mapped superclass to override a field - + diff --git a/docs/en/reference/limitations-and-known-issues.rst b/docs/en/reference/limitations-and-known-issues.rst index 8f273568fd1..571c251b538 100644 --- a/docs/en/reference/limitations-and-known-issues.rst +++ b/docs/en/reference/limitations-and-known-issues.rst @@ -65,15 +65,6 @@ Where the ``attribute_name`` column contains the key and The feature request for persistence of primitive value arrays `is described in the DDC-298 ticket `_. -Cascade Merge with Bi-directional Associations -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -There are two bugs now that concern the use of cascade merge in combination with bi-directional associations. -Make sure to study the behavior of cascade merge if you are using it: - -- `DDC-875 `_ Merge can sometimes add the same entity twice into a collection -- `DDC-763 `_ Cascade merge on associated entities can insert too many rows through "Persistence by Reachability" - Custom Persisters ~~~~~~~~~~~~~~~~~ diff --git a/docs/en/reference/metadata-drivers.rst b/docs/en/reference/metadata-drivers.rst index 6b9cb31e42c..e0509627924 100644 --- a/docs/en/reference/metadata-drivers.rst +++ b/docs/en/reference/metadata-drivers.rst @@ -60,7 +60,7 @@ implements the ``Driver`` interface: _loadMappingFile($file); - // populate ClassMetadataInfo instance from $data + // populate ClassMetadata instance from $data } /** @@ -154,14 +154,11 @@ entity when needed. You have all the methods you need to manually specify the mapping information instead of using some mapping file to populate it from. -The base ``ClassMetadataInfo`` class is responsible for only data -storage and is not meant for runtime use. It does not require that -the class actually exists yet so it is useful for describing some +The ``ClassMetadata`` class is responsible for only data storage +and is not meant for runtime use. It does not require that the +class actually exists yet so it is useful for describing some entity before it exists and using that information to generate for -example the entities themselves. The class ``ClassMetadata`` -extends ``ClassMetadataInfo`` and adds some functionality required -for runtime usage and requires that the PHP class is present and -can be autoloaded. +example the entities themselves. You can read more about the API of the ``ClassMetadata`` classes in the PHP Mapping chapter. diff --git a/docs/en/reference/php-mapping.rst b/docs/en/reference/php-mapping.rst index 78a721411d6..2f8150f39b8 100644 --- a/docs/en/reference/php-mapping.rst +++ b/docs/en/reference/php-mapping.rst @@ -180,14 +180,26 @@ It also has several methods that create builders (which are necessary for advanc - ``createManyToMany($name, $targetEntity)`` returns an ``ManyToManyAssociationBuilder`` instance - ``createOneToMany($name, $targetEntity)`` returns an ``OneToManyAssociationBuilder`` instance -ClassMetadataInfo API +ClassMetadata API --------------------- -The ``ClassMetadataInfo`` class is the base data object for storing +The ``ClassMetadata`` class is the base data object for storing the mapping metadata for a single entity. It contains all the getters and setters you need populate and retrieve information for an entity. +Internal +~~~~~~~~ + +- ``getReflectionClass()`` +- ``getReflectionProperties()`` +- ``getReflectionProperty($name)`` +- ``getSingleIdReflectionProperty()`` +- ``getIdentifierValues($entity)`` +- ``assignIdentifier($entity, $id)`` +- ``setFieldValue($entity, $field, $value)`` +- ``getFieldValue($entity, $field)`` + General Setters ~~~~~~~~~~~~~~~ @@ -215,11 +227,8 @@ Field Mapping Setters ~~~~~~~~~~~~~~~~~~~~~ -- ``mapField(array $mapping)`` -- ``mapOneToOne(array $mapping)`` -- ``mapOneToMany(array $mapping)`` -- ``mapManyToOne(array $mapping)`` -- ``mapManyToMany(array $mapping)`` +- ``addProperty(Property $property)`` +- ``addAssociation(AssociationMetadata $property)`` Lifecycle Callback Setters ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -249,12 +258,7 @@ Identifier Getters - ``getIdentifierColumnNames()`` -- ``usesIdGenerator()`` - ``isIdentifier($fieldName)`` -- ``isIdGeneratorIdentity()`` -- ``isIdGeneratorSequence()`` -- ``isIdGeneratorTable()`` -- ``isIdentifierNatural()`` - ``getIdentifierFieldNames()`` - ``getSingleIdentifierFieldName()`` - ``getSingleIdentifierColumnName()`` @@ -263,21 +267,9 @@ Inheritance Getters ~~~~~~~~~~~~~~~~~~~ -- ``isInheritanceTypeNone()`` -- ``isInheritanceTypeJoined()`` -- ``isInheritanceTypeSingleTable()`` -- ``isInheritanceTypeTablePerClass()`` - ``isInheritedField($fieldName)`` - ``isInheritedAssociation($fieldName)`` -Change Tracking Getters -~~~~~~~~~~~~~~~~~~~~~~~ - - -- ``isChangeTrackingDeferredExplicit()`` -- ``isChangeTrackingDeferredImplicit()`` -- ``isChangeTrackingNotify()`` - Field & Association Getters ~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -286,11 +278,8 @@ Field & Association Getters - ``isNullable($fieldName)`` - ``getColumnName($fieldName)`` - ``getFieldMapping($fieldName)`` -- ``getAssociationMapping($fieldName)`` -- ``getAssociationMappings()`` - ``getFieldName($columnName)`` - ``hasField($fieldName)`` -- ``getColumnNames(array $fieldNames = null)`` - ``getTypeOfField($fieldName)`` - ``getTypeOfColumn($columnName)`` - ``hasAssociation($fieldName)`` @@ -304,22 +293,4 @@ Lifecycle Callback Getters - ``hasLifecycleCallbacks($lifecycleEvent)`` - ``getLifecycleCallbacks($event)`` -ClassMetadata API ------------------ - -The ``ClassMetadata`` class extends ``ClassMetadataInfo`` and adds -the runtime functionality required by Doctrine. It adds a few extra -methods related to runtime reflection for working with the entities -themselves. - - -- ``getReflectionClass()`` -- ``getReflectionProperties()`` -- ``getReflectionProperty($name)`` -- ``getSingleIdReflectionProperty()`` -- ``getIdentifierValues($entity)`` -- ``setIdentifierValues($entity, $id)`` -- ``setFieldValue($entity, $field, $value)`` -- ``getFieldValue($entity, $field)`` - diff --git a/docs/en/reference/tools.rst b/docs/en/reference/tools.rst index c3580b36d57..390fccdd3af 100644 --- a/docs/en/reference/tools.rst +++ b/docs/en/reference/tools.rst @@ -73,7 +73,7 @@ sample ``cli-config.php`` file looks as follows: // Any way to access the EntityManager from your application $em = GetMyEntityManager(); - + $helperSet = new \Symfony\Component\Console\Helper\HelperSet(array( 'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()), 'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em) @@ -84,7 +84,7 @@ script will ultimately use. The Doctrine Binary will automatically find the first instance of HelperSet in the global variable namespace and use this. -.. note:: +.. note:: You have to adjust this snippet for your specific application or framework and use their facilities to access the Doctrine EntityManager and @@ -173,7 +173,7 @@ When using the SchemaTool class directly, create your schema using the ``createSchema()`` method. First create an instance of the ``SchemaTool`` and pass it an instance of the ``EntityManager`` that you want to use to create the schema. This method receives an -array of ``ClassMetadataInfo`` instances. +array of ``ClassMetadata`` instances. .. code-block:: php @@ -204,8 +204,8 @@ tables of the current model to clean up with orphaned tables. You can also use database introspection to update your schema easily with the ``updateSchema()`` method. It will compare your -existing database schema to the passed array of -``ClassMetadataInfo`` instances. +existing database schema to the passed array of ``ClassMetadata`` +instances. .. code-block:: php @@ -361,8 +361,7 @@ Reverse Engineering ------------------- You can use the ``DatabaseDriver`` to reverse engineer a database -to an array of ``ClassMetadataInfo`` instances and generate YAML, -XML, etc. from them. +to an array of ``ClassMetadata`` instances and generate YAML, XML, etc. from them. .. note:: @@ -384,7 +383,7 @@ First you need to retrieve the metadata instances with the $em->getConnection()->getSchemaManager() ) ); - + $cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory(); $cmf->setEntityManager($em); $metadata = $cmf->getAllMetadata(); diff --git a/docs/en/reference/transactions-and-concurrency.rst b/docs/en/reference/transactions-and-concurrency.rst index 5ce0852b2a7..22ad20eb183 100644 --- a/docs/en/reference/transactions-and-concurrency.rst +++ b/docs/en/reference/transactions-and-concurrency.rst @@ -104,18 +104,11 @@ functionally equivalent to the previously shown code looks as follows: $em->persist($user); }); -.. warning:: - - For historical reasons, ``EntityManager#transactional($func)`` will return - ``true`` whenever the return value of ``$func`` is loosely false. - Some examples of this include ``array()``, ``"0"``, ``""``, ``0``, and - ``null``. The difference between ``Connection#transactional($func)`` and ``EntityManager#transactional($func)`` is that the latter abstraction flushes the ``EntityManager`` prior to transaction -commit and rolls back the transaction when an -exception occurs. +commit. .. _transactions-and-concurrency_exception-handling: @@ -279,15 +272,15 @@ either when calling ``EntityManager#find()``: find('User', $theEntityId, LockMode::OPTIMISTIC, $expectedVersion); - + // do the work - + $em->flush(); } catch(OptimisticLockException $e) { echo "Sorry, but someone else has already changed this entity. Please apply the changes again!"; @@ -300,16 +293,16 @@ Or you can use ``EntityManager#lock()`` to find out: find('User', $theEntityId); - + try { // assert version $em->lock($entity, LockMode::OPTIMISTIC, $expectedVersion); - + } catch(OptimisticLockException $e) { echo "Sorry, but someone else has already changed this entity. Please apply the changes again!"; } @@ -348,7 +341,7 @@ See the example code, The form (GET Request): find('BlogPost', 123456); - + echo ''; echo ''; @@ -359,7 +352,7 @@ And the change headline action (POST Request): find('BlogPost', $postId, \Doctrine\DBAL\LockMode::OPTIMISTIC, $postVersion); .. _transactions-and-concurrency_pessimistic-locking: diff --git a/docs/en/reference/unitofwork.rst b/docs/en/reference/unitofwork.rst index cdfb6e0be4a..cb3866e9cfe 100644 --- a/docs/en/reference/unitofwork.rst +++ b/docs/en/reference/unitofwork.rst @@ -129,7 +129,6 @@ optimize the performance of the Flush Operation: - Temporarily mark entities as read only. If you have a very large UnitOfWork but know that a large set of entities has not changed, just mark them as read only with ``$entityManager->getUnitOfWork()->markReadOnly($entity)``. -- Flush only a single entity with ``$entityManager->flush($entity)``. - Use :doc:`Change Tracking Policies ` to use more explicit strategies of notifying the UnitOfWork what objects/properties changed. diff --git a/docs/en/reference/working-with-associations.rst b/docs/en/reference/working-with-associations.rst index e115efbc97e..7d18eee337c 100644 --- a/docs/en/reference/working-with-associations.rst +++ b/docs/en/reference/working-with-associations.rst @@ -410,7 +410,7 @@ Transitive persistence / Cascade Operations Doctrine 2 provides a mechanism for transitive persistence through cascading of certain operations. Each association to another entity or a collection of entities can be configured to automatically cascade the following operations to the associated entities: -``persist``, ``remove``, ``merge``, ``detach``, ``refresh`` or ``all``. +``persist``, ``remove``, ``refresh`` or ``all``. The main use case for ``cascade: persist`` is to avoid "exposing" associated entities to your PHP application. Continuing with the User-Comment example of this chapter, this is how the creation of a new user and a new diff --git a/docs/en/reference/working-with-objects.rst b/docs/en/reference/working-with-objects.rst index bef73cebaa3..7d2d385bcea 100644 --- a/docs/en/reference/working-with-objects.rst +++ b/docs/en/reference/working-with-objects.rst @@ -326,134 +326,41 @@ in multiple ways with very different performance impacts. Detaching entities ------------------ -An entity is detached from an EntityManager and thus no longer -managed by invoking the ``EntityManager#detach($entity)`` method on -it or by cascading the detach operation to it. Changes made to the -detached entity, if any (including removal of the entity), will not -be synchronized to the database after the entity has been +All entities are detached from an EntityManager and thus no longer +managed by it after invoking the ``EntityManager#clear()`` method. +Changes made to the detached entities, if any (including their removal), +will not be synchronized to the database after they have been detached. -Doctrine will not hold on to any references to a detached entity. +Doctrine will not hold on to any references to detached entities. Example: .. code-block:: php detach($entity); + $em->clear(); The semantics of the detach operation, applied to an entity X are as follows: - -- If X is a managed entity, the detach operation causes it to - become detached. The detach operation is cascaded to entities - referenced by X, if the relationships from X to these other - entities is mapped with cascade=DETACH or cascade=ALL (see - ":ref:`Transitive Persistence `"). Entities which previously referenced X +- If X is a managed entity, the ``clear`` operation causes it to + become detached. Entities which previously referenced X will continue to reference X. - If X is a new or detached entity, it is ignored by the detach operation. -- If X is a removed entity, the detach operation is cascaded to - entities referenced by X, if the relationships from X to these - other entities is mapped with cascade=DETACH or cascade=ALL (see - ":ref:`Transitive Persistence `"). Entities which previously referenced X - will continue to reference X. +- If X is a removed entity, it will become detached, and therefore + no longer scheduled to be removed. Entities which previously + referenced X will continue to reference X. There are several situations in which an entity is detached -automatically without invoking the ``detach`` method: +automatically: - -- When ``EntityManager#clear()`` is invoked, all entities that are - currently managed by the EntityManager instance become detached. - When serializing an entity. The entity retrieved upon subsequent unserialization will be detached (This is the case for all entities that are serialized and stored in some cache, i.e. when using the Query Result Cache). -The ``detach`` operation is usually not as frequently needed and -used as ``persist`` and ``remove``. - -Merging entities ----------------- - -Merging entities refers to the merging of (usually detached) -entities into the context of an EntityManager so that they become -managed again. To merge the state of an entity into an -EntityManager use the ``EntityManager#merge($entity)`` method. The -state of the passed entity will be merged into a managed copy of -this entity and this copy will subsequently be returned. - -Example: - -.. code-block:: php - - merge($detachedEntity); - // $entity now refers to the fully managed copy returned by the merge operation. - // The EntityManager $em now manages the persistence of $entity as usual. - -.. note:: - - When you want to serialize/unserialize entities you - have to make all entity properties protected, never private. The - reason for this is, if you serialize a class that was a proxy - instance before, the private variables won't be serialized and a - PHP Notice is thrown. - - -The semantics of the merge operation, applied to an entity X, are -as follows: - - -- If X is a detached entity, the state of X is copied onto a - pre-existing managed entity instance X' of the same identity. -- If X is a new entity instance, a new managed copy X' will be - created and the state of X is copied onto this managed instance. -- If X is a removed entity instance, an InvalidArgumentException - will be thrown. -- If X is a managed entity, it is ignored by the merge operation, - however, the merge operation is cascaded to entities referenced by - relationships from X if these relationships have been mapped with - the cascade element value MERGE or ALL (see ":ref:`Transitive Persistence `"). -- For all entities Y referenced by relationships from X having the - cascade element value MERGE or ALL, Y is merged recursively as Y'. - For all such Y referenced by X, X' is set to reference Y'. (Note - that if X is managed then X is the same object as X'.) -- If X is an entity merged to X', with a reference to another - entity Y, where cascade=MERGE or cascade=ALL is not specified, then - navigation of the same association from X' yields a reference to a - managed object Y' with the same persistent identity as Y. - -The ``merge`` operation will throw an ``OptimisticLockException`` -if the entity being merged uses optimistic locking through a -version field and the versions of the entity being merged and the -managed copy don't match. This usually means that the entity has -been modified while being detached. - -The ``merge`` operation is usually not as frequently needed and -used as ``persist`` and ``remove``. The most common scenario for -the ``merge`` operation is to reattach entities to an EntityManager -that come from some cache (and are therefore detached) and you want -to modify and persist such an entity. - -.. warning:: - - If you need to perform multiple merges of entities that share certain subparts - of their object-graphs and cascade merge, then you have to call ``EntityManager#clear()`` between the - successive calls to ``EntityManager#merge()``. Otherwise you might end up with - multiple copies of the "same" object in the database, however with different ids. - -.. note:: - - If you load some detached entities from a cache and you do - not need to persist or delete them or otherwise make use of them - without the need for persistence services there is no need to use - ``merge``. I.e. you can simply pass detached objects from a cache - directly to the view. - - Synchronization with the Database --------------------------------- @@ -563,7 +470,7 @@ during development. .. note:: Do not invoke ``flush`` after every change to an entity - or every single invocation of persist/remove/merge/... This is an + or every single invocation of persist/remove/refresh/... This is an anti-pattern and unnecessarily reduces the performance of your application. Instead, form units of work that operate on your objects and call ``flush`` when you are done. While serving a diff --git a/docs/en/reference/xml-mapping.rst b/docs/en/reference/xml-mapping.rst index 5f013152789..2bb615013f3 100644 --- a/docs/en/reference/xml-mapping.rst +++ b/docs/en/reference/xml-mapping.rst @@ -688,7 +688,6 @@ specified by their respective tags: - ```` -- ```` - ```` - ```` diff --git a/docs/en/reference/yaml-mapping.rst b/docs/en/reference/yaml-mapping.rst index ea54e277ae9..1f45192ca38 100644 --- a/docs/en/reference/yaml-mapping.rst +++ b/docs/en/reference/yaml-mapping.rst @@ -114,7 +114,7 @@ of several common elements: phonenumbers: targetEntity: Phonenumber mappedBy: user - cascade: ["persist", "merge"] + cascade: ["persist", "refresh"] manyToMany: groups: targetEntity: Group diff --git a/docs/en/tutorials/composite-primary-keys.rst b/docs/en/tutorials/composite-primary-keys.rst index d8256db7561..f2bac7c19dd 100644 --- a/docs/en/tutorials/composite-primary-keys.rst +++ b/docs/en/tutorials/composite-primary-keys.rst @@ -28,16 +28,19 @@ and year of production as primary keys: .. code-block:: php 'pdo_sqlite', 'path' => __DIR__ . '/db.sqlite', ); - + // obtaining the entity manager $entityManager = EntityManager::create($conn, $config); @@ -180,7 +180,7 @@ cli-config.php file must exist in the project root directory: - - @@ -333,6 +331,7 @@ + @@ -350,6 +349,7 @@ + diff --git a/lib/Doctrine/ORM/AbstractQuery.php b/lib/Doctrine/ORM/AbstractQuery.php index ba013bbbb69..f61e568af30 100644 --- a/lib/Doctrine/ORM/AbstractQuery.php +++ b/lib/Doctrine/ORM/AbstractQuery.php @@ -1,28 +1,12 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; use Doctrine\Common\Util\ClassUtils; use Doctrine\Common\Collections\Collection; -use Doctrine\Common\Collections\ArrayCollection; - +use Doctrine\Common\Collections\ArrayCollection;; use Doctrine\ORM\Query\Parameter; use Doctrine\ORM\Cache\QueryCacheKey; use Doctrine\DBAL\Cache\QueryCacheProfile; @@ -79,45 +63,45 @@ abstract class AbstractQuery * * @var \Doctrine\ORM\Query\ResultSetMapping */ - protected $_resultSetMapping; + protected $resultSetMapping; /** * The entity manager used by this query object. * * @var EntityManagerInterface */ - protected $_em; + protected $em; /** * The map of query hints. * * @var array */ - protected $_hints = []; + protected $hints = []; /** * The hydration mode. * * @var integer */ - protected $_hydrationMode = self::HYDRATE_OBJECT; + protected $hydrationMode = self::HYDRATE_OBJECT; /** * @var \Doctrine\DBAL\Cache\QueryCacheProfile */ - protected $_queryCacheProfile; + protected $queryCacheProfile; /** * Whether or not expire the result cache. * * @var boolean */ - protected $_expireResultCache = false; + protected $expireResultCache = false; /** * @var \Doctrine\DBAL\Cache\QueryCacheProfile */ - protected $_hydrationCacheProfile; + protected $hydrationCacheProfile; /** * Whether to use second level cache, if available. @@ -162,10 +146,10 @@ abstract class AbstractQuery */ public function __construct(EntityManagerInterface $em) { - $this->_em = $em; + $this->em = $em; $this->parameters = new ArrayCollection(); - $this->_hints = $em->getConfiguration()->getDefaultQueryHints(); - $this->hasCache = $this->_em->getConfiguration()->isSecondLevelCacheEnabled(); + $this->hints = $em->getConfiguration()->getDefaultQueryHints(); + $this->hasCache = $this->em->getConfiguration()->isSecondLevelCacheEnabled(); if ($this->hasCache) { $this->cacheLogger = $em->getConfiguration() @@ -280,11 +264,11 @@ abstract public function getSQL(); /** * Retrieves the associated EntityManager of this Query instance. * - * @return \Doctrine\ORM\EntityManager + * @return \Doctrine\ORM\EntityManagerInterface */ public function getEntityManager() { - return $this->_em; + return $this->em; } /** @@ -298,7 +282,7 @@ public function free() { $this->parameters = new ArrayCollection(); - $this->_hints = $this->_em->getConfiguration()->getDefaultQueryHints(); + $this->hints = $this->em->getConfiguration()->getDefaultQueryHints(); } /** @@ -328,7 +312,7 @@ function ($parameter) use ($key) } ); - return count($filteredParameters) ? $filteredParameters->first() : null; + return $filteredParameters->isEmpty() ? null : $filteredParameters->first(); } /** @@ -377,7 +361,7 @@ function ($parameter) use ($key) } ); - if (count($filteredParameters)) { + if (! $filteredParameters->isEmpty()) { $parameter = $filteredParameters->first(); $parameter->setValue($value, $type); @@ -404,6 +388,10 @@ public function processParameterValue($value) return $value; } + if ($value instanceof Mapping\ClassMetadata) { + return $value->discriminatorValue ?: $value->getClassName(); + } + if ($value instanceof Collection) { $value = $value->toArray(); } @@ -417,18 +405,14 @@ public function processParameterValue($value) return $value; } - if (is_object($value) && $this->_em->getMetadataFactory()->hasMetadataFor(ClassUtils::getClass($value))) { - $value = $this->_em->getUnitOfWork()->getSingleIdentifierValue($value); + if (is_object($value) && $this->em->getMetadataFactory()->hasMetadataFor(ClassUtils::getClass($value))) { + $value = $this->em->getUnitOfWork()->getSingleIdentifierValue($value); if ($value === null) { throw ORMInvalidArgumentException::invalidIdentifierBindingEntity(); } } - if ($value instanceof Mapping\ClassMetadata) { - return $value->name; - } - return $value; } @@ -442,7 +426,7 @@ public function processParameterValue($value) public function setResultSetMapping(Query\ResultSetMapping $rsm) { $this->translateNamespaces($rsm); - $this->_resultSetMapping = $rsm; + $this->resultSetMapping = $rsm; return $this; } @@ -454,7 +438,7 @@ public function setResultSetMapping(Query\ResultSetMapping $rsm) */ protected function getResultSetMapping() { - return $this->_resultSetMapping; + return $this->resultSetMapping; } /** @@ -467,7 +451,7 @@ protected function getResultSetMapping() private function translateNamespaces(Query\ResultSetMapping $rsm) { $translate = function ($alias) { - return $this->_em->getClassMetadata($alias)->getName(); + return $this->em->getClassMetadata($alias)->getClassName(); }; $rsm->aliasMap = array_map($translate, $rsm->aliasMap); @@ -499,11 +483,11 @@ private function translateNamespaces(Query\ResultSetMapping $rsm) public function setHydrationCacheProfile(QueryCacheProfile $profile = null) { if ($profile !== null && ! $profile->getResultCacheDriver()) { - $resultCacheDriver = $this->_em->getConfiguration()->getHydrationCacheImpl(); + $resultCacheDriver = $this->em->getConfiguration()->getHydrationCacheImpl(); $profile = $profile->setResultCacheDriver($resultCacheDriver); } - $this->_hydrationCacheProfile = $profile; + $this->hydrationCacheProfile = $profile; return $this; } @@ -513,7 +497,7 @@ public function setHydrationCacheProfile(QueryCacheProfile $profile = null) */ public function getHydrationCacheProfile() { - return $this->_hydrationCacheProfile; + return $this->hydrationCacheProfile; } /** @@ -528,12 +512,12 @@ public function getHydrationCacheProfile() */ public function setResultCacheProfile(QueryCacheProfile $profile = null) { - if ( ! $profile->getResultCacheDriver()) { - $resultCacheDriver = $this->_em->getConfiguration()->getResultCacheImpl(); + if (! $profile->getResultCacheDriver()) { + $resultCacheDriver = $this->em->getConfiguration()->getResultCacheImpl(); $profile = $profile->setResultCacheDriver($resultCacheDriver); } - $this->_queryCacheProfile = $profile; + $this->queryCacheProfile = $profile; return $this; } @@ -553,8 +537,8 @@ public function setResultCacheDriver($resultCacheDriver = null) throw ORMException::invalidResultCacheDriver(); } - $this->_queryCacheProfile = $this->_queryCacheProfile - ? $this->_queryCacheProfile->setResultCacheDriver($resultCacheDriver) + $this->queryCacheProfile = $this->queryCacheProfile + ? $this->queryCacheProfile->setResultCacheDriver($resultCacheDriver) : new QueryCacheProfile(0, null, $resultCacheDriver); return $this; @@ -569,11 +553,11 @@ public function setResultCacheDriver($resultCacheDriver = null) */ public function getResultCacheDriver() { - if ($this->_queryCacheProfile && $this->_queryCacheProfile->getResultCacheDriver()) { - return $this->_queryCacheProfile->getResultCacheDriver(); + if ($this->queryCacheProfile && $this->queryCacheProfile->getResultCacheDriver()) { + return $this->queryCacheProfile->getResultCacheDriver(); } - return $this->_em->getConfiguration()->getResultCacheImpl(); + return $this->em->getConfiguration()->getResultCacheImpl(); } /** @@ -595,7 +579,7 @@ public function useResultCache($bool, $lifetime = null, $resultCacheId = null) return $this; } - $this->_queryCacheProfile = null; + $this->queryCacheProfile = null; return $this; } @@ -611,9 +595,9 @@ public function setResultCacheLifetime($lifetime) { $lifetime = ($lifetime !== null) ? (int) $lifetime : 0; - $this->_queryCacheProfile = $this->_queryCacheProfile - ? $this->_queryCacheProfile->setLifetime($lifetime) - : new QueryCacheProfile($lifetime, null, $this->_em->getConfiguration()->getResultCacheImpl()); + $this->queryCacheProfile = $this->queryCacheProfile + ? $this->queryCacheProfile->setLifetime($lifetime) + : new QueryCacheProfile($lifetime, null, $this->em->getConfiguration()->getResultCacheImpl()); return $this; } @@ -627,7 +611,7 @@ public function setResultCacheLifetime($lifetime) */ public function getResultCacheLifetime() { - return $this->_queryCacheProfile ? $this->_queryCacheProfile->getLifetime() : 0; + return $this->queryCacheProfile ? $this->queryCacheProfile->getLifetime() : 0; } /** @@ -639,7 +623,7 @@ public function getResultCacheLifetime() */ public function expireResultCache($expire = true) { - $this->_expireResultCache = $expire; + $this->expireResultCache = $expire; return $this; } @@ -651,7 +635,7 @@ public function expireResultCache($expire = true) */ public function getExpireResultCache() { - return $this->_expireResultCache; + return $this->expireResultCache; } /** @@ -659,13 +643,13 @@ public function getExpireResultCache() */ public function getQueryCacheProfile() { - return $this->_queryCacheProfile; + return $this->queryCacheProfile; } /** * Change the default fetch mode of an association for this query. * - * $fetchMode can be one of ClassMetadata::FETCH_EAGER or ClassMetadata::FETCH_LAZY + * $fetchMode can be one of FetchMode::EAGER, FetchMode::LAZY or FetchMode::EXTRA_LAZY * * @param string $class * @param string $assocName @@ -675,11 +659,11 @@ public function getQueryCacheProfile() */ public function setFetchMode($class, $assocName, $fetchMode) { - if ($fetchMode !== Mapping\ClassMetadata::FETCH_EAGER) { - $fetchMode = Mapping\ClassMetadata::FETCH_LAZY; + if ($fetchMode !== Mapping\FetchMode::EAGER) { + $fetchMode = Mapping\FetchMode::LAZY; } - $this->_hints['fetchMode'][$class][$assocName] = $fetchMode; + $this->hints['fetchMode'][$class][$assocName] = $fetchMode; return $this; } @@ -694,7 +678,7 @@ public function setFetchMode($class, $assocName, $fetchMode) */ public function setHydrationMode($hydrationMode) { - $this->_hydrationMode = $hydrationMode; + $this->hydrationMode = $hydrationMode; return $this; } @@ -706,7 +690,7 @@ public function setHydrationMode($hydrationMode) */ public function getHydrationMode() { - return $this->_hydrationMode; + return $this->hydrationMode; } /** @@ -765,7 +749,7 @@ public function getOneOrNullResult($hydrationMode = null) } - if ($this->_hydrationMode !== self::HYDRATE_SINGLE_SCALAR && ! $result) { + if ($this->hydrationMode !== self::HYDRATE_SINGLE_SCALAR && ! $result) { return null; } @@ -799,7 +783,7 @@ public function getSingleResult($hydrationMode = null) { $result = $this->execute(null, $hydrationMode); - if ($this->_hydrationMode !== self::HYDRATE_SINGLE_SCALAR && ! $result) { + if ($this->hydrationMode !== self::HYDRATE_SINGLE_SCALAR && ! $result) { throw new NoResultException; } @@ -838,7 +822,7 @@ public function getSingleScalarResult() */ public function setHint($name, $value) { - $this->_hints[$name] = $value; + $this->hints[$name] = $value; return $this; } @@ -852,7 +836,7 @@ public function setHint($name, $value) */ public function getHint($name) { - return isset($this->_hints[$name]) ? $this->_hints[$name] : false; + return isset($this->hints[$name]) ? $this->hints[$name] : false; } /** @@ -864,7 +848,7 @@ public function getHint($name) */ public function hasHint($name) { - return isset($this->_hints[$name]); + return isset($this->hints[$name]); } /** @@ -874,7 +858,7 @@ public function hasHint($name) */ public function getHints() { - return $this->_hints; + return $this->hints; } /** @@ -897,9 +881,9 @@ public function iterate($parameters = null, $hydrationMode = null) } $rsm = $this->getResultSetMapping(); - $stmt = $this->_doExecute(); + $stmt = $this->doExecute(); - return $this->_em->newHydrator($this->_hydrationMode)->iterate($stmt, $rsm, $this->_hints); + return $this->em->newHydrator($this->hydrationMode)->iterate($stmt, $rsm, $this->hints); } /** @@ -939,7 +923,7 @@ private function executeIgnoreQueryCache($parameters = null, $hydrationMode = nu $setCacheEntry = function() {}; - if ($this->_hydrationCacheProfile !== null) { + if ($this->hydrationCacheProfile !== null) { list($cacheKey, $realCacheKey) = $this->getHydrationCacheId(); $queryCacheProfile = $this->getHydrationCacheProfile(); @@ -961,7 +945,7 @@ private function executeIgnoreQueryCache($parameters = null, $hydrationMode = nu }; } - $stmt = $this->_doExecute(); + $stmt = $this->doExecute(); if (is_numeric($stmt)) { $setCacheEntry($stmt); @@ -970,7 +954,7 @@ private function executeIgnoreQueryCache($parameters = null, $hydrationMode = nu } $rsm = $this->getResultSetMapping(); - $data = $this->_em->newHydrator($this->_hydrationMode)->hydrateAll($stmt, $rsm, $this->_hints); + $data = $this->em->newHydrator($this->hydrationMode)->hydrateAll($stmt, $rsm, $this->hints); $setCacheEntry($data); @@ -988,7 +972,7 @@ private function executeIgnoreQueryCache($parameters = null, $hydrationMode = nu private function executeUsingQueryCache($parameters = null, $hydrationMode = null) { $rsm = $this->getResultSetMapping(); - $queryCache = $this->_em->getCache()->getQueryCache($this->cacheRegion); + $queryCache = $this->em->getCache()->getQueryCache($this->cacheRegion); $queryKey = new QueryCacheKey( $this->getHash(), $this->lifetime, @@ -996,7 +980,7 @@ private function executeUsingQueryCache($parameters = null, $hydrationMode = nul $this->getTimestampKey() ); - $result = $queryCache->get($queryKey, $rsm, $this->_hints); + $result = $queryCache->get($queryKey, $rsm, $this->hints); if ($result !== null) { if ($this->cacheLogger) { @@ -1007,7 +991,7 @@ private function executeUsingQueryCache($parameters = null, $hydrationMode = nul } $result = $this->executeIgnoreQueryCache($parameters, $hydrationMode); - $cached = $queryCache->put($queryKey, $rsm, $result, $this->_hints); + $cached = $queryCache->put($queryKey, $rsm, $result, $this->hints); if ($this->cacheLogger) { $this->cacheLogger->queryCacheMiss($queryCache->getRegion()->getName(), $queryKey); @@ -1025,15 +1009,15 @@ private function executeUsingQueryCache($parameters = null, $hydrationMode = nul */ private function getTimestampKey() { - $entityName = reset($this->_resultSetMapping->aliasMap); + $entityName = reset($this->resultSetMapping->aliasMap); if (empty($entityName)) { return null; } - $metadata = $this->_em->getClassMetadata($entityName); + $metadata = $this->em->getClassMetadata($entityName); - return new Cache\TimestampCacheKey($metadata->rootEntityName); + return new Cache\TimestampCacheKey($metadata->getRootClassName()); } /** @@ -1072,9 +1056,9 @@ protected function getHydrationCacheId() */ public function setResultCacheId($id) { - $this->_queryCacheProfile = $this->_queryCacheProfile - ? $this->_queryCacheProfile->setCacheKey($id) - : new QueryCacheProfile(0, $id, $this->_em->getConfiguration()->getResultCacheImpl()); + $this->queryCacheProfile = $this->queryCacheProfile + ? $this->queryCacheProfile->setCacheKey($id) + : new QueryCacheProfile(0, $id, $this->em->getConfiguration()->getResultCacheImpl()); return $this; } @@ -1088,7 +1072,7 @@ public function setResultCacheId($id) */ public function getResultCacheId() { - return $this->_queryCacheProfile ? $this->_queryCacheProfile->getCacheKey() : null; + return $this->queryCacheProfile ? $this->queryCacheProfile->getCacheKey() : null; } /** @@ -1096,7 +1080,7 @@ public function getResultCacheId() * * @return \Doctrine\DBAL\Driver\Statement The executed database statement that holds the results. */ - abstract protected function _doExecute(); + abstract protected function doExecute(); /** * Cleanup Query resource when clone is called. @@ -1106,9 +1090,7 @@ abstract protected function _doExecute(); public function __clone() { $this->parameters = new ArrayCollection(); - - $this->_hints = []; - $this->_hints = $this->_em->getConfiguration()->getDefaultQueryHints(); + $this->hints = $this->em->getConfiguration()->getDefaultQueryHints(); } /** diff --git a/lib/Doctrine/ORM/Annotation/Annotation.php b/lib/Doctrine/ORM/Annotation/Annotation.php new file mode 100644 index 00000000000..8d4304f51fc --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/Annotation.php @@ -0,0 +1,9 @@ + + * @since 2.3 + * + * @Annotation + * @Target("ANNOTATION") + */ +final class AssociationOverride implements Annotation +{ + /** + * The name of the relationship property whose mapping is being overridden. + * + * @var string + */ + public $name; + + /** + * The join column that is being mapped to the persistent attribute. + * + * @var array<\Doctrine\ORM\Annotation\JoinColumn> + */ + public $joinColumns; + + /** + * The join table that maps the relationship. + * + * @var \Doctrine\ORM\Annotation\JoinTable + */ + public $joinTable; + + /** + * The name of the association-field on the inverse-side. + * + * @var string + */ + public $inversedBy; + + /** + * The fetching strategy to use for the association. + * + * @var string + * + * @Enum({"LAZY", "EAGER", "EXTRA_LAZY"}) + */ + public $fetch; +} diff --git a/lib/Doctrine/ORM/Annotation/AssociationOverrides.php b/lib/Doctrine/ORM/Annotation/AssociationOverrides.php new file mode 100644 index 00000000000..0588441c83e --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/AssociationOverrides.php @@ -0,0 +1,24 @@ + + * @since 2.3 + * + * @Annotation + * @Target("CLASS") + */ +final class AssociationOverrides implements Annotation +{ + /** + * Mapping overrides of relationship properties. + * + * @var array<\Doctrine\ORM\Annotation\AssociationOverride> + */ + public $value; +} diff --git a/lib/Doctrine/ORM/Annotation/AttributeOverride.php b/lib/Doctrine/ORM/Annotation/AttributeOverride.php new file mode 100644 index 00000000000..1403eb6ae93 --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/AttributeOverride.php @@ -0,0 +1,31 @@ + + * @since 2.3 + * + * @Annotation + * @Target("ANNOTATION") + */ +final class AttributeOverride implements Annotation +{ + /** + * The name of the property whose mapping is being overridden. + * + * @var string + */ + public $name; + + /** + * The column definition. + * + * @var \Doctrine\ORM\Annotation\Column + */ + public $column; +} diff --git a/lib/Doctrine/ORM/Annotation/AttributeOverrides.php b/lib/Doctrine/ORM/Annotation/AttributeOverrides.php new file mode 100644 index 00000000000..4df92b00c7a --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/AttributeOverrides.php @@ -0,0 +1,24 @@ + + * @since 2.3 + * + * @Annotation + * @Target("CLASS") + */ +final class AttributeOverrides implements Annotation +{ + /** + * One or more field or property mapping overrides. + * + * @var array<\Doctrine\ORM\Annotation\AttributeOverride> + */ + public $value; +} diff --git a/lib/Doctrine/ORM/Annotation/Cache.php b/lib/Doctrine/ORM/Annotation/Cache.php new file mode 100644 index 00000000000..a958a5a3104 --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/Cache.php @@ -0,0 +1,29 @@ + + * @since 2.5 + * + * @Annotation + * @Target({"CLASS","PROPERTY"}) + */ +final class Cache implements Annotation +{ + /** + * @Enum({"READ_ONLY", "NONSTRICT_READ_WRITE", "READ_WRITE"}) + * + * @var string The concurrency strategy. + */ + public $usage = 'READ_ONLY'; + + /** + * @var string Cache region name. + */ + public $region; +} diff --git a/lib/Doctrine/ORM/Annotation/ChangeTrackingPolicy.php b/lib/Doctrine/ORM/Annotation/ChangeTrackingPolicy.php new file mode 100644 index 00000000000..4898b1a2b06 --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/ChangeTrackingPolicy.php @@ -0,0 +1,21 @@ + + * @since 2.3 + * + * @Annotation + * @Target("ANNOTATION") + */ +final class ColumnResult implements Annotation +{ + /** + * The name of a column in the SELECT clause of a SQL query. + * + * @var string + */ + public $name; +} diff --git a/lib/Doctrine/ORM/Annotation/CustomIdGenerator.php b/lib/Doctrine/ORM/Annotation/CustomIdGenerator.php new file mode 100644 index 00000000000..771a27264a1 --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/CustomIdGenerator.php @@ -0,0 +1,22 @@ + + */ + public $value; +} diff --git a/lib/Doctrine/ORM/Annotation/DoctrineAnnotations.php b/lib/Doctrine/ORM/Annotation/DoctrineAnnotations.php new file mode 100644 index 00000000000..81ab6f711a9 --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/DoctrineAnnotations.php @@ -0,0 +1,54 @@ + + * @since 2.4 + * + * @Annotation + * @Target("CLASS") + */ +final class EntityListeners implements Annotation +{ + /** + * Specifies the names of the entity listeners. + * + * @var array + */ + public $value = []; +} diff --git a/lib/Doctrine/ORM/Annotation/EntityResult.php b/lib/Doctrine/ORM/Annotation/EntityResult.php new file mode 100644 index 00000000000..b3124cced14 --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/EntityResult.php @@ -0,0 +1,41 @@ + + * @since 2.3 + * + * @Annotation + * @Target("ANNOTATION") + */ +final class EntityResult implements Annotation +{ + /** + * The class of the result. + * + * @var string + */ + public $entityClass; + + /** + * Maps the columns specified in the SELECT list of the query to the properties or fields of the entity class. + * + * @var array<\Doctrine\ORM\Annotation\FieldResult> + */ + public $fields = []; + + /** + * Specifies the column name of the column in the SELECT list that is used to determine the type of the entity instance. + * + * @var string + */ + public $discriminatorColumn; +} diff --git a/lib/Doctrine/ORM/Annotation/FieldResult.php b/lib/Doctrine/ORM/Annotation/FieldResult.php new file mode 100644 index 00000000000..9a6f9094ea3 --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/FieldResult.php @@ -0,0 +1,31 @@ + + * @since 2.3 + * + * @Annotation + * @Target("ANNOTATION") + */ +final class FieldResult implements Annotation +{ + /** + * Name of the column in the SELECT clause. + * + * @var string + */ + public $name; + + /** + * Name of the persistent field or property of the class. + * + * @var string + */ + public $column; +} diff --git a/lib/Doctrine/ORM/Annotation/GeneratedValue.php b/lib/Doctrine/ORM/Annotation/GeneratedValue.php new file mode 100644 index 00000000000..fa92a50db58 --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/GeneratedValue.php @@ -0,0 +1,21 @@ + + */ + public $columns; + + /** + * @var bool + */ + public $unique = false; + + /** + * @var array + */ + public $flags = []; + + /** + * @var array + */ + public $options = []; +} diff --git a/lib/Doctrine/ORM/Annotation/InheritanceType.php b/lib/Doctrine/ORM/Annotation/InheritanceType.php new file mode 100644 index 00000000000..fe51a7f1394 --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/InheritanceType.php @@ -0,0 +1,21 @@ + + */ + public $value; +} diff --git a/lib/Doctrine/ORM/Annotation/JoinTable.php b/lib/Doctrine/ORM/Annotation/JoinTable.php new file mode 100644 index 00000000000..184c2179663 --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/JoinTable.php @@ -0,0 +1,32 @@ + + */ + public $joinColumns = []; + + /** + * @var array<\Doctrine\ORM\Annotation\JoinColumn> + */ + public $inverseJoinColumns = []; +} diff --git a/lib/Doctrine/ORM/Annotation/ManyToMany.php b/lib/Doctrine/ORM/Annotation/ManyToMany.php new file mode 100644 index 00000000000..aeeec2d36ff --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/ManyToMany.php @@ -0,0 +1,51 @@ + + */ + public $cascade = []; + + /** + * The fetching strategy to use for the association. + * + * @var string + * + * @Enum({"LAZY", "EAGER", "EXTRA_LAZY"}) + */ + public $fetch = 'LAZY'; + + /** + * @var boolean + */ + public $orphanRemoval = false; + + /** + * @var string + */ + public $indexBy; +} diff --git a/lib/Doctrine/ORM/Annotation/ManyToOne.php b/lib/Doctrine/ORM/Annotation/ManyToOne.php new file mode 100644 index 00000000000..b8f67dc135d --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/ManyToOne.php @@ -0,0 +1,36 @@ + + */ + public $cascade = []; + + /** + * The fetching strategy to use for the association. + * + * @var string + * + * @Enum({"LAZY", "EAGER", "EXTRA_LAZY"}) + */ + public $fetch = 'LAZY'; + + /** + * @var string + */ + public $inversedBy; +} diff --git a/lib/Doctrine/ORM/Annotation/MappedSuperclass.php b/lib/Doctrine/ORM/Annotation/MappedSuperclass.php new file mode 100644 index 00000000000..fe819533c50 --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/MappedSuperclass.php @@ -0,0 +1,17 @@ + + * @since 2.3 + * + * @Annotation + * @Target("CLASS") + */ +final class NamedNativeQueries implements Annotation +{ + /** + * One or more NamedNativeQuery annotations. + * + * @var array<\Doctrine\ORM\Annotation\NamedNativeQuery> + */ + public $value = []; +} diff --git a/lib/Doctrine/ORM/Annotation/NamedNativeQuery.php b/lib/Doctrine/ORM/Annotation/NamedNativeQuery.php new file mode 100644 index 00000000000..f23aea15942 --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/NamedNativeQuery.php @@ -0,0 +1,46 @@ + + * @since 2.3 + * + * @Annotation + * @Target("ANNOTATION") + */ +final class NamedNativeQuery implements Annotation +{ + /** + * The name used to refer to the query with the EntityManager methods that create query objects. + * + * @var string + */ + public $name; + + /** + * The SQL query string. + * + * @var string + */ + public $query; + + /** + * The class of the result. + * + * @var string + */ + public $resultClass; + + /** + * The name of a SqlResultSetMapping, as defined in metadata. + * + * @var string + */ + public $resultSetMapping; +} diff --git a/lib/Doctrine/ORM/Annotation/NamedQueries.php b/lib/Doctrine/ORM/Annotation/NamedQueries.php new file mode 100644 index 00000000000..7ba723eb3fc --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/NamedQueries.php @@ -0,0 +1,17 @@ + + */ + public $value; +} diff --git a/lib/Doctrine/ORM/Annotation/NamedQuery.php b/lib/Doctrine/ORM/Annotation/NamedQuery.php new file mode 100644 index 00000000000..998ae2b8bf7 --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/NamedQuery.php @@ -0,0 +1,22 @@ + + */ + public $cascade = []; + + /** + * The fetching strategy to use for the association. + * + * @var string + * + * @Enum({"LAZY", "EAGER", "EXTRA_LAZY"}) + */ + public $fetch = 'LAZY'; + + /** + * @var boolean + */ + public $orphanRemoval = false; + + /** + * @var string + */ + public $indexBy; +} diff --git a/lib/Doctrine/ORM/Annotation/OneToOne.php b/lib/Doctrine/ORM/Annotation/OneToOne.php new file mode 100644 index 00000000000..266657bdddd --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/OneToOne.php @@ -0,0 +1,46 @@ + + */ + public $cascade = []; + + /** + * The fetching strategy to use for the association. + * + * @var string + * + * @Enum({"LAZY", "EAGER", "EXTRA_LAZY"}) + */ + public $fetch = 'LAZY'; + + /** + * @var boolean + */ + public $orphanRemoval = false; +} diff --git a/lib/Doctrine/ORM/Annotation/OrderBy.php b/lib/Doctrine/ORM/Annotation/OrderBy.php new file mode 100644 index 00000000000..f38d2cedacc --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/OrderBy.php @@ -0,0 +1,17 @@ + + */ + public $value; +} diff --git a/lib/Doctrine/ORM/Annotation/PostLoad.php b/lib/Doctrine/ORM/Annotation/PostLoad.php new file mode 100644 index 00000000000..4e5a98ef82d --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/PostLoad.php @@ -0,0 +1,13 @@ + + * @since 2.3 + * + * @Annotation + * @Target("ANNOTATION") + */ +final class SqlResultSetMapping implements Annotation +{ + /** + * The name given to the result set mapping, and used to refer to it in the methods of the Query API. + * + * @var string + */ + public $name; + + /** + * Specifies the result set mapping to entities. + * + * @var array<\Doctrine\ORM\Annotation\EntityResult> + */ + public $entities = []; + + /** + * Specifies the result set mapping to scalar values. + * + * @var array<\Doctrine\ORM\Annotation\ColumnResult> + */ + public $columns = []; +} diff --git a/lib/Doctrine/ORM/Annotation/SqlResultSetMappings.php b/lib/Doctrine/ORM/Annotation/SqlResultSetMappings.php new file mode 100644 index 00000000000..fe2ad974392 --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/SqlResultSetMappings.php @@ -0,0 +1,25 @@ + + * @since 2.3 + * + * @Annotation + * @Target("CLASS") + */ +final class SqlResultSetMappings implements Annotation +{ + /** + * One or more SqlResultSetMapping annotations. + * + * @var array<\Doctrine\ORM\Annotation\SqlResultSetMapping> + */ + public $value = []; +} diff --git a/lib/Doctrine/ORM/Annotation/Table.php b/lib/Doctrine/ORM/Annotation/Table.php new file mode 100644 index 00000000000..41f6c6e6760 --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/Table.php @@ -0,0 +1,37 @@ + + */ + public $indexes = []; + + /** + * @var array<\Doctrine\ORM\Annotation\UniqueConstraint> + */ + public $uniqueConstraints = []; + + /** + * @var array + */ + public $options = []; +} diff --git a/lib/Doctrine/ORM/Annotation/UniqueConstraint.php b/lib/Doctrine/ORM/Annotation/UniqueConstraint.php new file mode 100644 index 00000000000..042e173a312 --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/UniqueConstraint.php @@ -0,0 +1,32 @@ + + */ + public $columns; + + /** + * @var array + */ + public $flags = []; + + /** + * @var array + */ + public $options = []; +} diff --git a/lib/Doctrine/ORM/Annotation/Version.php b/lib/Doctrine/ORM/Annotation/Version.php new file mode 100644 index 00000000000..cd88d8fba52 --- /dev/null +++ b/lib/Doctrine/ORM/Annotation/Version.php @@ -0,0 +1,13 @@ +. - */ + +declare(strict_types=1); namespace Doctrine\ORM; diff --git a/lib/Doctrine/ORM/Cache/AssociationCacheEntry.php b/lib/Doctrine/ORM/Cache/AssociationCacheEntry.php index dae5e602da7..70bd84c4af5 100644 --- a/lib/Doctrine/ORM/Cache/AssociationCacheEntry.php +++ b/lib/Doctrine/ORM/Cache/AssociationCacheEntry.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/CacheConfiguration.php b/lib/Doctrine/ORM/Cache/CacheConfiguration.php index eb3ec428df3..b4854f326bc 100644 --- a/lib/Doctrine/ORM/Cache/CacheConfiguration.php +++ b/lib/Doctrine/ORM/Cache/CacheConfiguration.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/CacheEntry.php b/lib/Doctrine/ORM/Cache/CacheEntry.php index c34b0ff9b00..1def4d390ca 100644 --- a/lib/Doctrine/ORM/Cache/CacheEntry.php +++ b/lib/Doctrine/ORM/Cache/CacheEntry.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/CacheException.php b/lib/Doctrine/ORM/Cache/CacheException.php index 315a8aac2ef..df698670633 100644 --- a/lib/Doctrine/ORM/Cache/CacheException.php +++ b/lib/Doctrine/ORM/Cache/CacheException.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/CacheFactory.php b/lib/Doctrine/ORM/Cache/CacheFactory.php index b915100623a..34de88422ff 100644 --- a/lib/Doctrine/ORM/Cache/CacheFactory.php +++ b/lib/Doctrine/ORM/Cache/CacheFactory.php @@ -1,25 +1,12 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\CacheMetadata; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Persisters\Collection\CollectionPersister; @@ -42,18 +29,26 @@ interface CacheFactory * * @return \Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister */ - public function buildCachedEntityPersister(EntityManagerInterface $em, EntityPersister $persister, ClassMetadata $metadata); + public function buildCachedEntityPersister( + EntityManagerInterface $em, + EntityPersister $persister, + ClassMetadata $metadata + ); /** * Build a collection persister for the given relation mapping. * - * @param \Doctrine\ORM\EntityManagerInterface $em The entity manager. - * @param \Doctrine\ORM\Persisters\Collection\CollectionPersister $persister The collection persister that will be cached. - * @param array $mapping The association mapping. + * @param \Doctrine\ORM\EntityManagerInterface $em The entity manager. + * @param \Doctrine\ORM\Persisters\Collection\CollectionPersister $persister The collection persister that will be cached. + * @param \Doctrine\ORM\Mapping\AssociationMetadata $association The association mapping. * * @return \Doctrine\ORM\Cache\Persister\Collection\CachedCollectionPersister */ - public function buildCachedCollectionPersister(EntityManagerInterface $em, CollectionPersister $persister, array $mapping); + public function buildCachedCollectionPersister( + EntityManagerInterface $em, + CollectionPersister $persister, + AssociationMetadata $association + ); /** * Build a query cache based on the given region name @@ -78,21 +73,21 @@ public function buildEntityHydrator(EntityManagerInterface $em, ClassMetadata $m /** * Build a collection hydrator * - * @param \Doctrine\ORM\EntityManagerInterface $em The Entity manager. - * @param array $mapping The association mapping. + * @param \Doctrine\ORM\EntityManagerInterface $em The Entity manager. + * @param \Doctrine\ORM\Mapping\AssociationMetadata $association The association mapping. * * @return \Doctrine\ORM\Cache\CollectionHydrator The built collection hydrator. */ - public function buildCollectionHydrator(EntityManagerInterface $em, array $mapping); + public function buildCollectionHydrator(EntityManagerInterface $em, AssociationMetadata $association); /** * Build a cache region * - * @param array $cache The cache configuration. + * @param \Doctrine\ORM\Mapping\CacheMetadata $cache The cache configuration. * * @return \Doctrine\ORM\Cache\Region The cache region. */ - public function getRegion(array $cache); + public function getRegion(CacheMetadata $cache); /** * Build timestamp cache region diff --git a/lib/Doctrine/ORM/Cache/CacheKey.php b/lib/Doctrine/ORM/Cache/CacheKey.php index 1641c9900dc..845e2204173 100644 --- a/lib/Doctrine/ORM/Cache/CacheKey.php +++ b/lib/Doctrine/ORM/Cache/CacheKey.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/CollectionCacheEntry.php b/lib/Doctrine/ORM/Cache/CollectionCacheEntry.php index b3a1defe14c..1c15e0d12dd 100644 --- a/lib/Doctrine/ORM/Cache/CollectionCacheEntry.php +++ b/lib/Doctrine/ORM/Cache/CollectionCacheEntry.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/CollectionCacheKey.php b/lib/Doctrine/ORM/Cache/CollectionCacheKey.php index 6b631455000..dd4a1575f1c 100644 --- a/lib/Doctrine/ORM/Cache/CollectionCacheKey.php +++ b/lib/Doctrine/ORM/Cache/CollectionCacheKey.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/CollectionHydrator.php b/lib/Doctrine/ORM/Cache/CollectionHydrator.php index 04cdde16268..81925597170 100644 --- a/lib/Doctrine/ORM/Cache/CollectionHydrator.php +++ b/lib/Doctrine/ORM/Cache/CollectionHydrator.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/ConcurrentRegion.php b/lib/Doctrine/ORM/Cache/ConcurrentRegion.php index 12da6d615ad..55257b1ae24 100644 --- a/lib/Doctrine/ORM/Cache/ConcurrentRegion.php +++ b/lib/Doctrine/ORM/Cache/ConcurrentRegion.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/DefaultCache.php b/lib/Doctrine/ORM/Cache/DefaultCache.php index 80fbd814388..0386651947b 100644 --- a/lib/Doctrine/ORM/Cache/DefaultCache.php +++ b/lib/Doctrine/ORM/Cache/DefaultCache.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; @@ -25,6 +10,7 @@ use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Cache\Persister\CachedPersister; +use Doctrine\ORM\Mapping\ToManyAssociationMetadata; use Doctrine\ORM\ORMInvalidArgumentException; /** @@ -78,7 +64,7 @@ public function __construct(EntityManagerInterface $em) public function getEntityCacheRegion($className) { $metadata = $this->em->getClassMetadata($className); - $persister = $this->uow->getEntityPersister($metadata->rootEntityName); + $persister = $this->uow->getEntityPersister($metadata->getRootClassName()); if ( ! ($persister instanceof CachedPersister)) { return null; @@ -93,7 +79,7 @@ public function getEntityCacheRegion($className) public function getCollectionCacheRegion($className, $association) { $metadata = $this->em->getClassMetadata($className); - $persister = $this->uow->getCollectionPersister($metadata->getAssociationMapping($association)); + $persister = $this->uow->getCollectionPersister($metadata->getProperty($association)); if ( ! ($persister instanceof CachedPersister)) { return null; @@ -108,7 +94,7 @@ public function getCollectionCacheRegion($className, $association) public function containsEntity($className, $identifier) { $metadata = $this->em->getClassMetadata($className); - $persister = $this->uow->getEntityPersister($metadata->rootEntityName); + $persister = $this->uow->getEntityPersister($metadata->getRootClassName()); if ( ! ($persister instanceof CachedPersister)) { return false; @@ -123,7 +109,7 @@ public function containsEntity($className, $identifier) public function evictEntity($className, $identifier) { $metadata = $this->em->getClassMetadata($className); - $persister = $this->uow->getEntityPersister($metadata->rootEntityName); + $persister = $this->uow->getEntityPersister($metadata->getRootClassName()); if ( ! ($persister instanceof CachedPersister)) { return; @@ -138,7 +124,7 @@ public function evictEntity($className, $identifier) public function evictEntityRegion($className) { $metadata = $this->em->getClassMetadata($className); - $persister = $this->uow->getEntityPersister($metadata->rootEntityName); + $persister = $this->uow->getEntityPersister($metadata->getRootClassName()); if ( ! ($persister instanceof CachedPersister)) { return; @@ -155,7 +141,7 @@ public function evictEntityRegions() $metadatas = $this->em->getMetadataFactory()->getAllMetadata(); foreach ($metadatas as $metadata) { - $persister = $this->uow->getEntityPersister($metadata->rootEntityName); + $persister = $this->uow->getEntityPersister($metadata->getRootClassName()); if ( ! ($persister instanceof CachedPersister)) { continue; @@ -171,7 +157,7 @@ public function evictEntityRegions() public function containsCollection($className, $association, $ownerIdentifier) { $metadata = $this->em->getClassMetadata($className); - $persister = $this->uow->getCollectionPersister($metadata->getAssociationMapping($association)); + $persister = $this->uow->getCollectionPersister($metadata->getProperty($association)); if ( ! ($persister instanceof CachedPersister)) { return false; @@ -186,7 +172,7 @@ public function containsCollection($className, $association, $ownerIdentifier) public function evictCollection($className, $association, $ownerIdentifier) { $metadata = $this->em->getClassMetadata($className); - $persister = $this->uow->getCollectionPersister($metadata->getAssociationMapping($association)); + $persister = $this->uow->getCollectionPersister($metadata->getProperty($association)); if ( ! ($persister instanceof CachedPersister)) { return; @@ -201,7 +187,7 @@ public function evictCollection($className, $association, $ownerIdentifier) public function evictCollectionRegion($className, $association) { $metadata = $this->em->getClassMetadata($className); - $persister = $this->uow->getCollectionPersister($metadata->getAssociationMapping($association)); + $persister = $this->uow->getCollectionPersister($metadata->getProperty($association)); if ( ! ($persister instanceof CachedPersister)) { return; @@ -218,10 +204,8 @@ public function evictCollectionRegions() $metadatas = $this->em->getMetadataFactory()->getAllMetadata(); foreach ($metadatas as $metadata) { - - foreach ($metadata->associationMappings as $association) { - - if ( ! $association['type'] & ClassMetadata::TO_MANY) { + foreach ($metadata->getDeclaredPropertiesIterator() as $association) { + if (! $association instanceof ToManyAssociationMetadata) { continue; } @@ -301,7 +285,7 @@ private function buildEntityCacheKey(ClassMetadata $metadata, $identifier) $identifier = $this->toIdentifierArray($metadata, $identifier); } - return new EntityCacheKey($metadata->rootEntityName, $identifier); + return new EntityCacheKey($metadata->getRootClassName(), $identifier); } /** @@ -317,7 +301,7 @@ private function buildCollectionCacheKey(ClassMetadata $metadata, $association, $ownerIdentifier = $this->toIdentifierArray($metadata, $ownerIdentifier); } - return new CollectionCacheKey($metadata->rootEntityName, $association, $ownerIdentifier); + return new CollectionCacheKey($metadata->getRootClassName(), $association, $ownerIdentifier); } /** diff --git a/lib/Doctrine/ORM/Cache/DefaultCacheFactory.php b/lib/Doctrine/ORM/Cache/DefaultCacheFactory.php index 77a773a53c8..a36c69d58ed 100644 --- a/lib/Doctrine/ORM/Cache/DefaultCacheFactory.php +++ b/lib/Doctrine/ORM/Cache/DefaultCacheFactory.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; @@ -35,6 +20,9 @@ use Doctrine\ORM\Cache\Region\FileLockRegion; use Doctrine\ORM\Cache\Region\UpdateTimestampCache; use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\CacheMetadata; +use Doctrine\ORM\Mapping\CacheUsage; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Persisters\Collection\CollectionPersister; use Doctrine\ORM\Persisters\Entity\EntityPersister; @@ -76,8 +64,8 @@ class DefaultCacheFactory implements CacheFactory */ public function __construct(RegionsConfiguration $cacheConfig, CacheAdapter $cache) { - $this->cache = $cache; $this->regionsConfig = $cacheConfig; + $this->cache = $cache; } /** @@ -115,47 +103,59 @@ public function setTimestampRegion(TimestampRegion $region) /** * {@inheritdoc} */ - public function buildCachedEntityPersister(EntityManagerInterface $em, EntityPersister $persister, ClassMetadata $metadata) + public function buildCachedEntityPersister( + EntityManagerInterface $em, + EntityPersister $persister, + ClassMetadata $metadata + ) { - $region = $this->getRegion($metadata->cache); - $usage = $metadata->cache['usage']; + $cache = $metadata->getCache(); + $region = $this->getRegion($cache); + $usage = $cache->getUsage(); - if ($usage === ClassMetadata::CACHE_USAGE_READ_ONLY) { - return new ReadOnlyCachedEntityPersister($persister, $region, $em, $metadata); - } + switch ($usage) { + case CacheUsage::READ_ONLY: + return new ReadOnlyCachedEntityPersister($persister, $region, $em, $metadata); - if ($usage === ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE) { - return new NonStrictReadWriteCachedEntityPersister($persister, $region, $em, $metadata); - } + case CacheUsage::READ_WRITE: + return new ReadWriteCachedEntityPersister($persister, $region, $em, $metadata); - if ($usage === ClassMetadata::CACHE_USAGE_READ_WRITE) { - return new ReadWriteCachedEntityPersister($persister, $region, $em, $metadata); - } + case CacheUsage::NONSTRICT_READ_WRITE: + return new NonStrictReadWriteCachedEntityPersister($persister, $region, $em, $metadata); - throw new \InvalidArgumentException(sprintf("Unrecognized access strategy type [%s]", $usage)); + default: + throw new \InvalidArgumentException(sprintf("Unrecognized access strategy type [%s]", $usage)); + } } /** * {@inheritdoc} */ - public function buildCachedCollectionPersister(EntityManagerInterface $em, CollectionPersister $persister, array $mapping) + public function buildCachedCollectionPersister( + EntityManagerInterface $em, + CollectionPersister $persister, + AssociationMetadata $association + ) { - $usage = $mapping['cache']['usage']; - $region = $this->getRegion($mapping['cache']); + $cache = $association->getCache(); + $region = $this->getRegion($cache); + $usage = $cache->getUsage(); - if ($usage === ClassMetadata::CACHE_USAGE_READ_ONLY) { - return new ReadOnlyCachedCollectionPersister($persister, $region, $em, $mapping); - } + switch ($usage) { + case CacheUsage::READ_ONLY: + return new ReadOnlyCachedCollectionPersister($persister, $region, $em, $association); - if ($usage === ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE) { - return new NonStrictReadWriteCachedCollectionPersister($persister, $region, $em, $mapping); - } + case CacheUsage::READ_WRITE: + return new ReadWriteCachedCollectionPersister($persister, $region, $em, $association); - if ($usage === ClassMetadata::CACHE_USAGE_READ_WRITE) { - return new ReadWriteCachedCollectionPersister($persister, $region, $em, $mapping); - } + case CacheUsage::NONSTRICT_READ_WRITE: + return new NonStrictReadWriteCachedCollectionPersister($persister, $region, $em, $association); - throw new \InvalidArgumentException(sprintf("Unrecognized access strategy type [%s]", $usage)); + default: + throw new \InvalidArgumentException( + sprintf("Unrecognized access strategy type [%s]", $usage) + ); + } } /** @@ -163,21 +163,18 @@ public function buildCachedCollectionPersister(EntityManagerInterface $em, Colle */ public function buildQueryCache(EntityManagerInterface $em, $regionName = null) { - return new DefaultQueryCache( - $em, - $this->getRegion( - [ - 'region' => $regionName ?: Cache::DEFAULT_QUERY_REGION_NAME, - 'usage' => ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE - ] - ) + $cacheMetadata = new CacheMetadata( + CacheUsage::NONSTRICT_READ_WRITE, + $regionName ?: Cache::DEFAULT_QUERY_REGION_NAME ); + + return new DefaultQueryCache($em, $this->getRegion($cacheMetadata)); } /** * {@inheritdoc} */ - public function buildCollectionHydrator(EntityManagerInterface $em, array $mapping) + public function buildCollectionHydrator(EntityManagerInterface $em, AssociationMetadata $association) { return new DefaultCollectionHydrator($em); } @@ -193,22 +190,22 @@ public function buildEntityHydrator(EntityManagerInterface $em, ClassMetadata $m /** * {@inheritdoc} */ - public function getRegion(array $cache) + public function getRegion(CacheMetadata $cache) { - if (isset($this->regions[$cache['region']])) { - return $this->regions[$cache['region']]; - } + $regionName = $cache->getRegion(); - $name = $cache['region']; - $cacheAdapter = $this->createRegionCache($name); - $lifetime = $this->regionsConfig->getLifetime($cache['region']); - - $region = ($cacheAdapter instanceof MultiGetCache) - ? new DefaultMultiGetRegion($name, $cacheAdapter, $lifetime) - : new DefaultRegion($name, $cacheAdapter, $lifetime); + if (isset($this->regions[$regionName])) { + return $this->regions[$regionName]; + } - if ($cache['usage'] === ClassMetadata::CACHE_USAGE_READ_WRITE) { + $cacheAdapter = $this->createRegionCache($regionName); + $lifetime = $this->regionsConfig->getLifetime($regionName); + $region = ($cacheAdapter instanceof MultiGetCache) + ? new DefaultMultiGetRegion($regionName, $cacheAdapter, $lifetime) + : new DefaultRegion($regionName, $cacheAdapter, $lifetime) + ; + if ($cache->getUsage() === CacheUsage::READ_WRITE) { if ( ! $this->fileLockRegionDirectory) { throw new \LogicException( 'If you want to use a "READ_WRITE" cache an implementation of "Doctrine\ORM\Cache\ConcurrentRegion" is required, ' . @@ -216,11 +213,11 @@ public function getRegion(array $cache) ); } - $directory = $this->fileLockRegionDirectory . DIRECTORY_SEPARATOR . $cache['region']; - $region = new FileLockRegion($region, $directory, $this->regionsConfig->getLockLifetime($cache['region'])); + $directory = $this->fileLockRegionDirectory . DIRECTORY_SEPARATOR . $regionName; + $region = new FileLockRegion($region, $directory, $this->regionsConfig->getLockLifetime($regionName)); } - return $this->regions[$cache['region']] = $region; + return $this->regions[$regionName] = $region; } /** diff --git a/lib/Doctrine/ORM/Cache/DefaultCollectionHydrator.php b/lib/Doctrine/ORM/Cache/DefaultCollectionHydrator.php index f12ccf50a78..bae94a6fb01 100644 --- a/lib/Doctrine/ORM/Cache/DefaultCollectionHydrator.php +++ b/lib/Doctrine/ORM/Cache/DefaultCollectionHydrator.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; @@ -65,7 +50,7 @@ public function buildCacheEntry(ClassMetadata $metadata, CollectionCacheKey $key $data = []; foreach ($collection as $index => $entity) { - $data[$index] = new EntityCacheKey($metadata->rootEntityName, $this->uow->getEntityIdentifier($entity)); + $data[$index] = new EntityCacheKey($metadata->getRootClassName(), $this->uow->getEntityIdentifier($entity)); } return new CollectionCacheEntry($data); @@ -74,11 +59,16 @@ public function buildCacheEntry(ClassMetadata $metadata, CollectionCacheKey $key /** * {@inheritdoc} */ - public function loadCacheEntry(ClassMetadata $metadata, CollectionCacheKey $key, CollectionCacheEntry $entry, PersistentCollection $collection) + public function loadCacheEntry( + ClassMetadata $metadata, + CollectionCacheKey $key, + CollectionCacheEntry $entry, + PersistentCollection $collection + ) { - $assoc = $metadata->associationMappings[$key->association]; /* @var $targetPersister \Doctrine\ORM\Cache\Persister\CachedPersister */ - $targetPersister = $this->uow->getEntityPersister($assoc['targetEntity']); + $association = $metadata->getProperty($key->association); + $targetPersister = $this->uow->getEntityPersister($association->getTargetEntity()); $targetRegion = $targetPersister->getCacheRegion(); $list = []; @@ -90,12 +80,14 @@ public function loadCacheEntry(ClassMetadata $metadata, CollectionCacheKey $key, /* @var $entityEntries \Doctrine\ORM\Cache\EntityCacheEntry[] */ foreach ($entityEntries as $index => $entityEntry) { - $list[$index] = $this->uow->createEntity($entityEntry->class, $entityEntry->resolveAssociationEntries($this->em), self::$hints); - } + $data = $entityEntry->resolveAssociationEntries($this->em); + + $entity = $this->uow->createEntity($entityEntry->class, $data, self::$hints); - array_walk($list, function($entity, $index) use ($collection) { $collection->hydrateSet($index, $entity); - }); + + $list[$index] = $entity; + } $this->uow->hydrationComplete(); diff --git a/lib/Doctrine/ORM/Cache/DefaultEntityHydrator.php b/lib/Doctrine/ORM/Cache/DefaultEntityHydrator.php index 7d72464dc01..84108ecd942 100644 --- a/lib/Doctrine/ORM/Cache/DefaultEntityHydrator.php +++ b/lib/Doctrine/ORM/Cache/DefaultEntityHydrator.php @@ -1,31 +1,19 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; use Doctrine\Common\Util\ClassUtils; +use Doctrine\ORM\Mapping\FetchMode; +use Doctrine\ORM\Mapping\FieldMetadata; +use Doctrine\ORM\Mapping\OneToOneAssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; use Doctrine\ORM\Query; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\EntityManagerInterface; -use Doctrine\ORM\Utility\IdentifierFlattener; /** * Default hydrator cache for entities @@ -36,7 +24,7 @@ class DefaultEntityHydrator implements EntityHydrator { /** - * @var \Doctrine\ORM\EntityManager + * @var \Doctrine\ORM\EntityManagerInterface */ private $em; @@ -45,13 +33,6 @@ class DefaultEntityHydrator implements EntityHydrator */ private $uow; - /** - * The IdentifierFlattener used for manipulating identifiers - * - * @var \Doctrine\ORM\Utility\IdentifierFlattener - */ - private $identifierFlattener; - /** * @var array */ @@ -62,9 +43,8 @@ class DefaultEntityHydrator implements EntityHydrator */ public function __construct(EntityManagerInterface $em) { - $this->em = $em; - $this->uow = $em->getUnitOfWork(); - $this->identifierFlattener = new IdentifierFlattener($em->getUnitOfWork(), $em->getMetadataFactory()); + $this->em = $em; + $this->uow = $em->getUnitOfWork(); } /** @@ -72,46 +52,68 @@ public function __construct(EntityManagerInterface $em) */ public function buildCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, $entity) { + $identifierFlattener = $this->em->getIdentifierFlattener(); + $persister = $this->uow->getEntityPersister($metadata->getClassName()); + $data = $this->uow->getOriginalEntityData($entity); - $data = array_merge($data, $metadata->getIdentifierValues($entity)); // why update has no identifier values ? + $data = array_merge($data, $persister->getIdentifier($entity)); // why update has no identifier values ? - foreach ($metadata->associationMappings as $name => $assoc) { - if ( ! isset($data[$name])) { + foreach ($metadata->getDeclaredPropertiesIterator() as $name => $association) { + if (! isset($data[$name]) || $association instanceof FieldMetadata) { continue; } - if ( ! ($assoc['type'] & ClassMetadata::TO_ONE)) { + if (! $association instanceof ToOneAssociationMetadata) { unset($data[$name]); continue; } - if ( ! isset($assoc['cache'])) { - $targetClassMetadata = $this->em->getClassMetadata($assoc['targetEntity']); - $owningAssociation = ( ! $assoc['isOwningSide']) - ? $targetClassMetadata->associationMappings[$assoc['mappedBy']] - : $assoc; - $associationIds = $this->identifierFlattener->flattenIdentifier( + $targetEntity = $association->getTargetEntity(); + $targetClassMetadata = $this->em->getClassMetadata($targetEntity); + $targetPersister = $this->uow->getEntityPersister($targetEntity); + + if (! $association->getCache()) { + $owningAssociation = ! $association->isOwningSide() + ? $targetClassMetadata->getProperty($association->getMappedBy()) + : $association; + $associationIds = $identifierFlattener->flattenIdentifier( $targetClassMetadata, - $targetClassMetadata->getIdentifierValues($data[$name]) + $targetPersister->getIdentifier($data[$name]) ); unset($data[$name]); foreach ($associationIds as $fieldName => $fieldValue) { - if (isset($targetClassMetadata->fieldMappings[$fieldName])) { - $fieldMapping = $targetClassMetadata->fieldMappings[$fieldName]; + // $fieldName = "name" + // $fieldColumnName = "custom_name" + $property = $targetClassMetadata->getProperty($fieldName); - $data[$owningAssociation['targetToSourceKeyColumns'][$fieldMapping['columnName']]] = $fieldValue; + if ($property instanceof FieldMetadata) { + foreach ($owningAssociation->getJoinColumns() as $joinColumn) { + // $joinColumnName = "custom_name" + // $joinColumnReferencedColumnName = "other_side_of_assoc_column_name" + if ($joinColumn->getReferencedColumnName() !== $property->getColumnName()) { + continue; + } + + $data[$joinColumn->getColumnName()] = $fieldValue; + + break; + } continue; } - $targetAssoc = $targetClassMetadata->associationMappings[$fieldName]; + $targetAssociation = $targetClassMetadata->getProperty($fieldName); + + foreach ($association->getJoinColumns() as $assocJoinColumn) { + foreach ($targetAssociation->getJoinColumns() as $targetAssocJoinColumn) { + if ($assocJoinColumn->getReferencedColumnName() !== $targetAssocJoinColumn->getColumnName()) { + continue; + } - foreach($assoc['targetToSourceKeyColumns'] as $referencedColumn => $localColumn) { - if (isset($targetAssoc['sourceToTargetKeyColumns'][$referencedColumn])) { - $data[$localColumn] = $fieldValue; + $data[$assocJoinColumn->getColumnName()] = $fieldValue; } } } @@ -119,7 +121,7 @@ public function buildCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, $e continue; } - if ( ! isset($assoc['id'])) { + if (! $association->isPrimaryKey()) { $targetClass = ClassUtils::getClass($data[$name]); $targetId = $this->uow->getEntityIdentifier($data[$name]); $data[$name] = new AssociationCacheEntry($targetClass, $targetId); @@ -128,29 +130,26 @@ public function buildCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, $e } // handle association identifier - $targetId = is_object($data[$name]) && $this->uow->isInIdentityMap($data[$name]) - ? $this->uow->getEntityIdentifier($data[$name]) - : $data[$name]; - - // @TODO - fix it ! - // handle UnitOfWork#createEntity hash generation - if ( ! is_array($targetId)) { - $data[reset($assoc['joinColumnFieldNames'])] = $targetId; - - $targetEntity = $this->em->getClassMetadata($assoc['targetEntity']); - $targetId = [$targetEntity->identifier[0] => $targetId]; - } + $targetId = $this->em->getIdentifierFlattener()->flattenIdentifier( + $targetClassMetadata, + $targetPersister->getIdentifier($data[$name]) + ); - $data[$name] = new AssociationCacheEntry($assoc['targetEntity'], $targetId); + $data[$name] = new AssociationCacheEntry($targetEntity, $targetId); } - return new EntityCacheEntry($metadata->name, $data); + return new EntityCacheEntry($metadata->getClassName(), $data); } /** * {@inheritdoc} */ - public function loadCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, EntityCacheEntry $entry, $entity = null) + public function loadCacheEntry( + ClassMetadata $metadata, + EntityCacheKey $key, + EntityCacheEntry $entry, + $entity = null + ) { $data = $entry->data; $hints = self::$hints; @@ -160,24 +159,28 @@ public function loadCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, Ent $hints[Query::HINT_REFRESH_ENTITY] = $entity; } - foreach ($metadata->associationMappings as $name => $assoc) { - if ( ! isset($assoc['cache']) || ! isset($data[$name])) { + foreach ($metadata->getDeclaredPropertiesIterator() as $name => $association) { + if ($association instanceof FieldMetadata || ! isset($data[$name]) || ! $association->getCache()) { continue; } $assocClass = $data[$name]->class; $assocId = $data[$name]->identifier; - $isEagerLoad = ($assoc['fetch'] === ClassMetadata::FETCH_EAGER || ($assoc['type'] === ClassMetadata::ONE_TO_ONE && ! $assoc['isOwningSide'])); + $isEagerLoad = ( + $association->getFetchMode() === FetchMode::EAGER || + ($association instanceof OneToOneAssociationMetadata && ! $association->isOwningSide()) + ); - if ( ! $isEagerLoad) { + if (! $isEagerLoad) { $data[$name] = $this->em->getReference($assocClass, $assocId); continue; } - $assocMetadata = $this->em->getClassMetadata($assoc['targetEntity']); - $assocKey = new EntityCacheKey($assocMetadata->rootEntityName, $assocId); - $assocPersister = $this->uow->getEntityPersister($assoc['targetEntity']); + $targetEntity = $association->getTargetEntity(); + $assocMetadata = $this->em->getClassMetadata($targetEntity); + $assocKey = new EntityCacheKey($assocMetadata->getRootClassName(), $assocId); + $assocPersister = $this->uow->getEntityPersister($targetEntity); $assocRegion = $assocPersister->getCacheRegion(); $assocEntry = $assocRegion->get($assocKey); @@ -185,7 +188,11 @@ public function loadCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, Ent return null; } - $data[$name] = $this->uow->createEntity($assocEntry->class, $assocEntry->resolveAssociationEntries($this->em), $hints); + $data[$name] = $this->uow->createEntity( + $assocEntry->class, + $assocEntry->resolveAssociationEntries($this->em), + $hints + ); } if ($entity !== null) { diff --git a/lib/Doctrine/ORM/Cache/DefaultQueryCache.php b/lib/Doctrine/ORM/Cache/DefaultQueryCache.php index 3ac20654780..0bc4bbffb0b 100644 --- a/lib/Doctrine/ORM/Cache/DefaultQueryCache.php +++ b/lib/Doctrine/ORM/Cache/DefaultQueryCache.php @@ -1,28 +1,15 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Cache\Persister\CachedPersister; use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; use Doctrine\ORM\Query\ResultSetMapping; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\PersistentCollection; @@ -114,7 +101,7 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = [] $cm = $this->em->getClassMetadata($entityName); $generateKeys = function (array $entry) use ($cm): EntityCacheKey { - return new EntityCacheKey($cm->rootEntityName, $entry['identifier']); + return new EntityCacheKey($cm->getRootClassName(), $entry['identifier']); }; $cacheKeys = new CollectionCacheEntry(array_map($generateKeys, $entry->result)); @@ -122,7 +109,7 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = [] // @TODO - move to cache hydration component foreach ($entry->result as $index => $entry) { - $entityEntry = is_array($entries) && array_key_exists($index, $entries) ? $entries[$index] : null; + $entityEntry = is_array($entries) ? ($entries[$index] ?? null) : null; if ($entityEntry === null) { if ($this->cacheLogger !== null) { @@ -137,7 +124,11 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = [] } if ( ! $hasRelation) { - $result[$index] = $this->uow->createEntity($entityEntry->class, $entityEntry->resolveAssociationEntries($this->em), self::$hints); + $result[$index] = $this->uow->createEntity( + $entityEntry->class, + $entityEntry->resolveAssociationEntries($this->em), + self::$hints + ); continue; } @@ -149,10 +140,11 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = [] $assocRegion = $assocPersister->getCacheRegion(); $assocMetadata = $this->em->getClassMetadata($assoc['targetEntity']); - if ($assoc['type'] & ClassMetadata::TO_ONE) { - - if (($assocEntry = $assocRegion->get($assocKey = new EntityCacheKey($assocMetadata->rootEntityName, $assoc['identifier']))) === null) { + // *-to-one association + if (isset($assoc['identifier'])) { + $assocKey = new EntityCacheKey($assocMetadata->getRootClassName(), $assoc['identifier']); + if (($assocEntry = $assocRegion->get($assocKey)) === null) { if ($this->cacheLogger !== null) { $this->cacheLogger->entityCacheMiss($assocRegion->getName(), $assocKey); } @@ -162,7 +154,11 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = [] return null; } - $data[$name] = $this->uow->createEntity($assocEntry->class, $assocEntry->resolveAssociationEntries($this->em), self::$hints); + $data[$name] = $this->uow->createEntity( + $assocEntry->class, + $assocEntry->resolveAssociationEntries($this->em), + self::$hints + ); if ($this->cacheLogger !== null) { $this->cacheLogger->entityCacheHit($assocRegion->getName(), $assocKey); @@ -176,15 +172,17 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = [] } $generateKeys = function ($id) use ($assocMetadata): EntityCacheKey { - return new EntityCacheKey($assocMetadata->rootEntityName, $id); + return new EntityCacheKey($assocMetadata->getRootClassName(), $id); }; - $collection = new PersistentCollection($this->em, $assocMetadata, new ArrayCollection()); $assocKeys = new CollectionCacheEntry(array_map($generateKeys, $assoc['list'])); $assocEntries = $assocRegion->getMultiple($assocKeys); + // *-to-many association + $collection = []; + foreach ($assoc['list'] as $assocIndex => $assocId) { - $assocEntry = is_array($assocEntries) && array_key_exists($assocIndex, $assocEntries) ? $assocEntries[$assocIndex] : null; + $assocEntry = is_array($assocEntries) ? ($assocEntries[$assocIndex] ?? null) : null; if ($assocEntry === null) { if ($this->cacheLogger !== null) { @@ -196,9 +194,11 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = [] return null; } - $element = $this->uow->createEntity($assocEntry->class, $assocEntry->resolveAssociationEntries($this->em), self::$hints); - - $collection->hydrateSet($assocIndex, $element); + $collection[$assocIndex] = $this->uow->createEntity( + $assocEntry->class, + $assocEntry->resolveAssociationEntries($this->em), + self::$hints + ); if ($this->cacheLogger !== null) { $this->cacheLogger->entityCacheHit($assocRegion->getName(), $assocKeys->identifiers[$assocIndex]); @@ -206,8 +206,6 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = [] } $data[$name] = $collection; - - $collection->setInitialized(true); } $result[$index] = $this->uow->createEntity($entityEntry->class, $data, self::$hints); @@ -277,7 +275,7 @@ public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $h $parentAlias = $rsm->parentAliasMap[$alias]; $parentClass = $rsm->aliasMap[$parentAlias]; $metadata = $this->em->getClassMetadata($parentClass); - $assoc = $metadata->associationMappings[$name]; + $association = $metadata->getProperty($name); $assocValue = $this->getAssociationValue($rsm, $alias, $entity); if ($assocValue === null) { @@ -287,7 +285,7 @@ public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $h // root entity association if ($rootAlias === $parentAlias) { // Cancel put result if association put fail - if ( ($assocInfo = $this->storeAssociationCache($key, $assoc, $assocValue)) === null) { + if (($assocInfo = $this->storeAssociationCache($key, $association, $assocValue)) === null) { return false; } @@ -299,7 +297,7 @@ public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $h // store single nested association if ( ! is_array($assocValue)) { // Cancel put result if association put fail - if ($this->storeAssociationCache($key, $assoc, $assocValue) === null) { + if ($this->storeAssociationCache($key, $association, $assocValue) === null) { return false; } @@ -309,7 +307,7 @@ public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $h // store array of nested association foreach ($assocValue as $aVal) { // Cancel put result if association put fail - if ($this->storeAssociationCache($key, $assoc, $aVal) === null) { + if ($this->storeAssociationCache($key, $association, $aVal) === null) { return false; } } @@ -321,33 +319,32 @@ public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $h /** * @param \Doctrine\ORM\Cache\QueryCacheKey $key - * @param array $assoc + * @param AssociationMetadata $assoc * @param mixed $assocValue * * @return array|null */ - private function storeAssociationCache(QueryCacheKey $key, array $assoc, $assocValue) + private function storeAssociationCache(QueryCacheKey $key, AssociationMetadata $association, $assocValue) { - $assocPersister = $this->uow->getEntityPersister($assoc['targetEntity']); + $assocPersister = $this->uow->getEntityPersister($association->getTargetEntity()); $assocMetadata = $assocPersister->getClassMetadata(); $assocRegion = $assocPersister->getCacheRegion(); // Handle *-to-one associations - if ($assoc['type'] & ClassMetadata::TO_ONE) { + if ($association instanceof ToOneAssociationMetadata) { $assocIdentifier = $this->uow->getEntityIdentifier($assocValue); - $entityKey = new EntityCacheKey($assocMetadata->rootEntityName, $assocIdentifier); + $entityKey = new EntityCacheKey($assocMetadata->getRootClassName(), $assocIdentifier); - if ( ! $assocValue instanceof Proxy && ($key->cacheMode & Cache::MODE_REFRESH) || ! $assocRegion->contains($entityKey)) { + if ((! $assocValue instanceof Proxy && ($key->cacheMode & Cache::MODE_REFRESH)) || ! $assocRegion->contains($entityKey)) { // Entity put fail - if ( ! $assocPersister->storeEntityCache($assocValue, $entityKey)) { + if (! $assocPersister->storeEntityCache($assocValue, $entityKey)) { return null; } } return [ - 'targetEntity' => $assocMetadata->rootEntityName, + 'targetEntity' => $assocMetadata->getRootClassName(), 'identifier' => $assocIdentifier, - 'type' => $assoc['type'] ]; } @@ -356,7 +353,7 @@ private function storeAssociationCache(QueryCacheKey $key, array $assoc, $assocV foreach ($assocValue as $assocItemIndex => $assocItem) { $assocIdentifier = $this->uow->getEntityIdentifier($assocItem); - $entityKey = new EntityCacheKey($assocMetadata->rootEntityName, $assocIdentifier); + $entityKey = new EntityCacheKey($assocMetadata->getRootClassName(), $assocIdentifier); if (($key->cacheMode & Cache::MODE_REFRESH) || ! $assocRegion->contains($entityKey)) { // Entity put fail @@ -369,9 +366,8 @@ private function storeAssociationCache(QueryCacheKey $key, array $assoc, $assocV } return [ - 'targetEntity' => $assocMetadata->rootEntityName, - 'type' => $assoc['type'], - 'list' => $list, + 'targetEntity' => $assocMetadata->getRootClassName(), + 'list' => $list, ]; } @@ -412,10 +408,10 @@ private function getAssociationValue(ResultSetMapping $rsm, $assocAlias, $entity */ private function getAssociationPathValue($value, array $path) { - $mapping = array_shift($path); - $metadata = $this->em->getClassMetadata($mapping['class']); - $assoc = $metadata->associationMappings[$mapping['field']]; - $value = $metadata->getFieldValue($value, $mapping['field']); + $mapping = array_shift($path); + $metadata = $this->em->getClassMetadata($mapping['class']); + $association = $metadata->getProperty($mapping['field']); + $value = $association->getValue($value); if ($value === null) { return null; @@ -426,7 +422,7 @@ private function getAssociationPathValue($value, array $path) } // Handle *-to-one associations - if ($assoc['type'] & ClassMetadata::TO_ONE) { + if ($association instanceof ToOneAssociationMetadata) { return $this->getAssociationPathValue($value, $path); } diff --git a/lib/Doctrine/ORM/Cache/EntityCacheEntry.php b/lib/Doctrine/ORM/Cache/EntityCacheEntry.php index 155618be984..9d07f42988c 100644 --- a/lib/Doctrine/ORM/Cache/EntityCacheEntry.php +++ b/lib/Doctrine/ORM/Cache/EntityCacheEntry.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/EntityCacheKey.php b/lib/Doctrine/ORM/Cache/EntityCacheKey.php index 281e610fa6c..0f0a92c6b8d 100644 --- a/lib/Doctrine/ORM/Cache/EntityCacheKey.php +++ b/lib/Doctrine/ORM/Cache/EntityCacheKey.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/EntityHydrator.php b/lib/Doctrine/ORM/Cache/EntityHydrator.php index 05a394da7b2..463f2999ea4 100644 --- a/lib/Doctrine/ORM/Cache/EntityHydrator.php +++ b/lib/Doctrine/ORM/Cache/EntityHydrator.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/Lock.php b/lib/Doctrine/ORM/Cache/Lock.php index 60f7d6c9d7d..1c98b500b14 100644 --- a/lib/Doctrine/ORM/Cache/Lock.php +++ b/lib/Doctrine/ORM/Cache/Lock.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; @@ -53,6 +38,6 @@ public function __construct($value, $time = null) */ public static function createLockRead() { - return new self(uniqid(time(), true)); + return new self(uniqid((string) time(), true)); } } diff --git a/lib/Doctrine/ORM/Cache/LockException.php b/lib/Doctrine/ORM/Cache/LockException.php index d4c76240aa9..49cc2d252f1 100644 --- a/lib/Doctrine/ORM/Cache/LockException.php +++ b/lib/Doctrine/ORM/Cache/LockException.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/Logging/CacheLogger.php b/lib/Doctrine/ORM/Cache/Logging/CacheLogger.php index bdae4eea8c5..3f9de4b8191 100644 --- a/lib/Doctrine/ORM/Cache/Logging/CacheLogger.php +++ b/lib/Doctrine/ORM/Cache/Logging/CacheLogger.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Logging; diff --git a/lib/Doctrine/ORM/Cache/Logging/CacheLoggerChain.php b/lib/Doctrine/ORM/Cache/Logging/CacheLoggerChain.php index 28a8125c972..938ed3f5861 100644 --- a/lib/Doctrine/ORM/Cache/Logging/CacheLoggerChain.php +++ b/lib/Doctrine/ORM/Cache/Logging/CacheLoggerChain.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Logging; diff --git a/lib/Doctrine/ORM/Cache/Logging/StatisticsCacheLogger.php b/lib/Doctrine/ORM/Cache/Logging/StatisticsCacheLogger.php index 122e3534ac7..93c504c3861 100644 --- a/lib/Doctrine/ORM/Cache/Logging/StatisticsCacheLogger.php +++ b/lib/Doctrine/ORM/Cache/Logging/StatisticsCacheLogger.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Logging; diff --git a/lib/Doctrine/ORM/Cache/MultiGetRegion.php b/lib/Doctrine/ORM/Cache/MultiGetRegion.php index be32b08f0fe..c1b01e9f2ae 100644 --- a/lib/Doctrine/ORM/Cache/MultiGetRegion.php +++ b/lib/Doctrine/ORM/Cache/MultiGetRegion.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/Persister/CachedPersister.php b/lib/Doctrine/ORM/Cache/Persister/CachedPersister.php index 89afd32095f..b76c332c92b 100644 --- a/lib/Doctrine/ORM/Cache/Persister/CachedPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/CachedPersister.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Persister; diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php index 7a10d17d932..0e3ebe72932 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php @@ -1,29 +1,17 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Persister\Collection; +use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\Criteria; use Doctrine\ORM\Cache\EntityCacheKey; use Doctrine\ORM\Cache\CollectionCacheKey; use Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\ToManyAssociationMetadata; use Doctrine\ORM\Persisters\Collection\CollectionPersister; use Doctrine\ORM\PersistentCollection; use Doctrine\ORM\EntityManagerInterface; @@ -63,7 +51,7 @@ abstract class AbstractCollectionPersister implements CachedCollectionPersister protected $targetEntity; /** - * @var array + * @var \Doctrine\ORM\Mapping\AssociationMetadata */ protected $association; @@ -93,12 +81,17 @@ abstract class AbstractCollectionPersister implements CachedCollectionPersister protected $cacheLogger; /** - * @param \Doctrine\ORM\Persisters\Collection\CollectionPersister $persister The collection persister that will be cached. - * @param \Doctrine\ORM\Cache\Region $region The collection region. - * @param \Doctrine\ORM\EntityManagerInterface $em The entity manager. - * @param array $association The association mapping. + * @param CollectionPersister $persister The collection persister that will be cached. + * @param Region $region The collection region. + * @param EntityManagerInterface $em The entity manager. + * @param AssociationMetadata $association The association mapping. */ - public function __construct(CollectionPersister $persister, Region $region, EntityManagerInterface $em, array $association) + public function __construct( + CollectionPersister $persister, + Region $region, + EntityManagerInterface $em, + AssociationMetadata $association + ) { $configuration = $em->getConfiguration(); $cacheConfig = $configuration->getSecondLevelCacheConfiguration(); @@ -112,8 +105,8 @@ public function __construct(CollectionPersister $persister, Region $region, Enti $this->metadataFactory = $em->getMetadataFactory(); $this->cacheLogger = $cacheConfig->getCacheLogger(); $this->hydrator = $cacheFactory->buildCollectionHydrator($em, $association); - $this->sourceEntity = $em->getClassMetadata($association['sourceEntity']); - $this->targetEntity = $em->getClassMetadata($association['targetEntity']); + $this->sourceEntity = $em->getClassMetadata($association->getSourceEntity()); + $this->targetEntity = $em->getClassMetadata($association->getTargetEntity()); } /** @@ -165,15 +158,15 @@ public function loadCollectionCache(PersistentCollection $collection, Collection public function storeCollectionCache(CollectionCacheKey $key, $elements) { /* @var $targetPersister CachedEntityPersister */ - $associationMapping = $this->sourceEntity->associationMappings[$key->association]; - $targetPersister = $this->uow->getEntityPersister($this->targetEntity->rootEntityName); - $targetRegion = $targetPersister->getCacheRegion(); - $targetHydrator = $targetPersister->getEntityHydrator(); + $association = $this->sourceEntity->getProperty($key->association); + $targetPersister = $this->uow->getEntityPersister($this->targetEntity->getRootClassName()); + $targetRegion = $targetPersister->getCacheRegion(); + $targetHydrator = $targetPersister->getEntityHydrator(); // Only preserve ordering if association configured it - if ( ! (isset($associationMapping['indexBy']) && $associationMapping['indexBy'])) { + if (! ($association instanceof ToManyAssociationMetadata && $association->getIndexedBy())) { // Elements may be an array or a Collection - $elements = array_values(is_array($elements) ? $elements : $elements->getValues()); + $elements = \array_values($elements instanceof Collection ? $elements->getValues() : $elements); } $entry = $this->hydrator->buildCacheEntry($this->targetEntity, $key, $elements); @@ -186,7 +179,7 @@ public function storeCollectionCache(CollectionCacheKey $key, $elements) $class = $this->targetEntity; $className = ClassUtils::getClass($elements[$index]); - if ($className !== $this->targetEntity->name) { + if ($className !== $this->targetEntity->getClassName()) { $class = $this->metadataFactory->getMetadataFor($className); } @@ -224,9 +217,10 @@ public function containsKey(PersistentCollection $collection, $key) */ public function count(PersistentCollection $collection) { - $ownerId = $this->uow->getEntityIdentifier($collection->getOwner()); - $key = new CollectionCacheKey($this->sourceEntity->rootEntityName, $this->association['fieldName'], $ownerId); - $entry = $this->region->get($key); + $fieldName = $this->association->getName(); + $ownerId = $this->uow->getEntityIdentifier($collection->getOwner()); + $key = new CollectionCacheKey($this->sourceEntity->getRootClassName(), $fieldName, $ownerId); + $entry = $this->region->get($key); if ($entry !== null) { return count($entry->identifiers); @@ -250,8 +244,8 @@ public function removeElement(PersistentCollection $collection, $element) { if ($persisterResult = $this->persister->removeElement($collection, $element)) { $this->evictCollectionCache($collection); - $this->evictElementCache($this->sourceEntity->rootEntityName, $collection->getOwner()); - $this->evictElementCache($this->targetEntity->rootEntityName, $element); + $this->evictElementCache($this->sourceEntity->getRootClassName(), $collection->getOwner()); + $this->evictElementCache($this->targetEntity->getRootClassName(), $element); } return $persisterResult; @@ -281,8 +275,8 @@ public function loadCriteria(PersistentCollection $collection, Criteria $criteri protected function evictCollectionCache(PersistentCollection $collection) { $key = new CollectionCacheKey( - $this->sourceEntity->rootEntityName, - $this->association['fieldName'], + $this->sourceEntity->getRootClassName(), + $this->association->getName(), $this->uow->getEntityIdentifier($collection->getOwner()) ); diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/CachedCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/CachedCollectionPersister.php index 5722027c49d..3ba3fd122c0 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/CachedCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/CachedCollectionPersister.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Persister\Collection; diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersister.php index fbd46f6eafe..27ef429645e 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersister.php @@ -1,26 +1,12 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Persister\Collection; use Doctrine\ORM\Cache\CollectionCacheKey; +use Doctrine\ORM\Mapping\ToManyAssociationMetadata; use Doctrine\ORM\PersistentCollection; /** @@ -62,8 +48,9 @@ public function afterTransactionRolledBack() */ public function delete(PersistentCollection $collection) { - $ownerId = $this->uow->getEntityIdentifier($collection->getOwner()); - $key = new CollectionCacheKey($this->sourceEntity->rootEntityName, $this->association['fieldName'], $ownerId); + $fieldName = $this->association->getName(); + $ownerId = $this->uow->getEntityIdentifier($collection->getOwner()); + $key = new CollectionCacheKey($this->sourceEntity->getRootClassName(), $fieldName, $ownerId); $this->persister->delete($collection); @@ -82,11 +69,13 @@ public function update(PersistentCollection $collection) return; } - $ownerId = $this->uow->getEntityIdentifier($collection->getOwner()); - $key = new CollectionCacheKey($this->sourceEntity->rootEntityName, $this->association['fieldName'], $ownerId); + $fieldName = $this->association->getName(); + $ownerId = $this->uow->getEntityIdentifier($collection->getOwner()); + $key = new CollectionCacheKey($this->sourceEntity->getRootClassName(), $fieldName, $ownerId); // Invalidate non initialized collections OR ordered collection - if ($isDirty && ! $isInitialized || isset($this->association['orderBy'])) { + if (($isDirty && ! $isInitialized) || + ($this->association instanceof ToManyAssociationMetadata && $this->association->getOrderBy())) { $this->persister->update($collection); $this->queuedCache['delete'][spl_object_hash($collection)] = $key; diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersister.php index dfc816c5ab9..4cfd2ad2410 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersister.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Persister\Collection; @@ -36,7 +21,10 @@ class ReadOnlyCachedCollectionPersister extends NonStrictReadWriteCachedCollecti public function update(PersistentCollection $collection) { if ($collection->isDirty() && $collection->getSnapshot()) { - throw CacheException::updateReadOnlyCollection(ClassUtils::getClass($collection->getOwner()), $this->association['fieldName']); + throw CacheException::updateReadOnlyCollection( + ClassUtils::getClass($collection->getOwner()), + $this->association->getName() + ); } parent::update($collection); diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersister.php index 74bb044451b..393f18ded55 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersister.php @@ -1,44 +1,36 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Persister\Collection; -use Doctrine\ORM\Persisters\Collection\CollectionPersister; -use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Cache\CollectionCacheKey; use Doctrine\ORM\Cache\ConcurrentRegion; +use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\AssociationMetadata; use Doctrine\ORM\PersistentCollection; +use Doctrine\ORM\Persisters\Collection\CollectionPersister; /** * @author Fabio B. Silva + * @author Guilherme Blanco * @since 2.5 */ class ReadWriteCachedCollectionPersister extends AbstractCollectionPersister { /** - * @param \Doctrine\ORM\Persisters\Collection\CollectionPersister $persister The collection persister that will be cached. - * @param \Doctrine\ORM\Cache\ConcurrentRegion $region The collection region. - * @param \Doctrine\ORM\EntityManagerInterface $em The entity manager. - * @param array $association The association mapping. + * @param CollectionPersister $persister The collection persister that will be cached. + * @param ConcurrentRegion $region The collection region. + * @param EntityManagerInterface $em The entity manager. + * @param AssociationMetadata $association The association mapping. */ - public function __construct(CollectionPersister $persister, ConcurrentRegion $region, EntityManagerInterface $em, array $association) + public function __construct( + CollectionPersister $persister, + ConcurrentRegion $region, + EntityManagerInterface $em, + AssociationMetadata $association + ) { parent::__construct($persister, $region, $em, $association); } @@ -89,7 +81,7 @@ public function afterTransactionRolledBack() public function delete(PersistentCollection $collection) { $ownerId = $this->uow->getEntityIdentifier($collection->getOwner()); - $key = new CollectionCacheKey($this->sourceEntity->rootEntityName, $this->association['fieldName'], $ownerId); + $key = new CollectionCacheKey($this->sourceEntity->getRootClassName(), $this->association->getName(), $ownerId); $lock = $this->region->lock($key); $this->persister->delete($collection); @@ -119,7 +111,7 @@ public function update(PersistentCollection $collection) $this->persister->update($collection); $ownerId = $this->uow->getEntityIdentifier($collection->getOwner()); - $key = new CollectionCacheKey($this->sourceEntity->rootEntityName, $this->association['fieldName'], $ownerId); + $key = new CollectionCacheKey($this->sourceEntity->getRootClassName(), $this->association->getName(), $ownerId); $lock = $this->region->lock($key); if ($lock === null) { diff --git a/lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php b/lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php index 53ea6a6fded..eaf0153e881 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Persister\Entity; @@ -27,7 +12,13 @@ use Doctrine\ORM\Cache\TimestampCacheKey; use Doctrine\ORM\Cache\QueryCacheKey; use Doctrine\ORM\Cache\Persister\CachedPersister; +use Doctrine\ORM\Mapping\AssociationMetadata; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\FetchMode; +use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata; +use Doctrine\ORM\Mapping\OneToManyAssociationMetadata; +use Doctrine\ORM\Mapping\OneToOneAssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; use Doctrine\ORM\PersistentCollection; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Persisters\Entity\EntityPersister; @@ -102,7 +93,7 @@ abstract class AbstractEntityPersister implements CachedEntityPersister protected $regionName; /** - * Associations configured as FETCH_EAGER, as well as all inverse one-to-one associations. + * Associations configured as FetchMode::EAGER, as well as all inverse one-to-one associations. * * @var array|null */ @@ -130,31 +121,21 @@ public function __construct(EntityPersister $persister, Region $region, EntityMa $this->cacheLogger = $cacheConfig->getCacheLogger(); $this->timestampRegion = $cacheFactory->getTimestampRegion(); $this->hydrator = $cacheFactory->buildEntityHydrator($em, $class); - $this->timestampKey = new TimestampCacheKey($this->class->rootEntityName); - } - - /** - * {@inheritdoc} - */ - public function addInsert($entity) - { - $this->persister->addInsert($entity); - } - - /** - * {@inheritdoc} - */ - public function getInserts() - { - return $this->persister->getInserts(); + $this->timestampKey = new TimestampCacheKey($this->class->getRootClassName()); } /** * {@inheritdoc} */ - public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit = null, $offset = null, array $orderBy = null) - { - return $this->persister->getSelectSQL($criteria, $assoc, $lockMode, $limit, $offset, $orderBy); + public function getSelectSQL( + $criteria, + AssociationMetadata $association = null, + $lockMode = null, + $limit = null, + $offset = null, + array $orderBy = [] + ) { + return $this->persister->getSelectSQL($criteria, $association, $lockMode, $limit, $offset, $orderBy); } /** @@ -184,9 +165,13 @@ public function getResultSetMapping() /** * {@inheritdoc} */ - public function getSelectConditionStatementSQL($field, $value, $assoc = null, $comparison = null) - { - return $this->persister->getSelectConditionStatementSQL($field, $value, $assoc, $comparison); + public function getSelectConditionStatementSQL( + $field, + $value, + AssociationMetadata $association = null, + $comparison = null + ) { + return $this->persister->getSelectConditionStatementSQL($field, $value, $association, $comparison); } /** @@ -195,7 +180,7 @@ public function getSelectConditionStatementSQL($field, $value, $assoc = null, $c public function exists($entity, Criteria $extraConditions = null) { if (null === $extraConditions) { - $key = new EntityCacheKey($this->class->rootEntityName, $this->class->getIdentifierValues($entity)); + $key = new EntityCacheKey($this->class->getRootClassName(), $this->getIdentifier($entity)); if ($this->region->contains($key)) { return true; @@ -229,7 +214,7 @@ public function storeEntityCache($entity, EntityCacheKey $key) $class = $this->class; $className = ClassUtils::getClass($entity); - if ($className !== $this->class->name) { + if ($className !== $this->class->getClassName()) { $class = $this->metadataFactory->getMetadataFor($className); } @@ -251,12 +236,11 @@ private function storeJoinedAssociations($entity) if ($this->joinedAssociations === null) { $associations = []; - foreach ($this->class->associationMappings as $name => $assoc) { - if (isset($assoc['cache']) && - ($assoc['type'] & ClassMetadata::TO_ONE) && - ($assoc['fetch'] === ClassMetadata::FETCH_EAGER || ! $assoc['isOwningSide'])) { - - $associations[] = $name; + foreach ($this->class->getDeclaredPropertiesIterator() as $association) { + if ($association instanceof ToOneAssociationMetadata && + $association->getCache() && + ($association->getFetchMode() === FetchMode::EAGER || ! $association->isOwningSide())) { + $associations[] = $association->getName(); } } @@ -264,17 +248,18 @@ private function storeJoinedAssociations($entity) } foreach ($this->joinedAssociations as $name) { - $assoc = $this->class->associationMappings[$name]; - $assocEntity = $this->class->getFieldValue($entity, $name); + $association = $this->class->getProperty($name); + $assocEntity = $association->getValue($entity); + $targetEntity = $association->getTargetEntity(); if ($assocEntity === null) { continue; } $assocId = $this->uow->getEntityIdentifier($assocEntity); - $assocMetadata = $this->metadataFactory->getMetadataFor($assoc['targetEntity']); - $assocKey = new EntityCacheKey($assocMetadata->rootEntityName, $assocId); - $assocPersister = $this->uow->getEntityPersister($assoc['targetEntity']); + $assocMetadata = $this->metadataFactory->getMetadataFor($targetEntity); + $assocKey = new EntityCacheKey($assocMetadata->getRootClassName(), $assocId); + $assocPersister = $this->uow->getEntityPersister($targetEntity); $assocPersister->storeEntityCache($assocEntity, $assocKey); } @@ -327,17 +312,25 @@ public function getClassMetadata() /** * {@inheritdoc} */ - public function getManyToManyCollection(array $assoc, $sourceEntity, $offset = null, $limit = null) - { - return $this->persister->getManyToManyCollection($assoc, $sourceEntity, $offset, $limit); + public function getManyToManyCollection( + ManyToManyAssociationMetadata $association, + $sourceEntity, + $offset = null, + $limit = null + ) { + return $this->persister->getManyToManyCollection($association, $sourceEntity, $offset, $limit); } /** * {@inheritdoc} */ - public function getOneToManyCollection(array $assoc, $sourceEntity, $offset = null, $limit = null) - { - return $this->persister->getOneToManyCollection($assoc, $sourceEntity, $offset, $limit); + public function getOneToManyCollection( + OneToManyAssociationMetadata $association, + $sourceEntity, + $offset = null, + $limit = null + ) { + return $this->persister->getOneToManyCollection($association, $sourceEntity, $offset, $limit); } /** @@ -351,20 +344,51 @@ public function getOwningTable($fieldName) /** * {@inheritdoc} */ - public function executeInserts() + public function getIdentifier($entity) : array { - $this->queuedCache['insert'] = $this->persister->getInserts(); + return $this->persister->getIdentifier($entity); + } - return $this->persister->executeInserts(); + /** + * {@inheritdoc} + */ + public function setIdentifier($entity, array $id) : void + { + $this->persister->setIdentifier($entity, $id); + } + + /** + * {@inheritdoc} + */ + public function getColumnValue($entity, string $columnName) + { + return $this->persister->getColumnValue($entity, $columnName); } /** * {@inheritdoc} */ - public function load(array $criteria, $entity = null, $assoc = null, array $hints = [], $lockMode = null, $limit = null, array $orderBy = null) + public function insert($entity) { - if ($entity !== null || $assoc !== null || ! empty($hints) || $lockMode !== null) { - return $this->persister->load($criteria, $entity, $assoc, $hints, $lockMode, $limit, $orderBy); + $this->queuedCache['insert'][] = $entity; + + $this->persister->insert($entity); + } + + /** + * {@inheritdoc} + */ + public function load( + array $criteria, + $entity = null, + AssociationMetadata $association = null, + array $hints = [], + $lockMode = null, + $limit = null, + array $orderBy = null + ) { + if ($entity !== null || $association !== null || ! empty($hints) || $lockMode !== null) { + return $this->persister->load($criteria, $entity, $association, $hints, $lockMode, $limit, $orderBy); } //handle only EntityRepository#findOneBy @@ -383,7 +407,9 @@ public function load(array $criteria, $entity = null, $assoc = null, array $hint return $result[0]; } - if (($result = $this->persister->load($criteria, $entity, $assoc, $hints, $lockMode, $limit, $orderBy)) === null) { + $result = $this->persister->load($criteria, $entity, $association, $hints, $lockMode, $limit, $orderBy); + + if ($result === null) { return null; } @@ -405,7 +431,7 @@ public function load(array $criteria, $entity = null, $assoc = null, array $hint /** * {@inheritdoc} */ - public function loadAll(array $criteria = [], array $orderBy = null, $limit = null, $offset = null) + public function loadAll(array $criteria = [], array $orderBy = [], $limit = null, $offset = null) { $query = $this->persister->getSelectSQL($criteria, null, null, $limit, $offset, $orderBy); $hash = $this->getHash($query, $criteria, null, null, null); @@ -443,12 +469,12 @@ public function loadAll(array $criteria = [], array $orderBy = null, $limit = nu */ public function loadById(array $identifier, $entity = null) { - $cacheKey = new EntityCacheKey($this->class->rootEntityName, $identifier); + $cacheKey = new EntityCacheKey($this->class->getRootClassName(), $identifier); $cacheEntry = $this->region->get($cacheKey); $class = $this->class; if ($cacheEntry !== null) { - if ($cacheEntry->class !== $this->class->name) { + if ($cacheEntry->class !== $this->class->getClassName()) { $class = $this->metadataFactory->getMetadataFor($cacheEntry->class); } @@ -470,7 +496,7 @@ public function loadById(array $identifier, $entity = null) $class = $this->class; $className = ClassUtils::getClass($entity); - if ($className !== $this->class->name) { + if ($className !== $this->class->getClassName()) { $class = $this->metadataFactory->getMetadataFor($className); } @@ -542,19 +568,22 @@ public function loadCriteria(Criteria $criteria) /** * {@inheritdoc} */ - public function loadManyToManyCollection(array $assoc, $sourceEntity, PersistentCollection $coll) - { - $persister = $this->uow->getCollectionPersister($assoc); + public function loadManyToManyCollection( + ManyToManyAssociationMetadata $association, + $sourceEntity, + PersistentCollection $collection + ) { + $persister = $this->uow->getCollectionPersister($association); $hasCache = ($persister instanceof CachedPersister); $key = null; if ( ! $hasCache) { - return $this->persister->loadManyToManyCollection($assoc, $sourceEntity, $coll); + return $this->persister->loadManyToManyCollection($association, $sourceEntity, $collection); } - $ownerId = $this->uow->getEntityIdentifier($coll->getOwner()); - $key = $this->buildCollectionCacheKey($assoc, $ownerId); - $list = $persister->loadCollectionCache($coll, $key); + $ownerId = $this->uow->getEntityIdentifier($collection->getOwner()); + $key = $this->buildCollectionCacheKey($association, $ownerId); + $list = $persister->loadCollectionCache($collection, $key); if ($list !== null) { if ($this->cacheLogger) { @@ -564,7 +593,7 @@ public function loadManyToManyCollection(array $assoc, $sourceEntity, Persistent return $list; } - $list = $this->persister->loadManyToManyCollection($assoc, $sourceEntity, $coll); + $list = $this->persister->loadManyToManyCollection($association, $sourceEntity, $collection); $persister->storeCollectionCache($key, $list); @@ -578,18 +607,21 @@ public function loadManyToManyCollection(array $assoc, $sourceEntity, Persistent /** * {@inheritdoc} */ - public function loadOneToManyCollection(array $assoc, $sourceEntity, PersistentCollection $coll) - { - $persister = $this->uow->getCollectionPersister($assoc); + public function loadOneToManyCollection( + OneToManyAssociationMetadata $association, + $sourceEntity, + PersistentCollection $collection + ) { + $persister = $this->uow->getCollectionPersister($association); $hasCache = ($persister instanceof CachedPersister); if ( ! $hasCache) { - return $this->persister->loadOneToManyCollection($assoc, $sourceEntity, $coll); + return $this->persister->loadOneToManyCollection($association, $sourceEntity, $collection); } - $ownerId = $this->uow->getEntityIdentifier($coll->getOwner()); - $key = $this->buildCollectionCacheKey($assoc, $ownerId); - $list = $persister->loadCollectionCache($coll, $key); + $ownerId = $this->uow->getEntityIdentifier($collection->getOwner()); + $key = $this->buildCollectionCacheKey($association, $ownerId); + $list = $persister->loadCollectionCache($collection, $key); if ($list !== null) { if ($this->cacheLogger) { @@ -599,7 +631,7 @@ public function loadOneToManyCollection(array $assoc, $sourceEntity, PersistentC return $list; } - $list = $this->persister->loadOneToManyCollection($assoc, $sourceEntity, $coll); + $list = $this->persister->loadOneToManyCollection($association, $sourceEntity, $collection); $persister->storeCollectionCache($key, $list); @@ -613,9 +645,9 @@ public function loadOneToManyCollection(array $assoc, $sourceEntity, PersistentC /** * {@inheritdoc} */ - public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifier = []) + public function loadToOneEntity(ToOneAssociationMetadata $association, $sourceEntity, array $identifier = []) { - return $this->persister->loadOneToOneEntity($assoc, $sourceEntity, $identifier); + return $this->persister->loadToOneEntity($association, $sourceEntity, $identifier); } /** @@ -640,11 +672,11 @@ public function refresh(array $id, $entity, $lockMode = null) * * @return CollectionCacheKey */ - protected function buildCollectionCacheKey(array $association, $ownerId) + protected function buildCollectionCacheKey(AssociationMetadata $association, $ownerId) { /** @var ClassMetadata $metadata */ - $metadata = $this->metadataFactory->getMetadataFor($association['sourceEntity']); + $metadata = $this->metadataFactory->getMetadataFor($association->getSourceEntity()); - return new CollectionCacheKey($metadata->rootEntityName, $association['fieldName'], $ownerId); + return new CollectionCacheKey($metadata->getRootClassName(), $association->getName(), $ownerId); } } diff --git a/lib/Doctrine/ORM/Cache/Persister/Entity/CachedEntityPersister.php b/lib/Doctrine/ORM/Cache/Persister/Entity/CachedEntityPersister.php index 89582700c63..8421fb9d36f 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Entity/CachedEntityPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Entity/CachedEntityPersister.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Persister\Entity; diff --git a/lib/Doctrine/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersister.php b/lib/Doctrine/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersister.php index a2844673bee..21244172bbf 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersister.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Persister\Entity; @@ -78,7 +63,7 @@ public function afterTransactionRolledBack() */ public function delete($entity) { - $key = new EntityCacheKey($this->class->rootEntityName, $this->uow->getEntityIdentifier($entity)); + $key = new EntityCacheKey($this->class->getRootClassName(), $this->uow->getEntityIdentifier($entity)); $deleted = $this->persister->delete($entity); if ($deleted) { @@ -103,7 +88,7 @@ public function update($entity) private function updateCache($entity, $isChanged) { $class = $this->metadataFactory->getMetadataFor(get_class($entity)); - $key = new EntityCacheKey($class->rootEntityName, $this->uow->getEntityIdentifier($entity)); + $key = new EntityCacheKey($class->getRootClassName(), $this->uow->getEntityIdentifier($entity)); $entry = $this->hydrator->buildCacheEntry($class, $key, $entity); $cached = $this->region->put($key, $entry); $isChanged = $isChanged ?: $cached; diff --git a/lib/Doctrine/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersister.php b/lib/Doctrine/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersister.php index ce93d7b0e61..0b78977abb5 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersister.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Persister\Entity; diff --git a/lib/Doctrine/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersister.php b/lib/Doctrine/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersister.php index 79a4c8c3dad..93e7ed97733 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersister.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Persister\Entity; @@ -101,7 +86,7 @@ public function afterTransactionRolledBack() */ public function delete($entity) { - $key = new EntityCacheKey($this->class->rootEntityName, $this->uow->getEntityIdentifier($entity)); + $key = new EntityCacheKey($this->class->getRootClassName(), $this->uow->getEntityIdentifier($entity)); $lock = $this->region->lock($key); $deleted = $this->persister->delete($entity); @@ -126,7 +111,7 @@ public function delete($entity) */ public function update($entity) { - $key = new EntityCacheKey($this->class->rootEntityName, $this->uow->getEntityIdentifier($entity)); + $key = new EntityCacheKey($this->class->getRootClassName(), $this->uow->getEntityIdentifier($entity)); $lock = $this->region->lock($key); $this->persister->update($entity); diff --git a/lib/Doctrine/ORM/Cache/QueryCache.php b/lib/Doctrine/ORM/Cache/QueryCache.php index de2496253b3..f8e89f80176 100644 --- a/lib/Doctrine/ORM/Cache/QueryCache.php +++ b/lib/Doctrine/ORM/Cache/QueryCache.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/QueryCacheEntry.php b/lib/Doctrine/ORM/Cache/QueryCacheEntry.php index b6af393fde1..1e9349f0d0e 100644 --- a/lib/Doctrine/ORM/Cache/QueryCacheEntry.php +++ b/lib/Doctrine/ORM/Cache/QueryCacheEntry.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/QueryCacheKey.php b/lib/Doctrine/ORM/Cache/QueryCacheKey.php index 0e072a36fc0..58886cb76df 100644 --- a/lib/Doctrine/ORM/Cache/QueryCacheKey.php +++ b/lib/Doctrine/ORM/Cache/QueryCacheKey.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/QueryCacheValidator.php b/lib/Doctrine/ORM/Cache/QueryCacheValidator.php index 682a41ec4fa..34b84ca9135 100644 --- a/lib/Doctrine/ORM/Cache/QueryCacheValidator.php +++ b/lib/Doctrine/ORM/Cache/QueryCacheValidator.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/Region.php b/lib/Doctrine/ORM/Cache/Region.php index 3bffbbce747..623261a5535 100644 --- a/lib/Doctrine/ORM/Cache/Region.php +++ b/lib/Doctrine/ORM/Cache/Region.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/Region/DefaultMultiGetRegion.php b/lib/Doctrine/ORM/Cache/Region/DefaultMultiGetRegion.php index 2cd94292b49..068b15a441e 100644 --- a/lib/Doctrine/ORM/Cache/Region/DefaultMultiGetRegion.php +++ b/lib/Doctrine/ORM/Cache/Region/DefaultMultiGetRegion.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Region; diff --git a/lib/Doctrine/ORM/Cache/Region/DefaultRegion.php b/lib/Doctrine/ORM/Cache/Region/DefaultRegion.php index be62a6fb957..86f76cd48b4 100644 --- a/lib/Doctrine/ORM/Cache/Region/DefaultRegion.php +++ b/lib/Doctrine/ORM/Cache/Region/DefaultRegion.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Region; diff --git a/lib/Doctrine/ORM/Cache/Region/FileLockRegion.php b/lib/Doctrine/ORM/Cache/Region/FileLockRegion.php index 880d9dabc5e..37310b262af 100644 --- a/lib/Doctrine/ORM/Cache/Region/FileLockRegion.php +++ b/lib/Doctrine/ORM/Cache/Region/FileLockRegion.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Region; diff --git a/lib/Doctrine/ORM/Cache/Region/UpdateTimestampCache.php b/lib/Doctrine/ORM/Cache/Region/UpdateTimestampCache.php index dfdf9062aa3..d8386bde1bb 100644 --- a/lib/Doctrine/ORM/Cache/Region/UpdateTimestampCache.php +++ b/lib/Doctrine/ORM/Cache/Region/UpdateTimestampCache.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache\Region; diff --git a/lib/Doctrine/ORM/Cache/RegionsConfiguration.php b/lib/Doctrine/ORM/Cache/RegionsConfiguration.php index d79c5b1af28..50fc3c1ad85 100644 --- a/lib/Doctrine/ORM/Cache/RegionsConfiguration.php +++ b/lib/Doctrine/ORM/Cache/RegionsConfiguration.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/TimestampCacheEntry.php b/lib/Doctrine/ORM/Cache/TimestampCacheEntry.php index 0b7ce0be6a0..173de47520f 100644 --- a/lib/Doctrine/ORM/Cache/TimestampCacheEntry.php +++ b/lib/Doctrine/ORM/Cache/TimestampCacheEntry.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/TimestampCacheKey.php b/lib/Doctrine/ORM/Cache/TimestampCacheKey.php index dfa72274b23..c2a28d33d2a 100644 --- a/lib/Doctrine/ORM/Cache/TimestampCacheKey.php +++ b/lib/Doctrine/ORM/Cache/TimestampCacheKey.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/TimestampQueryCacheValidator.php b/lib/Doctrine/ORM/Cache/TimestampQueryCacheValidator.php index c6404d3b25d..be01afd6db4 100644 --- a/lib/Doctrine/ORM/Cache/TimestampQueryCacheValidator.php +++ b/lib/Doctrine/ORM/Cache/TimestampQueryCacheValidator.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Cache/TimestampRegion.php b/lib/Doctrine/ORM/Cache/TimestampRegion.php index 9e0c25ca6ab..2cc6b6888df 100644 --- a/lib/Doctrine/ORM/Cache/TimestampRegion.php +++ b/lib/Doctrine/ORM/Cache/TimestampRegion.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Cache; diff --git a/lib/Doctrine/ORM/Configuration.php b/lib/Doctrine/ORM/Configuration.php index 6073fbe008c..bd4a8638977 100644 --- a/lib/Doctrine/ORM/Configuration.php +++ b/lib/Doctrine/ORM/Configuration.php @@ -1,42 +1,24 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; use Doctrine\Common\Annotations\AnnotationReader; use Doctrine\Common\Annotations\AnnotationRegistry; use Doctrine\Common\Annotations\CachedReader; -use Doctrine\Common\Annotations\SimpleAnnotationReader; use Doctrine\Common\Cache\ArrayCache; use Doctrine\Common\Cache\Cache as CacheDriver; -use Doctrine\Common\Persistence\Mapping\Driver\MappingDriver; use Doctrine\Common\Persistence\ObjectRepository; -use Doctrine\Common\Proxy\AbstractProxyFactory; use Doctrine\ORM\Cache\CacheConfiguration; use Doctrine\ORM\Mapping\ClassMetadataFactory; use Doctrine\ORM\Mapping\DefaultEntityListenerResolver; -use Doctrine\ORM\Mapping\DefaultNamingStrategy; -use Doctrine\ORM\Mapping\DefaultQuoteStrategy; use Doctrine\ORM\Mapping\Driver\AnnotationDriver; +use Doctrine\ORM\Mapping\Driver\MappingDriver; use Doctrine\ORM\Mapping\EntityListenerResolver; -use Doctrine\ORM\Mapping\NamingStrategy; -use Doctrine\ORM\Mapping\QuoteStrategy; +use Doctrine\ORM\Mapping\Factory\DefaultNamingStrategy; +use Doctrine\ORM\Mapping\Factory\NamingStrategy; +use Doctrine\ORM\Proxy\Factory\ProxyFactory; use Doctrine\ORM\Repository\DefaultRepositoryFactory; use Doctrine\ORM\Repository\RepositoryFactory; @@ -63,7 +45,7 @@ class Configuration extends \Doctrine\DBAL\Configuration */ public function setProxyDir($dir) { - $this->_attributes['proxyDir'] = $dir; + $this->attributes['proxyDir'] = $dir; } /** @@ -73,34 +55,34 @@ public function setProxyDir($dir) */ public function getProxyDir() { - return isset($this->_attributes['proxyDir']) - ? $this->_attributes['proxyDir'] + return isset($this->attributes['proxyDir']) + ? $this->attributes['proxyDir'] : null; } /** * Gets the strategy for automatically generating proxy classes. * - * @return int Possible values are constants of Doctrine\Common\Proxy\AbstractProxyFactory. + * @return int Possible values are constants of Doctrine\ORM\Proxy\Factory\StaticProxyFactory. */ public function getAutoGenerateProxyClasses() { - return isset($this->_attributes['autoGenerateProxyClasses']) - ? $this->_attributes['autoGenerateProxyClasses'] - : AbstractProxyFactory::AUTOGENERATE_ALWAYS; + return isset($this->attributes['autoGenerateProxyClasses']) + ? $this->attributes['autoGenerateProxyClasses'] + : ProxyFactory::AUTOGENERATE_ALWAYS; } /** * Sets the strategy for automatically generating proxy classes. * - * @param boolean|int $autoGenerate Possible values are constants of Doctrine\Common\Proxy\AbstractProxyFactory. + * @param boolean|int $autoGenerate Possible values are constants of Doctrine\ORM\Proxy\Factory\StaticProxyFactory. * True is converted to AUTOGENERATE_ALWAYS, false to AUTOGENERATE_NEVER. * * @return void */ public function setAutoGenerateProxyClasses($autoGenerate) { - $this->_attributes['autoGenerateProxyClasses'] = (int) $autoGenerate; + $this->attributes['autoGenerateProxyClasses'] = (int) $autoGenerate; } /** @@ -110,8 +92,8 @@ public function setAutoGenerateProxyClasses($autoGenerate) */ public function getProxyNamespace() { - return isset($this->_attributes['proxyNamespace']) - ? $this->_attributes['proxyNamespace'] + return isset($this->attributes['proxyNamespace']) + ? $this->attributes['proxyNamespace'] : null; } @@ -124,7 +106,7 @@ public function getProxyNamespace() */ public function setProxyNamespace($ns) { - $this->_attributes['proxyNamespace'] = $ns; + $this->attributes['proxyNamespace'] = $ns; } /** @@ -139,35 +121,23 @@ public function setProxyNamespace($ns) */ public function setMetadataDriverImpl(MappingDriver $driverImpl) { - $this->_attributes['metadataDriverImpl'] = $driverImpl; + $this->attributes['metadataDriverImpl'] = $driverImpl; } /** - * Adds a new default annotation driver with a correctly configured annotation reader. If $useSimpleAnnotationReader - * is true, the notation `@Entity` will work, otherwise, the notation `@ORM\Entity` will be supported. + * Adds a new default annotation driver with a correctly configured annotation reader. * * @param array $paths - * @param bool $useSimpleAnnotationReader * * @return AnnotationDriver */ - public function newDefaultAnnotationDriver($paths = [], $useSimpleAnnotationReader = true) + public function newDefaultAnnotationDriver($paths = []) { - AnnotationRegistry::registerFile(__DIR__ . '/Mapping/Driver/DoctrineAnnotations.php'); + AnnotationRegistry::registerFile(__DIR__ . '/Annotation/DoctrineAnnotations.php'); - if ($useSimpleAnnotationReader) { - // Register the ORM Annotations in the AnnotationRegistry - $reader = new SimpleAnnotationReader(); - $reader->addNamespace('Doctrine\ORM\Mapping'); - $cachedReader = new CachedReader($reader, new ArrayCache()); + $reader = new CachedReader(new AnnotationReader(), new ArrayCache()); - return new AnnotationDriver($cachedReader, (array) $paths); - } - - return new AnnotationDriver( - new CachedReader(new AnnotationReader(), new ArrayCache()), - (array) $paths - ); + return new AnnotationDriver($reader, (array) $paths); } /** @@ -180,7 +150,7 @@ public function newDefaultAnnotationDriver($paths = [], $useSimpleAnnotationRead */ public function addEntityNamespace($alias, $namespace) { - $this->_attributes['entityNamespaces'][$alias] = $namespace; + $this->attributes['entityNamespaces'][$alias] = $namespace; } /** @@ -194,11 +164,11 @@ public function addEntityNamespace($alias, $namespace) */ public function getEntityNamespace($entityNamespaceAlias) { - if ( ! isset($this->_attributes['entityNamespaces'][$entityNamespaceAlias])) { + if ( ! isset($this->attributes['entityNamespaces'][$entityNamespaceAlias])) { throw ORMException::unknownEntityNamespace($entityNamespaceAlias); } - return trim($this->_attributes['entityNamespaces'][$entityNamespaceAlias], '\\'); + return trim($this->attributes['entityNamespaces'][$entityNamespaceAlias], '\\'); } /** @@ -210,7 +180,7 @@ public function getEntityNamespace($entityNamespaceAlias) */ public function setEntityNamespaces(array $entityNamespaces) { - $this->_attributes['entityNamespaces'] = $entityNamespaces; + $this->attributes['entityNamespaces'] = $entityNamespaces; } /** @@ -220,7 +190,7 @@ public function setEntityNamespaces(array $entityNamespaces) */ public function getEntityNamespaces() { - return $this->_attributes['entityNamespaces']; + return $this->attributes['entityNamespaces']; } /** @@ -232,8 +202,8 @@ public function getEntityNamespaces() */ public function getMetadataDriverImpl() { - return isset($this->_attributes['metadataDriverImpl']) - ? $this->_attributes['metadataDriverImpl'] + return isset($this->attributes['metadataDriverImpl']) + ? $this->attributes['metadataDriverImpl'] : null; } @@ -244,8 +214,8 @@ public function getMetadataDriverImpl() */ public function getQueryCacheImpl() { - return isset($this->_attributes['queryCacheImpl']) - ? $this->_attributes['queryCacheImpl'] + return isset($this->attributes['queryCacheImpl']) + ? $this->attributes['queryCacheImpl'] : null; } @@ -258,7 +228,7 @@ public function getQueryCacheImpl() */ public function setQueryCacheImpl(CacheDriver $cacheImpl) { - $this->_attributes['queryCacheImpl'] = $cacheImpl; + $this->attributes['queryCacheImpl'] = $cacheImpl; } /** @@ -268,8 +238,8 @@ public function setQueryCacheImpl(CacheDriver $cacheImpl) */ public function getHydrationCacheImpl() { - return isset($this->_attributes['hydrationCacheImpl']) - ? $this->_attributes['hydrationCacheImpl'] + return isset($this->attributes['hydrationCacheImpl']) + ? $this->attributes['hydrationCacheImpl'] : null; } @@ -282,7 +252,7 @@ public function getHydrationCacheImpl() */ public function setHydrationCacheImpl(CacheDriver $cacheImpl) { - $this->_attributes['hydrationCacheImpl'] = $cacheImpl; + $this->attributes['hydrationCacheImpl'] = $cacheImpl; } /** @@ -292,8 +262,8 @@ public function setHydrationCacheImpl(CacheDriver $cacheImpl) */ public function getMetadataCacheImpl() { - return isset($this->_attributes['metadataCacheImpl']) - ? $this->_attributes['metadataCacheImpl'] + return isset($this->attributes['metadataCacheImpl']) + ? $this->attributes['metadataCacheImpl'] : null; } @@ -306,7 +276,7 @@ public function getMetadataCacheImpl() */ public function setMetadataCacheImpl(CacheDriver $cacheImpl) { - $this->_attributes['metadataCacheImpl'] = $cacheImpl; + $this->attributes['metadataCacheImpl'] = $cacheImpl; } /** @@ -319,7 +289,7 @@ public function setMetadataCacheImpl(CacheDriver $cacheImpl) */ public function addNamedQuery($name, $dql) { - $this->_attributes['namedQueries'][$name] = $dql; + $this->attributes['namedQueries'][$name] = $dql; } /** @@ -333,11 +303,11 @@ public function addNamedQuery($name, $dql) */ public function getNamedQuery($name) { - if ( ! isset($this->_attributes['namedQueries'][$name])) { + if ( ! isset($this->attributes['namedQueries'][$name])) { throw ORMException::namedQueryNotFound($name); } - return $this->_attributes['namedQueries'][$name]; + return $this->attributes['namedQueries'][$name]; } /** @@ -351,7 +321,7 @@ public function getNamedQuery($name) */ public function addNamedNativeQuery($name, $sql, Query\ResultSetMapping $rsm) { - $this->_attributes['namedNativeQueries'][$name] = [$sql, $rsm]; + $this->attributes['namedNativeQueries'][$name] = [$sql, $rsm]; } /** @@ -366,11 +336,11 @@ public function addNamedNativeQuery($name, $sql, Query\ResultSetMapping $rsm) */ public function getNamedNativeQuery($name) { - if ( ! isset($this->_attributes['namedNativeQueries'][$name])) { + if ( ! isset($this->attributes['namedNativeQueries'][$name])) { throw ORMException::namedNativeQueryNotFound($name); } - return $this->_attributes['namedNativeQueries'][$name]; + return $this->attributes['namedNativeQueries'][$name]; } /** @@ -423,7 +393,7 @@ public function ensureProductionSettings() */ public function addCustomStringFunction($name, $className) { - $this->_attributes['customStringFunctions'][strtolower($name)] = $className; + $this->attributes['customStringFunctions'][strtolower($name)] = $className; } /** @@ -437,8 +407,8 @@ public function getCustomStringFunction($name) { $name = strtolower($name); - return isset($this->_attributes['customStringFunctions'][$name]) - ? $this->_attributes['customStringFunctions'][$name] + return isset($this->attributes['customStringFunctions'][$name]) + ? $this->attributes['customStringFunctions'][$name] : null; } @@ -475,7 +445,7 @@ public function setCustomStringFunctions(array $functions) */ public function addCustomNumericFunction($name, $className) { - $this->_attributes['customNumericFunctions'][strtolower($name)] = $className; + $this->attributes['customNumericFunctions'][strtolower($name)] = $className; } /** @@ -489,8 +459,8 @@ public function getCustomNumericFunction($name) { $name = strtolower($name); - return isset($this->_attributes['customNumericFunctions'][$name]) - ? $this->_attributes['customNumericFunctions'][$name] + return isset($this->attributes['customNumericFunctions'][$name]) + ? $this->attributes['customNumericFunctions'][$name] : null; } @@ -527,7 +497,7 @@ public function setCustomNumericFunctions(array $functions) */ public function addCustomDatetimeFunction($name, $className) { - $this->_attributes['customDatetimeFunctions'][strtolower($name)] = $className; + $this->attributes['customDatetimeFunctions'][strtolower($name)] = $className; } /** @@ -541,8 +511,8 @@ public function getCustomDatetimeFunction($name) { $name = strtolower($name); - return isset($this->_attributes['customDatetimeFunctions'][$name]) - ? $this->_attributes['customDatetimeFunctions'][$name] + return isset($this->attributes['customDatetimeFunctions'][$name]) + ? $this->attributes['customDatetimeFunctions'][$name] : null; } @@ -574,7 +544,7 @@ public function setCustomDatetimeFunctions(array $functions) */ public function setCustomHydrationModes($modes) { - $this->_attributes['customHydrationModes'] = []; + $this->attributes['customHydrationModes'] = []; foreach ($modes as $modeName => $hydrator) { $this->addCustomHydrationMode($modeName, $hydrator); @@ -590,8 +560,8 @@ public function setCustomHydrationModes($modes) */ public function getCustomHydrationMode($modeName) { - return isset($this->_attributes['customHydrationModes'][$modeName]) - ? $this->_attributes['customHydrationModes'][$modeName] + return isset($this->attributes['customHydrationModes'][$modeName]) + ? $this->attributes['customHydrationModes'][$modeName] : null; } @@ -605,7 +575,7 @@ public function getCustomHydrationMode($modeName) */ public function addCustomHydrationMode($modeName, $hydrator) { - $this->_attributes['customHydrationModes'][$modeName] = $hydrator; + $this->attributes['customHydrationModes'][$modeName] = $hydrator; } /** @@ -617,7 +587,7 @@ public function addCustomHydrationMode($modeName, $hydrator) */ public function setClassMetadataFactoryName($cmfName) { - $this->_attributes['classMetadataFactoryName'] = $cmfName; + $this->attributes['classMetadataFactoryName'] = $cmfName; } /** @@ -625,11 +595,11 @@ public function setClassMetadataFactoryName($cmfName) */ public function getClassMetadataFactoryName() { - if ( ! isset($this->_attributes['classMetadataFactoryName'])) { - $this->_attributes['classMetadataFactoryName'] = ClassMetadataFactory::class; + if ( ! isset($this->attributes['classMetadataFactoryName'])) { + $this->attributes['classMetadataFactoryName'] = ClassMetadataFactory::class; } - return $this->_attributes['classMetadataFactoryName']; + return $this->attributes['classMetadataFactoryName']; } /** @@ -640,7 +610,7 @@ public function getClassMetadataFactoryName() */ public function addFilter($name, $className) { - $this->_attributes['filters'][$name] = $className; + $this->attributes['filters'][$name] = $className; } /** @@ -653,8 +623,8 @@ public function addFilter($name, $className) */ public function getFilterClassName($name) { - return isset($this->_attributes['filters'][$name]) - ? $this->_attributes['filters'][$name] + return isset($this->attributes['filters'][$name]) + ? $this->attributes['filters'][$name] : null; } @@ -677,7 +647,7 @@ public function setDefaultRepositoryClassName($className) throw ORMException::invalidEntityRepository($className); } - $this->_attributes['defaultRepositoryClassName'] = $className; + $this->attributes['defaultRepositoryClassName'] = $className; } /** @@ -689,8 +659,8 @@ public function setDefaultRepositoryClassName($className) */ public function getDefaultRepositoryClassName() { - return isset($this->_attributes['defaultRepositoryClassName']) - ? $this->_attributes['defaultRepositoryClassName'] + return isset($this->attributes['defaultRepositoryClassName']) + ? $this->attributes['defaultRepositoryClassName'] : EntityRepository::class; } @@ -705,7 +675,7 @@ public function getDefaultRepositoryClassName() */ public function setNamingStrategy(NamingStrategy $namingStrategy) { - $this->_attributes['namingStrategy'] = $namingStrategy; + $this->attributes['namingStrategy'] = $namingStrategy; } /** @@ -717,41 +687,11 @@ public function setNamingStrategy(NamingStrategy $namingStrategy) */ public function getNamingStrategy() { - if ( ! isset($this->_attributes['namingStrategy'])) { - $this->_attributes['namingStrategy'] = new DefaultNamingStrategy(); - } - - return $this->_attributes['namingStrategy']; - } - - /** - * Sets quote strategy. - * - * @since 2.3 - * - * @param \Doctrine\ORM\Mapping\QuoteStrategy $quoteStrategy - * - * @return void - */ - public function setQuoteStrategy(QuoteStrategy $quoteStrategy) - { - $this->_attributes['quoteStrategy'] = $quoteStrategy; - } - - /** - * Gets quote strategy. - * - * @since 2.3 - * - * @return \Doctrine\ORM\Mapping\QuoteStrategy - */ - public function getQuoteStrategy() - { - if ( ! isset($this->_attributes['quoteStrategy'])) { - $this->_attributes['quoteStrategy'] = new DefaultQuoteStrategy(); + if ( ! isset($this->attributes['namingStrategy'])) { + $this->attributes['namingStrategy'] = new DefaultNamingStrategy(); } - return $this->_attributes['quoteStrategy']; + return $this->attributes['namingStrategy']; } /** @@ -762,7 +702,7 @@ public function getQuoteStrategy() */ public function setEntityListenerResolver(EntityListenerResolver $resolver) { - $this->_attributes['entityListenerResolver'] = $resolver; + $this->attributes['entityListenerResolver'] = $resolver; } /** @@ -773,11 +713,11 @@ public function setEntityListenerResolver(EntityListenerResolver $resolver) */ public function getEntityListenerResolver() { - if ( ! isset($this->_attributes['entityListenerResolver'])) { - $this->_attributes['entityListenerResolver'] = new DefaultEntityListenerResolver(); + if ( ! isset($this->attributes['entityListenerResolver'])) { + $this->attributes['entityListenerResolver'] = new DefaultEntityListenerResolver(); } - return $this->_attributes['entityListenerResolver']; + return $this->attributes['entityListenerResolver']; } /** @@ -788,7 +728,7 @@ public function getEntityListenerResolver() */ public function setRepositoryFactory(RepositoryFactory $repositoryFactory) { - $this->_attributes['repositoryFactory'] = $repositoryFactory; + $this->attributes['repositoryFactory'] = $repositoryFactory; } /** @@ -799,8 +739,8 @@ public function setRepositoryFactory(RepositoryFactory $repositoryFactory) */ public function getRepositoryFactory() { - return isset($this->_attributes['repositoryFactory']) - ? $this->_attributes['repositoryFactory'] + return isset($this->attributes['repositoryFactory']) + ? $this->attributes['repositoryFactory'] : new DefaultRepositoryFactory(); } @@ -811,8 +751,8 @@ public function getRepositoryFactory() */ public function isSecondLevelCacheEnabled() { - return isset($this->_attributes['isSecondLevelCacheEnabled']) - ? $this->_attributes['isSecondLevelCacheEnabled'] + return isset($this->attributes['isSecondLevelCacheEnabled']) + ? $this->attributes['isSecondLevelCacheEnabled'] : false; } @@ -825,7 +765,7 @@ public function isSecondLevelCacheEnabled() */ public function setSecondLevelCacheEnabled($flag = true) { - $this->_attributes['isSecondLevelCacheEnabled'] = (boolean) $flag; + $this->attributes['isSecondLevelCacheEnabled'] = (boolean) $flag; } /** @@ -837,7 +777,7 @@ public function setSecondLevelCacheEnabled($flag = true) */ public function setSecondLevelCacheConfiguration(CacheConfiguration $cacheConfig) { - $this->_attributes['secondLevelCacheConfiguration'] = $cacheConfig; + $this->attributes['secondLevelCacheConfiguration'] = $cacheConfig; } /** @@ -847,12 +787,12 @@ public function setSecondLevelCacheConfiguration(CacheConfiguration $cacheConfig */ public function getSecondLevelCacheConfiguration() { - if ( ! isset($this->_attributes['secondLevelCacheConfiguration']) && $this->isSecondLevelCacheEnabled()) { - $this->_attributes['secondLevelCacheConfiguration'] = new CacheConfiguration(); + if ( ! isset($this->attributes['secondLevelCacheConfiguration']) && $this->isSecondLevelCacheEnabled()) { + $this->attributes['secondLevelCacheConfiguration'] = new CacheConfiguration(); } - return isset($this->_attributes['secondLevelCacheConfiguration']) - ? $this->_attributes['secondLevelCacheConfiguration'] + return isset($this->attributes['secondLevelCacheConfiguration']) + ? $this->attributes['secondLevelCacheConfiguration'] : null; } @@ -865,7 +805,7 @@ public function getSecondLevelCacheConfiguration() */ public function getDefaultQueryHints() { - return isset($this->_attributes['defaultQueryHints']) ? $this->_attributes['defaultQueryHints'] : []; + return isset($this->attributes['defaultQueryHints']) ? $this->attributes['defaultQueryHints'] : []; } /** @@ -877,7 +817,7 @@ public function getDefaultQueryHints() */ public function setDefaultQueryHints(array $defaultQueryHints) { - $this->_attributes['defaultQueryHints'] = $defaultQueryHints; + $this->attributes['defaultQueryHints'] = $defaultQueryHints; } /** @@ -891,8 +831,8 @@ public function setDefaultQueryHints(array $defaultQueryHints) */ public function getDefaultQueryHint($name) { - return isset($this->_attributes['defaultQueryHints'][$name]) - ? $this->_attributes['defaultQueryHints'][$name] + return isset($this->attributes['defaultQueryHints'][$name]) + ? $this->attributes['defaultQueryHints'][$name] : false; } @@ -906,6 +846,6 @@ public function getDefaultQueryHint($name) */ public function setDefaultQueryHint($name, $value) { - $this->_attributes['defaultQueryHints'][$name] = $value; + $this->attributes['defaultQueryHints'][$name] = $value; } } diff --git a/lib/Doctrine/ORM/Configuration/MetadataConfiguration.php b/lib/Doctrine/ORM/Configuration/MetadataConfiguration.php new file mode 100644 index 00000000000..51de6f4d810 --- /dev/null +++ b/lib/Doctrine/ORM/Configuration/MetadataConfiguration.php @@ -0,0 +1,155 @@ + + */ +class MetadataConfiguration +{ + /** + * @var string + */ + private $namespace; + + /** + * @var string + */ + private $directory; + + /** + * @var ClassMetadataResolver + */ + private $resolver; + + /** + * @var MappingDriver + */ + private $mappingDriver; + + /** + * @var NamingStrategy + */ + private $namingStrategy; + + /** + * @var int + */ + private $autoGenerate = AbstractClassMetadataFactory::AUTOGENERATE_ALWAYS; + + /** + * @return string + */ + public function getNamespace() : string + { + return $this->namespace; + } + + /** + * @param string $namespace + */ + public function setNamespace(string $namespace) + { + $this->namespace = ltrim($namespace, '\\'); + } + + /** + * @return string + */ + public function getDirectory() : string + { + return $this->directory; + } + + /** + * @param string $directory + */ + public function setDirectory(string $directory) + { + $this->directory = rtrim($directory, DIRECTORY_SEPARATOR); + } + + /** + * @return ClassMetadataResolver + */ + public function getResolver() : ClassMetadataResolver + { + return $this->resolver; + } + + /** + * @param ClassMetadataResolver $resolver + */ + public function setResolver(ClassMetadataResolver $resolver) + { + $this->resolver = $resolver; + } + + /** + * @return MappingDriver + */ + public function getMappingDriver() : MappingDriver + { + return $this->mappingDriver; + } + + /** + * @param MappingDriver $mappingDriver + */ + public function setMappingDriver(MappingDriver $mappingDriver) + { + $this->mappingDriver = $mappingDriver; + } + + /** + * @return NamingStrategy + */ + public function getNamingStrategy() : NamingStrategy + { + if (! $this->namingStrategy) { + $this->namingStrategy = new DefaultNamingStrategy(); + } + + return $this->namingStrategy; + } + + /** + * @param NamingStrategy $namingStrategy + */ + public function setNamingStrategy(NamingStrategy $namingStrategy) + { + $this->namingStrategy = $namingStrategy; + } + + /** + * @todo guilhermeblanco Get rid of this method and associated constants. Use the generator strategy instead. + * + * @return int + */ + public function getAutoGenerate() : int + { + return $this->autoGenerate; + } + + /** + * @param int $autoGenerate + */ + public function setAutoGenerate(int $autoGenerate) + { + $this->autoGenerate = $autoGenerate; + } +} diff --git a/lib/Doctrine/ORM/Configuration/ProxyConfiguration.php b/lib/Doctrine/ORM/Configuration/ProxyConfiguration.php new file mode 100644 index 00000000000..c2df70830ae --- /dev/null +++ b/lib/Doctrine/ORM/Configuration/ProxyConfiguration.php @@ -0,0 +1,106 @@ + + */ +class ProxyConfiguration +{ + /** + * @var ProxyResolver + */ + private $resolver; + + /** + * @var string + */ + private $namespace; + + /** + * @var string + */ + private $directory; + + /** + * @var int + */ + private $autoGenerate = ProxyFactory::AUTOGENERATE_ALWAYS; + + /** + * @return ProxyResolver + */ + public function getResolver(): ProxyResolver + { + return $this->resolver; + } + + /** + * @param ProxyResolver $resolver + */ + public function setResolver(ProxyResolver $resolver) + { + $this->resolver = $resolver; + } + + /** + * @return string + */ + public function getNamespace() : string + { + return $this->namespace; + } + + /** + * @param string $namespace + */ + public function setNamespace(string $namespace) + { + $this->namespace = $namespace; + } + + /** + * @return string + */ + public function getDirectory() : string + { + return $this->directory; + } + + /** + * @param string $directory + */ + public function setDirectory(string $directory) + { + $this->directory = $directory; + } + + /** + * @todo guilhermeblanco Get rid of this method and associated constants. Use the generator strategy instead. + * + * @return int + */ + public function getAutoGenerate() : int + { + return $this->autoGenerate; + } + + /** + * @param int $autoGenerate + */ + public function setAutoGenerate(int $autoGenerate) + { + $this->autoGenerate = $autoGenerate; + } +} diff --git a/lib/Doctrine/ORM/Decorator/EntityManagerDecorator.php b/lib/Doctrine/ORM/Decorator/EntityManagerDecorator.php index 69cc6f50739..096ae688e7e 100644 --- a/lib/Doctrine/ORM/Decorator/EntityManagerDecorator.php +++ b/lib/Doctrine/ORM/Decorator/EntityManagerDecorator.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Decorator; @@ -60,6 +45,14 @@ public function getExpressionBuilder() return $this->wrapped->getExpressionBuilder(); } + /** + * {@inheritdoc} + */ + public function getIdentifierFlattener() + { + return $this->wrapped->getIdentifierFlattener(); + } + /** * {@inheritdoc} */ @@ -71,7 +64,7 @@ public function beginTransaction() /** * {@inheritdoc} */ - public function transactional($func) + public function transactional(callable $func) { return $this->wrapped->transactional($func); } @@ -183,9 +176,9 @@ public function find($entityName, $id, $lockMode = null, $lockVersion = null) /** * {@inheritdoc} */ - public function flush($entity = null) + public function flush() { - return $this->wrapped->flush($entity); + return $this->wrapped->flush(); } /** diff --git a/lib/Doctrine/ORM/EntityManager.php b/lib/Doctrine/ORM/EntityManager.php index d4b032bfc1e..c1598576102 100644 --- a/lib/Doctrine/ORM/EntityManager.php +++ b/lib/Doctrine/ORM/EntityManager.php @@ -1,33 +1,20 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; -use Exception; use Doctrine\Common\EventManager; +use Doctrine\Common\Util\ClassUtils; use Doctrine\DBAL\Connection; use Doctrine\DBAL\DriverManager; use Doctrine\DBAL\LockMode; +use Doctrine\ORM\Configuration\ProxyConfiguration; +use Doctrine\ORM\Proxy\Factory\DefaultProxyResolver; +use Doctrine\ORM\Proxy\Factory\StaticProxyFactory; use Doctrine\ORM\Query\ResultSetMapping; -use Doctrine\ORM\Proxy\ProxyFactory; use Doctrine\ORM\Query\FilterCollection; -use Doctrine\Common\Util\ClassUtils; +use Doctrine\ORM\Utility\IdentifierFlattener; /** * The EntityManager is the central access point to ORM functionality. @@ -60,7 +47,7 @@ * @author Jonathan Wage * @author Roman Borschel */ -/* final */class EntityManager implements EntityManagerInterface +final class EntityManager implements EntityManagerInterface { /** * The used Configuration. @@ -100,7 +87,7 @@ /** * The proxy factory used to create dynamic proxies. * - * @var \Doctrine\ORM\Proxy\ProxyFactory + * @var \Doctrine\ORM\Proxy\Factory\ProxyFactory */ private $proxyFactory; @@ -118,6 +105,13 @@ */ private $expressionBuilder; + /** + * The IdentifierFlattener used for manipulating identifiers + * + * @var \Doctrine\ORM\Utility\IdentifierFlattener + */ + private $identifierFlattener; + /** * Whether the EntityManager is closed or not. * @@ -151,20 +145,24 @@ protected function __construct(Connection $conn, Configuration $config, EventMan $this->config = $config; $this->eventManager = $eventManager; + $proxyConfiguration = new ProxyConfiguration(); + + $proxyConfiguration->setResolver(new DefaultProxyResolver($config->getProxyNamespace(), $config->getProxyDir())); + $proxyConfiguration->setDirectory($config->getProxyDir()); + $proxyConfiguration->setNamespace($config->getProxyNamespace()); + $proxyConfiguration->setAutoGenerate($config->getAutoGenerateProxyClasses()); + $metadataFactoryClassName = $config->getClassMetadataFactoryName(); $this->metadataFactory = new $metadataFactoryClassName; + $this->metadataFactory->setEntityManager($this); $this->metadataFactory->setCacheDriver($this->config->getMetadataCacheImpl()); - $this->repositoryFactory = $config->getRepositoryFactory(); - $this->unitOfWork = new UnitOfWork($this); - $this->proxyFactory = new ProxyFactory( - $this, - $config->getProxyDir(), - $config->getProxyNamespace(), - $config->getAutoGenerateProxyClasses() - ); + $this->repositoryFactory = $config->getRepositoryFactory(); + $this->unitOfWork = new UnitOfWork($this); + $this->proxyFactory = new StaticProxyFactory($this, $proxyConfiguration); + $this->identifierFlattener = new IdentifierFlattener($this->unitOfWork, $this->metadataFactory); if ($config->isSecondLevelCacheEnabled()) { $cacheConfig = $config->getSecondLevelCacheConfiguration(); @@ -203,6 +201,14 @@ public function getExpressionBuilder() return $this->expressionBuilder; } + /** + * @return IdentifierFlattener + */ + public function getIdentifierFlattener() : IdentifierFlattener + { + return $this->identifierFlattener; + } + /** * {@inheritDoc} */ @@ -222,22 +228,18 @@ public function getCache() /** * {@inheritDoc} */ - public function transactional($func) + public function transactional(callable $func) { - if (!is_callable($func)) { - throw new \InvalidArgumentException('Expected argument of type "callable", got "' . gettype($func) . '"'); - } - $this->conn->beginTransaction(); try { - $return = call_user_func($func, $this); + $return = $func($this); $this->flush(); $this->conn->commit(); - return $return ?: true; - } catch (Exception $e) { + return $return; + } catch (\Throwable $e) { $this->close(); $this->conn->rollBack(); @@ -275,9 +277,9 @@ public function rollback() * * @param string $className * - * @return \Doctrine\ORM\Mapping\ClassMetadata + * @return Mapping\ClassMetadata */ - public function getClassMetadata($className) + public function getClassMetadata($className) : Mapping\ClassMetadata { return $this->metadataFactory->getMetadataFor($className); } @@ -335,6 +337,26 @@ public function createQueryBuilder() return new QueryBuilder($this); } + /** + * {@inheritDoc} + * + * @deprecated + */ + public function merge($object) + { + throw new \BadMethodCallException('@TODO method disabled - will be removed in 3.0 with a release of doctrine/common'); + } + + /** + * {@inheritDoc} + * + * @deprecated + */ + public function detach($object) + { + throw new \BadMethodCallException('@TODO method disabled - will be removed in 3.0 with a release of doctrine/common'); + } + /** * Flushes all changes to objects that have been queued up to now to the database. * This effectively synchronizes the in-memory state of managed objects with the @@ -343,19 +365,17 @@ public function createQueryBuilder() * If an entity is explicitly passed to this method only this entity and * the cascade-persist semantics + scheduled inserts/removals are synchronized. * - * @param null|object|array $entity - * * @return void * * @throws \Doctrine\ORM\OptimisticLockException If a version check on an entity that * makes use of optimistic locking fails. * @throws ORMException */ - public function flush($entity = null) + public function flush() { $this->errorIfClosed(); - $this->unitOfWork->commit($entity); + $this->unitOfWork->commit(); } /** @@ -379,9 +399,10 @@ public function flush($entity = null) public function find($entityName, $id, $lockMode = null, $lockVersion = null) { $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\')); + $className = $class->getClassName(); - if ( ! is_array($id)) { - if ($class->isIdentifierComposite) { + if (! is_array($id)) { + if ($class->isIdentifierComposite()) { throw ORMInvalidArgumentException::invalidCompositeIdentifier(); } @@ -402,7 +423,7 @@ public function find($entityName, $id, $lockMode = null, $lockVersion = null) foreach ($class->identifier as $identifier) { if ( ! isset($id[$identifier])) { - throw ORMException::missingIdentifierField($class->name, $identifier); + throw ORMException::missingIdentifierField($className, $identifier); } $sortedId[$identifier] = $id[$identifier]; @@ -410,14 +431,14 @@ public function find($entityName, $id, $lockMode = null, $lockVersion = null) } if ($id) { - throw ORMException::unrecognizedIdentifierFields($class->name, array_keys($id)); + throw ORMException::unrecognizedIdentifierFields($className, array_keys($id)); } $unitOfWork = $this->getUnitOfWork(); // Check identity map first - if (($entity = $unitOfWork->tryGetById($sortedId, $class->rootEntityName)) !== false) { - if ( ! ($entity instanceof $class->name)) { + if (($entity = $unitOfWork->tryGetById($sortedId, $class->getRootClassName())) !== false) { + if ( ! ($entity instanceof $className)) { return null; } @@ -429,7 +450,7 @@ public function find($entityName, $id, $lockMode = null, $lockVersion = null) case LockMode::NONE === $lockMode: case LockMode::PESSIMISTIC_READ === $lockMode: case LockMode::PESSIMISTIC_WRITE === $lockMode: - $persister = $unitOfWork->getEntityPersister($class->name); + $persister = $unitOfWork->getEntityPersister($className); $persister->refresh($sortedId, $entity, $lockMode); break; } @@ -437,12 +458,12 @@ public function find($entityName, $id, $lockMode = null, $lockVersion = null) return $entity; // Hit! } - $persister = $unitOfWork->getEntityPersister($class->name); + $persister = $unitOfWork->getEntityPersister($className); switch (true) { case LockMode::OPTIMISTIC === $lockMode: - if ( ! $class->isVersioned) { - throw OptimisticLockException::notVersioned($class->name); + if ( ! $class->isVersioned()) { + throw OptimisticLockException::notVersioned($className); } $entity = $persister->load($sortedId); @@ -470,16 +491,31 @@ public function find($entityName, $id, $lockMode = null, $lockVersion = null) public function getReference($entityName, $id) { $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\')); + $className = $class->getClassName(); if ( ! is_array($id)) { + if ($class->isIdentifierComposite()) { + throw ORMInvalidArgumentException::invalidCompositeIdentifier(); + } + $id = [$class->identifier[0] => $id]; } + foreach ($id as $i => $value) { + if (is_object($value) && $this->metadataFactory->hasMetadataFor(ClassUtils::getClass($value))) { + $id[$i] = $this->unitOfWork->getSingleIdentifierValue($value); + + if ($id[$i] === null) { + throw ORMInvalidArgumentException::invalidIdentifierBindingEntity(); + } + } + } + $sortedId = []; foreach ($class->identifier as $identifier) { if ( ! isset($id[$identifier])) { - throw ORMException::missingIdentifierField($class->name, $identifier); + throw ORMException::missingIdentifierField($className, $identifier); } $sortedId[$identifier] = $id[$identifier]; @@ -487,19 +523,19 @@ public function getReference($entityName, $id) } if ($id) { - throw ORMException::unrecognizedIdentifierFields($class->name, array_keys($id)); + throw ORMException::unrecognizedIdentifierFields($className, array_keys($id)); } // Check identity map first, if its already in there just return it. - if (($entity = $this->unitOfWork->tryGetById($sortedId, $class->rootEntityName)) !== false) { - return ($entity instanceof $class->name) ? $entity : null; + if (($entity = $this->unitOfWork->tryGetById($sortedId, $class->getRootClassName())) !== false) { + return ($entity instanceof $className) ? $entity : null; } - if ($class->subClasses) { + if ($class->getSubClasses()) { return $this->find($entityName, $sortedId); } - $entity = $this->proxyFactory->getProxy($class->name, $sortedId); + $entity = $this->proxyFactory->getProxy($className, $sortedId); $this->unitOfWork->registerManaged($entity, $sortedId, []); @@ -509,24 +545,55 @@ public function getReference($entityName, $id) /** * {@inheritDoc} */ - public function getPartialReference($entityName, $identifier) + public function getPartialReference($entityName, $id) { $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\')); + $className = $class->getClassName(); - // Check identity map first, if its already in there just return it. - if (($entity = $this->unitOfWork->tryGetById($identifier, $class->rootEntityName)) !== false) { - return ($entity instanceof $class->name) ? $entity : null; + if ( ! is_array($id)) { + if ($class->isIdentifierComposite()) { + throw ORMInvalidArgumentException::invalidCompositeIdentifier(); + } + + $id = [$class->identifier[0] => $id]; + } + + foreach ($id as $i => $value) { + if (is_object($value) && $this->metadataFactory->hasMetadataFor(ClassUtils::getClass($value))) { + $id[$i] = $this->unitOfWork->getSingleIdentifierValue($value); + + if ($id[$i] === null) { + throw ORMInvalidArgumentException::invalidIdentifierBindingEntity(); + } + } + } + + $sortedId = []; + + foreach ($class->identifier as $identifier) { + if ( ! isset($id[$identifier])) { + throw ORMException::missingIdentifierField($className, $identifier); + } + + $sortedId[$identifier] = $id[$identifier]; + unset($id[$identifier]); + } + + if ($id) { + throw ORMException::unrecognizedIdentifierFields($className, array_keys($id)); } - if ( ! is_array($identifier)) { - $identifier = [$class->identifier[0] => $identifier]; + // Check identity map first, if its already in there just return it. + if (($entity = $this->unitOfWork->tryGetById($sortedId, $class->getRootClassName())) !== false) { + return ($entity instanceof $className) ? $entity : null; } - $entity = $class->newInstance(); + $persister = $this->unitOfWork->getEntityPersister($class->getClassName()); + $entity = $this->unitOfWork->newInstance($class); - $class->setIdentifierValues($entity, $identifier); + $persister->setIdentifier($entity, $sortedId); - $this->unitOfWork->registerManaged($entity, $identifier, []); + $this->unitOfWork->registerManaged($entity, $sortedId, []); $this->unitOfWork->markReadOnly($entity); return $entity; @@ -536,25 +603,13 @@ public function getPartialReference($entityName, $identifier) * Clears the EntityManager. All entities that are currently managed * by this EntityManager become detached. * - * @param string|null $entityName if given, only entities of this type will get detached + * @param null $entityName Unused. @todo Remove from ObjectManager. * * @return void - * - * @throws ORMInvalidArgumentException if a non-null non-string value is given - * @throws \Doctrine\Common\Persistence\Mapping\MappingException if a $entityName is given, but that entity is not - * found in the mappings */ public function clear($entityName = null) { - if (null !== $entityName && ! is_string($entityName)) { - throw ORMInvalidArgumentException::invalidEntityName($entityName); - } - - $this->unitOfWork->clear( - null === $entityName - ? null - : $this->metadataFactory->getMetadataFor($entityName)->getName() - ); + $this->unitOfWork->clear(); } /** @@ -640,51 +695,6 @@ public function refresh($entity) $this->unitOfWork->refresh($entity); } - /** - * Detaches an entity from the EntityManager, causing a managed entity to - * become detached. Unflushed changes made to the entity if any - * (including removal of the entity), will not be synchronized to the database. - * Entities which previously referenced the detached entity will continue to - * reference it. - * - * @param object $entity The entity to detach. - * - * @return void - * - * @throws ORMInvalidArgumentException - */ - public function detach($entity) - { - if ( ! is_object($entity)) { - throw ORMInvalidArgumentException::invalidObject('EntityManager#detach()', $entity); - } - - $this->unitOfWork->detach($entity); - } - - /** - * Merges the state of a detached entity into the persistence context - * of this EntityManager and returns the managed copy of the entity. - * The entity passed to merge will not become associated/managed with this EntityManager. - * - * @param object $entity The detached entity to merge into the persistence context. - * - * @return object The managed copy of the entity. - * - * @throws ORMInvalidArgumentException - * @throws ORMException - */ - public function merge($entity) - { - if ( ! is_object($entity)) { - throw ORMInvalidArgumentException::invalidObject('EntityManager#merge()', $entity); - } - - $this->errorIfClosed(); - - return $this->unitOfWork->merge($entity); - } - /** * {@inheritDoc} * diff --git a/lib/Doctrine/ORM/EntityManagerAware.php b/lib/Doctrine/ORM/EntityManagerAware.php new file mode 100644 index 00000000000..bb26ad7c9fd --- /dev/null +++ b/lib/Doctrine/ORM/EntityManagerAware.php @@ -0,0 +1,36 @@ + + */ +interface EntityManagerAware +{ + /** + * Injects responsible EntityManager and the ClassMetadata into this persistent object. + * + * @param EntityManagerInterface $entityManager + * @param ClassMetadata $classMetadata + * + * @return void + */ + public function injectEntityManager(EntityManagerInterface $entityManager, ClassMetadata $classMetadata) : void; +} diff --git a/lib/Doctrine/ORM/EntityManagerInterface.php b/lib/Doctrine/ORM/EntityManagerInterface.php index 09c7efdf9d2..5d8ed5ba68f 100644 --- a/lib/Doctrine/ORM/EntityManagerInterface.php +++ b/lib/Doctrine/ORM/EntityManagerInterface.php @@ -1,26 +1,12 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\ORM\Query\ResultSetMapping; +use Doctrine\ORM\Utility\IdentifierFlattener; /** * EntityManager interface @@ -62,6 +48,13 @@ public function getConnection(); */ public function getExpressionBuilder(); + /** + * Gets an IdentifierFlattener used for converting Entities into an array of identifier values. + * + * @return IdentifierFlattener + */ + public function getIdentifierFlattener(); + /** * Starts a transaction on the underlying database connection. * @@ -81,9 +74,11 @@ public function beginTransaction(); * * @param callable $func The function to execute transactionally. * - * @return mixed The non-empty value returned from the closure or true instead. + * @return mixed The value returned from the closure. + * + * @throws \Throwable */ - public function transactional($func); + public function transactional(callable $func); /** * Commits a transaction on the underlying database connection. @@ -269,7 +264,7 @@ public function newHydrator($hydrationMode); /** * Gets the proxy factory used by the EntityManager to create entity proxies. * - * @return \Doctrine\ORM\Proxy\ProxyFactory + * @return \Doctrine\ORM\Proxy\Factory\ProxyFactory */ public function getProxyFactory(); diff --git a/lib/Doctrine/ORM/EntityNotFoundException.php b/lib/Doctrine/ORM/EntityNotFoundException.php index 5b21e15c276..146adbdc058 100644 --- a/lib/Doctrine/ORM/EntityNotFoundException.php +++ b/lib/Doctrine/ORM/EntityNotFoundException.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; diff --git a/lib/Doctrine/ORM/EntityRepository.php b/lib/Doctrine/ORM/EntityRepository.php index 6be570ba3be..30ddf8ea79d 100644 --- a/lib/Doctrine/ORM/EntityRepository.php +++ b/lib/Doctrine/ORM/EntityRepository.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; @@ -43,29 +28,29 @@ class EntityRepository implements ObjectRepository, Selectable /** * @var string */ - protected $_entityName; + protected $entityName; /** - * @var EntityManager + * @var EntityManagerInterface */ - protected $_em; + protected $em; /** * @var \Doctrine\ORM\Mapping\ClassMetadata */ - protected $_class; + protected $class; /** * Initializes a new EntityRepository. * - * @param EntityManager $em The EntityManager to use. - * @param Mapping\ClassMetadata $class The class descriptor. + * @param EntityManagerInterface $em The EntityManager to use. + * @param Mapping\ClassMetadata $class The class descriptor. */ public function __construct(EntityManagerInterface $em, Mapping\ClassMetadata $class) { - $this->_entityName = $class->name; - $this->_em = $em; - $this->_class = $class; + $this->entityName = $class->getClassName(); + $this->em = $em; + $this->class = $class; } /** @@ -78,9 +63,9 @@ public function __construct(EntityManagerInterface $em, Mapping\ClassMetadata $c */ public function createQueryBuilder($alias, $indexBy = null) { - return $this->_em->createQueryBuilder() + return $this->em->createQueryBuilder() ->select($alias) - ->from($this->_entityName, $alias, $indexBy); + ->from($this->entityName, $alias, $indexBy); } /** @@ -94,8 +79,8 @@ public function createQueryBuilder($alias, $indexBy = null) */ public function createResultSetMappingBuilder($alias) { - $rsm = new ResultSetMappingBuilder($this->_em, ResultSetMappingBuilder::COLUMN_RENAMING_INCREMENT); - $rsm->addRootEntityFromClassMetadata($this->_entityName, $alias); + $rsm = new ResultSetMappingBuilder($this->em, ResultSetMappingBuilder::COLUMN_RENAMING_INCREMENT); + $rsm->addRootEntityFromClassMetadata($this->entityName, $alias); return $rsm; } @@ -109,7 +94,10 @@ public function createResultSetMappingBuilder($alias) */ public function createNamedQuery($queryName) { - return $this->_em->createQuery($this->_class->getNamedQuery($queryName)); + $namedQuery = $this->class->getNamedQuery($queryName); + $resolvedQuery = str_replace('__CLASS__', $this->class->getClassName(), $namedQuery); + + return $this->em->createQuery($resolvedQuery); } /** @@ -121,11 +109,12 @@ public function createNamedQuery($queryName) */ public function createNativeNamedQuery($queryName) { - $queryMapping = $this->_class->getNamedNativeQuery($queryName); - $rsm = new Query\ResultSetMappingBuilder($this->_em); - $rsm->addNamedNativeQueryMapping($this->_class, $queryMapping); + $queryMapping = $this->class->getNamedNativeQuery($queryName); + $rsm = new Query\ResultSetMappingBuilder($this->em); - return $this->_em->createNativeQuery($queryMapping['query'], $rsm); + $rsm->addNamedNativeQueryMapping($this->class, $queryMapping); + + return $this->em->createNativeQuery($queryMapping['query'], $rsm); } /** @@ -135,7 +124,7 @@ public function createNativeNamedQuery($queryName) */ public function clear() { - $this->_em->clear($this->_class->rootEntityName); + $this->em->clear($this->class->getRootClassName()); } /** @@ -151,7 +140,7 @@ public function clear() */ public function find($id, $lockMode = null, $lockVersion = null) { - return $this->_em->find($this->_entityName, $id, $lockMode, $lockVersion); + return $this->em->find($this->entityName, $id, $lockMode, $lockVersion); } /** @@ -167,31 +156,33 @@ public function findAll() /** * Finds entities by a set of criteria. * - * @param array $criteria - * @param array|null $orderBy - * @param int|null $limit - * @param int|null $offset + * @param array $criteria + * @param array $orderBy + * @param int|null $limit + * @param int|null $offset * * @return array The objects. + * + * @todo guilhermeblanco Change orderBy to use a blank array by default (requires Common\Persistence change). */ public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) { - $persister = $this->_em->getUnitOfWork()->getEntityPersister($this->_entityName); + $persister = $this->em->getUnitOfWork()->getEntityPersister($this->entityName); - return $persister->loadAll($criteria, $orderBy, $limit, $offset); + return $persister->loadAll($criteria, $orderBy !== null ? $orderBy : [], $limit, $offset); } /** * Finds a single entity by a set of criteria. * - * @param array $criteria - * @param array|null $orderBy + * @param array $criteria + * @param array $orderBy * * @return object|null The entity instance or NULL if the entity can not be found. */ - public function findOneBy(array $criteria, array $orderBy = null) + public function findOneBy(array $criteria, array $orderBy = []) { - $persister = $this->_em->getUnitOfWork()->getEntityPersister($this->_entityName); + $persister = $this->em->getUnitOfWork()->getEntityPersister($this->entityName); return $persister->load($criteria, null, null, [], null, 1, $orderBy); } @@ -207,7 +198,7 @@ public function findOneBy(array $criteria, array $orderBy = null) */ public function count(array $criteria) { - return $this->_em->getUnitOfWork()->getEntityPersister($this->_entityName)->count($criteria); + return $this->em->getUnitOfWork()->getEntityPersister($this->entityName)->count($criteria); } /** @@ -246,7 +237,7 @@ public function __call($method, $arguments) */ protected function getEntityName() { - return $this->_entityName; + return $this->entityName; } /** @@ -258,11 +249,11 @@ public function getClassName() } /** - * @return EntityManager + * @return EntityManagerInterface */ protected function getEntityManager() { - return $this->_em; + return $this->em; } /** @@ -270,7 +261,7 @@ protected function getEntityManager() */ protected function getClassMetadata() { - return $this->_class; + return $this->class; } /** @@ -283,7 +274,7 @@ protected function getClassMetadata() */ public function matching(Criteria $criteria) { - $persister = $this->_em->getUnitOfWork()->getEntityPersister($this->_entityName); + $persister = $this->em->getUnitOfWork()->getEntityPersister($this->entityName); return new LazyCriteriaCollection($persister, $criteria); } @@ -307,8 +298,8 @@ private function resolveMagicCall($method, $by, array $arguments) $fieldName = lcfirst(Inflector::classify($by)); - if (! ($this->_class->hasField($fieldName) || $this->_class->hasAssociation($fieldName))) { - throw ORMException::invalidMagicCall($this->_entityName, $fieldName, $method . $by); + if (null === $this->class->getProperty($fieldName)) { + throw ORMException::invalidMagicCall($this->entityName, $fieldName, $method . $by); } return $this->$method([$fieldName => $arguments[0]], ...array_slice($arguments, 1)); diff --git a/lib/Doctrine/ORM/Event/LifecycleEventArgs.php b/lib/Doctrine/ORM/Event/LifecycleEventArgs.php index c7eb80bf61f..e87e1d77d64 100644 --- a/lib/Doctrine/ORM/Event/LifecycleEventArgs.php +++ b/lib/Doctrine/ORM/Event/LifecycleEventArgs.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Event; @@ -45,7 +30,7 @@ public function getEntity() /** * Retrieves associated EntityManager. * - * @return \Doctrine\ORM\EntityManager + * @return \Doctrine\ORM\EntityManagerInterface */ public function getEntityManager() { diff --git a/lib/Doctrine/ORM/Event/ListenersInvoker.php b/lib/Doctrine/ORM/Event/ListenersInvoker.php index 7be8d48ebb1..16b615dbe51 100644 --- a/lib/Doctrine/ORM/Event/ListenersInvoker.php +++ b/lib/Doctrine/ORM/Event/ListenersInvoker.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Event; diff --git a/lib/Doctrine/ORM/Event/LoadClassMetadataEventArgs.php b/lib/Doctrine/ORM/Event/LoadClassMetadataEventArgs.php index 5df698d6973..3ce3733d803 100644 --- a/lib/Doctrine/ORM/Event/LoadClassMetadataEventArgs.php +++ b/lib/Doctrine/ORM/Event/LoadClassMetadataEventArgs.php @@ -1,46 +1,60 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Event; -use Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs as BaseLoadClassMetadataEventArgs; +use Doctrine\Common\EventArgs; +use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\ClassMetadata; /** * Class that holds event arguments for a loadMetadata event. * * @author Jonathan H. Wage * @since 2.0 - * - * Note: method annotations are used instead of method overrides (due to BC policy) - * - * @method __construct(\Doctrine\ORM\Mapping\ClassMetadata $classMetadata, \Doctrine\ORM\EntityManager $objectManager) - * @method \Doctrine\ORM\Mapping\ClassMetadata getClassMetadata() */ -class LoadClassMetadataEventArgs extends BaseLoadClassMetadataEventArgs +class LoadClassMetadataEventArgs extends EventArgs { + /** + * @var ClassMetadata + */ + private $classMetadata; + + /** + * @var EntityManagerInterface + */ + private $entityManager; + + /** + * Constructor. + * + * @param ClassMetadata $classMetadata + * @param EntityManagerInterface $entityManager + */ + public function __construct(ClassMetadata $classMetadata, EntityManagerInterface $entityManager) + { + $this->classMetadata = $classMetadata; + $this->entityManager = $entityManager; + } + + /** + * Retrieves the associated ClassMetadata. + * + * @return ClassMetadata + */ + public function getClassMetadata() : ClassMetadata + { + return $this->classMetadata; + } + /** * Retrieve associated EntityManager. * - * @return \Doctrine\ORM\EntityManager + * @return EntityManagerInterface */ - public function getEntityManager() + public function getEntityManager() : EntityManagerInterface { - return $this->getObjectManager(); + return $this->entityManager; } } diff --git a/lib/Doctrine/ORM/Event/OnClassMetadataNotFoundEventArgs.php b/lib/Doctrine/ORM/Event/OnClassMetadataNotFoundEventArgs.php index a044a7e321d..3aca26c9756 100644 --- a/lib/Doctrine/ORM/Event/OnClassMetadataNotFoundEventArgs.php +++ b/lib/Doctrine/ORM/Event/OnClassMetadataNotFoundEventArgs.php @@ -1,27 +1,13 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Event; use Doctrine\Common\Persistence\Event\ManagerEventArgs; -use Doctrine\Common\Persistence\Mapping\ClassMetadata; -use Doctrine\Common\Persistence\ObjectManager; +use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\ClassMetadataBuildingContext; /** * Class that holds event arguments for a `onClassMetadataNotFound` event. @@ -29,8 +15,11 @@ * This object is mutable by design, allowing callbacks having access to it to set the * found metadata in it, and therefore "cancelling" a `onClassMetadataNotFound` event * + * @package Doctrine\ORM\Event + * @since 2.5 + * + * @author Guilherme Blanco * @author Marco Pivetta - * @since 2.5 */ class OnClassMetadataNotFoundEventArgs extends ManagerEventArgs { @@ -39,6 +28,11 @@ class OnClassMetadataNotFoundEventArgs extends ManagerEventArgs */ private $className; + /** + * @var ClassMetadataBuildingContext + */ + private $metadataBuildingContext; + /** * @var ClassMetadata|null */ @@ -47,20 +41,28 @@ class OnClassMetadataNotFoundEventArgs extends ManagerEventArgs /** * Constructor. * - * @param string $className - * @param ObjectManager $objectManager + * @param string $className + * @param ClassMetadataBuildingContext $metadataBuildingContext + * @param EntityManagerInterface $entityManager */ - public function __construct($className, ObjectManager $objectManager) + public function __construct( + string $className, + ClassMetadataBuildingContext $metadataBuildingContext, + EntityManagerInterface $entityManager + ) { - $this->className = (string) $className; + parent::__construct($entityManager); - parent::__construct($objectManager); + $this->className = $className; + $this->metadataBuildingContext = $metadataBuildingContext; } /** * @param ClassMetadata|null $classMetadata + * + * @return void */ - public function setFoundMetadata(ClassMetadata $classMetadata = null) + public function setFoundMetadata(?ClassMetadata $classMetadata) : void { $this->foundMetadata = $classMetadata; } @@ -68,7 +70,7 @@ public function setFoundMetadata(ClassMetadata $classMetadata = null) /** * @return ClassMetadata|null */ - public function getFoundMetadata() + public function getFoundMetadata() : ?ClassMetadata { return $this->foundMetadata; } @@ -78,9 +80,17 @@ public function getFoundMetadata() * * @return string */ - public function getClassName() + public function getClassName() : string { return $this->className; } + + /** + * @return ClassMetadataBuildingContext + */ + public function getClassMetadataBuildingContext() : ClassMetadataBuildingContext + { + return $this->metadataBuildingContext; + } } diff --git a/lib/Doctrine/ORM/Event/OnClearEventArgs.php b/lib/Doctrine/ORM/Event/OnClearEventArgs.php index dd827c72568..4137c81bdab 100644 --- a/lib/Doctrine/ORM/Event/OnClearEventArgs.php +++ b/lib/Doctrine/ORM/Event/OnClearEventArgs.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Event; @@ -37,50 +22,23 @@ class OnClearEventArgs extends \Doctrine\Common\EventArgs */ private $em; - /** - * @var string - */ - private $entityClass; - /** * Constructor. * * @param EntityManagerInterface $em - * @param string|null $entityClass Optional entity class. */ - public function __construct(EntityManagerInterface $em, $entityClass = null) + public function __construct(EntityManagerInterface $em) { - $this->em = $em; - $this->entityClass = $entityClass; + $this->em = $em; } /** * Retrieves associated EntityManager. * - * @return \Doctrine\ORM\EntityManager + * @return \Doctrine\ORM\EntityManagerInterface */ public function getEntityManager() { return $this->em; } - - /** - * Name of the entity class that is cleared, or empty if all are cleared. - * - * @return string|null - */ - public function getEntityClass() - { - return $this->entityClass; - } - - /** - * Checks if event clears all entities. - * - * @return bool - */ - public function clearsAllEntities() - { - return ($this->entityClass === null); - } } diff --git a/lib/Doctrine/ORM/Event/OnFlushEventArgs.php b/lib/Doctrine/ORM/Event/OnFlushEventArgs.php index 6a9c7c7f464..a61a9c0a9c5 100644 --- a/lib/Doctrine/ORM/Event/OnFlushEventArgs.php +++ b/lib/Doctrine/ORM/Event/OnFlushEventArgs.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Event; @@ -51,7 +36,7 @@ public function __construct(EntityManagerInterface $em) /** * Retrieve associated EntityManager. * - * @return \Doctrine\ORM\EntityManager + * @return \Doctrine\ORM\EntityManagerInterface */ public function getEntityManager() { diff --git a/lib/Doctrine/ORM/Event/PostFlushEventArgs.php b/lib/Doctrine/ORM/Event/PostFlushEventArgs.php index 860f2d33b90..88165c687eb 100644 --- a/lib/Doctrine/ORM/Event/PostFlushEventArgs.php +++ b/lib/Doctrine/ORM/Event/PostFlushEventArgs.php @@ -1,21 +1,6 @@ . - */ +declare(strict_types=1); + namespace Doctrine\ORM\Event; use Doctrine\Common\EventArgs; @@ -32,7 +17,7 @@ class PostFlushEventArgs extends EventArgs { /** - * @var \Doctrine\ORM\EntityManager + * @var \Doctrine\ORM\EntityManagerInterface */ private $em; @@ -49,7 +34,7 @@ public function __construct(EntityManagerInterface $em) /** * Retrieves associated EntityManager. * - * @return \Doctrine\ORM\EntityManager + * @return \Doctrine\ORM\EntityManagerInterface */ public function getEntityManager() { diff --git a/lib/Doctrine/ORM/Event/PreFlushEventArgs.php b/lib/Doctrine/ORM/Event/PreFlushEventArgs.php index d01a9263960..cc1e1955805 100644 --- a/lib/Doctrine/ORM/Event/PreFlushEventArgs.php +++ b/lib/Doctrine/ORM/Event/PreFlushEventArgs.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Event; @@ -34,7 +19,7 @@ class PreFlushEventArgs extends EventArgs { /** - * @var \Doctrine\ORM\EntityManager + * @var \Doctrine\ORM\EntityManagerInterface */ private $em; @@ -49,7 +34,7 @@ public function __construct(EntityManagerInterface $em) } /** - * @return \Doctrine\ORM\EntityManager + * @return \Doctrine\ORM\EntityManagerInterface */ public function getEntityManager() { diff --git a/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php b/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php index d9a9f9db2cc..d009d991f6c 100644 --- a/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php +++ b/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Event; diff --git a/lib/Doctrine/ORM/Events.php b/lib/Doctrine/ORM/Events.php index e16b47a4214..6ff6af4f93e 100644 --- a/lib/Doctrine/ORM/Events.php +++ b/lib/Doctrine/ORM/Events.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; @@ -114,7 +99,7 @@ private function __construct() /** * The loadClassMetadata event occurs after the mapping metadata for a class - * has been loaded from a mapping source (annotations/xml/yaml). + * has been loaded from a mapping source (annotations/xml). * * @var string */ diff --git a/lib/Doctrine/ORM/Id/AbstractIdGenerator.php b/lib/Doctrine/ORM/Id/AbstractIdGenerator.php deleted file mode 100644 index dada71e43ad..00000000000 --- a/lib/Doctrine/ORM/Id/AbstractIdGenerator.php +++ /dev/null @@ -1,49 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Id; - -use Doctrine\ORM\EntityManager; - -abstract class AbstractIdGenerator -{ - /** - * Generates an identifier for an entity. - * - * @param EntityManager $em - * @param \Doctrine\ORM\Mapping\Entity $entity - * @return mixed - */ - abstract public function generate(EntityManager $em, $entity); - - /** - * Gets whether this generator is a post-insert generator which means that - * {@link generate()} must be called after the entity has been inserted - * into the database. - * - * By default, this method returns FALSE. Generators that have this requirement - * must override this method and return TRUE. - * - * @return boolean - */ - public function isPostInsertGenerator() - { - return false; - } -} diff --git a/lib/Doctrine/ORM/Id/AssignedGenerator.php b/lib/Doctrine/ORM/Id/AssignedGenerator.php deleted file mode 100644 index 691eaee4221..00000000000 --- a/lib/Doctrine/ORM/Id/AssignedGenerator.php +++ /dev/null @@ -1,66 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Id; - -use Doctrine\ORM\EntityManager; -use Doctrine\ORM\ORMException; - -/** - * Special generator for application-assigned identifiers (doesn't really generate anything). - * - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - */ -class AssignedGenerator extends AbstractIdGenerator -{ - /** - * Returns the identifier assigned to the given entity. - * - * {@inheritDoc} - * - * @throws \Doctrine\ORM\ORMException - */ - public function generate(EntityManager $em, $entity) - { - $class = $em->getClassMetadata(get_class($entity)); - $idFields = $class->getIdentifierFieldNames(); - $identifier = []; - - foreach ($idFields as $idField) { - $value = $class->getFieldValue($entity, $idField); - - if ( ! isset($value)) { - throw ORMException::entityMissingAssignedIdForField($entity, $idField); - } - - if (isset($class->associationMappings[$idField])) { - // NOTE: Single Columns as associated identifiers only allowed - this constraint it is enforced. - $value = $em->getUnitOfWork()->getSingleIdentifierValue($value); - } - - $identifier[$idField] = $value; - } - - return $identifier; - } -} diff --git a/lib/Doctrine/ORM/Id/BigIntegerIdentityGenerator.php b/lib/Doctrine/ORM/Id/BigIntegerIdentityGenerator.php deleted file mode 100644 index 01d139f485b..00000000000 --- a/lib/Doctrine/ORM/Id/BigIntegerIdentityGenerator.php +++ /dev/null @@ -1,66 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Id; - -use Doctrine\ORM\EntityManager; - -/** - * Id generator that obtains IDs from special "identity" columns. These are columns - * that automatically get a database-generated, auto-incremented identifier on INSERT. - * This generator obtains the last insert id after such an insert. - */ -class BigIntegerIdentityGenerator extends AbstractIdGenerator -{ - /** - * The name of the sequence to pass to lastInsertId(), if any. - * - * @var string - */ - private $sequenceName; - - /** - * Constructor. - * - * @param string|null $sequenceName The name of the sequence to pass to lastInsertId() - * to obtain the last generated identifier within the current - * database session/connection, if any. - */ - public function __construct($sequenceName = null) - { - $this->sequenceName = $sequenceName; - } - - /** - * {@inheritDoc} - */ - public function generate(EntityManager $em, $entity) - { - return (string) $em->getConnection()->lastInsertId($this->sequenceName); - } - - /** - * {@inheritDoc} - */ - public function isPostInsertGenerator() - { - return true; - } -} - diff --git a/lib/Doctrine/ORM/Id/IdentityGenerator.php b/lib/Doctrine/ORM/Id/IdentityGenerator.php deleted file mode 100644 index b9f68c625f6..00000000000 --- a/lib/Doctrine/ORM/Id/IdentityGenerator.php +++ /dev/null @@ -1,65 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Id; - -use Doctrine\ORM\EntityManager; - -/** - * Id generator that obtains IDs from special "identity" columns. These are columns - * that automatically get a database-generated, auto-incremented identifier on INSERT. - * This generator obtains the last insert id after such an insert. - */ -class IdentityGenerator extends AbstractIdGenerator -{ - /** - * The name of the sequence to pass to lastInsertId(), if any. - * - * @var string - */ - private $sequenceName; - - /** - * Constructor. - * - * @param string|null $sequenceName The name of the sequence to pass to lastInsertId() - * to obtain the last generated identifier within the current - * database session/connection, if any. - */ - public function __construct($sequenceName = null) - { - $this->sequenceName = $sequenceName; - } - - /** - * {@inheritDoc} - */ - public function generate(EntityManager $em, $entity) - { - return (int) $em->getConnection()->lastInsertId($this->sequenceName); - } - - /** - * {@inheritdoc} - */ - public function isPostInsertGenerator() - { - return true; - } -} diff --git a/lib/Doctrine/ORM/Id/SequenceGenerator.php b/lib/Doctrine/ORM/Id/SequenceGenerator.php deleted file mode 100644 index 9d8e9eb75aa..00000000000 --- a/lib/Doctrine/ORM/Id/SequenceGenerator.php +++ /dev/null @@ -1,132 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Id; - -use Doctrine\ORM\EntityManager; -use Serializable; - -/** - * Represents an ID generator that uses a database sequence. - * - * @since 2.0 - * @author Roman Borschel - */ -class SequenceGenerator extends AbstractIdGenerator implements Serializable -{ - /** - * The allocation size of the sequence. - * - * @var int - */ - private $_allocationSize; - - /** - * The name of the sequence. - * - * @var string - */ - private $_sequenceName; - - /** - * @var int - */ - private $_nextValue = 0; - - /** - * @var int|null - */ - private $_maxValue = null; - - /** - * Initializes a new sequence generator. - * - * @param string $sequenceName The name of the sequence. - * @param integer $allocationSize The allocation size of the sequence. - */ - public function __construct($sequenceName, $allocationSize) - { - $this->_sequenceName = $sequenceName; - $this->_allocationSize = $allocationSize; - } - - /** - * {@inheritDoc} - */ - public function generate(EntityManager $em, $entity) - { - if ($this->_maxValue === null || $this->_nextValue == $this->_maxValue) { - // Allocate new values - $conn = $em->getConnection(); - $sql = $conn->getDatabasePlatform()->getSequenceNextValSQL($this->_sequenceName); - - // Using `query` to force usage of the master server in MasterSlaveConnection - $this->_nextValue = (int) $conn->query($sql)->fetchColumn(); - $this->_maxValue = $this->_nextValue + $this->_allocationSize; - } - - return $this->_nextValue++; - } - - /** - * Gets the maximum value of the currently allocated bag of values. - * - * @return integer|null - */ - public function getCurrentMaxValue() - { - return $this->_maxValue; - } - - /** - * Gets the next value that will be returned by generate(). - * - * @return integer - */ - public function getNextValue() - { - return $this->_nextValue; - } - - /** - * @return string - */ - public function serialize() - { - return serialize( - [ - 'allocationSize' => $this->_allocationSize, - 'sequenceName' => $this->_sequenceName - ] - ); - } - - /** - * @param string $serialized - * - * @return void - */ - public function unserialize($serialized) - { - $array = unserialize($serialized); - - $this->_sequenceName = $array['sequenceName']; - $this->_allocationSize = $array['allocationSize']; - } -} diff --git a/lib/Doctrine/ORM/Id/TableGenerator.php b/lib/Doctrine/ORM/Id/TableGenerator.php deleted file mode 100644 index 02385f51158..00000000000 --- a/lib/Doctrine/ORM/Id/TableGenerator.php +++ /dev/null @@ -1,109 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Id; - -use Doctrine\ORM\EntityManager; - -/** - * Id generator that uses a single-row database table and a hi/lo algorithm. - * - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - */ -class TableGenerator extends AbstractIdGenerator -{ - /** - * @var string - */ - private $_tableName; - - /** - * @var string - */ - private $_sequenceName; - - /** - * @var int - */ - private $_allocationSize; - - /** - * @var int|null - */ - private $_nextValue; - - /** - * @var int|null - */ - private $_maxValue; - - /** - * @param string $tableName - * @param string $sequenceName - * @param int $allocationSize - */ - public function __construct($tableName, $sequenceName = 'default', $allocationSize = 10) - { - $this->_tableName = $tableName; - $this->_sequenceName = $sequenceName; - $this->_allocationSize = $allocationSize; - } - - /** - * {@inheritDoc} - */ - public function generate( - EntityManager $em, $entity) - { - if ($this->_maxValue === null || $this->_nextValue == $this->_maxValue) { - // Allocate new values - $conn = $em->getConnection(); - - if ($conn->getTransactionNestingLevel() === 0) { - // use select for update - $sql = $conn->getDatabasePlatform()->getTableHiLoCurrentValSql($this->_tableName, $this->_sequenceName); - $currentLevel = $conn->fetchColumn($sql); - - if ($currentLevel != null) { - $this->_nextValue = $currentLevel; - $this->_maxValue = $this->_nextValue + $this->_allocationSize; - - $updateSql = $conn->getDatabasePlatform()->getTableHiLoUpdateNextValSql( - $this->_tableName, $this->_sequenceName, $this->_allocationSize - ); - - if ($conn->executeUpdate($updateSql, [1 => $currentLevel, 2 => $currentLevel+1]) !== 1) { - // no affected rows, concurrency issue, throw exception - } - } else { - // no current level returned, TableGenerator seems to be broken, throw exception - } - } else { - // only table locks help here, implement this or throw exception? - // or do we want to work with table locks exclusively? - } - } - - return $this->_nextValue++; - } -} diff --git a/lib/Doctrine/ORM/Id/UuidGenerator.php b/lib/Doctrine/ORM/Id/UuidGenerator.php deleted file mode 100644 index 7cac5ccf40f..00000000000 --- a/lib/Doctrine/ORM/Id/UuidGenerator.php +++ /dev/null @@ -1,42 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Id; - -use Doctrine\ORM\EntityManager; - -/** - * Represents an ID generator that uses the database UUID expression - * - * @since 2.3 - * @author Maarten de Keizer - */ -class UuidGenerator extends AbstractIdGenerator -{ - /** - * {@inheritDoc} - */ - public function generate(EntityManager $em, $entity) - { - $conn = $em->getConnection(); - $sql = 'SELECT ' . $conn->getDatabasePlatform()->getGuidExpression(); - - return $conn->query($sql)->fetchColumn(0); - } -} diff --git a/lib/Doctrine/ORM/Internal/CommitOrderCalculator.php b/lib/Doctrine/ORM/Internal/CommitOrderCalculator.php index 067a8c577ba..4a6d384a80b 100644 --- a/lib/Doctrine/ORM/Internal/CommitOrderCalculator.php +++ b/lib/Doctrine/ORM/Internal/CommitOrderCalculator.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Internal; diff --git a/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php b/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php index 6a7061285be..7b1746febff 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php @@ -1,28 +1,11 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Internal\Hydration; -use Doctrine\DBAL\Types\Type; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Events; -use Doctrine\ORM\Mapping\ClassMetadata; use PDO; /** @@ -41,56 +24,56 @@ abstract class AbstractHydrator * * @var \Doctrine\ORM\Query\ResultSetMapping */ - protected $_rsm; + protected $rsm; /** * The EntityManager instance. * * @var EntityManagerInterface */ - protected $_em; + protected $em; /** * The dbms Platform instance. * * @var \Doctrine\DBAL\Platforms\AbstractPlatform */ - protected $_platform; + protected $platform; /** * The UnitOfWork of the associated EntityManager. * * @var \Doctrine\ORM\UnitOfWork */ - protected $_uow; + protected $uow; /** * Local ClassMetadata cache to avoid going to the EntityManager all the time. * * @var array */ - protected $_metadataCache = []; + protected $metadataCache = []; /** * The cache used during row-by-row hydration. * * @var array */ - protected $_cache = []; + protected $cache = []; /** * The statement that provides the data to hydrate. * * @var \Doctrine\DBAL\Driver\Statement */ - protected $_stmt; + protected $stmt; /** * The query hints. * * @var array */ - protected $_hints; + protected $hints; /** * Initializes a new instance of a class derived from AbstractHydrator. @@ -99,9 +82,9 @@ abstract class AbstractHydrator */ public function __construct(EntityManagerInterface $em) { - $this->_em = $em; - $this->_platform = $em->getConnection()->getDatabasePlatform(); - $this->_uow = $em->getUnitOfWork(); + $this->em = $em; + $this->platform = $em->getConnection()->getDatabasePlatform(); + $this->uow = $em->getUnitOfWork(); } /** @@ -115,11 +98,11 @@ public function __construct(EntityManagerInterface $em) */ public function iterate($stmt, $resultSetMapping, array $hints = []) { - $this->_stmt = $stmt; - $this->_rsm = $resultSetMapping; - $this->_hints = $hints; + $this->stmt = $stmt; + $this->rsm = $resultSetMapping; + $this->hints = $hints; - $evm = $this->_em->getEventManager(); + $evm = $this->em->getEventManager(); $evm->addEventListener([Events::onClear], $this); @@ -139,9 +122,9 @@ public function iterate($stmt, $resultSetMapping, array $hints = []) */ public function hydrateAll($stmt, $resultSetMapping, array $hints = []) { - $this->_stmt = $stmt; - $this->_rsm = $resultSetMapping; - $this->_hints = $hints; + $this->stmt = $stmt; + $this->rsm = $resultSetMapping; + $this->hints = $hints; $this->prepare(); @@ -160,9 +143,9 @@ public function hydrateAll($stmt, $resultSetMapping, array $hints = []) */ public function hydrateRow() { - $row = $this->_stmt->fetch(PDO::FETCH_ASSOC); + $row = $this->stmt->fetch(PDO::FETCH_ASSOC); - if ( ! $row) { + if (! $row) { $this->cleanup(); return false; @@ -205,17 +188,16 @@ protected function prepare() */ protected function cleanup() { - $this->_stmt->closeCursor(); + $this->stmt->closeCursor(); - $this->_stmt = null; - $this->_rsm = null; - $this->_cache = []; - $this->_metadataCache = []; + $this->stmt = null; + $this->rsm = null; + $this->cache = []; + $this->metadataCache = []; - $this - ->_em - ->getEventManager() - ->removeEventListener([Events::onClear], $this); + $this->em + ->getEventManager() + ->removeEventListener([Events::onClear], $this); } /** @@ -274,7 +256,7 @@ protected function gatherRowData(array $data, array &$id, array &$nonemptyCompon $argIndex = $cacheKeyInfo['argIndex']; $objIndex = $cacheKeyInfo['objIndex']; $type = $cacheKeyInfo['type']; - $value = $type->convertToPHPValue($value, $this->_platform); + $value = $type->convertToPHPValue($value, $this->platform); $rowData['newObjects'][$objIndex]['class'] = $cacheKeyInfo['class']; $rowData['newObjects'][$objIndex]['args'][$argIndex] = $value; @@ -282,7 +264,7 @@ protected function gatherRowData(array $data, array &$id, array &$nonemptyCompon case (isset($cacheKeyInfo['isScalar'])): $type = $cacheKeyInfo['type']; - $value = $type->convertToPHPValue($value, $this->_platform); + $value = $type->convertToPHPValue($value, $this->platform); $rowData['scalars'][$fieldName] = $value; break; @@ -300,7 +282,7 @@ protected function gatherRowData(array $data, array &$id, array &$nonemptyCompon } $rowData['data'][$dqlAlias][$fieldName] = $type - ? $type->convertToPHPValue($value, $this->_platform) + ? $type->convertToPHPValue($value, $this->platform) : $value; if ($cacheKeyInfo['isIdentifier'] && $value !== null) { @@ -344,7 +326,7 @@ protected function gatherScalarRowData(&$data) $type = $cacheKeyInfo['type']; $fieldName = $dqlAlias . '_' . $fieldName; $value = $type - ? $type->convertToPHPValue($value, $this->_platform) + ? $type->convertToPHPValue($value, $this->platform) : $value; } @@ -363,61 +345,58 @@ protected function gatherScalarRowData(&$data) */ protected function hydrateColumnInfo($key) { - if (isset($this->_cache[$key])) { - return $this->_cache[$key]; + if (isset($this->cache[$key])) { + return $this->cache[$key]; } switch (true) { // NOTE: Most of the times it's a field mapping, so keep it first!!! - case (isset($this->_rsm->fieldMappings[$key])): - $classMetadata = $this->getClassMetadata($this->_rsm->declaringClasses[$key]); - $fieldName = $this->_rsm->fieldMappings[$key]; - $fieldMapping = $classMetadata->fieldMappings[$fieldName]; + case (isset($this->rsm->fieldMappings[$key])): + $classMetadata = $this->getClassMetadata($this->rsm->declaringClasses[$key]); + $fieldName = $this->rsm->fieldMappings[$key]; + $property = $classMetadata->getProperty($fieldName); - return $this->_cache[$key] = [ - 'isIdentifier' => in_array($fieldName, $classMetadata->identifier), + return $this->cache[$key] = [ + 'isIdentifier' => $property->isPrimaryKey(), 'fieldName' => $fieldName, - 'type' => Type::getType($fieldMapping['type']), - 'dqlAlias' => $this->_rsm->columnOwnerMap[$key], + 'type' => $property->getType(), + 'dqlAlias' => $this->rsm->columnOwnerMap[$key], ]; - case (isset($this->_rsm->newObjectMappings[$key])): + case (isset($this->rsm->newObjectMappings[$key])): // WARNING: A NEW object is also a scalar, so it must be declared before! - $mapping = $this->_rsm->newObjectMappings[$key]; + $mapping = $this->rsm->newObjectMappings[$key]; - return $this->_cache[$key] = [ + return $this->cache[$key] = [ 'isScalar' => true, 'isNewObjectParameter' => true, - 'fieldName' => $this->_rsm->scalarMappings[$key], - 'type' => Type::getType($this->_rsm->typeMappings[$key]), + 'fieldName' => $this->rsm->scalarMappings[$key], + 'type' => $this->rsm->typeMappings[$key], 'argIndex' => $mapping['argIndex'], 'objIndex' => $mapping['objIndex'], 'class' => new \ReflectionClass($mapping['className']), ]; - case (isset($this->_rsm->scalarMappings[$key])): - return $this->_cache[$key] = [ + case (isset($this->rsm->scalarMappings[$key])): + return $this->cache[$key] = [ 'isScalar' => true, - 'fieldName' => $this->_rsm->scalarMappings[$key], - 'type' => Type::getType($this->_rsm->typeMappings[$key]), + 'fieldName' => $this->rsm->scalarMappings[$key], + 'type' => $this->rsm->typeMappings[$key], ]; - case (isset($this->_rsm->metaMappings[$key])): + case (isset($this->rsm->metaMappings[$key])): // Meta column (has meaning in relational schema only, i.e. foreign keys or discriminator columns). - $fieldName = $this->_rsm->metaMappings[$key]; - $dqlAlias = $this->_rsm->columnOwnerMap[$key]; - $type = isset($this->_rsm->typeMappings[$key]) - ? Type::getType($this->_rsm->typeMappings[$key]) - : null; + $fieldName = $this->rsm->metaMappings[$key]; + $dqlAlias = $this->rsm->columnOwnerMap[$key]; // Cache metadata fetch - $this->getClassMetadata($this->_rsm->aliasMap[$dqlAlias]); + $this->getClassMetadata($this->rsm->aliasMap[$dqlAlias]); - return $this->_cache[$key] = [ - 'isIdentifier' => isset($this->_rsm->isIdentifierColumn[$dqlAlias][$key]), + return $this->cache[$key] = [ + 'isIdentifier' => isset($this->rsm->isIdentifierColumn[$dqlAlias][$key]), 'isMetaColumn' => true, 'fieldName' => $fieldName, - 'type' => $type, + 'type' => $this->rsm->typeMappings[$key], 'dqlAlias' => $dqlAlias, ]; } @@ -436,43 +415,10 @@ protected function hydrateColumnInfo($key) */ protected function getClassMetadata($className) { - if ( ! isset($this->_metadataCache[$className])) { - $this->_metadataCache[$className] = $this->_em->getClassMetadata($className); - } - - return $this->_metadataCache[$className]; - } - - /** - * Register entity as managed in UnitOfWork. - * - * @param ClassMetadata $class - * @param object $entity - * @param array $data - * - * @return void - * - * @todo The "$id" generation is the same of UnitOfWork#createEntity. Remove this duplication somehow - */ - protected function registerManaged(ClassMetadata $class, $entity, array $data) - { - if ($class->isIdentifierComposite) { - $id = []; - - foreach ($class->identifier as $fieldName) { - $id[$fieldName] = isset($class->associationMappings[$fieldName]) - ? $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']] - : $data[$fieldName]; - } - } else { - $fieldName = $class->identifier[0]; - $id = [ - $fieldName => isset($class->associationMappings[$fieldName]) - ? $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']] - : $data[$fieldName] - ]; + if ( ! isset($this->metadataCache[$className])) { + $this->metadataCache[$className] = $this->em->getClassMetadata($className); } - $this->_em->getUnitOfWork()->registerManaged($entity, $id, $data); + return $this->metadataCache[$className]; } } diff --git a/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php b/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php index c26b99be38c..c32e3bb9434 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php @@ -1,24 +1,10 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Internal\Hydration; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; use PDO; use Doctrine\ORM\Mapping\ClassMetadata; @@ -35,45 +21,48 @@ class ArrayHydrator extends AbstractHydrator /** * @var array */ - private $_rootAliases = []; + private $rootAliases = []; /** * @var bool */ - private $_isSimpleQuery = false; + private $isSimpleQuery = false; /** * @var array */ - private $_identifierMap = []; + private $identifierMap = []; /** * @var array */ - private $_resultPointers = []; + private $resultPointers = []; /** * @var array */ - private $_idTemplate = []; + private $idTemplate = []; /** * @var int */ - private $_resultCounter = 0; + private $resultCounter = 0; /** * {@inheritdoc} */ protected function prepare() { - $this->_isSimpleQuery = count($this->_rsm->aliasMap) <= 1; + $simpleQuery = 0; - foreach ($this->_rsm->aliasMap as $dqlAlias => $className) { - $this->_identifierMap[$dqlAlias] = []; - $this->_resultPointers[$dqlAlias] = []; - $this->_idTemplate[$dqlAlias] = ''; + foreach ($this->rsm->aliasMap as $dqlAlias => $className) { + $this->identifierMap[$dqlAlias] = []; + $this->resultPointers[$dqlAlias] = []; + $this->idTemplate[$dqlAlias] = ''; + $simpleQuery += 1; // avoiding counting the alias map } + + $this->isSimpleQuery = $simpleQuery < 2; } /** @@ -83,7 +72,7 @@ protected function hydrateAllData() { $result = []; - while ($data = $this->_stmt->fetch(PDO::FETCH_ASSOC)) { + while ($data = $this->stmt->fetch(PDO::FETCH_ASSOC)) { $this->hydrateRowData($data, $result); } @@ -96,7 +85,7 @@ protected function hydrateAllData() protected function hydrateRowData(array $row, array &$result) { // 1) Initialize - $id = $this->_idTemplate; // initialize the id-memory + $id = $this->idTemplate; // initialize the id-memory $nonemptyComponents = []; $rowData = $this->gatherRowData($row, $id, $nonemptyComponents); @@ -104,10 +93,10 @@ protected function hydrateRowData(array $row, array &$result) foreach ($rowData['data'] as $dqlAlias => $data) { $index = false; - if (isset($this->_rsm->parentAliasMap[$dqlAlias])) { + if (isset($this->rsm->parentAliasMap[$dqlAlias])) { // It's a joined result - $parent = $this->_rsm->parentAliasMap[$dqlAlias]; + $parent = $this->rsm->parentAliasMap[$dqlAlias]; $path = $parent . '.' . $dqlAlias; // missing parent data, skipping as RIGHT JOIN hydration is not supported. @@ -117,24 +106,24 @@ protected function hydrateRowData(array $row, array &$result) // Get a reference to the right element in the result tree. // This element will get the associated element attached. - if ($this->_rsm->isMixed && isset($this->_rootAliases[$parent])) { - $first = reset($this->_resultPointers); + if ($this->rsm->isMixed && isset($this->rootAliases[$parent])) { + $first = reset($this->resultPointers); // TODO: Exception if $key === null ? - $baseElement =& $this->_resultPointers[$parent][key($first)]; - } else if (isset($this->_resultPointers[$parent])) { - $baseElement =& $this->_resultPointers[$parent]; + $baseElement =& $this->resultPointers[$parent][key($first)]; + } else if (isset($this->resultPointers[$parent])) { + $baseElement =& $this->resultPointers[$parent]; } else { - unset($this->_resultPointers[$dqlAlias]); // Ticket #1228 + unset($this->resultPointers[$dqlAlias]); // Ticket #1228 continue; } - $relationAlias = $this->_rsm->relationMap[$dqlAlias]; - $parentClass = $this->_metadataCache[$this->_rsm->aliasMap[$parent]]; - $relation = $parentClass->associationMappings[$relationAlias]; + $relationAlias = $this->rsm->relationMap[$dqlAlias]; + $parentClass = $this->metadataCache[$this->rsm->aliasMap[$parent]]; + $relation = $parentClass->getProperty($relationAlias); // Check the type of the relation (many or single-valued) - if ( ! ($relation['type'] & ClassMetadata::TO_ONE)) { + if (! $relation instanceof ToOneAssociationMetadata) { $oneToOne = false; if ( ! isset($baseElement[$relationAlias])) { @@ -142,22 +131,22 @@ protected function hydrateRowData(array $row, array &$result) } if (isset($nonemptyComponents[$dqlAlias])) { - $indexExists = isset($this->_identifierMap[$path][$id[$parent]][$id[$dqlAlias]]); - $index = $indexExists ? $this->_identifierMap[$path][$id[$parent]][$id[$dqlAlias]] : false; + $indexExists = isset($this->identifierMap[$path][$id[$parent]][$id[$dqlAlias]]); + $index = $indexExists ? $this->identifierMap[$path][$id[$parent]][$id[$dqlAlias]] : false; $indexIsValid = $index !== false ? isset($baseElement[$relationAlias][$index]) : false; if ( ! $indexExists || ! $indexIsValid) { $element = $data; - if (isset($this->_rsm->indexByMap[$dqlAlias])) { - $baseElement[$relationAlias][$row[$this->_rsm->indexByMap[$dqlAlias]]] = $element; + if (isset($this->rsm->indexByMap[$dqlAlias])) { + $baseElement[$relationAlias][$row[$this->rsm->indexByMap[$dqlAlias]]] = $element; } else { $baseElement[$relationAlias][] = $element; } end($baseElement[$relationAlias]); - $this->_identifierMap[$path][$id[$parent]][$id[$dqlAlias]] = key($baseElement[$relationAlias]); + $this->identifierMap[$path][$id[$parent]][$id[$dqlAlias]] = key($baseElement[$relationAlias]); } } } else { @@ -181,40 +170,40 @@ protected function hydrateRowData(array $row, array &$result) } else { // It's a root result element - $this->_rootAliases[$dqlAlias] = true; // Mark as root - $entityKey = $this->_rsm->entityMappings[$dqlAlias] ?: 0; + $this->rootAliases[$dqlAlias] = true; // Mark as root + $entityKey = $this->rsm->entityMappings[$dqlAlias] ?: 0; // if this row has a NULL value for the root result id then make it a null result. if ( ! isset($nonemptyComponents[$dqlAlias]) ) { - $result[] = $this->_rsm->isMixed + $result[] = $this->rsm->isMixed ? [$entityKey => null] : null; - $resultKey = $this->_resultCounter; - ++$this->_resultCounter; + $resultKey = $this->resultCounter; + ++$this->resultCounter; continue; } // Check for an existing element - if ($this->_isSimpleQuery || ! isset($this->_identifierMap[$dqlAlias][$id[$dqlAlias]])) { - $element = $this->_rsm->isMixed + if ($this->isSimpleQuery || ! isset($this->identifierMap[$dqlAlias][$id[$dqlAlias]])) { + $element = $this->rsm->isMixed ? [$entityKey => $data] : $data; - if (isset($this->_rsm->indexByMap[$dqlAlias])) { - $resultKey = $row[$this->_rsm->indexByMap[$dqlAlias]]; + if (isset($this->rsm->indexByMap[$dqlAlias])) { + $resultKey = $row[$this->rsm->indexByMap[$dqlAlias]]; $result[$resultKey] = $element; } else { - $resultKey = $this->_resultCounter; + $resultKey = $this->resultCounter; $result[] = $element; - ++$this->_resultCounter; + ++$this->resultCounter; } - $this->_identifierMap[$dqlAlias][$id[$dqlAlias]] = $resultKey; + $this->identifierMap[$dqlAlias][$id[$dqlAlias]] = $resultKey; } else { - $index = $this->_identifierMap[$dqlAlias][$id[$dqlAlias]]; + $index = $this->identifierMap[$dqlAlias][$id[$dqlAlias]]; $resultKey = $index; } @@ -223,16 +212,16 @@ protected function hydrateRowData(array $row, array &$result) } if ( ! isset($resultKey)) { - $this->_resultCounter++; + $this->resultCounter++; } // Append scalar values to mixed result sets if (isset($rowData['scalars'])) { if ( ! isset($resultKey)) { // this only ever happens when no object is fetched (scalar result only) - $resultKey = isset($this->_rsm->indexByMap['scalars']) - ? $row[$this->_rsm->indexByMap['scalars']] - : $this->_resultCounter - 1; + $resultKey = isset($this->rsm->indexByMap['scalars']) + ? $row[$this->rsm->indexByMap['scalars']] + : $this->resultCounter - 1; } foreach ($rowData['scalars'] as $name => $value) { @@ -243,17 +232,18 @@ protected function hydrateRowData(array $row, array &$result) // Append new object to mixed result sets if (isset($rowData['newObjects'])) { if ( ! isset($resultKey)) { - $resultKey = $this->_resultCounter - 1; + $resultKey = $this->resultCounter - 1; } $scalarCount = (isset($rowData['scalars'])? count($rowData['scalars']): 0); + $onlyOneRootAlias = 0 === $scalarCount && 1 === count($rowData['newObjects']); foreach ($rowData['newObjects'] as $objIndex => $newObject) { $class = $newObject['class']; $args = $newObject['args']; $obj = $class->newInstanceArgs($args); - if (count($args) == $scalarCount || ($scalarCount == 0 && count($rowData['newObjects']) == 1)) { + if ($onlyOneRootAlias || \count($args) === $scalarCount) { $result[$resultKey] = $obj; continue; @@ -278,19 +268,19 @@ protected function hydrateRowData(array $row, array &$result) private function updateResultPointer(array &$coll, $index, $dqlAlias, $oneToOne) { if ($coll === null) { - unset($this->_resultPointers[$dqlAlias]); // Ticket #1228 + unset($this->resultPointers[$dqlAlias]); // Ticket #1228 return; } if ($oneToOne) { - $this->_resultPointers[$dqlAlias] =& $coll; + $this->resultPointers[$dqlAlias] =& $coll; return; } if ($index !== false) { - $this->_resultPointers[$dqlAlias] =& $coll[$index]; + $this->resultPointers[$dqlAlias] =& $coll[$index]; return; } @@ -300,7 +290,7 @@ private function updateResultPointer(array &$coll, $index, $dqlAlias, $oneToOne) } end($coll); - $this->_resultPointers[$dqlAlias] =& $coll[key($coll)]; + $this->resultPointers[$dqlAlias] =& $coll[key($coll)]; return; } diff --git a/lib/Doctrine/ORM/Internal/Hydration/HydrationException.php b/lib/Doctrine/ORM/Internal/Hydration/HydrationException.php index 9caf03ddfb9..e2b0a0f8d59 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/HydrationException.php +++ b/lib/Doctrine/ORM/Internal/Hydration/HydrationException.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Internal\Hydration; diff --git a/lib/Doctrine/ORM/Internal/Hydration/IterableResult.php b/lib/Doctrine/ORM/Internal/Hydration/IterableResult.php index 1774ca0305b..5dc674c280c 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/IterableResult.php +++ b/lib/Doctrine/ORM/Internal/Hydration/IterableResult.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Internal\Hydration; @@ -31,29 +16,29 @@ class IterableResult implements \Iterator /** * @var \Doctrine\ORM\Internal\Hydration\AbstractHydrator */ - private $_hydrator; + private $hydrator; /** * @var boolean */ - private $_rewinded = false; + private $rewinded = false; /** * @var integer */ - private $_key = -1; + private $key = -1; /** * @var object|null */ - private $_current = null; + private $current = null; /** * @param \Doctrine\ORM\Internal\Hydration\AbstractHydrator $hydrator */ public function __construct($hydrator) { - $this->_hydrator = $hydrator; + $this->hydrator = $hydrator; } /** @@ -63,11 +48,11 @@ public function __construct($hydrator) */ public function rewind() { - if ($this->_rewinded == true) { + if ($this->rewinded == true) { throw new HydrationException("Can only iterate a Result once."); } else { - $this->_current = $this->next(); - $this->_rewinded = true; + $this->current = $this->next(); + $this->rewinded = true; } } @@ -78,10 +63,10 @@ public function rewind() */ public function next() { - $this->_current = $this->_hydrator->hydrateRow(); - $this->_key++; + $this->current = $this->hydrator->hydrateRow(); + $this->key++; - return $this->_current; + return $this->current; } /** @@ -89,7 +74,7 @@ public function next() */ public function current() { - return $this->_current; + return $this->current; } /** @@ -97,7 +82,7 @@ public function current() */ public function key() { - return $this->_key; + return $this->key; } /** @@ -105,6 +90,6 @@ public function key() */ public function valid() { - return ($this->_current!=false); + return ($this->current!=false); } } diff --git a/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php b/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php index 42f59973942..c415ef4a45a 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php @@ -1,31 +1,20 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Internal\Hydration; -use Doctrine\ORM\UnitOfWork; +use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; use PDO; +use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\ORM\Event\PostLoadEventDispatcher; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\PersistentCollection; -use Doctrine\ORM\Query; -use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Proxy\Proxy; +use Doctrine\ORM\Query; +use Doctrine\ORM\UnitOfWork; /** * The ObjectHydrator constructs an object graph out of an SQL result set. @@ -79,53 +68,53 @@ class ObjectHydrator extends AbstractHydrator */ protected function prepare() { - if ( ! isset($this->_hints[UnitOfWork::HINT_DEFEREAGERLOAD])) { - $this->_hints[UnitOfWork::HINT_DEFEREAGERLOAD] = true; + if (! isset($this->hints[UnitOfWork::HINT_DEFEREAGERLOAD])) { + $this->hints[UnitOfWork::HINT_DEFEREAGERLOAD] = true; } - foreach ($this->_rsm->aliasMap as $dqlAlias => $className) { + foreach ($this->rsm->aliasMap as $dqlAlias => $className) { $this->identifierMap[$dqlAlias] = []; $this->idTemplate[$dqlAlias] = ''; // Remember which associations are "fetch joined", so that we know where to inject // collection stubs or proxies and where not. - if ( ! isset($this->_rsm->relationMap[$dqlAlias])) { + if (! isset($this->rsm->relationMap[$dqlAlias])) { continue; } - $parent = $this->_rsm->parentAliasMap[$dqlAlias]; + $parent = $this->rsm->parentAliasMap[$dqlAlias]; - if ( ! isset($this->_rsm->aliasMap[$parent])) { + if (! isset($this->rsm->aliasMap[$parent])) { throw HydrationException::parentObjectOfRelationNotFound($dqlAlias, $parent); } - $sourceClassName = $this->_rsm->aliasMap[$parent]; + $sourceClassName = $this->rsm->aliasMap[$parent]; $sourceClass = $this->getClassMetadata($sourceClassName); - $assoc = $sourceClass->associationMappings[$this->_rsm->relationMap[$dqlAlias]]; + $association = $sourceClass->getProperty($this->rsm->relationMap[$dqlAlias]); - $this->_hints['fetched'][$parent][$assoc['fieldName']] = true; + $this->hints['fetched'][$parent][$association->getName()] = true; - if ($assoc['type'] === ClassMetadata::MANY_TO_MANY) { + if ($association instanceof ManyToManyAssociationMetadata) { continue; } // Mark any non-collection opposite sides as fetched, too. - if ($assoc['mappedBy']) { - $this->_hints['fetched'][$dqlAlias][$assoc['mappedBy']] = true; + if ($association->getMappedBy()) { + $this->hints['fetched'][$dqlAlias][$association->getMappedBy()] = true; continue; } // handle fetch-joined owning side bi-directional one-to-one associations - if ($assoc['inversedBy']) { + if ($association->getInversedBy()) { $class = $this->getClassMetadata($className); - $inverseAssoc = $class->associationMappings[$assoc['inversedBy']]; + $inverseAssoc = $class->getProperty($association->getInversedBy()); - if ( ! ($inverseAssoc['type'] & ClassMetadata::TO_ONE)) { + if (! ($inverseAssoc instanceof ToOneAssociationMetadata)) { continue; } - $this->_hints['fetched'][$dqlAlias][$inverseAssoc['fieldName']] = true; + $this->hints['fetched'][$dqlAlias][$inverseAssoc->getName()] = true; } } } @@ -135,7 +124,7 @@ protected function prepare() */ protected function cleanup() { - $eagerLoad = (isset($this->_hints[UnitOfWork::HINT_DEFEREAGERLOAD])) && $this->_hints[UnitOfWork::HINT_DEFEREAGERLOAD] == true; + $eagerLoad = (isset($this->hints[UnitOfWork::HINT_DEFEREAGERLOAD])) && $this->hints[UnitOfWork::HINT_DEFEREAGERLOAD] == true; parent::cleanup(); @@ -145,10 +134,10 @@ protected function cleanup() $this->resultPointers = []; if ($eagerLoad) { - $this->_uow->triggerEagerLoads(); + $this->uow->triggerEagerLoads(); } - $this->_uow->hydrationComplete(); + $this->uow->hydrationComplete(); } /** @@ -158,7 +147,7 @@ protected function hydrateAllData() { $result = []; - while ($row = $this->_stmt->fetch(PDO::FETCH_ASSOC)) { + while ($row = $this->stmt->fetch(PDO::FETCH_ASSOC)) { $this->hydrateRowData($row, $result); } @@ -182,28 +171,22 @@ protected function hydrateAllData() */ private function initRelatedCollection($entity, $class, $fieldName, $parentDqlAlias) { - $oid = spl_object_hash($entity); - $relation = $class->associationMappings[$fieldName]; - $value = $class->reflFields[$fieldName]->getValue($entity); + /** @var ToManyAssociationMetadata $association */ + $association = $class->getProperty($fieldName); + $value = $association->getValue($entity); + $oid = spl_object_hash($entity); - if ($value === null || is_array($value)) { - $value = new ArrayCollection((array) $value); - } + if (! $value instanceof PersistentCollection) { + $value = $association->wrap($entity, $value, $this->em); - if ( ! $value instanceof PersistentCollection) { - $value = new PersistentCollection( - $this->_em, $this->_metadataCache[$relation['targetEntity']], $value - ); - $value->setOwner($entity, $relation); + $association->setValue($entity, $value); - $class->reflFields[$fieldName]->setValue($entity, $value); - $this->_uow->setOriginalEntityProperty($oid, $fieldName, $value); + $this->uow->setOriginalEntityProperty($oid, $fieldName, $value); $this->initializedCollections[$oid . $fieldName] = $value; } else if ( - isset($this->_hints[Query::HINT_REFRESH]) || - isset($this->_hints['fetched'][$parentDqlAlias][$fieldName]) && - ! $value->isInitialized() + isset($this->hints[Query::HINT_REFRESH]) || + (isset($this->hints['fetched'][$parentDqlAlias][$fieldName]) && ! $value->isInitialized()) ) { // Is already PersistentCollection, but either REFRESH or FETCH-JOIN and UNINITIALIZED! $value->setDirty(false); @@ -231,16 +214,16 @@ private function initRelatedCollection($entity, $class, $fieldName, $parentDqlAl */ private function getEntity(array $data, $dqlAlias) { - $className = $this->_rsm->aliasMap[$dqlAlias]; + $className = $this->rsm->aliasMap[$dqlAlias]; - if (isset($this->_rsm->discriminatorColumns[$dqlAlias])) { - $fieldName = $this->_rsm->discriminatorColumns[$dqlAlias]; + if (isset($this->rsm->discriminatorColumns[$dqlAlias])) { + $fieldName = $this->rsm->discriminatorColumns[$dqlAlias]; - if ( ! isset($this->_rsm->metaMappings[$fieldName])) { + if ( ! isset($this->rsm->metaMappings[$fieldName])) { throw HydrationException::missingDiscriminatorMetaMappingColumn($className, $fieldName, $dqlAlias); } - $discrColumn = $this->_rsm->metaMappings[$fieldName]; + $discrColumn = $this->rsm->metaMappings[$fieldName]; if ( ! isset($data[$discrColumn])) { throw HydrationException::missingDiscriminatorColumn($className, $discrColumn, $dqlAlias); @@ -250,7 +233,7 @@ private function getEntity(array $data, $dqlAlias) throw HydrationException::emptyDiscriminatorValue($dqlAlias); } - $discrMap = $this->_metadataCache[$className]->discriminatorMap; + $discrMap = $this->metadataCache[$className]->discriminatorMap; $discriminatorValue = (string) $data[$discrColumn]; if ( ! isset($discrMap[$discriminatorValue])) { @@ -262,13 +245,15 @@ private function getEntity(array $data, $dqlAlias) unset($data[$discrColumn]); } - if (isset($this->_hints[Query::HINT_REFRESH_ENTITY]) && isset($this->rootAliases[$dqlAlias])) { - $this->registerManaged($this->_metadataCache[$className], $this->_hints[Query::HINT_REFRESH_ENTITY], $data); + if (isset($this->hints[Query::HINT_REFRESH_ENTITY]) && isset($this->rootAliases[$dqlAlias])) { + $id = $this->em->getIdentifierFlattener()->flattenIdentifier($this->metadataCache[$className], $data); + + $this->em->getUnitOfWork()->registerManaged($this->hints[Query::HINT_REFRESH_ENTITY], $id, $data); } - $this->_hints['fetchAlias'] = $dqlAlias; + $this->hints['fetchAlias'] = $dqlAlias; - return $this->_uow->createEntity($className, $data, $this->_hints); + return $this->uow->createEntity($className, $data, $this->hints); } /** @@ -279,25 +264,11 @@ private function getEntity(array $data, $dqlAlias) */ private function getEntityFromIdentityMap($className, array $data) { - // TODO: Abstract this code and UnitOfWork::createEntity() equivalent? - $class = $this->_metadataCache[$className]; - - /* @var $class ClassMetadata */ - if ($class->isIdentifierComposite) { - $idHash = ''; + /* @var ClassMetadata $class */ + $class = $this->metadataCache[$className]; + $id = $this->em->getIdentifierFlattener()->flattenIdentifier($class, $data); - foreach ($class->identifier as $fieldName) { - $idHash .= ' ' . (isset($class->associationMappings[$fieldName]) - ? $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']] - : $data[$fieldName]); - } - - return $this->_uow->tryGetByIdHash(ltrim($idHash), $class->rootEntityName); - } else if (isset($class->associationMappings[$class->identifier[0]])) { - return $this->_uow->tryGetByIdHash($data[$class->associationMappings[$class->identifier[0]]['joinColumns'][0]['name']], $class->rootEntityName); - } - - return $this->_uow->tryGetByIdHash($data[$class->identifier[0]], $class->rootEntityName); + return $this->uow->tryGetById($id, $class->getRootClassName()); } /** @@ -335,29 +306,28 @@ protected function hydrateRowData(array $row, array &$result) // Hydrate the data chunks foreach ($rowData['data'] as $dqlAlias => $data) { - $entityName = $this->_rsm->aliasMap[$dqlAlias]; + $entityName = $this->rsm->aliasMap[$dqlAlias]; - if (isset($this->_rsm->parentAliasMap[$dqlAlias])) { + if (isset($this->rsm->parentAliasMap[$dqlAlias])) { // It's a joined result - $parentAlias = $this->_rsm->parentAliasMap[$dqlAlias]; + $parentAlias = $this->rsm->parentAliasMap[$dqlAlias]; // we need the $path to save into the identifier map which entities were already // seen for this parent-child relationship $path = $parentAlias . '.' . $dqlAlias; // We have a RIGHT JOIN result here. Doctrine cannot hydrate RIGHT JOIN Object-Graphs - if ( ! isset($nonemptyComponents[$parentAlias])) { + if (! isset($nonemptyComponents[$parentAlias])) { // TODO: Add special case code where we hydrate the right join objects into identity map at least continue; } - $parentClass = $this->_metadataCache[$this->_rsm->aliasMap[$parentAlias]]; - $relationField = $this->_rsm->relationMap[$dqlAlias]; - $relation = $parentClass->associationMappings[$relationField]; - $reflField = $parentClass->reflFields[$relationField]; + $parentClass = $this->metadataCache[$this->rsm->aliasMap[$parentAlias]]; + $relationField = $this->rsm->relationMap[$dqlAlias]; + $association = $parentClass->getProperty($relationField); // Get a reference to the parent object to which the joined element belongs. - if ($this->_rsm->isMixed && isset($this->rootAliases[$parentAlias])) { + if ($this->rsm->isMixed && isset($this->rootAliases[$parentAlias])) { $objectClass = $this->resultPointers[$parentAlias]; $parentObject = $objectClass[key($objectClass)]; } else if (isset($this->resultPointers[$parentAlias])) { @@ -371,22 +341,22 @@ protected function hydrateRowData(array $row, array &$result) $rowData['data'][$parentAlias][$relationField] = $element; // Mark as not-fetched again - unset($this->_hints['fetched'][$parentAlias][$relationField]); + unset($this->hints['fetched'][$parentAlias][$relationField]); continue; } $oid = spl_object_hash($parentObject); // Check the type of the relation (many or single-valued) - if ( ! ($relation['type'] & ClassMetadata::TO_ONE)) { + if (! ($association instanceof ToOneAssociationMetadata)) { // PATH A: Collection-valued association - $reflFieldValue = $reflField->getValue($parentObject); + $reflFieldValue = $association->getValue($parentObject); if (isset($nonemptyComponents[$dqlAlias])) { $collKey = $oid . $relationField; if (isset($this->initializedCollections[$collKey])) { $reflFieldValue = $this->initializedCollections[$collKey]; - } else if ( ! isset($this->existingCollections[$collKey])) { + } else if (! isset($this->existingCollections[$collKey])) { $reflFieldValue = $this->initRelatedCollection($parentObject, $parentClass, $relationField, $parentAlias); } @@ -394,7 +364,7 @@ protected function hydrateRowData(array $row, array &$result) $index = $indexExists ? $this->identifierMap[$path][$id[$parentAlias]][$id[$dqlAlias]] : false; $indexIsValid = $index !== false ? isset($reflFieldValue[$index]) : false; - if ( ! $indexExists || ! $indexIsValid) { + if (! $indexExists || ! $indexIsValid) { if (isset($this->existingCollections[$collKey])) { // Collection exists, only look for the element in the identity map. if ($element = $this->getEntityFromIdentityMap($entityName, $data)) { @@ -405,8 +375,8 @@ protected function hydrateRowData(array $row, array &$result) } else { $element = $this->getEntity($data, $dqlAlias); - if (isset($this->_rsm->indexByMap[$dqlAlias])) { - $indexValue = $row[$this->_rsm->indexByMap[$dqlAlias]]; + if (isset($this->rsm->indexByMap[$dqlAlias])) { + $indexValue = $row[$this->rsm->indexByMap[$dqlAlias]]; $reflFieldValue->hydrateSet($indexValue, $element); $this->identifierMap[$path][$id[$parentAlias]][$id[$dqlAlias]] = $indexValue; } else { @@ -426,45 +396,60 @@ protected function hydrateRowData(array $row, array &$result) } else if ($reflFieldValue instanceof PersistentCollection && $reflFieldValue->isInitialized() === false) { $reflFieldValue->setInitialized(true); } - } else { // PATH B: Single-valued association - $reflFieldValue = $reflField->getValue($parentObject); + $reflFieldValue = $association->getValue($parentObject); - if ( ! $reflFieldValue || isset($this->_hints[Query::HINT_REFRESH]) || ($reflFieldValue instanceof Proxy && !$reflFieldValue->__isInitialized__)) { + if (! $reflFieldValue || isset($this->hints[Query::HINT_REFRESH]) || + ($reflFieldValue instanceof Proxy && ! $reflFieldValue->__isInitialized())) { // we only need to take action if this value is null, // we refresh the entity or its an uninitialized proxy. if (isset($nonemptyComponents[$dqlAlias])) { $element = $this->getEntity($data, $dqlAlias); - $reflField->setValue($parentObject, $element); - $this->_uow->setOriginalEntityProperty($oid, $relationField, $element); - $targetClass = $this->_metadataCache[$relation['targetEntity']]; - if ($relation['isOwningSide']) { + $association->setValue($parentObject, $element); + $this->uow->setOriginalEntityProperty($oid, $relationField, $element); + + $mappedBy = $association->getMappedBy(); + $targetClass = $this->metadataCache[$association->getTargetEntity()]; + + if ($association->isOwningSide()) { // TODO: Just check hints['fetched'] here? // If there is an inverse mapping on the target class its bidirectional - if ($relation['inversedBy']) { - $inverseAssoc = $targetClass->associationMappings[$relation['inversedBy']]; - if ($inverseAssoc['type'] & ClassMetadata::TO_ONE) { - $targetClass->reflFields[$inverseAssoc['fieldName']]->setValue($element, $parentObject); - $this->_uow->setOriginalEntityProperty(spl_object_hash($element), $inverseAssoc['fieldName'], $parentObject); + if ($association->getInversedBy()) { + $inverseAssociation = $targetClass->getProperty($association->getInversedBy()); + + if ($inverseAssociation instanceof ToOneAssociationMetadata) { + $inverseAssociation->setValue($element, $parentObject); + + $this->uow->setOriginalEntityProperty( + spl_object_hash($element), + $inverseAssociation->getName(), + $parentObject + ); } - } else if ($parentClass === $targetClass && $relation['mappedBy']) { - // Special case: bi-directional self-referencing one-one on the same class - $targetClass->reflFields[$relationField]->setValue($element, $parentObject); } } else { // For sure bidirectional, as there is no inverse side in unidirectional mappings - $targetClass->reflFields[$relation['mappedBy']]->setValue($element, $parentObject); - $this->_uow->setOriginalEntityProperty(spl_object_hash($element), $relation['mappedBy'], $parentObject); + $inverseAssociation = $targetClass->getProperty($mappedBy); + + $inverseAssociation->setValue($element, $parentObject); + + $this->uow->setOriginalEntityProperty( + spl_object_hash($element), + $mappedBy, + $parentObject + ); } + // Update result pointer $this->resultPointers[$dqlAlias] = $element; } else { - $this->_uow->setOriginalEntityProperty($oid, $relationField, null); - $reflField->setValue($parentObject, null); + $association->setValue($parentObject, null); + + $this->uow->setOriginalEntityProperty($oid, $relationField, null); } - // else leave $reflFieldValue null for single-valued associations + // else leave $reflFieldValue null for single-valued associations } else { // Update result pointer $this->resultPointers[$dqlAlias] = $reflFieldValue; @@ -473,11 +458,11 @@ protected function hydrateRowData(array $row, array &$result) } else { // PATH C: Its a root result element $this->rootAliases[$dqlAlias] = true; // Mark as root alias - $entityKey = $this->_rsm->entityMappings[$dqlAlias] ?: 0; + $entityKey = $this->rsm->entityMappings[$dqlAlias] ?: 0; // if this row has a NULL value for the root result id then make it a null result. if ( ! isset($nonemptyComponents[$dqlAlias]) ) { - if ($this->_rsm->isMixed) { + if ($this->rsm->isMixed) { $result[] = [$entityKey => null]; } else { $result[] = null; @@ -491,15 +476,15 @@ protected function hydrateRowData(array $row, array &$result) if ( ! isset($this->identifierMap[$dqlAlias][$id[$dqlAlias]])) { $element = $this->getEntity($data, $dqlAlias); - if ($this->_rsm->isMixed) { + if ($this->rsm->isMixed) { $element = [$entityKey => $element]; } - if (isset($this->_rsm->indexByMap[$dqlAlias])) { - $resultKey = $row[$this->_rsm->indexByMap[$dqlAlias]]; + if (isset($this->rsm->indexByMap[$dqlAlias])) { + $resultKey = $row[$this->rsm->indexByMap[$dqlAlias]]; - if (isset($this->_hints['collection'])) { - $this->_hints['collection']->hydrateSet($resultKey, $element); + if (isset($this->hints['collection'])) { + $this->hints['collection']->hydrateSet($resultKey, $element); } $result[$resultKey] = $element; @@ -507,8 +492,8 @@ protected function hydrateRowData(array $row, array &$result) $resultKey = $this->resultCounter; ++$this->resultCounter; - if (isset($this->_hints['collection'])) { - $this->_hints['collection']->hydrateAdd($element); + if (isset($this->hints['collection'])) { + $this->hints['collection']->hydrateAdd($element); } $result[] = $element; @@ -527,8 +512,8 @@ protected function hydrateRowData(array $row, array &$result) } } - if (isset($this->_hints[Query::HINT_INTERNAL_ITERATION]) && $this->_hints[Query::HINT_INTERNAL_ITERATION]) { - $this->_uow->hydrationComplete(); + if (isset($this->hints[Query::HINT_INTERNAL_ITERATION]) && $this->hints[Query::HINT_INTERNAL_ITERATION]) { + $this->uow->hydrationComplete(); } } @@ -539,8 +524,8 @@ protected function hydrateRowData(array $row, array &$result) // Append scalar values to mixed result sets if (isset($rowData['scalars'])) { if ( ! isset($resultKey) ) { - $resultKey = (isset($this->_rsm->indexByMap['scalars'])) - ? $row[$this->_rsm->indexByMap['scalars']] + $resultKey = (isset($this->rsm->indexByMap['scalars'])) + ? $row[$this->rsm->indexByMap['scalars']] : $this->resultCounter - 1; } @@ -556,14 +541,14 @@ protected function hydrateRowData(array $row, array &$result) } - $scalarCount = (isset($rowData['scalars'])? count($rowData['scalars']): 0); + $hasNoScalars = ! (isset($rowData['scalars']) && $rowData['scalars']); foreach ($rowData['newObjects'] as $objIndex => $newObject) { $class = $newObject['class']; $args = $newObject['args']; $obj = $class->newInstanceArgs($args); - if ($scalarCount == 0 && count($rowData['newObjects']) == 1 ) { + if ($hasNoScalars && \count($rowData['newObjects']) === 1 ) { $result[$resultKey] = $obj; continue; @@ -586,7 +571,7 @@ public function onClear($eventArgs) { parent::onClear($eventArgs); - $aliases = array_keys($this->identifierMap); + $aliases = array_keys($this->identifierMap); $this->identifierMap = array_fill_keys($aliases, []); } diff --git a/lib/Doctrine/ORM/Internal/Hydration/ScalarHydrator.php b/lib/Doctrine/ORM/Internal/Hydration/ScalarHydrator.php index 093e89c4e13..e1e3c36af8a 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/ScalarHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/ScalarHydrator.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Internal\Hydration; @@ -37,7 +22,7 @@ protected function hydrateAllData() { $result = []; - while ($data = $this->_stmt->fetch(\PDO::FETCH_ASSOC)) { + while ($data = $this->stmt->fetch(\PDO::FETCH_ASSOC)) { $this->hydrateRowData($data, $result); } diff --git a/lib/Doctrine/ORM/Internal/Hydration/SimpleObjectHydrator.php b/lib/Doctrine/ORM/Internal/Hydration/SimpleObjectHydrator.php index bf2beaba347..f8a0806fa13 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/SimpleObjectHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/SimpleObjectHydrator.php @@ -1,24 +1,10 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Internal\Hydration; +use Doctrine\ORM\Mapping\InheritanceType; use PDO; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Query; @@ -35,15 +21,15 @@ class SimpleObjectHydrator extends AbstractHydrator */ protected function prepare() { - if (count($this->_rsm->aliasMap) !== 1) { + if (count($this->rsm->aliasMap) !== 1) { throw new \RuntimeException("Cannot use SimpleObjectHydrator with a ResultSetMapping that contains more than one object result."); } - if ($this->_rsm->scalarMappings) { + if ($this->rsm->scalarMappings) { throw new \RuntimeException("Cannot use SimpleObjectHydrator with a ResultSetMapping that contains scalar mappings."); } - $this->class = $this->getClassMetadata(reset($this->_rsm->aliasMap)); + $this->class = $this->getClassMetadata(reset($this->rsm->aliasMap)); } /** @@ -53,8 +39,8 @@ protected function cleanup() { parent::cleanup(); - $this->_uow->triggerEagerLoads(); - $this->_uow->hydrationComplete(); + $this->uow->triggerEagerLoads(); + $this->uow->hydrationComplete(); } /** @@ -64,11 +50,11 @@ protected function hydrateAllData() { $result = []; - while ($row = $this->_stmt->fetch(PDO::FETCH_ASSOC)) { + while ($row = $this->stmt->fetch(PDO::FETCH_ASSOC)) { $this->hydrateRowData($row, $result); } - $this->_em->getUnitOfWork()->triggerEagerLoads(); + $this->em->getUnitOfWork()->triggerEagerLoads(); return $result; } @@ -78,24 +64,24 @@ protected function hydrateAllData() */ protected function hydrateRowData(array $sqlResult, array &$result) { - $entityName = $this->class->name; + $entityName = $this->class->getClassName(); $data = []; // We need to find the correct entity class name if we have inheritance in resultset - if ($this->class->inheritanceType !== ClassMetadata::INHERITANCE_TYPE_NONE) { - $discrColumnName = $this->_platform->getSQLResultCasing($this->class->discriminatorColumn['name']); + if ($this->class->inheritanceType !== InheritanceType::NONE) { + $discrColumnName = $this->platform->getSQLResultCasing($this->class->discriminatorColumn->getColumnName()); // Find mapped discriminator column from the result set. - if ($metaMappingDiscrColumnName = array_search($discrColumnName, $this->_rsm->metaMappings)) { + if ($metaMappingDiscrColumnName = array_search($discrColumnName, $this->rsm->metaMappings)) { $discrColumnName = $metaMappingDiscrColumnName; } if ( ! isset($sqlResult[$discrColumnName])) { - throw HydrationException::missingDiscriminatorColumn($entityName, $discrColumnName, key($this->_rsm->aliasMap)); + throw HydrationException::missingDiscriminatorColumn($entityName, $discrColumnName, key($this->rsm->aliasMap)); } if ($sqlResult[$discrColumnName] === '') { - throw HydrationException::emptyDiscriminatorValue(key($this->_rsm->aliasMap)); + throw HydrationException::emptyDiscriminatorValue(key($this->rsm->aliasMap)); } $discrMap = $this->class->discriminatorMap; @@ -111,7 +97,7 @@ protected function hydrateRowData(array $sqlResult, array &$result) foreach ($sqlResult as $column => $value) { // An ObjectHydrator should be used instead of SimpleObjectHydrator - if (isset($this->_rsm->relationMap[$column])) { + if (isset($this->rsm->relationMap[$column])) { throw new \Exception(sprintf('Unable to retrieve association information for column "%s"', $column)); } @@ -127,7 +113,7 @@ protected function hydrateRowData(array $sqlResult, array &$result) // Convert field to a valid PHP value if (isset($cacheKeyInfo['type'])) { $type = $cacheKeyInfo['type']; - $value = $type->convertToPHPValue($value, $this->_platform); + $value = $type->convertToPHPValue($value, $this->platform); } $fieldName = $cacheKeyInfo['fieldName']; @@ -138,17 +124,19 @@ protected function hydrateRowData(array $sqlResult, array &$result) } } - if (isset($this->_hints[Query::HINT_REFRESH_ENTITY])) { - $this->registerManaged($this->class, $this->_hints[Query::HINT_REFRESH_ENTITY], $data); + if (isset($this->hints[Query::HINT_REFRESH_ENTITY])) { + $id = $this->em->getIdentifierFlattener()->flattenIdentifier($this->class, $data); + + $this->em->getUnitOfWork()->registerManaged($this->hints[Query::HINT_REFRESH_ENTITY], $id, $data); } - $uow = $this->_em->getUnitOfWork(); - $entity = $uow->createEntity($entityName, $data, $this->_hints); + $uow = $this->em->getUnitOfWork(); + $entity = $uow->createEntity($entityName, $data, $this->hints); $result[] = $entity; - if (isset($this->_hints[Query::HINT_INTERNAL_ITERATION]) && $this->_hints[Query::HINT_INTERNAL_ITERATION]) { - $this->_uow->hydrationComplete(); + if (isset($this->hints[Query::HINT_INTERNAL_ITERATION]) && $this->hints[Query::HINT_INTERNAL_ITERATION]) { + $this->uow->hydrationComplete(); } } } diff --git a/lib/Doctrine/ORM/Internal/Hydration/SingleScalarHydrator.php b/lib/Doctrine/ORM/Internal/Hydration/SingleScalarHydrator.php index b9caeb11b83..38521183f59 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/SingleScalarHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/SingleScalarHydrator.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Internal\Hydration; @@ -36,7 +21,7 @@ class SingleScalarHydrator extends AbstractHydrator */ protected function hydrateAllData() { - $data = $this->_stmt->fetchAll(\PDO::FETCH_ASSOC); + $data = $this->stmt->fetchAll(\PDO::FETCH_ASSOC); $numRows = count($data); if ($numRows === 0) { diff --git a/lib/Doctrine/ORM/Internal/HydrationCompleteHandler.php b/lib/Doctrine/ORM/Internal/HydrationCompleteHandler.php index 72a0c70348e..197a18162a0 100644 --- a/lib/Doctrine/ORM/Internal/HydrationCompleteHandler.php +++ b/lib/Doctrine/ORM/Internal/HydrationCompleteHandler.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Internal; diff --git a/lib/Doctrine/ORM/LazyCriteriaCollection.php b/lib/Doctrine/ORM/LazyCriteriaCollection.php index ad0238fbb95..72e8c82de67 100644 --- a/lib/Doctrine/ORM/LazyCriteriaCollection.php +++ b/lib/Doctrine/ORM/LazyCriteriaCollection.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; diff --git a/lib/Doctrine/ORM/Mapping/AbstractClassMetadataFactory.php b/lib/Doctrine/ORM/Mapping/AbstractClassMetadataFactory.php new file mode 100644 index 00000000000..fa69c724b8e --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/AbstractClassMetadataFactory.php @@ -0,0 +1,408 @@ + + * @author Guilherme Blanco + * @author Jonathan Wage + * @author Roman Borschel + */ +abstract class AbstractClassMetadataFactory implements ClassMetadataFactory +{ + /** + * Salt used by specific Object Manager implementation. + * + * @var string + */ + protected $cacheSalt = '$CLASSMETADATA'; + + /** + * @var \Doctrine\Common\Cache\Cache|null + */ + private $cacheDriver; + + /** + * @var ClassMetadata[] + */ + private $loadedMetadata = []; + + /** + * @var bool + */ + protected $initialized = false; + + /** + * @var ReflectionService|null + */ + protected $reflectionService; + + /** + * Sets the cache driver used by the factory to cache ClassMetadata instances. + * + * @param \Doctrine\Common\Cache\Cache $cacheDriver + * + * @return void + */ + public function setCacheDriver(?Cache $cacheDriver = null) : void + { + $this->cacheDriver = $cacheDriver; + } + + /** + * Gets the cache driver used by the factory to cache ClassMetadata instances. + * + * @return Cache|null + */ + public function getCacheDriver() : ?Cache + { + return $this->cacheDriver; + } + + /** + * Returns an array of all the loaded metadata currently in memory. + * + * @return ClassMetadata[] + */ + public function getLoadedMetadata() : array + { + return $this->loadedMetadata; + } + + /** + * Sets the reflectionService. + * + * @param ReflectionService $reflectionService + * + * @return void + */ + public function setReflectionService(ReflectionService $reflectionService) : void + { + $this->reflectionService = $reflectionService; + } + + /** + * Gets the reflection service associated with this metadata factory. + * + * @return ReflectionService + */ + public function getReflectionService() : ReflectionService + { + if ($this->reflectionService === null) { + $this->reflectionService = new RuntimeReflectionService(); + } + + return $this->reflectionService; + } + + /** + * Checks whether the factory has the metadata for a class loaded already. + * + * @param string $className + * + * @return bool TRUE if the metadata of the class in question is already loaded, FALSE otherwise. + */ + public function hasMetadataFor($className) : bool + { + return isset($this->loadedMetadata[$className]); + } + + /** + * Sets the metadata descriptor for a specific class. + * + * NOTE: This is only useful in very special cases, like when generating proxy classes. + * + * @param string $className + * @param ClassMetadata $class + * + * @return void + */ + public function setMetadataFor($className, $class) : void + { + $this->loadedMetadata[$className] = $class; + } + + /** + * Forces the factory to load the metadata of all classes known to the underlying + * mapping driver. + * + * @return array The ClassMetadata instances of all mapped classes. + * + * @throws \InvalidArgumentException + * @throws \ReflectionException + * @throws MappingException + */ + public function getAllMetadata() : array + { + if (! $this->initialized) { + $this->initialize(); + } + + $driver = $this->getDriver(); + $metadata = []; + + foreach ($driver->getAllClassNames() as $className) { + $metadata[] = $this->getMetadataFor($className); + } + + return $metadata; + } + + /** + * Gets the class metadata descriptor for a class. + * + * @param string $className The name of the class. + * + * @return ClassMetadata + * + * @throws \InvalidArgumentException + * @throws ReflectionException + * @throws CommonMappingException + */ + public function getMetadataFor($className) : ClassMetadata + { + if (isset($this->loadedMetadata[$className])) { + return $this->loadedMetadata[$className]; + } + + $realClassName = $this->normalizeClassName($className); + + if (isset($this->loadedMetadata[$realClassName])) { + // We do not have the alias name in the map, include it + return $this->loadedMetadata[$className] = $this->loadedMetadata[$realClassName]; + } + + $metadataBuildingContext = $this->newClassMetadataBuildingContext(); + $loadingException = null; + + try { + if ($this->cacheDriver) { + $cached = $this->cacheDriver->fetch($realClassName . $this->cacheSalt); + + if ($cached instanceof ClassMetadata) { + $this->loadedMetadata[$realClassName] = $cached; + + $cached->wakeupReflection($metadataBuildingContext->getReflectionService()); + } else { + foreach ($this->loadMetadata($realClassName, $metadataBuildingContext) as $loadedClass) { + $loadedClassName = $loadedClass->getClassName(); + + $this->cacheDriver->save($loadedClassName . $this->cacheSalt, $loadedClass, null); + } + } + } else { + $this->loadMetadata($realClassName, $metadataBuildingContext); + } + } catch (CommonMappingException $loadingException) { + if (! $fallbackMetadataResponse = $this->onNotFoundMetadata($realClassName, $metadataBuildingContext)) { + throw $loadingException; + } + + $this->loadedMetadata[$realClassName] = $fallbackMetadataResponse; + } + + if ($className !== $realClassName) { + // We do not have the alias name in the map, include it + $this->loadedMetadata[$className] = $this->loadedMetadata[$realClassName]; + } + + $metadataBuildingContext->validate(); + + return $this->loadedMetadata[$className]; + } + + /** + * Loads the metadata of the class in question and all it's ancestors whose metadata + * is still not loaded. + * + * Important: The class $name does not necessarily exist at this point here. + * Scenarios in a code-generation setup might have access to XML/YAML + * Mapping files without the actual PHP code existing here. That is why the + * {@see Doctrine\Common\Persistence\Mapping\ReflectionService} interface + * should be used for reflection. + * + * @param string $name The name of the class for which the metadata should + * get loaded. + * @param ClassMetadataBuildingContext $metadataBuildingContext + * + * @return array + * + * @throws \InvalidArgumentException + */ + protected function loadMetadata(string $name, ClassMetadataBuildingContext $metadataBuildingContext) : array + { + if ( ! $this->initialized) { + $this->initialize(); + } + + $loaded = []; + + $parentClasses = $this->getParentClasses($name); + $parentClasses[] = $name; + + // Move down the hierarchy of parent classes, starting from the topmost class + $parent = null; + + foreach ($parentClasses as $className) { + if (isset($this->loadedMetadata[$className])) { + $parent = $this->loadedMetadata[$className]; + + continue; + } + + $class = $this->doLoadMetadata($className, $parent, $metadataBuildingContext); + + $this->loadedMetadata[$className] = $class; + + $parent = $class; + + $loaded[] = $class; + } + + return $loaded; + } + + /** + * {@inheritDoc} + */ + public function isTransient($className) : bool + { + if ( ! $this->initialized) { + $this->initialize(); + } + + return $this->getDriver()->isTransient($this->normalizeClassName($className)); + } + + /** + * Gets an array of parent classes for the given entity class. + * + * @param string $name + * + * @return array + * + * @throws \InvalidArgumentException + */ + protected function getParentClasses($name) : array + { + // Collect parent classes, ignoring transient (not-mapped) classes. + $parentClasses = []; + + foreach (array_reverse($this->getReflectionService()->getParentClasses($name)) as $parentClass) { + if ( ! $this->getDriver()->isTransient($parentClass)) { + $parentClasses[] = $parentClass; + } + } + + return $parentClasses; + } + + /** + * Provides a fallback hook for loading metadata when loading failed due to reflection/mapping exceptions + * + * Override this method to implement a fallback strategy for failed metadata loading + * + * @param string $className + * @param ClassMetadataBuildingContext $metadataBuildingContext + * + * @return \Doctrine\ORM\Mapping\ClassMetadata|null + */ + protected function onNotFoundMetadata( + string $className, + ClassMetadataBuildingContext $metadataBuildingContext + ) : ?ClassMetadata + { + return null; + } + + /** + * @param string $className + * + * @return string + */ + private function normalizeClassName(string $className) : string + { + if (strpos($className, ':') !== false) { + [$namespaceAlias, $simpleClassName] = explode(':', $className, 2); + + return $this->getFqcnFromAlias($namespaceAlias, $simpleClassName); + } + + return ClassUtils::getRealClass($className); + } + + /** + * Lazy initialization of this stuff, especially the metadata driver, + * since these are not needed at all when a metadata cache is active. + * + * @return void + */ + abstract protected function initialize() : void; + + /** + * Gets the fully qualified class-name from the namespace alias. + * + * @param string $namespaceAlias + * @param string $simpleClassName + * + * @return string + */ + abstract protected function getFqcnFromAlias($namespaceAlias, $simpleClassName) : string; + + /** + * Returns the mapping driver implementation. + * + * @return Driver\MappingDriver + */ + abstract protected function getDriver() : Driver\MappingDriver; + + /** + * Checks whether the class metadata is an entity. + * + * This method should return false for mapped superclasses or embedded classes. + * + * @param ClassMetadata $class + * + * @return bool + */ + abstract protected function isEntity(ClassMetadata $class) : bool; + + /** + * Creates a new ClassMetadata instance for the given class name. + * + * @param string $className + * @param ClassMetadata|null $parent + * @param ClassMetadataBuildingContext $metadataBuildingContext + * + * @return ClassMetadata + */ + abstract protected function doLoadMetadata( + string $className, + ?ClassMetadata $parent, + ClassMetadataBuildingContext $metadataBuildingContext + ) : ClassMetadata; + + /** + * Creates a new ClassMetadataBuildingContext instance. + * + * @return ClassMetadataBuildingContext + */ + abstract protected function newClassMetadataBuildingContext() : ClassMetadataBuildingContext; +} diff --git a/lib/Doctrine/ORM/Mapping/Annotation.php b/lib/Doctrine/ORM/Mapping/Annotation.php deleted file mode 100644 index 19374ff3146..00000000000 --- a/lib/Doctrine/ORM/Mapping/Annotation.php +++ /dev/null @@ -1,24 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -interface Annotation -{ -} diff --git a/lib/Doctrine/ORM/Mapping/AnsiQuoteStrategy.php b/lib/Doctrine/ORM/Mapping/AnsiQuoteStrategy.php deleted file mode 100644 index d18c8be7c72..00000000000 --- a/lib/Doctrine/ORM/Mapping/AnsiQuoteStrategy.php +++ /dev/null @@ -1,96 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -use Doctrine\DBAL\Platforms\AbstractPlatform; - -/** - * ANSI compliant quote strategy, this strategy does not apply any quote. - * To use this strategy all mapped tables and columns should be ANSI compliant. - * - * @since 2.5 - * @author Fabio B. Silva - */ -class AnsiQuoteStrategy implements QuoteStrategy -{ - /** - * {@inheritdoc} - */ - public function getColumnName($fieldName, ClassMetadata $class, AbstractPlatform $platform) - { - return $class->fieldMappings[$fieldName]['columnName']; - } - - /** - * {@inheritdoc} - */ - public function getTableName(ClassMetadata $class, AbstractPlatform $platform) - { - return $class->table['name']; - } - - /** - * {@inheritdoc} - */ - public function getSequenceName(array $definition, ClassMetadata $class, AbstractPlatform $platform) - { - return $definition['sequenceName']; - } - - /** - * {@inheritdoc} - */ - public function getJoinColumnName(array $joinColumn, ClassMetadata $class, AbstractPlatform $platform) - { - return $joinColumn['name']; - } - - /** - * {@inheritdoc} - */ - public function getReferencedJoinColumnName(array $joinColumn, ClassMetadata $class, AbstractPlatform $platform) - { - return $joinColumn['referencedColumnName']; - } - - /** - * {@inheritdoc} - */ - public function getJoinTableName(array $association, ClassMetadata $class, AbstractPlatform $platform) - { - return $association['joinTable']['name']; - } - - /** - * {@inheritdoc} - */ - public function getIdentifierColumnNames(ClassMetadata $class, AbstractPlatform $platform) - { - return $class->identifier; - } - - /** - * {@inheritdoc} - */ - public function getColumnAlias($columnName, $counter, AbstractPlatform $platform, ClassMetadata $class = null) - { - return $platform->getSQLResultCasing($columnName . '_' . $counter); - } -} diff --git a/lib/Doctrine/ORM/Mapping/AssociationMetadata.php b/lib/Doctrine/ORM/Mapping/AssociationMetadata.php new file mode 100644 index 00000000000..07a7e1ee4b9 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/AssociationMetadata.php @@ -0,0 +1,317 @@ + + */ +class AssociationMetadata implements Property +{ + /** @var ClassMetadata */ + private $declaringClass; + + /** @var \ReflectionProperty */ + private $reflection; + + /** @var string */ + private $name; + + /** @var boolean */ + protected $primaryKey = false; + + /** @var string */ + private $fetchMode = FetchMode::LAZY; + + /** @var string */ + private $targetEntity; + + /** @var string */ + private $sourceEntity; + + /** @var null|string */ + private $mappedBy; + + /** @var null|string */ + private $inversedBy; + + /** @var array */ + private $cascade = []; + + /** @var bool */ + private $owningSide = true; + + /** @var bool */ + private $orphanRemoval = false; + + /** @var null|CacheMetadata */ + private $cache = null; + + /** + * AssociationMetadata constructor. + * + * @param string $name + */ + public function __construct(string $name) + { + $this->name = $name; + } + + /** + * {@inheritdoc} + */ + public function getDeclaringClass() : ComponentMetadata + { + return $this->declaringClass; + } + + /** + * @param ComponentMetadata $declaringClass + */ + public function setDeclaringClass(ComponentMetadata $declaringClass) : void + { + $this->declaringClass = $declaringClass; + } + + /** + * {@inheritdoc} + */ + public function getName() : string + { + return $this->name; + } + + /** + * {@inheritdoc} + */ + public function setName($name) : void + { + $this->name = $name; + } + + /** + * @param bool $isPrimaryKey + */ + public function setPrimaryKey(bool $isPrimaryKey) : void + { + $this->primaryKey = $isPrimaryKey; + } + + /** + * @return bool + */ + public function isPrimaryKey() : bool + { + return $this->primaryKey; + } + + /** + * @return string + */ + public function getTargetEntity() : string + { + return $this->targetEntity; + } + + /** + * @param string $targetEntity + */ + public function setTargetEntity(string $targetEntity) : void + { + $this->targetEntity = $targetEntity; + } + + /** + * @return string + */ + public function getSourceEntity() : string + { + return $this->sourceEntity; + } + + /** + * @param string $sourceEntity + */ + public function setSourceEntity(string $sourceEntity) : void + { + $this->sourceEntity = $sourceEntity; + } + + /** + * @return array + */ + public function getCascade() : array + { + return $this->cascade; + } + + /** + * @param array $cascade + */ + public function setCascade(array $cascade) : void + { + $this->cascade = $cascade; + } + + /** + * @param bool $owningSide + */ + public function setOwningSide(bool $owningSide) : void + { + $this->owningSide = $owningSide; + } + + /** + * @return bool + */ + public function isOwningSide() : bool + { + return $this->owningSide; + } + + /** + * @return string + */ + public function getFetchMode() : string + { + return $this->fetchMode; + } + + /** + * @param string $fetchMode + */ + public function setFetchMode(string $fetchMode) : void + { + $this->fetchMode = $fetchMode; + } + + /** + * @return string|null + */ + public function getMappedBy() : ?string + { + return $this->mappedBy; + } + + /** + * @param string $mappedBy + */ + public function setMappedBy(string $mappedBy) : void + { + $this->mappedBy = $mappedBy; + } + + /** + * @return null|string + */ + public function getInversedBy() : ?string + { + return $this->inversedBy; + } + + /** + * @param null|string $inversedBy + */ + public function setInversedBy(string $inversedBy = null) : void + { + $this->inversedBy = $inversedBy; + } + + /** + * @param bool $orphanRemoval + */ + public function setOrphanRemoval(bool $orphanRemoval) : void + { + $this->orphanRemoval = $orphanRemoval; + } + + /** + * @return bool + */ + public function isOrphanRemoval() : bool + { + return $this->orphanRemoval; + } + + /** + * @return null|CacheMetadata + */ + public function getCache() : ?CacheMetadata + { + return $this->cache; + } + + /** + * @param null|CacheMetadata $cache + */ + public function setCache(CacheMetadata $cache = null) : void + { + $this->cache = $cache; + } + + /** + * {@inheritdoc} + */ + public function setValue($object, $value) : void + { + $this->reflection->setValue($object, $value); + } + + /** + * {@inheritdoc} + */ + public function getValue($object) + { + return $this->reflection->getValue($object); + } + + /** + * {@inheritdoc} + */ + public function isAssociation() : bool + { + return true; + } + + /** + * {@inheritdoc} + */ + public function isField() : bool + { + return false; + } + + /** + * {@inheritdoc} + */ + public function setReflectionProperty(\ReflectionProperty $reflectionProperty) : void + { + $this->reflection = $reflectionProperty; + } + + /** + * {@inheritdoc} + */ + public function wakeupReflection(ReflectionService $reflectionService) : void + { + $this->setReflectionProperty( + $reflectionService->getAccessibleProperty($this->declaringClass->getClassName(), $this->name) + ); + } + + public function __clone() + { + if ($this->cache) { + $this->cache = clone $this->cache; + } + } +} diff --git a/lib/Doctrine/ORM/Mapping/AssociationOverride.php b/lib/Doctrine/ORM/Mapping/AssociationOverride.php deleted file mode 100644 index e208b16228a..00000000000 --- a/lib/Doctrine/ORM/Mapping/AssociationOverride.php +++ /dev/null @@ -1,69 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * This annotation is used to override association mapping of property for an entity relationship. - * - * @author Fabio B. Silva - * @since 2.3 - * - * @Annotation - * @Target("ANNOTATION") - */ -final class AssociationOverride implements Annotation -{ - /** - * The name of the relationship property whose mapping is being overridden. - * - * @var string - */ - public $name; - - /** - * The join column that is being mapped to the persistent attribute. - * - * @var array<\Doctrine\ORM\Mapping\JoinColumn> - */ - public $joinColumns; - - /** - * The join table that maps the relationship. - * - * @var \Doctrine\ORM\Mapping\JoinTable - */ - public $joinTable; - - /** - * The name of the association-field on the inverse-side. - * - * @var string - */ - public $inversedBy; - - /** - * The fetching strategy to use for the association. - * - * @var string - * - * @Enum({"LAZY", "EAGER", "EXTRA_LAZY"}) - */ - public $fetch; -} diff --git a/lib/Doctrine/ORM/Mapping/AssociationOverrides.php b/lib/Doctrine/ORM/Mapping/AssociationOverrides.php deleted file mode 100644 index 217c9e45735..00000000000 --- a/lib/Doctrine/ORM/Mapping/AssociationOverrides.php +++ /dev/null @@ -1,39 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * This annotation is used to override association mappings of relationship properties. - * - * @author Fabio B. Silva - * @since 2.3 - * - * @Annotation - * @Target("CLASS") - */ -final class AssociationOverrides implements Annotation -{ - /** - * Mapping overrides of relationship properties. - * - * @var array<\Doctrine\ORM\Mapping\AssociationOverride> - */ - public $value; -} diff --git a/lib/Doctrine/ORM/Mapping/AttributeOverride.php b/lib/Doctrine/ORM/Mapping/AttributeOverride.php deleted file mode 100644 index f86d3a1521d..00000000000 --- a/lib/Doctrine/ORM/Mapping/AttributeOverride.php +++ /dev/null @@ -1,46 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * This annotation is used to override the mapping of a entity property. - * - * @author Fabio B. Silva - * @since 2.3 - * - * @Annotation - * @Target("ANNOTATION") - */ -final class AttributeOverride implements Annotation -{ - /** - * The name of the property whose mapping is being overridden. - * - * @var string - */ - public $name; - - /** - * The column definition. - * - * @var \Doctrine\ORM\Mapping\Column - */ - public $column; -} diff --git a/lib/Doctrine/ORM/Mapping/AttributeOverrides.php b/lib/Doctrine/ORM/Mapping/AttributeOverrides.php deleted file mode 100644 index 63b2cc66e7f..00000000000 --- a/lib/Doctrine/ORM/Mapping/AttributeOverrides.php +++ /dev/null @@ -1,39 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * This annotation is used to override the mapping of a entity property. - * - * @author Fabio B. Silva - * @since 2.3 - * - * @Annotation - * @Target("CLASS") - */ -final class AttributeOverrides implements Annotation -{ - /** - * One or more field or property mapping overrides. - * - * @var array<\Doctrine\ORM\Mapping\AttributeOverride> - */ - public $value; -} diff --git a/lib/Doctrine/ORM/Mapping/Builder/AssociationBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/AssociationBuilder.php deleted file mode 100644 index 7f4fddc96ba..00000000000 --- a/lib/Doctrine/ORM/Mapping/Builder/AssociationBuilder.php +++ /dev/null @@ -1,244 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping\Builder; - -use Doctrine\ORM\Mapping\ClassMetadata; - -class AssociationBuilder -{ - /** - * @var ClassMetadataBuilder - */ - protected $builder; - - /** - * @var array - */ - protected $mapping; - - /** - * @var array|null - */ - protected $joinColumns; - - /** - * @var int - */ - protected $type; - - /** - * @param ClassMetadataBuilder $builder - * @param array $mapping - * @param int $type - */ - public function __construct(ClassMetadataBuilder $builder, array $mapping, $type) - { - $this->builder = $builder; - $this->mapping = $mapping; - $this->type = $type; - } - - /** - * @param string $fieldName - * - * @return AssociationBuilder - */ - public function mappedBy($fieldName) - { - $this->mapping['mappedBy'] = $fieldName; - - return $this; - } - - /** - * @param string $fieldName - * - * @return AssociationBuilder - */ - public function inversedBy($fieldName) - { - $this->mapping['inversedBy'] = $fieldName; - - return $this; - } - - /** - * @return AssociationBuilder - */ - public function cascadeAll() - { - $this->mapping['cascade'] = ["ALL"]; - - return $this; - } - - /** - * @return AssociationBuilder - */ - public function cascadePersist() - { - $this->mapping['cascade'][] = "persist"; - - return $this; - } - - /** - * @return AssociationBuilder - */ - public function cascadeRemove() - { - $this->mapping['cascade'][] = "remove"; - - return $this; - } - - /** - * @return AssociationBuilder - */ - public function cascadeMerge() - { - $this->mapping['cascade'][] = "merge"; - - return $this; - } - - /** - * @return AssociationBuilder - */ - public function cascadeDetach() - { - $this->mapping['cascade'][] = "detach"; - - return $this; - } - - /** - * @return AssociationBuilder - */ - public function cascadeRefresh() - { - $this->mapping['cascade'][] = "refresh"; - - return $this; - } - - /** - * @return AssociationBuilder - */ - public function fetchExtraLazy() - { - $this->mapping['fetch'] = ClassMetadata::FETCH_EXTRA_LAZY; - - return $this; - } - - /** - * @return AssociationBuilder - */ - public function fetchEager() - { - $this->mapping['fetch'] = ClassMetadata::FETCH_EAGER; - - return $this; - } - - /** - * @return AssociationBuilder - */ - public function fetchLazy() - { - $this->mapping['fetch'] = ClassMetadata::FETCH_LAZY; - - return $this; - } - - /** - * Add Join Columns. - * - * @param string $columnName - * @param string $referencedColumnName - * @param bool $nullable - * @param bool $unique - * @param string|null $onDelete - * @param string|null $columnDef - * - * @return AssociationBuilder - */ - public function addJoinColumn($columnName, $referencedColumnName, $nullable = true, $unique = false, $onDelete = null, $columnDef = null) - { - $this->joinColumns[] = [ - 'name' => $columnName, - 'referencedColumnName' => $referencedColumnName, - 'nullable' => $nullable, - 'unique' => $unique, - 'onDelete' => $onDelete, - 'columnDefinition' => $columnDef, - ]; - - return $this; - } - - /** - * Sets field as primary key. - * - * @return self - */ - public function makePrimaryKey() - { - $this->mapping['id'] = true; - - return $this; - } - - /** - * Removes orphan entities when detached from their parent. - * - * @return self - */ - public function orphanRemoval() - { - $this->mapping['orphanRemoval'] = true; - - return $this; - } - - /** - * @return ClassMetadataBuilder - * - * @throws \InvalidArgumentException - */ - public function build() - { - $mapping = $this->mapping; - if ($this->joinColumns) { - $mapping['joinColumns'] = $this->joinColumns; - } - $cm = $this->builder->getClassMetadata(); - if ($this->type == ClassMetadata::MANY_TO_ONE) { - $cm->mapManyToOne($mapping); - } else if ($this->type == ClassMetadata::ONE_TO_ONE) { - $cm->mapOneToOne($mapping); - } else { - throw new \InvalidArgumentException("Type should be a ToOne Association here"); - } - - return $this->builder; - } -} diff --git a/lib/Doctrine/ORM/Mapping/Builder/ClassMetadataBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/ClassMetadataBuilder.php deleted file mode 100644 index c08b374feeb..00000000000 --- a/lib/Doctrine/ORM/Mapping/Builder/ClassMetadataBuilder.php +++ /dev/null @@ -1,553 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping\Builder; - -use Doctrine\ORM\Mapping\ClassMetadata; -use Doctrine\ORM\Mapping\ClassMetadataInfo; - -/** - * Builder Object for ClassMetadata - * - * @license http://www.opensource.org/licenses/mit-license.php MIT - * @link www.doctrine-project.com - * @since 2.2 - * @author Benjamin Eberlei - * @author Guilherme Blanco - */ -class ClassMetadataBuilder -{ - /** - * @var \Doctrine\ORM\Mapping\ClassMetadataInfo - */ - private $cm; - - /** - * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $cm - */ - public function __construct(ClassMetadataInfo $cm) - { - $this->cm = $cm; - } - - /** - * @return ClassMetadata - */ - public function getClassMetadata() - { - return $this->cm; - } - - /** - * Marks the class as mapped superclass. - * - * @return ClassMetadataBuilder - */ - public function setMappedSuperClass() - { - $this->cm->isMappedSuperclass = true; - $this->cm->isEmbeddedClass = false; - - return $this; - } - - /** - * Marks the class as embeddable. - * - * @return ClassMetadataBuilder - */ - public function setEmbeddable() - { - $this->cm->isEmbeddedClass = true; - $this->cm->isMappedSuperclass = false; - - return $this; - } - - /** - * Adds and embedded class - * - * @param string $fieldName - * @param string $class - * @param string|null $columnPrefix - * - * @return $this - */ - public function addEmbedded($fieldName, $class, $columnPrefix = null) - { - $this->cm->mapEmbedded( - [ - 'fieldName' => $fieldName, - 'class' => $class, - 'columnPrefix' => $columnPrefix - ] - ); - - return $this; - } - - /** - * Sets custom Repository class name. - * - * @param string $repositoryClassName - * - * @return ClassMetadataBuilder - */ - public function setCustomRepositoryClass($repositoryClassName) - { - $this->cm->setCustomRepositoryClass($repositoryClassName); - - return $this; - } - - /** - * Marks class read only. - * - * @return ClassMetadataBuilder - */ - public function setReadOnly() - { - $this->cm->markReadOnly(); - - return $this; - } - - /** - * Sets the table name. - * - * @param string $name - * - * @return ClassMetadataBuilder - */ - public function setTable($name) - { - $this->cm->setPrimaryTable(['name' => $name]); - - return $this; - } - - /** - * Adds Index. - * - * @param array $columns - * @param string $name - * - * @return ClassMetadataBuilder - */ - public function addIndex(array $columns, $name) - { - if (!isset($this->cm->table['indexes'])) { - $this->cm->table['indexes'] = []; - } - - $this->cm->table['indexes'][$name] = ['columns' => $columns]; - - return $this; - } - - /** - * Adds Unique Constraint. - * - * @param array $columns - * @param string $name - * - * @return ClassMetadataBuilder - */ - public function addUniqueConstraint(array $columns, $name) - { - if ( ! isset($this->cm->table['uniqueConstraints'])) { - $this->cm->table['uniqueConstraints'] = []; - } - - $this->cm->table['uniqueConstraints'][$name] = ['columns' => $columns]; - - return $this; - } - - /** - * Adds named query. - * - * @param string $name - * @param string $dqlQuery - * - * @return ClassMetadataBuilder - */ - public function addNamedQuery($name, $dqlQuery) - { - $this->cm->addNamedQuery( - [ - 'name' => $name, - 'query' => $dqlQuery, - ] - ); - - return $this; - } - - /** - * Sets class as root of a joined table inheritance hierarchy. - * - * @return ClassMetadataBuilder - */ - public function setJoinedTableInheritance() - { - $this->cm->setInheritanceType(ClassMetadata::INHERITANCE_TYPE_JOINED); - - return $this; - } - - /** - * Sets class as root of a single table inheritance hierarchy. - * - * @return ClassMetadataBuilder - */ - public function setSingleTableInheritance() - { - $this->cm->setInheritanceType(ClassMetadata::INHERITANCE_TYPE_SINGLE_TABLE); - - return $this; - } - - /** - * Sets the discriminator column details. - * - * @param string $name - * @param string $type - * @param int $length - * - * @return ClassMetadataBuilder - */ - public function setDiscriminatorColumn($name, $type = 'string', $length = 255) - { - $this->cm->setDiscriminatorColumn( - [ - 'name' => $name, - 'type' => $type, - 'length' => $length, - ] - ); - - return $this; - } - - /** - * Adds a subclass to this inheritance hierarchy. - * - * @param string $name - * @param string $class - * - * @return ClassMetadataBuilder - */ - public function addDiscriminatorMapClass($name, $class) - { - $this->cm->addDiscriminatorMapClass($name, $class); - - return $this; - } - - /** - * Sets deferred explicit change tracking policy. - * - * @return ClassMetadataBuilder - */ - public function setChangeTrackingPolicyDeferredExplicit() - { - $this->cm->setChangeTrackingPolicy(ClassMetadata::CHANGETRACKING_DEFERRED_EXPLICIT); - - return $this; - } - - /** - * Sets notify change tracking policy. - * - * @return ClassMetadataBuilder - */ - public function setChangeTrackingPolicyNotify() - { - $this->cm->setChangeTrackingPolicy(ClassMetadata::CHANGETRACKING_NOTIFY); - - return $this; - } - - /** - * Adds lifecycle event. - * - * @param string $methodName - * @param string $event - * - * @return ClassMetadataBuilder - */ - public function addLifecycleEvent($methodName, $event) - { - $this->cm->addLifecycleCallback($methodName, $event); - - return $this; - } - - /** - * Adds Field. - * - * @param string $name - * @param string $type - * @param array $mapping - * - * @return ClassMetadataBuilder - */ - public function addField($name, $type, array $mapping = []) - { - $mapping['fieldName'] = $name; - $mapping['type'] = $type; - - $this->cm->mapField($mapping); - - return $this; - } - - /** - * Creates a field builder. - * - * @param string $name - * @param string $type - * - * @return FieldBuilder - */ - public function createField($name, $type) - { - return new FieldBuilder( - $this, - [ - 'fieldName' => $name, - 'type' => $type - ] - ); - } - - /** - * Creates an embedded builder. - * - * @param string $fieldName - * @param string $class - * - * @return EmbeddedBuilder - */ - public function createEmbedded($fieldName, $class) - { - return new EmbeddedBuilder( - $this, - [ - 'fieldName' => $fieldName, - 'class' => $class, - 'columnPrefix' => null - ] - ); - } - - /** - * Adds a simple many to one association, optionally with the inversed by field. - * - * @param string $name - * @param string $targetEntity - * @param string|null $inversedBy - * - * @return ClassMetadataBuilder - */ - public function addManyToOne($name, $targetEntity, $inversedBy = null) - { - $builder = $this->createManyToOne($name, $targetEntity); - - if ($inversedBy) { - $builder->inversedBy($inversedBy); - } - - return $builder->build(); - } - - /** - * Creates a ManyToOne Association Builder. - * - * Note: This method does not add the association, you have to call build() on the AssociationBuilder. - * - * @param string $name - * @param string $targetEntity - * - * @return AssociationBuilder - */ - public function createManyToOne($name, $targetEntity) - { - return new AssociationBuilder( - $this, - [ - 'fieldName' => $name, - 'targetEntity' => $targetEntity - ], - ClassMetadata::MANY_TO_ONE - ); - } - - /** - * Creates a OneToOne Association Builder. - * - * @param string $name - * @param string $targetEntity - * - * @return AssociationBuilder - */ - public function createOneToOne($name, $targetEntity) - { - return new AssociationBuilder( - $this, - [ - 'fieldName' => $name, - 'targetEntity' => $targetEntity - ], - ClassMetadata::ONE_TO_ONE - ); - } - - /** - * Adds simple inverse one-to-one association. - * - * @param string $name - * @param string $targetEntity - * @param string $mappedBy - * - * @return ClassMetadataBuilder - */ - public function addInverseOneToOne($name, $targetEntity, $mappedBy) - { - $builder = $this->createOneToOne($name, $targetEntity); - $builder->mappedBy($mappedBy); - - return $builder->build(); - } - - /** - * Adds simple owning one-to-one association. - * - * @param string $name - * @param string $targetEntity - * @param string|null $inversedBy - * - * @return ClassMetadataBuilder - */ - public function addOwningOneToOne($name, $targetEntity, $inversedBy = null) - { - $builder = $this->createOneToOne($name, $targetEntity); - - if ($inversedBy) { - $builder->inversedBy($inversedBy); - } - - return $builder->build(); - } - - /** - * Creates a ManyToMany Association Builder. - * - * @param string $name - * @param string $targetEntity - * - * @return ManyToManyAssociationBuilder - */ - public function createManyToMany($name, $targetEntity) - { - return new ManyToManyAssociationBuilder( - $this, - [ - 'fieldName' => $name, - 'targetEntity' => $targetEntity - ], - ClassMetadata::MANY_TO_MANY - ); - } - - /** - * Adds a simple owning many to many association. - * - * @param string $name - * @param string $targetEntity - * @param string|null $inversedBy - * - * @return ClassMetadataBuilder - */ - public function addOwningManyToMany($name, $targetEntity, $inversedBy = null) - { - $builder = $this->createManyToMany($name, $targetEntity); - - if ($inversedBy) { - $builder->inversedBy($inversedBy); - } - - return $builder->build(); - } - - /** - * Adds a simple inverse many to many association. - * - * @param string $name - * @param string $targetEntity - * @param string $mappedBy - * - * @return ClassMetadataBuilder - */ - public function addInverseManyToMany($name, $targetEntity, $mappedBy) - { - $builder = $this->createManyToMany($name, $targetEntity); - $builder->mappedBy($mappedBy); - - return $builder->build(); - } - - /** - * Creates a one to many association builder. - * - * @param string $name - * @param string $targetEntity - * - * @return OneToManyAssociationBuilder - */ - public function createOneToMany($name, $targetEntity) - { - return new OneToManyAssociationBuilder( - $this, - [ - 'fieldName' => $name, - 'targetEntity' => $targetEntity - ], - ClassMetadata::ONE_TO_MANY - ); - } - - /** - * Adds simple OneToMany association. - * - * @param string $name - * @param string $targetEntity - * @param string $mappedBy - * - * @return ClassMetadataBuilder - */ - public function addOneToMany($name, $targetEntity, $mappedBy) - { - $builder = $this->createOneToMany($name, $targetEntity); - $builder->mappedBy($mappedBy); - - return $builder->build(); - } -} diff --git a/lib/Doctrine/ORM/Mapping/Builder/EmbeddedBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/EmbeddedBuilder.php deleted file mode 100644 index de8383c5357..00000000000 --- a/lib/Doctrine/ORM/Mapping/Builder/EmbeddedBuilder.php +++ /dev/null @@ -1,80 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping\Builder; - -/** - * Embedded Builder - * - * @license http://www.opensource.org/licenses/mit-license.php MIT - * @link www.doctrine-project.com - * @since 2.5 - * @author Guido Contreras Woda - */ -class EmbeddedBuilder -{ - /** - * @var ClassMetadataBuilder - */ - private $builder; - - /** - * @var array - */ - private $mapping; - - /** - * @param ClassMetadataBuilder $builder - * @param array $mapping - */ - public function __construct(ClassMetadataBuilder $builder, array $mapping) - { - $this->builder = $builder; - $this->mapping = $mapping; - } - - /** - * Sets the column prefix for all of the embedded columns. - * - * @param string $columnPrefix - * @return $this - */ - public function setColumnPrefix($columnPrefix) - { - $this->mapping['columnPrefix'] = $columnPrefix; - - return $this; - } - - /** - * Finalizes this embeddable and attach it to the ClassMetadata. - * - * Without this call an EmbeddedBuilder has no effect on the ClassMetadata. - * - * @return ClassMetadataBuilder - */ - public function build() - { - $cm = $this->builder->getClassMetadata(); - - $cm->mapEmbedded($this->mapping); - - return $this->builder; - } -} diff --git a/lib/Doctrine/ORM/Mapping/Builder/EntityListenerBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/EntityListenerBuilder.php deleted file mode 100644 index e962726091c..00000000000 --- a/lib/Doctrine/ORM/Mapping/Builder/EntityListenerBuilder.php +++ /dev/null @@ -1,72 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping\Builder; - -use Doctrine\ORM\Mapping\MappingException; -use Doctrine\ORM\Mapping\ClassMetadata; -use Doctrine\ORM\Events; - -/** - * Builder for entity listeners. - * - * @since 2.4 - * @author Fabio B. Silva - */ -class EntityListenerBuilder -{ - /** - * @var array Hash-map to handle event names. - */ - static private $events = [ - Events::preRemove => true, - Events::postRemove => true, - Events::prePersist => true, - Events::postPersist => true, - Events::preUpdate => true, - Events::postUpdate => true, - Events::postLoad => true, - Events::preFlush => true - ]; - - /** - * Lookup the entity class to find methods that match to event lifecycle names - * - * @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata. - * @param string $className The listener class name. - * - * @throws \Doctrine\ORM\Mapping\MappingException When the listener class not found. - */ - static public function bindEntityListener(ClassMetadata $metadata, $className) - { - $class = $metadata->fullyQualifiedClassName($className); - - if ( ! class_exists($class)) { - throw MappingException::entityListenerClassNotFound($class, $className); - } - - foreach (get_class_methods($class) as $method) { - if ( ! isset(self::$events[$method])) { - continue; - } - - $metadata->addEntityListener($method, $class, $method); - } - } -} diff --git a/lib/Doctrine/ORM/Mapping/Builder/FieldBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/FieldBuilder.php deleted file mode 100644 index d0128d4a933..00000000000 --- a/lib/Doctrine/ORM/Mapping/Builder/FieldBuilder.php +++ /dev/null @@ -1,296 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping\Builder; - -/** - * Field Builder - * - * @license http://www.opensource.org/licenses/mit-license.php MIT - * @link www.doctrine-project.com - * @since 2.2 - * @author Benjamin Eberlei - */ -class FieldBuilder -{ - /** - * @var ClassMetadataBuilder - */ - private $builder; - - /** - * @var array - */ - private $mapping; - - /** - * @var bool - */ - private $version; - - /** - * @var string - */ - private $generatedValue; - - /** - * @var array - */ - private $sequenceDef; - - /** - * @var string|null - */ - private $customIdGenerator; - - /** - * @param ClassMetadataBuilder $builder - * @param array $mapping - */ - public function __construct(ClassMetadataBuilder $builder, array $mapping) - { - $this->builder = $builder; - $this->mapping = $mapping; - } - - /** - * Sets length. - * - * @param int $length - * - * @return FieldBuilder - */ - public function length($length) - { - $this->mapping['length'] = $length; - - return $this; - } - - /** - * Sets nullable. - * - * @param bool $flag - * - * @return FieldBuilder - */ - public function nullable($flag = true) - { - $this->mapping['nullable'] = (bool) $flag; - - return $this; - } - - /** - * Sets Unique. - * - * @param bool $flag - * - * @return FieldBuilder - */ - public function unique($flag = true) - { - $this->mapping['unique'] = (bool) $flag; - - return $this; - } - - /** - * Sets column name. - * - * @param string $name - * - * @return FieldBuilder - */ - public function columnName($name) - { - $this->mapping['columnName'] = $name; - - return $this; - } - - /** - * Sets Precision. - * - * @param int $p - * - * @return FieldBuilder - */ - public function precision($p) - { - $this->mapping['precision'] = $p; - - return $this; - } - - /** - * Sets scale. - * - * @param int $s - * - * @return FieldBuilder - */ - public function scale($s) - { - $this->mapping['scale'] = $s; - - return $this; - } - - /** - * Sets field as primary key. - * - * @deprecated Use makePrimaryKey() instead - * @return FieldBuilder - */ - public function isPrimaryKey() - { - return $this->makePrimaryKey(); - } - - /** - * Sets field as primary key. - * - * @return FieldBuilder - */ - public function makePrimaryKey() - { - $this->mapping['id'] = true; - - return $this; - } - - /** - * Sets an option. - * - * @param string $name - * @param mixed $value - * - * @return FieldBuilder - */ - public function option($name, $value) - { - $this->mapping['options'][$name] = $value; - - return $this; - } - - /** - * @param string $strategy - * - * @return FieldBuilder - */ - public function generatedValue($strategy = 'AUTO') - { - $this->generatedValue = $strategy; - - return $this; - } - - /** - * Sets field versioned. - * - * @return FieldBuilder - */ - public function isVersionField() - { - $this->version = true; - - return $this; - } - - /** - * Sets Sequence Generator. - * - * @param string $sequenceName - * @param int $allocationSize - * @param int $initialValue - * - * @return FieldBuilder - */ - public function setSequenceGenerator($sequenceName, $allocationSize = 1, $initialValue = 1) - { - $this->sequenceDef = [ - 'sequenceName' => $sequenceName, - 'allocationSize' => $allocationSize, - 'initialValue' => $initialValue, - ]; - - return $this; - } - - /** - * Sets column definition. - * - * @param string $def - * - * @return FieldBuilder - */ - public function columnDefinition($def) - { - $this->mapping['columnDefinition'] = $def; - - return $this; - } - - /** - * Set the FQCN of the custom ID generator. - * This class must extend \Doctrine\ORM\Id\AbstractIdGenerator. - * - * @param string $customIdGenerator - * - * @return $this - */ - public function setCustomIdGenerator($customIdGenerator) - { - $this->customIdGenerator = (string) $customIdGenerator; - - return $this; - } - - /** - * Finalizes this field and attach it to the ClassMetadata. - * - * Without this call a FieldBuilder has no effect on the ClassMetadata. - * - * @return ClassMetadataBuilder - */ - public function build() - { - $cm = $this->builder->getClassMetadata(); - if ($this->generatedValue) { - $cm->setIdGeneratorType(constant('Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_' . $this->generatedValue)); - } - - if ($this->version) { - $cm->setVersionMapping($this->mapping); - } - - $cm->mapField($this->mapping); - if ($this->sequenceDef) { - $cm->setSequenceGeneratorDefinition($this->sequenceDef); - } - - if ($this->customIdGenerator) { - $cm->setCustomGeneratorDefinition(['class' => $this->customIdGenerator]); - } - - return $this->builder; - } -} diff --git a/lib/Doctrine/ORM/Mapping/Builder/ManyToManyAssociationBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/ManyToManyAssociationBuilder.php deleted file mode 100644 index a71859dfd38..00000000000 --- a/lib/Doctrine/ORM/Mapping/Builder/ManyToManyAssociationBuilder.php +++ /dev/null @@ -1,101 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping\Builder; - -/** - * ManyToMany Association Builder - * - * @license http://www.opensource.org/licenses/mit-license.php MIT - * @link www.doctrine-project.com - * @since 2.0 - * @author Benjamin Eberlei - */ -class ManyToManyAssociationBuilder extends OneToManyAssociationBuilder -{ - /** - * @var string|null - */ - private $joinTableName; - - /** - * @var array - */ - private $inverseJoinColumns = []; - - /** - * @param string $name - * - * @return ManyToManyAssociationBuilder - */ - public function setJoinTable($name) - { - $this->joinTableName = $name; - - return $this; - } - - /** - * Adds Inverse Join Columns. - * - * @param string $columnName - * @param string $referencedColumnName - * @param bool $nullable - * @param bool $unique - * @param string|null $onDelete - * @param string|null $columnDef - * - * @return ManyToManyAssociationBuilder - */ - public function addInverseJoinColumn($columnName, $referencedColumnName, $nullable = true, $unique = false, $onDelete = null, $columnDef = null) - { - $this->inverseJoinColumns[] = [ - 'name' => $columnName, - 'referencedColumnName' => $referencedColumnName, - 'nullable' => $nullable, - 'unique' => $unique, - 'onDelete' => $onDelete, - 'columnDefinition' => $columnDef, - ]; - - return $this; - } - - /** - * @return ClassMetadataBuilder - */ - public function build() - { - $mapping = $this->mapping; - $mapping['joinTable'] = []; - if ($this->joinColumns) { - $mapping['joinTable']['joinColumns'] = $this->joinColumns; - } - if ($this->inverseJoinColumns) { - $mapping['joinTable']['inverseJoinColumns'] = $this->inverseJoinColumns; - } - if ($this->joinTableName) { - $mapping['joinTable']['name'] = $this->joinTableName; - } - $cm = $this->builder->getClassMetadata(); - $cm->mapManyToMany($mapping); - - return $this->builder; - } -} diff --git a/lib/Doctrine/ORM/Mapping/Builder/OneToManyAssociationBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/OneToManyAssociationBuilder.php deleted file mode 100644 index 347dfd04d89..00000000000 --- a/lib/Doctrine/ORM/Mapping/Builder/OneToManyAssociationBuilder.php +++ /dev/null @@ -1,70 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping\Builder; - -/** - * OneToMany Association Builder - * - * @license http://www.opensource.org/licenses/mit-license.php MIT - * @link www.doctrine-project.com - * @since 2.0 - * @author Benjamin Eberlei - */ -class OneToManyAssociationBuilder extends AssociationBuilder -{ - /** - * @param array $fieldNames - * - * @return OneToManyAssociationBuilder - */ - public function setOrderBy(array $fieldNames) - { - $this->mapping['orderBy'] = $fieldNames; - - return $this; - } - - /** - * @param string $fieldName - * - * @return OneToManyAssociationBuilder - */ - public function setIndexBy($fieldName) - { - $this->mapping['indexBy'] = $fieldName; - - return $this; - } - - /** - * @return ClassMetadataBuilder - */ - public function build() - { - $mapping = $this->mapping; - if ($this->joinColumns) { - $mapping['joinColumns'] = $this->joinColumns; - } - $cm = $this->builder->getClassMetadata(); - $cm->mapOneToMany($mapping); - - return $this->builder; - } -} diff --git a/lib/Doctrine/ORM/Mapping/Cache.php b/lib/Doctrine/ORM/Mapping/Cache.php deleted file mode 100644 index 3226b603160..00000000000 --- a/lib/Doctrine/ORM/Mapping/Cache.php +++ /dev/null @@ -1,44 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * Caching to an entity or a collection. - * - * @author Fabio B. Silva - * @since 2.5 - * - * @Annotation - * @Target({"CLASS","PROPERTY"}) - */ -final class Cache implements Annotation -{ - /** - * @Enum({"READ_ONLY", "NONSTRICT_READ_WRITE", "READ_WRITE"}) - * - * @var string The concurrency strategy. - */ - public $usage = 'READ_ONLY'; - - /** - * @var string Cache region name. - */ - public $region; -} diff --git a/lib/Doctrine/ORM/Mapping/CacheMetadata.php b/lib/Doctrine/ORM/Mapping/CacheMetadata.php new file mode 100644 index 00000000000..2df50a352bf --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/CacheMetadata.php @@ -0,0 +1,51 @@ + + */ +class CacheMetadata +{ + /** @var string */ + private $usage; + + /** @var string */ + private $region; + + /** + * Constructor. + * + * @param string $usage + * @param string $region + */ + public function __construct(string $usage, string $region) + { + $this->usage = $usage; + $this->region = $region; + } + + /** + * @return string + */ + public function getUsage() : string + { + return $this->usage; + } + + /** + * @return string + */ + public function getRegion() : string + { + return $this->region; + } +} diff --git a/lib/Doctrine/ORM/Mapping/CacheUsage.php b/lib/Doctrine/ORM/Mapping/CacheUsage.php new file mode 100644 index 00000000000..f75f52ee8db --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/CacheUsage.php @@ -0,0 +1,40 @@ + + */ +final class CacheUsage +{ + /** + * ReadOnly cache can do reads, inserts and deletes, cannot perform updates or employ any locks, + */ + const READ_ONLY = 'READ_ONLY'; + + /** + * Read Write Attempts to lock the entity before update/delete. + */ + const READ_WRITE = 'READ_WRITE'; + + /** + * Nonstrict Read Write Cache doesn’t employ any locks but can do inserts, update and deletes. + */ + const NONSTRICT_READ_WRITE = 'NONSTRICT_READ_WRITE'; + + /** + * Will break upon instantiation. + * + */ + private function __construct() + { + } +} diff --git a/lib/Doctrine/ORM/Mapping/ChangeTrackingPolicy.php b/lib/Doctrine/ORM/Mapping/ChangeTrackingPolicy.php index 3657b764f1e..fa36eb18d0c 100644 --- a/lib/Doctrine/ORM/Mapping/ChangeTrackingPolicy.php +++ b/lib/Doctrine/ORM/Mapping/ChangeTrackingPolicy.php @@ -1,36 +1,48 @@ . - */ + + +declare(strict_types=1); namespace Doctrine\ORM\Mapping; /** - * @Annotation - * @Target("CLASS") + * Class ChangeTrackingPolicy + * + * @package Doctrine\ORM\Mapping + * @since 3.0 + * + * @author Guilherme Blanco */ -final class ChangeTrackingPolicy implements Annotation +final class ChangeTrackingPolicy { /** - * The change tracking policy. + * DEFERRED_IMPLICIT means that changes of entities are calculated at commit-time + * by doing a property-by-property comparison with the original data. This will + * be done for all entities that are in MANAGED state at commit-time. * - * @var string + * This is the default change tracking policy. + */ + const DEFERRED_IMPLICIT = 'DEFERRED_IMPLICIT'; + + /** + * DEFERRED_EXPLICIT means that changes of entities are calculated at commit-time + * by doing a property-by-property comparison with the original data. This will + * be done only for entities that were explicitly saved (through persist() or a cascade). + */ + const DEFERRED_EXPLICIT = 'DEFERRED_EXPLICIT'; + + /** + * NOTIFY means that Doctrine relies on the entities sending out notifications when their + * properties change. Such entity classes must implement the NotifyPropertyChanged + * interface. + */ + const NOTIFY = 'NOTIFY'; + + /** + * Will break upon instantiation. * - * @Enum({"DEFERRED_IMPLICIT", "DEFERRED_EXPLICIT", "NOTIFY"}) */ - public $value; + private function __construct() + { + } } diff --git a/lib/Doctrine/ORM/Mapping/ClassMetadata.php b/lib/Doctrine/ORM/Mapping/ClassMetadata.php index a57f1e15a10..1393676f84a 100644 --- a/lib/Doctrine/ORM/Mapping/ClassMetadata.php +++ b/lib/Doctrine/ORM/Mapping/ClassMetadata.php @@ -1,29 +1,1894 @@ . - */ + + +declare(strict_types=1); namespace Doctrine\ORM\Mapping; +use Doctrine\ORM\Cache\CacheException; +use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\Factory\NamingStrategy; +use Doctrine\ORM\Reflection\ReflectionService; +use Doctrine\ORM\Sequencing\Planning\ValueGenerationPlan; +use Doctrine\ORM\Utility\PersisterHelper; + /** - * {@inheritDoc} + * A ClassMetadata instance holds all the object-relational mapping metadata + * of an entity and its associations. * - * @todo remove or rename ClassMetadataInfo to ClassMetadata + * @author Roman Borschel + * @author Jonathan H. Wage + * @author Guilherme Blanco + * @since 2.0 */ -class ClassMetadata extends ClassMetadataInfo +class ClassMetadata extends ComponentMetadata implements TableOwner { + /** + * The name of the custom repository class used for the entity class. + * (Optional). + * + * @var string + */ + protected $customRepositoryClassName; + + /** + * READ-ONLY: Whether this class describes the mapping of a mapped superclass. + * + * @var boolean + */ + public $isMappedSuperclass = false; + + /** + * READ-ONLY: Whether this class describes the mapping of an embeddable class. + * + * @var boolean + */ + public $isEmbeddedClass = false; + + /** + * Whether this class describes the mapping of a read-only class. + * That means it is never considered for change-tracking in the UnitOfWork. + * It is a very helpful performance optimization for entities that are immutable, + * either in your domain or through the relation database (coming from a view, + * or a history table for example). + * + * @var boolean + */ + private $readOnly = false; + + /** + * The names of all subclasses (descendants). + * + * @var array + */ + protected $subClasses = []; + + /** + * READ-ONLY: The names of all embedded classes based on properties. + * + * @var array + */ + //public $embeddedClasses = []; + + /** + * The named queries allowed to be called directly from Repository. + * + * @var array + */ + protected $namedQueries = []; + + /** + * READ-ONLY: The named native queries allowed to be called directly from Repository. + * + * A native SQL named query definition has the following structure: + *
+     * array(
+     *     'name'               => ,
+     *     'query'              => ,
+     *     'resultClass'        => ,
+     *     'resultSetMapping'   => 
+     * )
+     * 
+ * + * @var array + */ + public $namedNativeQueries = []; + + /** + * READ-ONLY: The mappings of the results of native SQL queries. + * + * A native result mapping definition has the following structure: + *
+     * array(
+     *     'name'               => ,
+     *     'entities'           => array(),
+     *     'columns'            => array()
+     * )
+     * 
+ * + * @var array + */ + public $sqlResultSetMappings = []; + + /** + * READ-ONLY: The registered lifecycle callbacks for entities of this class. + * + * @var array> + */ + public $lifecycleCallbacks = []; + + /** + * READ-ONLY: The registered entity listeners. + * + * @var array + */ + public $entityListeners = []; + + /** + * READ-ONLY: The field names of all fields that are part of the identifier/primary key + * of the mapped entity class. + * + * @var string[] + */ + public $identifier = []; + + /** + * READ-ONLY: The inheritance mapping type used by the class. + * + * @var string + */ + public $inheritanceType = InheritanceType::NONE; + + /** + * READ-ONLY: The policy used for change-tracking on entities of this class. + * + * @var string + */ + public $changeTrackingPolicy = ChangeTrackingPolicy::DEFERRED_IMPLICIT; + + /** + * READ-ONLY: The discriminator value of this class. + * + * This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies + * where a discriminator column is used. + * + * @var mixed + * + * @see discriminatorColumn + */ + public $discriminatorValue; + + /** + * READ-ONLY: The discriminator map of all mapped classes in the hierarchy. + * + * This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies + * where a discriminator column is used. + * + * @var array + * + * @see discriminatorColumn + */ + public $discriminatorMap = []; + + /** + * READ-ONLY: The definition of the discriminator column used in JOINED and SINGLE_TABLE + * inheritance mappings. + * + * @var DiscriminatorColumnMetadata + */ + public $discriminatorColumn; + + /** + * READ-ONLY: The primary table metadata. + * + * @var TableMetadata + */ + public $table; + + /** + * READ-ONLY: An array of field names. Used to look up field names from column names. + * Keys are column names and values are field names. + * + * @var array + */ + public $fieldNames = []; + + /** + * READ-ONLY: The field which is used for versioning in optimistic locking (if any). + * + * @var FieldMetadata|null + */ + public $versionProperty; + + /** + * NamingStrategy determining the default column and table names. + * + * @var NamingStrategy + */ + protected $namingStrategy; + + /** + * Value generation plan is responsible for generating values for auto-generated fields. + * + * @var ValueGenerationPlan + */ + protected $valueGenerationPlan; + + /** + * Initializes a new ClassMetadata instance that will hold the object-relational mapping + * metadata of the class with the given name. + * + * @param string $entityName The name of the entity class. + * @param ClassMetadataBuildingContext $metadataBuildingContext + */ + public function __construct( + string $entityName, + ClassMetadataBuildingContext $metadataBuildingContext + ) + { + parent::__construct($entityName, $metadataBuildingContext); + + $this->namingStrategy = $metadataBuildingContext->getNamingStrategy(); + } + + /** + * @todo guilhermeblanco Remove once ClassMetadataFactory is finished + * + * @param string $className + */ + public function setClassName(string $className) + { + $this->className = $className; + } + + /** + * @return \ArrayIterator + */ + public function getColumnsIterator() : \ArrayIterator + { + $iterator = parent::getColumnsIterator(); + + if ($this->discriminatorColumn) { + $iterator->offsetSet($this->discriminatorColumn->getColumnName(), $this->discriminatorColumn); + } + + return $iterator; + } + + /** + * @return \ArrayIterator + */ + public function getAncestorsIterator() : \ArrayIterator + { + $ancestors = new \ArrayIterator(); + $parent = $this; + + while (($parent = $parent->parent) !== null) { + if ($parent instanceof ClassMetadata && $parent->isMappedSuperclass) { + continue; + } + + $ancestors->append($parent); + } + + return $ancestors; + } + + /** + * @return string + */ + public function getRootClassName() : string + { + return ($this->parent instanceof ClassMetadata && ! $this->parent->isMappedSuperclass) + ? $this->parent->getRootClassName() + : $this->className + ; + } + + /** + * Handles metadata cloning nicely. + */ + public function __clone() + { + if ($this->cache) { + $this->cache = clone $this->cache; + } + + foreach ($this->declaredProperties as $name => $property) { + $this->declaredProperties[$name] = clone $property; + } + } + + /** + * Creates a string representation of this instance. + * + * @return string The string representation of this instance. + * + * @todo Construct meaningful string representation. + */ + public function __toString() + { + return __CLASS__ . '@' . spl_object_hash($this); + } + + /** + * Determines which fields get serialized. + * + * It is only serialized what is necessary for best unserialization performance. + * That means any metadata properties that are not set or empty or simply have + * their default value are NOT serialized. + * + * Parts that are also NOT serialized because they can not be properly unserialized: + * - reflectionClass + * + * @return array The names of all the fields that should be serialized. + */ + public function __sleep() + { + $serialized = []; + + // This metadata is always serialized/cached. + $serialized = array_merge($serialized, [ + 'declaredProperties', + 'fieldNames', + //'embeddedClasses', + 'identifier', + 'className', + 'parent', + 'table', + 'valueGenerationPlan', + ]); + + // The rest of the metadata is only serialized if necessary. + if ($this->changeTrackingPolicy !== ChangeTrackingPolicy::DEFERRED_IMPLICIT) { + $serialized[] = 'changeTrackingPolicy'; + } + + if ($this->customRepositoryClassName) { + $serialized[] = 'customRepositoryClassName'; + } + + if ($this->inheritanceType !== InheritanceType::NONE) { + $serialized[] = 'inheritanceType'; + $serialized[] = 'discriminatorColumn'; + $serialized[] = 'discriminatorValue'; + $serialized[] = 'discriminatorMap'; + $serialized[] = 'subClasses'; + } + + if ($this->isMappedSuperclass) { + $serialized[] = 'isMappedSuperclass'; + } + + if ($this->isEmbeddedClass) { + $serialized[] = 'isEmbeddedClass'; + } + + if ($this->isVersioned()) { + $serialized[] = 'versionProperty'; + } + + if ($this->lifecycleCallbacks) { + $serialized[] = 'lifecycleCallbacks'; + } + + if ($this->entityListeners) { + $serialized[] = 'entityListeners'; + } + + if ($this->namedQueries) { + $serialized[] = 'namedQueries'; + } + + if ($this->namedNativeQueries) { + $serialized[] = 'namedNativeQueries'; + } + + if ($this->sqlResultSetMappings) { + $serialized[] = 'sqlResultSetMappings'; + } + + if ($this->cache) { + $serialized[] = 'cache'; + } + + if ($this->readOnly) { + $serialized[] = 'readOnly'; + } + + return $serialized; + } + + /** + * Restores some state that can not be serialized/unserialized. + * + * @param ReflectionService $reflectionService + * + * @return void + */ + public function wakeupReflection(ReflectionService $reflectionService) : void + { + // Restore ReflectionClass and properties + $this->reflectionClass = $reflectionService->getClass($this->className); + + if (! $this->reflectionClass) { + return; + } + + $this->className = $this->reflectionClass->getName(); + + foreach ($this->declaredProperties as $property) { + /** @var Property $property */ + $property->wakeupReflection($reflectionService); + } + } + + /** + * Validates Identifier. + * + * @return void + * + * @throws MappingException + */ + public function validateIdentifier() : void + { + if ($this->isMappedSuperclass || $this->isEmbeddedClass) { + return; + } + + // Verify & complete identifier mapping + if (! $this->identifier) { + throw MappingException::identifierRequired($this->className); + } + } + + /** + * Validates field value generators. + */ + public function validateValueGenerators() : void + { + foreach ($this->getPropertiesIterator() as $property) { + if (! $property instanceof FieldMetadata || ! $property->hasValueGenerator()) { + continue; + } + + $generator = $property->getValueGenerator(); + + if ($generator->getType() !== GeneratorType::IDENTITY) { + continue; + } + + if (! $property->isPrimaryKey()) { + throw MappingException::nonPrimaryidentityGeneratorNotSupported($this->className); + } + + if ($this->isIdentifierComposite()) { + throw MappingException::compositeIdentityGeneratorNotSupported($this->className); + } + } + } + + /** + * Validates association targets actually exist. + * + * @return void + * + * @throws MappingException + */ + public function validateAssociations() : void + { + array_map( + function (Property $property) { + if (! ($property instanceof AssociationMetadata)) { + return; + } + + $targetEntity = $property->getTargetEntity(); + + if (! class_exists($targetEntity)) { + throw MappingException::invalidTargetEntityClass($targetEntity, $this->className, $property->getName()); + } + }, + $this->declaredProperties + ); + } + + /** + * Validates lifecycle callbacks. + * + * @param ReflectionService $reflectionService + * + * @return void + * + * @throws MappingException + */ + public function validateLifecycleCallbacks(ReflectionService $reflectionService) : void + { + foreach ($this->lifecycleCallbacks as $callbacks) { + /** @var array $callbacks */ + foreach ($callbacks as $callbackFuncName) { + if (! $reflectionService->hasPublicMethod($this->className, $callbackFuncName)) { + throw MappingException::lifecycleCallbackMethodNotFound($this->className, $callbackFuncName); + } + } + } + } + + /** + * Sets the change tracking policy used by this class. + * + * @param string $policy + * + * @return void + */ + public function setChangeTrackingPolicy(string $policy) : void + { + $this->changeTrackingPolicy = $policy; + } + + /** + * Checks whether a field is part of the identifier/primary key field(s). + * + * @param string $fieldName The field name. + * + * @return bool TRUE if the field is part of the table identifier/primary key field(s), FALSE otherwise. + */ + public function isIdentifier(string $fieldName) : bool + { + if (! $this->identifier) { + return false; + } + + if (! $this->isIdentifierComposite()) { + return $fieldName === $this->identifier[0]; + } + + return in_array($fieldName, $this->identifier, true); + } + + /** + * @return bool + */ + public function isIdentifierComposite() : bool + { + return isset($this->identifier[1]); + } + + /** + * Gets the named query. + * + * @see ClassMetadata::$namedQueries + * + * @param string $queryName The query name. + * + * @return string + * + * @throws MappingException + */ + public function getNamedQuery($queryName) : string + { + if (! isset($this->namedQueries[$queryName])) { + throw MappingException::queryNotFound($this->className, $queryName); + } + + return $this->namedQueries[$queryName]; + } + + /** + * Gets all named queries of the class. + * + * @return array + */ + public function getNamedQueries() : array + { + return $this->namedQueries; + } + + /** + * Gets the named native query. + * + * @see ClassMetadata::$namedNativeQueries + * + * @param string $queryName The query name. + * + * @return array + * + * @throws MappingException + */ + public function getNamedNativeQuery($queryName) : array + { + if ( ! isset($this->namedNativeQueries[$queryName])) { + throw MappingException::queryNotFound($this->className, $queryName); + } + + return $this->namedNativeQueries[$queryName]; + } + + /** + * Gets all named native queries of the class. + * + * @return array + */ + public function getNamedNativeQueries() : array + { + return $this->namedNativeQueries; + } + + /** + * Gets the result set mapping. + * + * @see ClassMetadata::$sqlResultSetMappings + * + * @param string $name The result set mapping name. + * + * @return array + * + * @throws MappingException + */ + public function getSqlResultSetMapping($name) + { + if (! isset($this->sqlResultSetMappings[$name])) { + throw MappingException::resultMappingNotFound($this->className, $name); + } + + return $this->sqlResultSetMappings[$name]; + } + + /** + * Gets all sql result set mappings of the class. + * + * @return array + */ + public function getSqlResultSetMappings() + { + return $this->sqlResultSetMappings; + } + + /** + * Validates & completes the basic mapping information for field mapping. + * + * @param FieldMetadata $property + * + * @throws MappingException If something is wrong with the mapping. + */ + protected function validateAndCompleteFieldMapping(FieldMetadata $property) + { + $fieldName = $property->getName(); + $columnName = $property->getColumnName(); + + if (empty($columnName)) { + $columnName = $this->namingStrategy->propertyToColumnName($fieldName, $this->className); + + $property->setColumnName($columnName); + } + + if (! $this->isMappedSuperclass) { + $property->setTableName($this->getTableName()); + } + + // Check for already declared column + if (isset($this->fieldNames[$columnName]) || + ($this->discriminatorColumn !== null && $this->discriminatorColumn->getColumnName() === $columnName)) { + throw MappingException::duplicateColumnName($this->className, $columnName); + } + + // Complete id mapping + if ($property->isPrimaryKey()) { + if ($this->versionProperty !== null && $this->versionProperty->getName() === $fieldName) { + throw MappingException::cannotVersionIdField($this->className, $fieldName); + } + + if ($property->getType()->canRequireSQLConversion()) { + throw MappingException::sqlConversionNotAllowedForPrimaryKeyProperties($property); + }; + + if (! in_array($fieldName, $this->identifier)) { + $this->identifier[] = $fieldName; + } + } + + $this->fieldNames[$columnName] = $fieldName; + } + + /** + * Validates & completes the basic mapping information for field mapping. + * + * @param VersionFieldMetadata $property + * + * @throws MappingException If something is wrong with the mapping. + */ + protected function validateAndCompleteVersionFieldMapping(VersionFieldMetadata $property) + { + $this->versionProperty = $property; + + $options = $property->getOptions(); + + if (isset($options['default'])) { + return; + } + + if (in_array($property->getTypeName(), ['integer', 'bigint', 'smallint'])) { + $property->setOptions(array_merge($options, ['default' => 1])); + + return; + } + + if ($property->getTypeName() === 'datetime') { + $property->setOptions(array_merge($options, ['default' => 'CURRENT_TIMESTAMP'])); + + return; + } + + throw MappingException::unsupportedOptimisticLockingType($property->getType()); + } + + /** + * Validates & completes the basic mapping information that is common to all + * association mappings (one-to-one, many-ot-one, one-to-many, many-to-many). + * + * @param AssociationMetadata $property + * + * @throws MappingException If something is wrong with the mapping. + * @throws CacheException If entity is not cacheable. + */ + protected function validateAndCompleteAssociationMapping(AssociationMetadata $property) + { + $fieldName = $property->getName(); + $targetEntity = $property->getTargetEntity(); + + if (! $targetEntity) { + throw MappingException::missingTargetEntity($fieldName); + } + + $property->setSourceEntity($this->className); + $property->setOwningSide($property->getMappedBy() === null); + $property->setTargetEntity($targetEntity); + + // Complete id mapping + if ($property->isPrimaryKey()) { + if ($property->isOrphanRemoval()) { + throw MappingException::illegalOrphanRemovalOnIdentifierAssociation($this->className, $fieldName); + } + + if ( ! in_array($property->getName(), $this->identifier)) { + if ($property instanceof ToOneAssociationMetadata && count($property->getJoinColumns()) >= 2) { + throw MappingException::cannotMapCompositePrimaryKeyEntitiesAsForeignId( + $property->getTargetEntity(), + $this->className, + $fieldName + ); + } + + $this->identifier[] = $property->getName(); + } + + if ($this->cache && !$property->getCache()) { + throw CacheException::nonCacheableEntityAssociation($this->className, $fieldName); + } + + if ($property instanceof ToManyAssociationMetadata) { + throw MappingException::illegalToManyIdentifierAssociation($this->className, $property->getName()); + } + } + + // Cascades + $cascadeTypes = ['remove', 'persist', 'refresh']; + $cascades = array_map('strtolower', $property->getCascade()); + + if (in_array('all', $cascades)) { + $cascades = $cascadeTypes; + } + + if (count($cascades) !== count(array_intersect($cascades, $cascadeTypes))) { + $diffCascades = array_diff($cascades, array_intersect($cascades, $cascadeTypes)); + + throw MappingException::invalidCascadeOption($diffCascades, $this->className, $fieldName); + } + + $property->setCascade($cascades); + } + + /** + * Validates & completes a to-one association mapping. + * + * @param ToOneAssociationMetadata $property The association mapping to validate & complete. + * + * @throws \RuntimeException + * @throws MappingException + */ + protected function validateAndCompleteToOneAssociationMetadata(ToOneAssociationMetadata $property) + { + $fieldName = $property->getName(); + + if ($property->getJoinColumns()) { + $property->setOwningSide(true); + } + + if ($property->isOwningSide()) { + if (empty($property->getJoinColumns())) { + // Apply default join column + $property->addJoinColumn(new JoinColumnMetadata()); + } + + $uniqueConstraintColumns = []; + + foreach ($property->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + if ($property instanceof OneToOneAssociationMetadata && $this->inheritanceType !== InheritanceType::SINGLE_TABLE) { + if (1 === count($property->getJoinColumns())) { + if (! $property->isPrimaryKey()) { + $joinColumn->setUnique(true); + } + } else { + $uniqueConstraintColumns[] = $joinColumn->getColumnName(); + } + } + + $joinColumn->setTableName(! $this->isMappedSuperclass ? $this->getTableName() : null); + + if (! $joinColumn->getColumnName()) { + $joinColumn->setColumnName($this->namingStrategy->joinColumnName($fieldName, $this->className)); + } + + if (! $joinColumn->getReferencedColumnName()) { + $joinColumn->setReferencedColumnName($this->namingStrategy->referenceColumnName()); + } + + $this->fieldNames[$joinColumn->getColumnName()] = $fieldName; + } + + if ($uniqueConstraintColumns) { + if ( ! $this->table) { + throw new \RuntimeException( + "ClassMetadata::setTable() has to be called before defining a one to one relationship." + ); + } + + $this->table->addUniqueConstraint( + [ + 'name' => sprintf('%s_uniq', $fieldName), + 'columns' => $uniqueConstraintColumns, + 'options' => [], + 'flags' => [], + ] + ); + } + } + + if ($property->isOrphanRemoval()) { + $cascades = $property->getCascade(); + + if (! in_array('remove', $cascades)) { + $cascades[] = 'remove'; + + $property->setCascade($cascades); + } + + // @todo guilhermeblanco where is this used? + // @todo guilhermeblanco Shouldn￿'t we iterate through JoinColumns to set non-uniqueness? + //$property->setUnique(false); + } + + if ($property->isPrimaryKey() && ! $property->isOwningSide()) { + throw MappingException::illegalInverseIdentifierAssociation($this->className, $fieldName); + } + } + + /** + * Validates & completes a to-many association mapping. + * + * @param ToManyAssociationMetadata $property The association mapping to validate & complete. + * + * @throws MappingException + */ + protected function validateAndCompleteToManyAssociationMetadata(ToManyAssociationMetadata $property) + { + // Do nothing + } + + /** + * Validates & completes a one-to-one association mapping. + * + * @param OneToOneAssociationMetadata $property The association mapping to validate & complete. + */ + protected function validateAndCompleteOneToOneMapping(OneToOneAssociationMetadata $property) + { + // Do nothing + } + + /** + * Validates & completes a many-to-one association mapping. + * + * @param ManyToOneAssociationMetadata $property The association mapping to validate & complete. + * + * @throws MappingException + */ + protected function validateAndCompleteManyToOneMapping(ManyToOneAssociationMetadata $property) + { + // A many-to-one mapping is essentially a one-one backreference + if ($property->isOrphanRemoval()) { + throw MappingException::illegalOrphanRemoval($this->className, $property->getName()); + } + } + + /** + * Validates & completes a one-to-many association mapping. + * + * @param OneToManyAssociationMetadata $property The association mapping to validate & complete. + * + * @throws MappingException + */ + protected function validateAndCompleteOneToManyMapping(OneToManyAssociationMetadata $property) + { + // OneToMany MUST be inverse side + $property->setOwningSide(false); + + // OneToMany MUST have mappedBy + if (! $property->getMappedBy()) { + throw MappingException::oneToManyRequiresMappedBy($property->getName()); + } + + if ($property->isOrphanRemoval()) { + $cascades = $property->getCascade(); + + if (! in_array('remove', $cascades)) { + $cascades[] = 'remove'; + + $property->setCascade($cascades); + } + } + } + + /** + * Validates & completes a many-to-many association mapping. + * + * @param ManyToManyAssociationMetadata $property The association mapping to validate & complete. + * + * @throws MappingException + */ + protected function validateAndCompleteManyToManyMapping(ManyToManyAssociationMetadata $property) + { + if ($property->isOwningSide()) { + // owning side MUST have a join table + $joinTable = $property->getJoinTable() ?: new JoinTableMetadata(); + + $property->setJoinTable($joinTable); + + if (! $joinTable->getName()) { + $joinTableName = $this->namingStrategy->joinTableName( + $property->getSourceEntity(), + $property->getTargetEntity(), + $property->getName() + ); + + $joinTable->setName($joinTableName); + } + + $selfReferencingEntityWithoutJoinColumns = $property->getSourceEntity() == $property->getTargetEntity() && ! $joinTable->hasColumns(); + + if (! $joinTable->getJoinColumns()) { + $referencedColumnName = $this->namingStrategy->referenceColumnName(); + $sourceReferenceName = $selfReferencingEntityWithoutJoinColumns ? 'source' : $referencedColumnName; + $columnName = $this->namingStrategy->joinKeyColumnName($property->getSourceEntity(), $sourceReferenceName); + $joinColumn = new JoinColumnMetadata(); + + $joinColumn->setColumnName($columnName); + $joinColumn->setReferencedColumnName($referencedColumnName); + $joinColumn->setOnDelete('CASCADE'); + + $joinTable->addJoinColumn($joinColumn); + } + + if (! $joinTable->getInverseJoinColumns()) { + $referencedColumnName = $this->namingStrategy->referenceColumnName(); + $targetReferenceName = $selfReferencingEntityWithoutJoinColumns ? 'target' : $referencedColumnName; + $columnName = $this->namingStrategy->joinKeyColumnName($property->getTargetEntity(), $targetReferenceName); + $joinColumn = new JoinColumnMetadata(); + + $joinColumn->setColumnName($columnName); + $joinColumn->setReferencedColumnName($referencedColumnName); + $joinColumn->setOnDelete('CASCADE'); + + $joinTable->addInverseJoinColumn($joinColumn); + } + + foreach ($joinTable->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + if (! $joinColumn->getReferencedColumnName()) { + $joinColumn->setReferencedColumnName($this->namingStrategy->referenceColumnName()); + } + + $referencedColumnName = $joinColumn->getReferencedColumnName(); + + if (! $joinColumn->getColumnName()) { + $columnName = $this->namingStrategy->joinKeyColumnName( + $property->getSourceEntity(), + $referencedColumnName + ); + + $joinColumn->setColumnName($columnName); + } + } + + foreach ($joinTable->getInverseJoinColumns() as $inverseJoinColumn) { + /** @var JoinColumnMetadata $inverseJoinColumn */ + if (! $inverseJoinColumn->getReferencedColumnName()) { + $inverseJoinColumn->setReferencedColumnName($this->namingStrategy->referenceColumnName()); + } + + $referencedColumnName = $inverseJoinColumn->getReferencedColumnName(); + + if (! $inverseJoinColumn->getColumnName()) { + $columnName = $this->namingStrategy->joinKeyColumnName( + $property->getTargetEntity(), + $referencedColumnName + ); + + $inverseJoinColumn->setColumnName($columnName); + } + } + } + } + + /** + * {@inheritDoc} + */ + public function getIdentifierFieldNames() + { + return $this->identifier; + } + + /** + * Gets the name of the single id field. Note that this only works on + * entity classes that have a single-field pk. + * + * @return string + * + * @throws MappingException If the class has a composite primary key. + */ + public function getSingleIdentifierFieldName() + { + if ($this->isIdentifierComposite()) { + throw MappingException::singleIdNotAllowedOnCompositePrimaryKey($this->className); + } + + if ( ! isset($this->identifier[0])) { + throw MappingException::noIdDefined($this->className); + } + + return $this->identifier[0]; + } + + /** + * INTERNAL: + * Sets the mapped identifier/primary key fields of this class. + * Mainly used by the ClassMetadataFactory to assign inherited identifiers. + * + * @param array $identifier + * + * @return void + */ + public function setIdentifier(array $identifier) + { + $this->identifier = $identifier; + } + + /** + * {@inheritDoc} + */ + public function getIdentifier() + { + return $this->identifier; + } + + /** + * {@inheritDoc} + */ + public function hasField($fieldName) + { + return isset($this->declaredProperties[$fieldName]) + && $this->declaredProperties[$fieldName] instanceof FieldMetadata; + } + + /** + * Returns an array with identifier column names and their corresponding ColumnMetadata. + * + * @param EntityManagerInterface $em + * + * @return array + */ + public function getIdentifierColumns(EntityManagerInterface $em) : array + { + $columns = []; + + foreach ($this->identifier as $idProperty) { + $property = $this->getProperty($idProperty); + + if ($property instanceof FieldMetadata) { + $columns[$property->getColumnName()] = $property; + + continue; + } + + /** @var AssociationMetadata $property */ + + // Association defined as Id field + $targetClass = $em->getClassMetadata($property->getTargetEntity()); + + if (! $property->isOwningSide()) { + $property = $targetClass->getProperty($property->getMappedBy()); + $targetClass = $em->getClassMetadata($property->getTargetEntity()); + } + + $joinColumns = $property instanceof ManyToManyAssociationMetadata + ? $property->getJoinTable()->getInverseJoinColumns() + : $property->getJoinColumns() + ; + + foreach ($joinColumns as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $columnName = $joinColumn->getColumnName(); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $em)); + } + + $columns[$columnName] = $joinColumn; + } + } + + return $columns; + } + + /** + * Gets the name of the primary table. + * + * @return string|null + */ + public function getTableName() : ?string + { + return $this->table->getName(); + } + + /** + * Gets primary table's schema name. + * + * @return string|null + */ + public function getSchemaName() : ?string + { + return $this->table->getSchema(); + } + + /** + * Gets the table name to use for temporary identifier tables of this class. + * + * @return string + */ + public function getTemporaryIdTableName() : string + { + $schema = null === $this->getSchemaName() + ? '' + : $this->getSchemaName() . '_' + ; + + // replace dots with underscores because PostgreSQL creates temporary tables in a special schema + return $schema . $this->getTableName() . '_id_tmp'; + } + + /** + * Sets the mapped subclasses of this class. + * + * @todo guilhermeblanco Only used for ClassMetadataTest. Remove if possible! + * + * @param array $subclasses The names of all mapped subclasses. + * + * @return void + */ + public function setSubclasses(array $subclasses) : void + { + foreach ($subclasses as $subclass) { + $this->subClasses[] = $subclass; + } + } + + /** + * @return array + */ + public function getSubClasses() : array + { + return $this->subClasses; + } + + /** + * Sets the inheritance type used by the class and its subclasses. + * + * @param integer $type + * + * @return void + * + * @throws MappingException + */ + public function setInheritanceType($type) : void + { + if ( ! $this->isInheritanceType($type)) { + throw MappingException::invalidInheritanceType($this->className, $type); + } + + $this->inheritanceType = $type; + } + + /** + * Sets the override property mapping for an entity relationship. + * + * @param Property $property + * + * @return void + * + * @throws \RuntimeException + * @throws MappingException + * @throws CacheException + */ + public function setPropertyOverride(Property $property) : void + { + $fieldName = $property->getName(); + + if (! isset($this->declaredProperties[$fieldName])) { + throw MappingException::invalidOverrideFieldName($this->className, $fieldName); + } + + $originalProperty = $this->getProperty($fieldName); + $originalPropertyClassName = get_class($originalProperty); + + // If moving from transient to persistent, assume it's a new property + if ($originalPropertyClassName === TransientMetadata::class) { + unset($this->declaredProperties[$fieldName]); + + $this->addProperty($property); + + return; + } + + // Do not allow to change property type + if ($originalPropertyClassName !== get_class($property)) { + throw MappingException::invalidOverridePropertyType($this->className, $fieldName); + } + + // Do not allow to change version property + if ($originalProperty instanceof VersionFieldMetadata) { + throw MappingException::invalidOverrideVersionField($this->className, $fieldName); + } + + unset($this->declaredProperties[$fieldName]); + + if ($property instanceof FieldMetadata) { + // Unset defined fieldName prior to override + unset($this->fieldNames[$originalProperty->getColumnName()]); + + // Revert what should not be allowed to change + $property->setDeclaringClass($originalProperty->getDeclaringClass()); + $property->setPrimaryKey($originalProperty->isPrimaryKey()); + } else if ($property instanceof AssociationMetadata) { + // Unset all defined fieldNames prior to override + if ($originalProperty instanceof ToOneAssociationMetadata && $originalProperty->isOwningSide()) { + foreach ($originalProperty->getJoinColumns() as $joinColumn) { + unset($this->fieldNames[$joinColumn->getColumnName()]); + } + } + + // Override what it should be allowed to change + if ($property->getInversedBy()) { + $originalProperty->setInversedBy($property->getInversedBy()); + } + + if ($property->getFetchMode() !== $originalProperty->getFetchMode()) { + $originalProperty->setFetchMode($property->getFetchMode()); + } + + if ($originalProperty instanceof ToOneAssociationMetadata && $property->getJoinColumns()) { + $originalProperty->setJoinColumns($property->getJoinColumns()); + } else if ($originalProperty instanceof ManyToManyAssociationMetadata && $property->getJoinTable()) { + $originalProperty->setJoinTable($property->getJoinTable()); + } + + $property = $originalProperty; + } + + $this->addProperty($property); + } + + /** + * Checks if this entity is the root in any entity-inheritance-hierarchy. + * + * @return bool + */ + public function isRootEntity() + { + return $this->className === $this->getRootClassName(); + } + + /** + * Checks whether a mapped field is inherited from a superclass. + * + * @param string $fieldName + * + * @return boolean TRUE if the field is inherited, FALSE otherwise. + */ + public function isInheritedProperty($fieldName) + { + $declaringClass = $this->declaredProperties[$fieldName]->getDeclaringClass(); + + return ! ($declaringClass->className === $this->className); + } + + /** + * {@inheritdoc} + */ + public function setTable(TableMetadata $table) : void + { + $this->table = $table; + + if (empty($table->getName())) { + $table->setName($this->namingStrategy->classToTableName($this->className)); + } + } + + /** + * Checks whether the given type identifies an inheritance type. + * + * @param integer $type + * + * @return boolean TRUE if the given type identifies an inheritance type, FALSe otherwise. + */ + private function isInheritanceType($type) + { + return $type == InheritanceType::NONE + || $type == InheritanceType::SINGLE_TABLE + || $type == InheritanceType::JOINED + || $type == InheritanceType::TABLE_PER_CLASS; + } + + /** + * @param string $columnName + * + * @return LocalColumnMetadata|null + */ + public function getColumn(string $columnName): ?LocalColumnMetadata + { + foreach ($this->declaredProperties as $property) { + if ($property instanceof LocalColumnMetadata && $property->getColumnName() === $columnName) { + return $property; + } + } + + return null; + } + + /** + * Add a property mapping. + * + * @param Property $property + * + * @throws \RuntimeException + * @throws MappingException + * @throws CacheException + */ + public function addProperty(Property $property) + { + $fieldName = $property->getName(); + + // Check for empty field name + if (empty($fieldName)) { + throw MappingException::missingFieldName($this->className); + } + + $property->setDeclaringClass($this); + + switch (true) { + case ($property instanceof VersionFieldMetadata): + $this->validateAndCompleteFieldMapping($property); + $this->validateAndCompleteVersionFieldMapping($property); + break; + + case ($property instanceof FieldMetadata): + $this->validateAndCompleteFieldMapping($property); + break; + + case ($property instanceof OneToOneAssociationMetadata): + $this->validateAndCompleteAssociationMapping($property); + $this->validateAndCompleteToOneAssociationMetadata($property); + $this->validateAndCompleteOneToOneMapping($property); + break; + + case ($property instanceof OneToManyAssociationMetadata): + $this->validateAndCompleteAssociationMapping($property); + $this->validateAndCompleteToManyAssociationMetadata($property); + $this->validateAndCompleteOneToManyMapping($property); + break; + + case ($property instanceof ManyToOneAssociationMetadata): + $this->validateAndCompleteAssociationMapping($property); + $this->validateAndCompleteToOneAssociationMetadata($property); + $this->validateAndCompleteManyToOneMapping($property); + break; + + case ($property instanceof ManyToManyAssociationMetadata): + $this->validateAndCompleteAssociationMapping($property); + $this->validateAndCompleteToManyAssociationMetadata($property); + $this->validateAndCompleteManyToManyMapping($property); + break; + + default: + // Transient properties are ignored on purpose here! =) + break; + } + + $this->addDeclaredProperty($property); + } + + /** + * INTERNAL: + * Adds a property mapping without completing/validating it. + * This is mainly used to add inherited property mappings to derived classes. + * + * @param Property $property + * + * @return void + */ + public function addInheritedProperty(Property $property) + { + $inheritedProperty = clone $property; + $declaringClass = $property->getDeclaringClass(); + + if ($inheritedProperty instanceof FieldMetadata) { + if (! $declaringClass->isMappedSuperclass) { + $inheritedProperty->setTableName($property->getTableName()); + } + + $this->fieldNames[$property->getColumnName()] = $property->getName(); + } else if ($inheritedProperty instanceof AssociationMetadata) { + if ($declaringClass->isMappedSuperclass) { + $inheritedProperty->setSourceEntity($this->className); + } + + // Need to add inherited fieldNames + if ($inheritedProperty instanceof ToOneAssociationMetadata && $inheritedProperty->isOwningSide()) { + foreach ($inheritedProperty->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $this->fieldNames[$joinColumn->getColumnName()] = $property->getName(); + } + } + } + + if (isset($this->declaredProperties[$property->getName()])) { + throw MappingException::duplicateProperty($this->className, $this->getProperty($property->getName())); + } + + $this->declaredProperties[$property->getName()] = $inheritedProperty; + + if ($inheritedProperty instanceof VersionFieldMetadata) { + $this->versionProperty = $inheritedProperty; + } + } + + /** + * INTERNAL: + * Adds a named query to this class. + * + * @param string $name + * @param string $query + * + * @return void + * + * @throws MappingException + */ + public function addNamedQuery(string $name, string $query) + { + if (isset($this->namedQueries[$name])) { + throw MappingException::duplicateQueryMapping($this->className, $name); + } + + $this->namedQueries[$name] = $query; + } + + /** + * INTERNAL: + * Adds a named native query to this class. + * + * @param string $name + * @param string $query + * @param array $queryMapping + * + * @return void + * + * @throws MappingException + */ + public function addNamedNativeQuery(string $name, string $query, array $queryMapping) + { + if (isset($this->namedNativeQueries[$name])) { + throw MappingException::duplicateQueryMapping($this->className, $name); + } + + if (! isset($queryMapping['resultClass']) && ! isset($queryMapping['resultSetMapping'])) { + throw MappingException::missingQueryMapping($this->className, $name); + } + + if (isset($queryMapping['resultClass']) && $queryMapping['resultClass'] !== '__CLASS__') { + $queryMapping['resultClass'] = $this->fullyQualifiedClassName($queryMapping['resultClass']); + } + + $this->namedNativeQueries[$name] = array_merge(['query' => $query], $queryMapping); + } + + /** + * INTERNAL: + * Adds a sql result set mapping to this class. + * + * @param array $resultMapping + * + * @return void + * + * @throws MappingException + */ + public function addSqlResultSetMapping(array $resultMapping) + { + if (!isset($resultMapping['name'])) { + throw MappingException::nameIsMandatoryForSqlResultSetMapping($this->className); + } + + if (isset($this->sqlResultSetMappings[$resultMapping['name']])) { + throw MappingException::duplicateResultSetMapping($this->className, $resultMapping['name']); + } + + if (isset($resultMapping['entities'])) { + foreach ($resultMapping['entities'] as $key => $entityResult) { + if (! isset($entityResult['entityClass'])) { + throw MappingException::missingResultSetMappingEntity($this->className, $resultMapping['name']); + } + + $entityClassName = ($entityResult['entityClass'] !== '__CLASS__') + ? $this->fullyQualifiedClassName($entityResult['entityClass']) + : $entityResult['entityClass'] + ; + + $resultMapping['entities'][$key]['entityClass'] = $entityClassName; + + if (isset($entityResult['fields'])) { + foreach ($entityResult['fields'] as $k => $field) { + if (! isset($field['name'])) { + throw MappingException::missingResultSetMappingFieldName($this->className, $resultMapping['name']); + } + + if (! isset($field['column'])) { + $fieldName = $field['name']; + + if (strpos($fieldName, '.')) { + list(, $fieldName) = explode('.', $fieldName); + } + + $resultMapping['entities'][$key]['fields'][$k]['column'] = $fieldName; + } + } + } + } + } + + $this->sqlResultSetMappings[$resultMapping['name']] = $resultMapping; + } + + /** + * Registers a custom repository class for the entity class. + * + * @param string|null $repositoryClassName The class name of the custom mapper. + * + * @return void + */ + public function setCustomRepositoryClassName(?string $repositoryClassName) + { + $this->customRepositoryClassName = $repositoryClassName; + } + + /** + * @return string|null + */ + public function getCustomRepositoryClassName() : ?string + { + return $this->customRepositoryClassName; + } + + /** + * Whether the class has any attached lifecycle listeners or callbacks for a lifecycle event. + * + * @param string $lifecycleEvent + * + * @return boolean + */ + public function hasLifecycleCallbacks($lifecycleEvent) + { + return isset($this->lifecycleCallbacks[$lifecycleEvent]); + } + + /** + * Gets the registered lifecycle callbacks for an event. + * + * @param string $event + * + * @return array + */ + public function getLifecycleCallbacks($event) + { + return isset($this->lifecycleCallbacks[$event]) ? $this->lifecycleCallbacks[$event] : []; + } + + /** + * Adds a lifecycle callback for entities of this class. + * + * @param string $callback + * @param string $event + * + * @return void + */ + public function addLifecycleCallback($callback, $event) + { + if (isset($this->lifecycleCallbacks[$event]) && in_array($callback, $this->lifecycleCallbacks[$event])) { + return; + } + + $this->lifecycleCallbacks[$event][] = $callback; + } + + /** + * Sets the lifecycle callbacks for entities of this class. + * Any previously registered callbacks are overwritten. + * + * @param array $callbacks + * + * @return void + */ + public function setLifecycleCallbacks(array $callbacks) : void + { + $this->lifecycleCallbacks = $callbacks; + } + + /** + * Adds a entity listener for entities of this class. + * + * @param string $eventName The entity lifecycle event. + * @param string $class The listener class. + * @param string $method The listener callback method. + * + * @return void + * + * @throws \Doctrine\ORM\Mapping\MappingException + */ + public function addEntityListener(string $eventName, string $class, string $method) : void + { + $listener = [ + 'class' => $class, + 'method' => $method, + ]; + + if (! class_exists($class)) { + throw MappingException::entityListenerClassNotFound($class, $this->className); + } + + if (! method_exists($class, $method)) { + throw MappingException::entityListenerMethodNotFound($class, $method, $this->className); + } + + if (isset($this->entityListeners[$eventName]) && in_array($listener, $this->entityListeners[$eventName], true)) { + throw MappingException::duplicateEntityListener($class, $method, $this->className); + } + + $this->entityListeners[$eventName][] = $listener; + } + + /** + * Sets the discriminator column definition. + * + * @param DiscriminatorColumnMetadata $discriminatorColumn + * + * @return void + * + * @throws MappingException + * + * @see getDiscriminatorColumn() + */ + public function setDiscriminatorColumn(DiscriminatorColumnMetadata $discriminatorColumn) : void + { + if (isset($this->fieldNames[$discriminatorColumn->getColumnName()])) { + throw MappingException::duplicateColumnName($this->className, $discriminatorColumn->getColumnName()); + } + + $discriminatorColumn->setTableName($discriminatorColumn->getTableName() ?? $this->getTableName()); + + $allowedTypeList = ['boolean', 'array', 'object', 'datetime', 'time', 'date']; + + if (in_array($discriminatorColumn->getTypeName(), $allowedTypeList, true)) { + throw MappingException::invalidDiscriminatorColumnType($discriminatorColumn->getTypeName()); + } + + $this->discriminatorColumn = $discriminatorColumn; + } + + /** + * Sets the discriminator values used by this class. + * Used for JOINED and SINGLE_TABLE inheritance mapping strategies. + * + * @param array $map + * + * @return void + * + * @throws MappingException + */ + public function setDiscriminatorMap(array $map) : void + { + foreach ($map as $value => $className) { + $this->addDiscriminatorMapClass($value, $className); + } + } + + /** + * Adds one entry of the discriminator map with a new class and corresponding name. + * + * @param string|int $name + * @param string $className + * + * @return void + * + * @throws MappingException + */ + public function addDiscriminatorMapClass($name, string $className) : void + { + $this->discriminatorMap[$name] = $className; + + if ($this->className === $className) { + $this->discriminatorValue = $name; + + return; + } + + if (! (class_exists($className) || interface_exists($className))) { + throw MappingException::invalidClassInDiscriminatorMap($className, $this->className); + } + + if (is_subclass_of($className, $this->className) && ! in_array($className, $this->subClasses, true)) { + $this->subClasses[] = $className; + } + } + + /** + * @return ValueGenerationPlan + */ + public function getValueGenerationPlan() : ValueGenerationPlan + { + return $this->valueGenerationPlan; + } + + /** + * @param ValueGenerationPlan $valueGenerationPlan + */ + public function setValueGenerationPlan(ValueGenerationPlan $valueGenerationPlan) : void + { + $this->valueGenerationPlan = $valueGenerationPlan; + } + + /** + * Checks whether the class has a named query with the given query name. + * + * @param string $queryName + * + * @return boolean + */ + public function hasNamedQuery($queryName) : bool + { + return isset($this->namedQueries[$queryName]); + } + + /** + * Checks whether the class has a named native query with the given query name. + * + * @param string $queryName + * + * @return boolean + */ + public function hasNamedNativeQuery($queryName) : bool + { + return isset($this->namedNativeQueries[$queryName]); + } + + /** + * Checks whether the class has a named native query with the given query name. + * + * @param string $name + * + * @return boolean + */ + public function hasSqlResultSetMapping($name) : bool + { + return isset($this->sqlResultSetMappings[$name]); + } + + /** + * Marks this class as read only, no change tracking is applied to it. + * + * @return void + */ + public function asReadOnly() : void + { + $this->readOnly = true; + } + + /** + * Whether this class is read only or not. + * + * @return bool + */ + public function isReadOnly() : bool + { + return $this->readOnly; + } + + /** + * @return bool + */ + public function isVersioned() : bool + { + return $this->versionProperty !== null; + } + + /** + * Map Embedded Class + * + * @param array $mapping + * + * @throws MappingException + * @return void + */ + public function mapEmbedded(array $mapping) : void + { + /*if (isset($this->declaredProperties[$mapping['fieldName']])) { + throw MappingException::duplicateProperty($this->className, $this->getProperty($mapping['fieldName'])); + } + + $this->embeddedClasses[$mapping['fieldName']] = [ + 'class' => $this->fullyQualifiedClassName($mapping['class']), + 'columnPrefix' => $mapping['columnPrefix'], + 'declaredField' => isset($mapping['declaredField']) ? $mapping['declaredField'] : null, + 'originalField' => isset($mapping['originalField']) ? $mapping['originalField'] : null, + 'declaringClass' => $this, + ];*/ + } + + /** + * Inline the embeddable class + * + * @param string $property + * @param ClassMetadata $embeddable + */ + public function inlineEmbeddable($property, ClassMetadata $embeddable) : void + { + /*foreach ($embeddable->fieldMappings as $fieldName => $fieldMapping) { + $fieldMapping['fieldName'] = $property . "." . $fieldName; + $fieldMapping['originalClass'] = $fieldMapping['originalClass'] ?? $embeddable->getClassName(); + $fieldMapping['originalField'] = $fieldMapping['originalField'] ?? $fieldName; + $fieldMapping['declaredField'] = isset($fieldMapping['declaredField']) + ? $property . '.' . $fieldMapping['declaredField'] + : $property; + + if (! empty($this->embeddedClasses[$property]['columnPrefix'])) { + $fieldMapping['columnName'] = $this->embeddedClasses[$property]['columnPrefix'] . $fieldMapping['columnName']; + } elseif ($this->embeddedClasses[$property]['columnPrefix'] !== false) { + $fieldMapping['columnName'] = $this->namingStrategy->embeddedFieldToColumnName( + $property, + $fieldMapping['columnName'], + $this->reflectionClass->getName(), + $embeddable->reflectionClass->getName() + ); + } + + $this->mapField($fieldMapping); + }*/ + } } diff --git a/lib/Doctrine/ORM/Mapping/ClassMetadataBuildingContext.php b/lib/Doctrine/ORM/Mapping/ClassMetadataBuildingContext.php new file mode 100644 index 00000000000..fa16e0b47de --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/ClassMetadataBuildingContext.php @@ -0,0 +1,132 @@ +. + */ + +declare(strict_types=1); + +namespace Doctrine\ORM\Mapping; + +use Doctrine\ORM\Mapping\Factory\DefaultNamingStrategy; +use Doctrine\ORM\Mapping\Factory\NamingStrategy; +use Doctrine\ORM\Reflection\ReflectionService; + +/** + * Class ClassMetadataBuildingContext + * + * @package Doctrine\ORM\Mapping\Factory + * @since 3.0 + * + * @author Guilherme Blanco + */ +class ClassMetadataBuildingContext +{ + /** @var AbstractClassMetadataFactory */ + private $classMetadataFactory; + + /** @var ReflectionService */ + private $reflectionService; + + /** @var NamingStrategy */ + private $namingStrategy; + + /** + * @var array + */ + protected $secondPassList = []; + + /** + * @var bool + */ + private $inSecondPass = false; + + /** + * ClassMetadataBuildingContext constructor. + * + * @param AbstractClassMetadataFactory $classMetadataFactory + * @param ReflectionService $reflectionService + * @param NamingStrategy|null $namingStrategy + */ + public function __construct( + AbstractClassMetadataFactory $classMetadataFactory, + ReflectionService $reflectionService, + ?NamingStrategy $namingStrategy = null + ) + { + $this->classMetadataFactory = $classMetadataFactory; + $this->reflectionService = $reflectionService; + $this->namingStrategy = $namingStrategy ?: new DefaultNamingStrategy(); + } + + /** + * @return AbstractClassMetadataFactory + */ + public function getClassMetadataFactory() : AbstractClassMetadataFactory + { + return $this->classMetadataFactory; + } + + /** + * @return ReflectionService + */ + public function getReflectionService() : ReflectionService + { + return $this->reflectionService; + } + + /** + * @return NamingStrategy + */ + public function getNamingStrategy() : NamingStrategy + { + return $this->namingStrategy; + } + + /** + * @param SecondPass $secondPass + * + * @return void + */ + public function addSecondPass(SecondPass $secondPass) : void + { + $this->secondPassList[] = $secondPass; + } + + /** + * @return bool + */ + public function isInSecondPass() : bool + { + return $this->inSecondPass; + } + + /** + * @return void + */ + public function validate() : void + { + $this->inSecondPass = true; + + foreach ($this->secondPassList as $secondPass) { + /** @var SecondPass $secondPass */ + $secondPass->process($this); + } + + $this->inSecondPass = false; + } +} diff --git a/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php b/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php index a1412d2f1ad..d57b9ceb333 100644 --- a/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php +++ b/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php @@ -1,35 +1,20 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Mapping; -use Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory; -use Doctrine\Common\Persistence\Mapping\ClassMetadata as ClassMetadataInterface; -use Doctrine\Common\Persistence\Mapping\ReflectionService; use Doctrine\DBAL\Platforms; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Event\LoadClassMetadataEventArgs; use Doctrine\ORM\Event\OnClassMetadataNotFoundEventArgs; use Doctrine\ORM\Events; -use Doctrine\ORM\Id\BigIntegerIdentityGenerator; -use Doctrine\ORM\Id\IdentityGenerator; use Doctrine\ORM\ORMException; +use Doctrine\ORM\Sequencing; +use Doctrine\ORM\Sequencing\Planning\ColumnValueGeneratorExecutor; +use Doctrine\ORM\Sequencing\Planning\CompositeValueGenerationPlan; +use Doctrine\ORM\Sequencing\Planning\NoopValueGenerationPlan; +use Doctrine\ORM\Sequencing\Planning\SingleValueGenerationPlan; use ReflectionException; /** @@ -56,7 +41,7 @@ class ClassMetadataFactory extends AbstractClassMetadataFactory private $targetPlatform; /** - * @var \Doctrine\Common\Persistence\Mapping\Driver\MappingDriver + * @var Driver\MappingDriver */ private $driver; @@ -66,18 +51,13 @@ class ClassMetadataFactory extends AbstractClassMetadataFactory private $evm; /** - * @var array - */ - private $embeddablesActiveNesting = []; - - /** - * {@inheritDoc} + * {@inheritdoc} */ - protected function loadMetadata($name) + protected function loadMetadata(string $name, ClassMetadataBuildingContext $metadataBuildingContext) : array { - $loaded = parent::loadMetadata($name); + $loaded = parent::loadMetadata($name, $metadataBuildingContext); - array_map([$this, 'resolveDiscriminatorValue'], array_map([$this, 'getMetadataFor'], $loaded)); + array_map([$this, 'resolveDiscriminatorValue'], $loaded); return $loaded; } @@ -91,9 +71,11 @@ public function setEntityManager(EntityManagerInterface $em) } /** - * {@inheritDoc} + * {@inheritdoc} + * + * @throws ORMException */ - protected function initialize() + protected function initialize() : void { $this->driver = $this->em->getConfiguration()->getMetadataDriverImpl(); $this->evm = $this->em->getEventManager(); @@ -101,15 +83,18 @@ protected function initialize() } /** - * {@inheritDoc} + * {@inheritdoc} */ - protected function onNotFoundMetadata($className) + protected function onNotFoundMetadata( + string $className, + ClassMetadataBuildingContext $metadataBuildingContext + ) : ?ClassMetadata { if (! $this->evm->hasListeners(Events::onClassMetadataNotFound)) { - return; + return null; } - $eventArgs = new OnClassMetadataNotFoundEventArgs($className, $this->em); + $eventArgs = new OnClassMetadataNotFoundEventArgs($className, $metadataBuildingContext, $this->em); $this->evm->dispatchEvent(Events::onClassMetadataNotFound, $eventArgs); @@ -117,177 +102,174 @@ protected function onNotFoundMetadata($className) } /** - * {@inheritDoc} + * {@inheritdoc} + * + * @throws MappingException + * @throws ORMException */ - protected function doLoadMetadata($class, $parent, $rootEntityFound, array $nonSuperclassParents) + protected function doLoadMetadata( + string $className, + ?ClassMetadata $parent, + ClassMetadataBuildingContext $metadataBuildingContext + ) : ClassMetadata { - /* @var $class ClassMetadata */ - /* @var $parent ClassMetadata */ + $classMetadata = new ClassMetadata($className, $metadataBuildingContext); + if ($parent) { - $class->setInheritanceType($parent->inheritanceType); - $class->setDiscriminatorColumn($parent->discriminatorColumn); - $class->setIdGeneratorType($parent->generatorType); - $this->addInheritedFields($class, $parent); - $this->addInheritedRelations($class, $parent); - $this->addInheritedEmbeddedClasses($class, $parent); - $class->setIdentifier($parent->identifier); - $class->setVersioned($parent->isVersioned); - $class->setVersionField($parent->versionField); - $class->setDiscriminatorMap($parent->discriminatorMap); - $class->setLifecycleCallbacks($parent->lifecycleCallbacks); - $class->setChangeTrackingPolicy($parent->changeTrackingPolicy); - - if ( ! empty($parent->customGeneratorDefinition)) { - $class->setCustomGeneratorDefinition($parent->customGeneratorDefinition); + $classMetadata->setParent($parent); + + $this->addInheritedProperties($classMetadata, $parent); + + $classMetadata->setInheritanceType($parent->inheritanceType); + $classMetadata->setIdentifier($parent->identifier); + + if ($parent->discriminatorColumn) { + $classMetadata->setDiscriminatorColumn($parent->discriminatorColumn); + $classMetadata->setDiscriminatorMap($parent->discriminatorMap); } + $classMetadata->setLifecycleCallbacks($parent->lifecycleCallbacks); + $classMetadata->setChangeTrackingPolicy($parent->changeTrackingPolicy); + if ($parent->isMappedSuperclass) { - $class->setCustomRepositoryClass($parent->customRepositoryClassName); + $classMetadata->setCustomRepositoryClassName($parent->getCustomRepositoryClassName()); } } // Invoke driver try { - $this->driver->loadMetadataForClass($class->getName(), $class); + $this->driver->loadMetadataForClass($classMetadata->getClassName(), $classMetadata, $metadataBuildingContext); } catch (ReflectionException $e) { - throw MappingException::reflectionFailure($class->getName(), $e); - } - - // If this class has a parent the id generator strategy is inherited. - // However this is only true if the hierarchy of parents contains the root entity, - // if it consists of mapped superclasses these don't necessarily include the id field. - if ($parent && $rootEntityFound) { - $this->inheritIdGeneratorMapping($class, $parent); - } else { - $this->completeIdGeneratorMapping($class); + throw MappingException::reflectionFailure($classMetadata->getClassName(), $e); } - if (!$class->isMappedSuperclass) { - foreach ($class->embeddedClasses as $property => $embeddableClass) { + $this->completeIdentifierGeneratorMappings($classMetadata); - if (isset($embeddableClass['inherited'])) { - continue; - } - - if ( ! (isset($embeddableClass['class']) && $embeddableClass['class'])) { - throw MappingException::missingEmbeddedClass($property); - } + if ($parent) { + $this->addInheritedNamedQueries($classMetadata, $parent); - if (isset($this->embeddablesActiveNesting[$embeddableClass['class']])) { - throw MappingException::infiniteEmbeddableNesting($class->name, $property); - } + if ($parent->getCache()) { + $classMetadata->setCache(clone $parent->getCache()); + } - $this->embeddablesActiveNesting[$class->name] = true; + if ( ! empty($parent->namedNativeQueries)) { + $this->addInheritedNamedNativeQueries($classMetadata, $parent); + } - $embeddableMetadata = $this->getMetadataFor($embeddableClass['class']); + if ( ! empty($parent->sqlResultSetMappings)) { + $this->addInheritedSqlResultSetMappings($classMetadata, $parent); + } - if ($embeddableMetadata->isEmbeddedClass) { - $this->addNestedEmbeddedClasses($embeddableMetadata, $class, $property); - } + if ( ! empty($parent->entityListeners) && empty($classMetadata->entityListeners)) { + $classMetadata->entityListeners = $parent->entityListeners; + } + } - $identifier = $embeddableMetadata->getIdentifier(); + if (! $classMetadata->discriminatorMap && $classMetadata->inheritanceType !== InheritanceType::NONE && $classMetadata->isRootEntity()) { + $this->addDefaultDiscriminatorMap($classMetadata); + } - if (! empty($identifier)) { - $this->inheritIdGeneratorMapping($class, $embeddableMetadata); - } + $this->completeRuntimeMetadata($classMetadata, $parent); - $class->inlineEmbeddable($property, $embeddableMetadata); + if ($this->evm->hasListeners(Events::loadClassMetadata)) { + $eventArgs = new LoadClassMetadataEventArgs($classMetadata, $this->em); - unset($this->embeddablesActiveNesting[$class->name]); - } + $this->evm->dispatchEvent(Events::loadClassMetadata, $eventArgs); } - if ($parent) { - if ($parent->isInheritanceTypeSingleTable()) { - $class->setPrimaryTable($parent->table); - } + $this->buildValueGenerationPlan($classMetadata); + $this->validateRuntimeMetadata($classMetadata, $parent); - if ($parent) { - $this->addInheritedIndexes($class, $parent); - } + return $classMetadata; + } - if ($parent->cache) { - $class->cache = $parent->cache; - } + /** + * @param ClassMetadata $class + * @param ClassMetadata|null $parent + * + * @return void + */ + protected function completeRuntimeMetadata(ClassMetadata $class, ClassMetadata $parent = null) : void + { + if (! $parent || ! $parent->isMappedSuperclass) { + return; + } - if ($parent->containsForeignIdentifier) { - $class->containsForeignIdentifier = true; - } + if ($class->isMappedSuperclass) { + return; + } - if ( ! empty($parent->namedQueries)) { - $this->addInheritedNamedQueries($class, $parent); - } + $tableName = $class->getTableName(); - if ( ! empty($parent->namedNativeQueries)) { - $this->addInheritedNamedNativeQueries($class, $parent); - } + // Resolve column table names + foreach ($class->getDeclaredPropertiesIterator() as $property) { + if ($property instanceof FieldMetadata) { + $property->setTableName($property->getTableName() ?? $tableName); - if ( ! empty($parent->sqlResultSetMappings)) { - $this->addInheritedSqlResultSetMappings($class, $parent); + continue; } - if ( ! empty($parent->entityListeners) && empty($class->entityListeners)) { - $class->entityListeners = $parent->entityListeners; + if (! ($property instanceof ToOneAssociationMetadata)) { + continue; } - } - - $class->setParentClasses($nonSuperclassParents); - - if ($class->isRootEntity() && ! $class->isInheritanceTypeNone() && ! $class->discriminatorMap) { - $this->addDefaultDiscriminatorMap($class); - } - if ($this->evm->hasListeners(Events::loadClassMetadata)) { - $eventArgs = new LoadClassMetadataEventArgs($class, $this->em); - $this->evm->dispatchEvent(Events::loadClassMetadata, $eventArgs); + // Resolve association join column table names + foreach ($property->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $joinColumn->setTableName($joinColumn->getTableName() ?? $tableName); + } } - - $this->validateRuntimeMetadata($class, $parent); } /** * Validate runtime metadata is correctly defined. * - * @param ClassMetadata $class - * @param ClassMetadataInterface|null $parent + * @param ClassMetadata $class + * @param ClassMetadata|null $parent * * @return void * * @throws MappingException */ - protected function validateRuntimeMetadata($class, $parent) + protected function validateRuntimeMetadata(ClassMetadata $class, ClassMetadata $parent = null) : void { - if ( ! $class->reflClass ) { + if (! $class->getReflectionClass()) { // only validate if there is a reflection class instance return; } $class->validateIdentifier(); + $class->validateValueGenerators(); $class->validateAssociations(); $class->validateLifecycleCallbacks($this->getReflectionService()); // verify inheritance - if ( ! $class->isMappedSuperclass && !$class->isInheritanceTypeNone()) { + if ( ! $class->isMappedSuperclass && $class->inheritanceType !== InheritanceType::NONE) { if ( ! $parent) { - if (count($class->discriminatorMap) == 0) { - throw MappingException::missingDiscriminatorMap($class->name); + if (! $class->discriminatorMap) { + throw MappingException::missingDiscriminatorMap($class->getClassName()); } + if ( ! $class->discriminatorColumn) { - throw MappingException::missingDiscriminatorColumn($class->name); + throw MappingException::missingDiscriminatorColumn($class->getClassName()); } } - } else if ($class->isMappedSuperclass && $class->name == $class->rootEntityName && (count($class->discriminatorMap) || $class->discriminatorColumn)) { + } else if (($class->discriminatorMap || $class->discriminatorColumn) && $class->isMappedSuperclass && $class->isRootEntity()) { // second condition is necessary for mapped superclasses in the middle of an inheritance hierarchy - throw MappingException::noInheritanceOnMappedSuperClass($class->name); + throw MappingException::noInheritanceOnMappedSuperClass($class->getClassName()); } } /** - * {@inheritDoc} + * {@inheritdoc} */ - protected function newClassMetadataInstance($className) + protected function newClassMetadataBuildingContext() : ClassMetadataBuildingContext { - return new ClassMetadata($className, $this->em->getConfiguration()->getNamingStrategy()); + return new ClassMetadataBuildingContext( + $this, + $this->getReflectionService(), + $this->em->getConfiguration()->getNamingStrategy() + ); } /** @@ -298,22 +280,20 @@ protected function newClassMetadataInstance($className) * * @return void * + * @throws \InvalidArgumentException + * @throws \ReflectionException * @throws MappingException */ - private function resolveDiscriminatorValue(ClassMetadata $metadata) + private function resolveDiscriminatorValue(ClassMetadata $metadata) : void { - if ($metadata->discriminatorValue - || ! $metadata->discriminatorMap - || $metadata->isMappedSuperclass - || ! $metadata->reflClass - || $metadata->reflClass->isAbstract() - ) { + if ($metadata->discriminatorValue || ! $metadata->discriminatorMap || $metadata->isMappedSuperclass || + ! $metadata->getReflectionClass() || $metadata->getReflectionClass()->isAbstract()) { return; } // minor optimization: avoid loading related metadata when not needed foreach ($metadata->discriminatorMap as $discriminatorValue => $discriminatorClass) { - if ($discriminatorClass === $metadata->name) { + if ($discriminatorClass === $metadata->getClassName()) { $metadata->discriminatorValue = $discriminatorValue; return; @@ -322,14 +302,14 @@ private function resolveDiscriminatorValue(ClassMetadata $metadata) // iterate over discriminator mappings and resolve actual referenced classes according to existing metadata foreach ($metadata->discriminatorMap as $discriminatorValue => $discriminatorClass) { - if ($metadata->name === $this->getMetadataFor($discriminatorClass)->getName()) { + if ($metadata->getClassName() === $this->getMetadataFor($discriminatorClass)->getClassName()) { $metadata->discriminatorValue = $discriminatorValue; return; } } - throw MappingException::mappedClassNotPartOfDiscriminatorMap($metadata->name, $metadata->rootEntityName); + throw MappingException::mappedClassNotPartOfDiscriminatorMap($metadata->getClassName(), $metadata->getRootClassName()); } /** @@ -346,13 +326,13 @@ private function resolveDiscriminatorValue(ClassMetadata $metadata) * * @throws MappingException */ - private function addDefaultDiscriminatorMap(ClassMetadata $class) + private function addDefaultDiscriminatorMap(ClassMetadata $class) : void { $allClasses = $this->driver->getAllClassNames(); - $fqcn = $class->getName(); - $map = [$this->getShortName($class->name) => $fqcn]; - + $fqcn = $class->getClassName(); + $map = [$this->getShortName($fqcn) => $fqcn]; $duplicates = []; + foreach ($allClasses as $subClassCandidate) { if (is_subclass_of($subClassCandidate, $fqcn)) { $shortName = $this->getShortName($subClassCandidate); @@ -361,12 +341,12 @@ private function addDefaultDiscriminatorMap(ClassMetadata $class) $duplicates[] = $shortName; } - $map[$shortName] = $subClassCandidate; + $map[$shortName] = $class->fullyQualifiedClassName($subClassCandidate); } } if ($duplicates) { - throw MappingException::duplicateDiscriminatorEntry($class->name, $duplicates, $map); + throw MappingException::duplicateDiscriminatorEntry($class->getClassName(), $duplicates, $map); } $class->setDiscriminatorMap($map); @@ -379,7 +359,7 @@ private function addDefaultDiscriminatorMap(ClassMetadata $class) * * @return string */ - private function getShortName($className) + private function getShortName($className) : string { if (strpos($className, "\\") === false) { return strtolower($className); @@ -393,150 +373,46 @@ private function getShortName($className) /** * Adds inherited fields to the subclass mapping. * - * @param \Doctrine\ORM\Mapping\ClassMetadata $subClass - * @param \Doctrine\ORM\Mapping\ClassMetadata $parentClass - * - * @return void - */ - private function addInheritedFields(ClassMetadata $subClass, ClassMetadata $parentClass) - { - foreach ($parentClass->fieldMappings as $mapping) { - if ( ! isset($mapping['inherited']) && ! $parentClass->isMappedSuperclass) { - $mapping['inherited'] = $parentClass->name; - } - if ( ! isset($mapping['declared'])) { - $mapping['declared'] = $parentClass->name; - } - $subClass->addInheritedFieldMapping($mapping); - } - foreach ($parentClass->reflFields as $name => $field) { - $subClass->reflFields[$name] = $field; - } - } - - /** - * Adds inherited association mappings to the subclass mapping. - * - * @param \Doctrine\ORM\Mapping\ClassMetadata $subClass - * @param \Doctrine\ORM\Mapping\ClassMetadata $parentClass + * @param ClassMetadata $subClass + * @param ClassMetadata $parentClass * * @return void * * @throws MappingException */ - private function addInheritedRelations(ClassMetadata $subClass, ClassMetadata $parentClass) + private function addInheritedProperties(ClassMetadata $subClass, ClassMetadata $parentClass) : void { - foreach ($parentClass->associationMappings as $field => $mapping) { - if ($parentClass->isMappedSuperclass) { - if ($mapping['type'] & ClassMetadata::TO_MANY && !$mapping['isOwningSide']) { - throw MappingException::illegalToManyAssociationOnMappedSuperclass($parentClass->name, $field); - } - $mapping['sourceEntity'] = $subClass->name; - } + $isAbstract = $parentClass->isMappedSuperclass; - //$subclassMapping = $mapping; - if ( ! isset($mapping['inherited']) && ! $parentClass->isMappedSuperclass) { - $mapping['inherited'] = $parentClass->name; + foreach ($parentClass->getDeclaredPropertiesIterator() as $fieldName => $property) { + if ($isAbstract && $property instanceof ToManyAssociationMetadata && ! $property->isOwningSide()) { + throw MappingException::illegalToManyAssociationOnMappedSuperclass($parentClass->getClassName(), $fieldName); } - if ( ! isset($mapping['declared'])) { - $mapping['declared'] = $parentClass->name; - } - $subClass->addInheritedAssociationMapping($mapping); - } - } - private function addInheritedEmbeddedClasses(ClassMetadata $subClass, ClassMetadata $parentClass) - { - foreach ($parentClass->embeddedClasses as $field => $embeddedClass) { - if ( ! isset($embeddedClass['inherited']) && ! $parentClass->isMappedSuperclass) { - $embeddedClass['inherited'] = $parentClass->name; - } - if ( ! isset($embeddedClass['declared'])) { - $embeddedClass['declared'] = $parentClass->name; - } - - $subClass->embeddedClasses[$field] = $embeddedClass; + $subClass->addInheritedProperty($property); } } /** - * Adds nested embedded classes metadata to a parent class. + * Adds inherited named queries to the subclass mapping. * - * @param ClassMetadata $subClass Sub embedded class metadata to add nested embedded classes metadata from. - * @param ClassMetadata $parentClass Parent class to add nested embedded classes metadata to. - * @param string $prefix Embedded classes' prefix to use for nested embedded classes field names. - */ - private function addNestedEmbeddedClasses(ClassMetadata $subClass, ClassMetadata $parentClass, $prefix) - { - foreach ($subClass->embeddedClasses as $property => $embeddableClass) { - if (isset($embeddableClass['inherited'])) { - continue; - } - - $embeddableMetadata = $this->getMetadataFor($embeddableClass['class']); - - $parentClass->mapEmbedded( - [ - 'fieldName' => $prefix . '.' . $property, - 'class' => $embeddableMetadata->name, - 'columnPrefix' => $embeddableClass['columnPrefix'], - 'declaredField' => $embeddableClass['declaredField'] - ? $prefix . '.' . $embeddableClass['declaredField'] - : $prefix, - 'originalField' => $embeddableClass['originalField'] ?: $property, - ] - ); - } - } - - /** - * Copy the table indices from the parent class superclass to the child class + * @since 2.2 * * @param ClassMetadata $subClass * @param ClassMetadata $parentClass * * @return void - */ - private function addInheritedIndexes(ClassMetadata $subClass, ClassMetadata $parentClass) - { - if (! $parentClass->isMappedSuperclass) { - return; - } - - foreach (['uniqueConstraints', 'indexes'] as $indexType) { - if (isset($parentClass->table[$indexType])) { - foreach ($parentClass->table[$indexType] as $indexName => $index) { - if (isset($subClass->table[$indexType][$indexName])) { - continue; // Let the inheriting table override indices - } - - $subClass->table[$indexType][$indexName] = $index; - } - } - } - } - - /** - * Adds inherited named queries to the subclass mapping. - * - * @since 2.2 * - * @param \Doctrine\ORM\Mapping\ClassMetadata $subClass - * @param \Doctrine\ORM\Mapping\ClassMetadata $parentClass - * - * @return void + * @throws MappingException */ - private function addInheritedNamedQueries(ClassMetadata $subClass, ClassMetadata $parentClass) + private function addInheritedNamedQueries(ClassMetadata $subClass, ClassMetadata $parentClass) : void { - foreach ($parentClass->namedQueries as $name => $query) { - if ( ! isset ($subClass->namedQueries[$name])) { - $subClass->addNamedQuery( - [ - 'name' => $query['name'], - 'query' => $query['query'] - ] - ); + foreach ($parentClass->getNamedQueries() as $name => $query) { + if ($subClass->hasNamedQuery($name)) { + continue; } + + $subClass->addNamedQuery($name, $query); } } @@ -545,25 +421,28 @@ private function addInheritedNamedQueries(ClassMetadata $subClass, ClassMetadata * * @since 2.3 * - * @param \Doctrine\ORM\Mapping\ClassMetadata $subClass - * @param \Doctrine\ORM\Mapping\ClassMetadata $parentClass + * @param ClassMetadata $subClass + * @param ClassMetadata $parentClass * * @return void + * + * @throws MappingException */ - private function addInheritedNamedNativeQueries(ClassMetadata $subClass, ClassMetadata $parentClass) + private function addInheritedNamedNativeQueries(ClassMetadata $subClass, ClassMetadata $parentClass) : void { foreach ($parentClass->namedNativeQueries as $name => $query) { - if ( ! isset ($subClass->namedNativeQueries[$name])) { - $subClass->addNamedNativeQuery( - [ - 'name' => $query['name'], - 'query' => $query['query'], - 'isSelfClass' => $query['isSelfClass'], - 'resultSetMapping' => $query['resultSetMapping'], - 'resultClass' => $query['isSelfClass'] ? $subClass->name : $query['resultClass'], - ] - ); + if (isset($subClass->namedNativeQueries[$name])) { + continue; } + + $subClass->addNamedNativeQuery( + $name, + $query['query'], + [ + 'resultSetMapping' => $query['resultSetMapping'], + 'resultClass' => $query['resultClass'], + ] + ); } } @@ -572,33 +451,37 @@ private function addInheritedNamedNativeQueries(ClassMetadata $subClass, ClassMe * * @since 2.3 * - * @param \Doctrine\ORM\Mapping\ClassMetadata $subClass - * @param \Doctrine\ORM\Mapping\ClassMetadata $parentClass + * @param ClassMetadata $subClass + * @param ClassMetadata $parentClass * * @return void + * + * @throws MappingException */ - private function addInheritedSqlResultSetMappings(ClassMetadata $subClass, ClassMetadata $parentClass) + private function addInheritedSqlResultSetMappings(ClassMetadata $subClass, ClassMetadata $parentClass) : void { foreach ($parentClass->sqlResultSetMappings as $name => $mapping) { - if ( ! isset ($subClass->sqlResultSetMappings[$name])) { - $entities = []; - foreach ($mapping['entities'] as $entity) { - $entities[] = [ - 'fields' => $entity['fields'], - 'isSelfClass' => $entity['isSelfClass'], - 'discriminatorColumn' => $entity['discriminatorColumn'], - 'entityClass' => $entity['isSelfClass'] ? $subClass->name : $entity['entityClass'], - ]; - } + if (isset ($subClass->sqlResultSetMappings[$name])) { + continue; + } - $subClass->addSqlResultSetMapping( - [ - 'name' => $mapping['name'], - 'columns' => $mapping['columns'], - 'entities' => $entities, - ] - ); + $entities = []; + + foreach ($mapping['entities'] as $entity) { + $entities[] = [ + 'fields' => $entity['fields'], + 'discriminatorColumn' => $entity['discriminatorColumn'], + 'entityClass' => $entity['entityClass'], + ]; } + + $subClass->addSqlResultSetMapping( + [ + 'name' => $mapping['name'], + 'columns' => $mapping['columns'], + 'entities' => $entities, + ] + ); } } @@ -606,189 +489,218 @@ private function addInheritedSqlResultSetMappings(ClassMetadata $subClass, Class * Completes the ID generator mapping. If "auto" is specified we choose the generator * most appropriate for the targeted database platform. * - * @param ClassMetadataInfo $class + * @param ClassMetadata $class * * @return void * * @throws ORMException */ - private function completeIdGeneratorMapping(ClassMetadataInfo $class) + private function completeIdentifierGeneratorMappings(ClassMetadata $class) : void { - $idGenType = $class->generatorType; - if ($idGenType == ClassMetadata::GENERATOR_TYPE_AUTO) { - if ($this->getTargetPlatform()->prefersSequences()) { - $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_SEQUENCE); - } else if ($this->getTargetPlatform()->prefersIdentityColumns()) { - $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY); - } else { - $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_TABLE); + foreach ($class->getDeclaredPropertiesIterator() as $property) { + if ( ! $property instanceof FieldMetadata /*&& ! $property instanceof AssocationMetadata*/) { + continue; } - } - // Create & assign an appropriate ID generator instance - switch ($class->generatorType) { - case ClassMetadata::GENERATOR_TYPE_IDENTITY: - $sequenceName = null; - $fieldName = $class->identifier ? $class->getSingleIdentifierFieldName() : null; - - // Platforms that do not have native IDENTITY support need a sequence to emulate this behaviour. - if ($this->getTargetPlatform()->usesSequenceEmulatedIdentityColumns()) { - $columnName = $class->getSingleIdentifierColumnName(); - $quoted = isset($class->fieldMappings[$fieldName]['quoted']) || isset($class->table['quoted']); - $sequencePrefix = $class->getSequencePrefix($this->getTargetPlatform()); - $sequenceName = $this->getTargetPlatform()->getIdentitySequenceName($sequencePrefix, $columnName); - $definition = [ - 'sequenceName' => $this->getTargetPlatform()->fixSchemaElementName($sequenceName) - ]; - - if ($quoted) { - $definition['quoted'] = true; - } - - $sequenceName = $this - ->em - ->getConfiguration() - ->getQuoteStrategy() - ->getSequenceName($definition, $class, $this->getTargetPlatform()); - } + $this->completeFieldIdentifierGeneratorMapping($property); + } + } - $generator = ($fieldName && $class->fieldMappings[$fieldName]['type'] === 'bigint') - ? new BigIntegerIdentityGenerator($sequenceName) - : new IdentityGenerator($sequenceName); + private function completeFieldIdentifierGeneratorMapping(FieldMetadata $field) + { + if (!$field->hasValueGenerator()) { + return; + } - $class->setIdGenerator($generator); + $platform = $this->getTargetPlatform(); + $class = $field->getDeclaringClass(); + $generator = $field->getValueGenerator(); - break; + if ($generator->getType() === GeneratorType::AUTO) { + $generator = new ValueGeneratorMetadata( + $platform->prefersSequences() + ? GeneratorType::SEQUENCE + : ($platform->prefersIdentityColumns() + ? GeneratorType::IDENTITY + : GeneratorType::TABLE + ), + $field->getValueGenerator()->getDefinition() + ); + $field->setValueGenerator($generator); + } - case ClassMetadata::GENERATOR_TYPE_SEQUENCE: + // Validate generator definition and set defaults where needed + switch ($generator->getType()) { + case GeneratorType::SEQUENCE: // If there is no sequence definition yet, create a default definition - $definition = $class->sequenceGeneratorDefinition; - - if ( ! $definition) { - $fieldName = $class->getSingleIdentifierFieldName(); - $sequenceName = $class->getSequenceName($this->getTargetPlatform()); - $quoted = isset($class->fieldMappings[$fieldName]['quoted']) || isset($class->table['quoted']); - - $definition = [ - 'sequenceName' => $this->getTargetPlatform()->fixSchemaElementName($sequenceName), - 'allocationSize' => 1, - 'initialValue' => 1, - ]; - - if ($quoted) { - $definition['quoted'] = true; - } - - $class->setSequenceGeneratorDefinition($definition); + if ($generator->getDefinition()) { + break; } - $sequenceGenerator = new \Doctrine\ORM\Id\SequenceGenerator( - $this->em->getConfiguration()->getQuoteStrategy()->getSequenceName($definition, $class, $this->getTargetPlatform()), - $definition['allocationSize'] + // @todo guilhermeblanco Move sequence generation to DBAL + $sequencePrefix = $platform->getSequencePrefix($field->getTableName(), $field->getSchemaName()); + $idSequenceName = sprintf('%s_%s_seq', $sequencePrefix, $field->getColumnName()); + $sequenceName = $platform->fixSchemaElementName($idSequenceName); + + $field->setValueGenerator( + new ValueGeneratorMetadata( + $generator->getType(), + [ + 'sequenceName' => $sequenceName, + 'allocationSize' => 1, + ] + ) ); - $class->setIdGenerator($sequenceGenerator); - break; - - case ClassMetadata::GENERATOR_TYPE_NONE: - $class->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator()); - break; - case ClassMetadata::GENERATOR_TYPE_UUID: - $class->setIdGenerator(new \Doctrine\ORM\Id\UuidGenerator()); break; - case ClassMetadata::GENERATOR_TYPE_TABLE: + case GeneratorType::TABLE: throw new ORMException("TableGenerator not yet implemented."); break; - case ClassMetadata::GENERATOR_TYPE_CUSTOM: - $definition = $class->customGeneratorDefinition; + case GeneratorType::CUSTOM: + $definition = $generator->getDefinition(); + if ( ! isset($definition['class'])) { + throw new ORMException(sprintf('Cannot instantiate custom generator, no class has been defined')); + } if ( ! class_exists($definition['class'])) { - throw new ORMException("Can't instantiate custom generator : " . - $definition['class']); + throw new ORMException(sprintf('Cannot instantiate custom generator : %s', var_export($definition, true))); //$definition['class'])); } - $class->setIdGenerator(new $definition['class']); - break; - default: - throw new ORMException("Unknown generator type: " . $class->generatorType); - } - } - - /** - * Inherits the ID generator mapping from a parent class. - * - * @param ClassMetadataInfo $class - * @param ClassMetadataInfo $parent - */ - private function inheritIdGeneratorMapping(ClassMetadataInfo $class, ClassMetadataInfo $parent) - { - if ($parent->isIdGeneratorSequence()) { - $class->setSequenceGeneratorDefinition($parent->sequenceGeneratorDefinition); - } elseif ($parent->isIdGeneratorTable()) { - $class->tableGeneratorDefinition = $parent->tableGeneratorDefinition; - } + break; - if ($parent->generatorType) { - $class->setIdGeneratorType($parent->generatorType); - } + case GeneratorType::IDENTITY: + case GeneratorType::NONE: + case GeneratorType::UUID: + break; - if ($parent->idGenerator) { - $class->setIdGenerator($parent->idGenerator); + default: + throw new ORMException("Unknown generator type: " . $generator->getType()); } } /** * {@inheritDoc} */ - protected function wakeupReflection(ClassMetadataInterface $class, ReflectionService $reflService) + protected function getFqcnFromAlias($namespaceAlias, $simpleClassName) : string { - /* @var $class ClassMetadata */ - $class->wakeupReflection($reflService); + return $this->em->getConfiguration()->getEntityNamespace($namespaceAlias) . '\\' . $simpleClassName; } /** * {@inheritDoc} */ - protected function initializeReflection(ClassMetadataInterface $class, ReflectionService $reflService) + protected function getDriver() : Driver\MappingDriver { - /* @var $class ClassMetadata */ - $class->initializeReflection($reflService); + return $this->driver; } /** * {@inheritDoc} */ - protected function getFqcnFromAlias($namespaceAlias, $simpleClassName) + protected function isEntity(ClassMetadata $class) : bool { - return $this->em->getConfiguration()->getEntityNamespace($namespaceAlias) . '\\' . $simpleClassName; + return isset($class->isMappedSuperclass) && $class->isMappedSuperclass === false; } /** - * {@inheritDoc} + * @return Platforms\AbstractPlatform */ - protected function getDriver() + private function getTargetPlatform() : Platforms\AbstractPlatform { - return $this->driver; + if (!$this->targetPlatform) { + $this->targetPlatform = $this->em->getConnection()->getDatabasePlatform(); + } + + return $this->targetPlatform; } /** - * {@inheritDoc} + * @param ClassMetadata $class + * + * @return void */ - protected function isEntity(ClassMetadataInterface $class) + private function buildValueGenerationPlan(ClassMetadata $class) : void { - return isset($class->isMappedSuperclass) && $class->isMappedSuperclass === false; + /** @var LocalColumnMetadata[] $generatedProperties */ + $generatedProperties = []; + + foreach ($class->getDeclaredPropertiesIterator() as $property) { + if (! ($property instanceof LocalColumnMetadata && $property->hasValueGenerator())) { + continue; + } + + $generatedProperties[] = $property; + } + + switch (count($generatedProperties)) { + case 0: + $class->setValueGenerationPlan(new NoopValueGenerationPlan()); + break; + + case 1: + $property = reset($generatedProperties); + $executor = new ColumnValueGeneratorExecutor($property, $this->createPropertyValueGenerator($class, $property)); + + $class->setValueGenerationPlan(new SingleValueGenerationPlan($class, $executor)); + break; + + default: + $executors = []; + + foreach ($generatedProperties as $property) { + $executors[] = new ColumnValueGeneratorExecutor($property, $this->createPropertyValueGenerator($class, $property)); + } + + $class->setValueGenerationPlan(new CompositeValueGenerationPlan($class, $executors)); + break; + } } /** - * @return Platforms\AbstractPlatform + * @param ClassMetadata $class + * @param LocalColumnMetadata $property + * + * @return Sequencing\Generator */ - private function getTargetPlatform() + private function createPropertyValueGenerator( + ClassMetadata $class, + LocalColumnMetadata $property + ) : Sequencing\Generator { - if (!$this->targetPlatform) { - $this->targetPlatform = $this->em->getConnection()->getDatabasePlatform(); - } + $platform = $this->getTargetPlatform(); - return $this->targetPlatform; + switch ($property->getValueGenerator()->getType()) { + case GeneratorType::IDENTITY: + $sequenceName = null; + + // Platforms that do not have native IDENTITY support need a sequence to emulate this behaviour. + if ($platform->usesSequenceEmulatedIdentityColumns()) { + $sequencePrefix = $platform->getSequencePrefix($class->getTableName(), $class->getSchemaName()); + $idSequenceName = $platform->getIdentitySequenceName($sequencePrefix, $property->getColumnName()); + $sequenceName = $platform->quoteIdentifier($platform->fixSchemaElementName($idSequenceName)); + } + + return $property->getTypeName() === 'bigint' + ? new Sequencing\BigIntegerIdentityGenerator($sequenceName) + : new Sequencing\IdentityGenerator($sequenceName); + + case GeneratorType::SEQUENCE: + $definition = $property->getValueGenerator()->getDefinition(); + return new Sequencing\SequenceGenerator( + $platform->quoteIdentifier($definition['sequenceName']), + $definition['allocationSize'] + ); + break; + + case GeneratorType::UUID: + return new Sequencing\UuidGenerator(); + break; + + case GeneratorType::CUSTOM: + $class = $property->getValueGenerator()->getDefinition()['class']; + return new $class(); + break; + } } } diff --git a/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php b/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php deleted file mode 100644 index b5eebcdde2c..00000000000 --- a/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php +++ /dev/null @@ -1,3397 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -use BadMethodCallException; -use Doctrine\Instantiator\Instantiator; -use InvalidArgumentException; -use RuntimeException; -use Doctrine\DBAL\Types\Type; -use Doctrine\DBAL\Platforms\AbstractPlatform; -use ReflectionClass; -use Doctrine\Common\Persistence\Mapping\ClassMetadata; -use Doctrine\Common\ClassLoader; -use Doctrine\ORM\Cache\CacheException; - -/** - * A ClassMetadata instance holds all the object-relational mapping metadata - * of an entity and its associations. - * - * Once populated, ClassMetadata instances are usually cached in a serialized form. - * - * IMPORTANT NOTE: - * - * The fields of this class are only public for 2 reasons: - * 1) To allow fast READ access. - * 2) To drastically reduce the size of a serialized instance (private/protected members - * get the whole class name, namespace inclusive, prepended to every property in - * the serialized representation). - * - * @author Roman Borschel - * @author Jonathan H. Wage - * @since 2.0 - */ -class ClassMetadataInfo implements ClassMetadata -{ - /* The inheritance mapping types */ - /** - * NONE means the class does not participate in an inheritance hierarchy - * and therefore does not need an inheritance mapping type. - */ - const INHERITANCE_TYPE_NONE = 1; - - /** - * JOINED means the class will be persisted according to the rules of - * Class Table Inheritance. - */ - const INHERITANCE_TYPE_JOINED = 2; - - /** - * SINGLE_TABLE means the class will be persisted according to the rules of - * Single Table Inheritance. - */ - const INHERITANCE_TYPE_SINGLE_TABLE = 3; - - /** - * TABLE_PER_CLASS means the class will be persisted according to the rules - * of Concrete Table Inheritance. - */ - const INHERITANCE_TYPE_TABLE_PER_CLASS = 4; - - /* The Id generator types. */ - /** - * AUTO means the generator type will depend on what the used platform prefers. - * Offers full portability. - */ - const GENERATOR_TYPE_AUTO = 1; - - /** - * SEQUENCE means a separate sequence object will be used. Platforms that do - * not have native sequence support may emulate it. Full portability is currently - * not guaranteed. - */ - const GENERATOR_TYPE_SEQUENCE = 2; - - /** - * TABLE means a separate table is used for id generation. - * Offers full portability. - */ - const GENERATOR_TYPE_TABLE = 3; - - /** - * IDENTITY means an identity column is used for id generation. The database - * will fill in the id column on insertion. Platforms that do not support - * native identity columns may emulate them. Full portability is currently - * not guaranteed. - */ - const GENERATOR_TYPE_IDENTITY = 4; - - /** - * NONE means the class does not have a generated id. That means the class - * must have a natural, manually assigned id. - */ - const GENERATOR_TYPE_NONE = 5; - - /** - * UUID means that a UUID/GUID expression is used for id generation. Full - * portability is currently not guaranteed. - */ - const GENERATOR_TYPE_UUID = 6; - - /** - * CUSTOM means that customer will use own ID generator that supposedly work - */ - const GENERATOR_TYPE_CUSTOM = 7; - - /** - * DEFERRED_IMPLICIT means that changes of entities are calculated at commit-time - * by doing a property-by-property comparison with the original data. This will - * be done for all entities that are in MANAGED state at commit-time. - * - * This is the default change tracking policy. - */ - const CHANGETRACKING_DEFERRED_IMPLICIT = 1; - - /** - * DEFERRED_EXPLICIT means that changes of entities are calculated at commit-time - * by doing a property-by-property comparison with the original data. This will - * be done only for entities that were explicitly saved (through persist() or a cascade). - */ - const CHANGETRACKING_DEFERRED_EXPLICIT = 2; - - /** - * NOTIFY means that Doctrine relies on the entities sending out notifications - * when their properties change. Such entity classes must implement - * the NotifyPropertyChanged interface. - */ - const CHANGETRACKING_NOTIFY = 3; - - /** - * Specifies that an association is to be fetched when it is first accessed. - */ - const FETCH_LAZY = 2; - - /** - * Specifies that an association is to be fetched when the owner of the - * association is fetched. - */ - const FETCH_EAGER = 3; - - /** - * Specifies that an association is to be fetched lazy (on first access) and that - * commands such as Collection#count, Collection#slice are issued directly against - * the database if the collection is not yet initialized. - */ - const FETCH_EXTRA_LAZY = 4; - - /** - * Identifies a one-to-one association. - */ - const ONE_TO_ONE = 1; - - /** - * Identifies a many-to-one association. - */ - const MANY_TO_ONE = 2; - - /** - * Identifies a one-to-many association. - */ - const ONE_TO_MANY = 4; - - /** - * Identifies a many-to-many association. - */ - const MANY_TO_MANY = 8; - - /** - * Combined bitmask for to-one (single-valued) associations. - */ - const TO_ONE = 3; - - /** - * Combined bitmask for to-many (collection-valued) associations. - */ - const TO_MANY = 12; - - /** - * ReadOnly cache can do reads, inserts and deletes, cannot perform updates or employ any locks, - */ - const CACHE_USAGE_READ_ONLY = 1; - - /** - * Nonstrict Read Write Cache doesn’t employ any locks but can do inserts, update and deletes. - */ - const CACHE_USAGE_NONSTRICT_READ_WRITE = 2; - - /** - * Read Write Attempts to lock the entity before update/delete. - */ - const CACHE_USAGE_READ_WRITE = 3; - - /** - * READ-ONLY: The name of the entity class. - * - * @var string - */ - public $name; - - /** - * READ-ONLY: The namespace the entity class is contained in. - * - * @var string - * - * @todo Not really needed. Usage could be localized. - */ - public $namespace; - - /** - * READ-ONLY: The name of the entity class that is at the root of the mapped entity inheritance - * hierarchy. If the entity is not part of a mapped inheritance hierarchy this is the same - * as {@link $name}. - * - * @var string - */ - public $rootEntityName; - - /** - * READ-ONLY: The definition of custom generator. Only used for CUSTOM - * generator type - * - * The definition has the following structure: - * - * array( - * 'class' => 'ClassName', - * ) - * - * - * @var array - * - * @todo Merge with tableGeneratorDefinition into generic generatorDefinition - */ - public $customGeneratorDefinition; - - /** - * The name of the custom repository class used for the entity class. - * (Optional). - * - * @var string - */ - public $customRepositoryClassName; - - /** - * READ-ONLY: Whether this class describes the mapping of a mapped superclass. - * - * @var boolean - */ - public $isMappedSuperclass = false; - - /** - * READ-ONLY: Whether this class describes the mapping of an embeddable class. - * - * @var boolean - */ - public $isEmbeddedClass = false; - - /** - * READ-ONLY: The names of the parent classes (ancestors). - * - * @var array - */ - public $parentClasses = []; - - /** - * READ-ONLY: The names of all subclasses (descendants). - * - * @var array - */ - public $subClasses = []; - - /** - * READ-ONLY: The names of all embedded classes based on properties. - * - * @var array - */ - public $embeddedClasses = []; - - /** - * READ-ONLY: The named queries allowed to be called directly from Repository. - * - * @var array - */ - public $namedQueries = []; - - /** - * READ-ONLY: The named native queries allowed to be called directly from Repository. - * - * A native SQL named query definition has the following structure: - *
-     * array(
-     *     'name'               => ,
-     *     'query'              => ,
-     *     'resultClass'        => ,
-     *     'resultSetMapping'   => 
-     * )
-     * 
- * - * @var array - */ - public $namedNativeQueries = []; - - /** - * READ-ONLY: The mappings of the results of native SQL queries. - * - * A native result mapping definition has the following structure: - *
-     * array(
-     *     'name'               => ,
-     *     'entities'           => array(),
-     *     'columns'            => array()
-     * )
-     * 
- * - * @var array - */ - public $sqlResultSetMappings = []; - - /** - * READ-ONLY: The field names of all fields that are part of the identifier/primary key - * of the mapped entity class. - * - * @var array - */ - public $identifier = []; - - /** - * READ-ONLY: The inheritance mapping type used by the class. - * - * @var integer - */ - public $inheritanceType = self::INHERITANCE_TYPE_NONE; - - /** - * READ-ONLY: The Id generator type used by the class. - * - * @var int - */ - public $generatorType = self::GENERATOR_TYPE_NONE; - - /** - * READ-ONLY: The field mappings of the class. - * Keys are field names and values are mapping definitions. - * - * The mapping definition array has the following values: - * - * - fieldName (string) - * The name of the field in the Entity. - * - * - type (string) - * The type name of the mapped field. Can be one of Doctrine's mapping types - * or a custom mapping type. - * - * - columnName (string, optional) - * The column name. Optional. Defaults to the field name. - * - * - length (integer, optional) - * The database length of the column. Optional. Default value taken from - * the type. - * - * - id (boolean, optional) - * Marks the field as the primary key of the entity. Multiple fields of an - * entity can have the id attribute, forming a composite key. - * - * - nullable (boolean, optional) - * Whether the column is nullable. Defaults to FALSE. - * - * - columnDefinition (string, optional, schema-only) - * The SQL fragment that is used when generating the DDL for the column. - * - * - precision (integer, optional, schema-only) - * The precision of a decimal column. Only valid if the column type is decimal. - * - * - scale (integer, optional, schema-only) - * The scale of a decimal column. Only valid if the column type is decimal. - * - * - 'unique' (string, optional, schema-only) - * Whether a unique constraint should be generated for the column. - * - * @var array - */ - public $fieldMappings = []; - - /** - * READ-ONLY: An array of field names. Used to look up field names from column names. - * Keys are column names and values are field names. - * - * @var array - */ - public $fieldNames = []; - - /** - * READ-ONLY: A map of field names to column names. Keys are field names and values column names. - * Used to look up column names from field names. - * This is the reverse lookup map of $_fieldNames. - * - * @var array - * - * @deprecated 3.0 Remove this. - */ - public $columnNames = []; - - /** - * READ-ONLY: The discriminator value of this class. - * - * This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies - * where a discriminator column is used. - * - * @var mixed - * - * @see discriminatorColumn - */ - public $discriminatorValue; - - /** - * READ-ONLY: The discriminator map of all mapped classes in the hierarchy. - * - * This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies - * where a discriminator column is used. - * - * @var mixed - * - * @see discriminatorColumn - */ - public $discriminatorMap = []; - - /** - * READ-ONLY: The definition of the discriminator column used in JOINED and SINGLE_TABLE - * inheritance mappings. - * - * @var array - */ - public $discriminatorColumn; - - /** - * READ-ONLY: The primary table definition. The definition is an array with the - * following entries: - * - * name => - * schema => - * indexes => array - * uniqueConstraints => array - * - * @var array - */ - public $table; - - /** - * READ-ONLY: The registered lifecycle callbacks for entities of this class. - * - * @var array[] - */ - public $lifecycleCallbacks = []; - - /** - * READ-ONLY: The registered entity listeners. - * - * @var array - */ - public $entityListeners = []; - - /** - * READ-ONLY: The association mappings of this class. - * - * The mapping definition array supports the following keys: - * - * - fieldName (string) - * The name of the field in the entity the association is mapped to. - * - * - targetEntity (string) - * The class name of the target entity. If it is fully-qualified it is used as is. - * If it is a simple, unqualified class name the namespace is assumed to be the same - * as the namespace of the source entity. - * - * - mappedBy (string, required for bidirectional associations) - * The name of the field that completes the bidirectional association on the owning side. - * This key must be specified on the inverse side of a bidirectional association. - * - * - inversedBy (string, required for bidirectional associations) - * The name of the field that completes the bidirectional association on the inverse side. - * This key must be specified on the owning side of a bidirectional association. - * - * - cascade (array, optional) - * The names of persistence operations to cascade on the association. The set of possible - * values are: "persist", "remove", "detach", "merge", "refresh", "all" (implies all others). - * - * - orderBy (array, one-to-many/many-to-many only) - * A map of field names (of the target entity) to sorting directions (ASC/DESC). - * Example: array('priority' => 'desc') - * - * - fetch (integer, optional) - * The fetching strategy to use for the association, usually defaults to FETCH_LAZY. - * Possible values are: ClassMetadata::FETCH_EAGER, ClassMetadata::FETCH_LAZY. - * - * - joinTable (array, optional, many-to-many only) - * Specification of the join table and its join columns (foreign keys). - * Only valid for many-to-many mappings. Note that one-to-many associations can be mapped - * through a join table by simply mapping the association as many-to-many with a unique - * constraint on the join table. - * - * - indexBy (string, optional, to-many only) - * Specification of a field on target-entity that is used to index the collection by. - * This field HAS to be either the primary key or a unique column. Otherwise the collection - * does not contain all the entities that are actually related. - * - * A join table definition has the following structure: - *
-     * array(
-     *     'name' => ,
-     *      'joinColumns' => array(),
-     *      'inverseJoinColumns' => array()
-     * )
-     * 
- * - * @var array - */ - public $associationMappings = []; - - /** - * READ-ONLY: Flag indicating whether the identifier/primary key of the class is composite. - * - * @var boolean - */ - public $isIdentifierComposite = false; - - /** - * READ-ONLY: Flag indicating whether the identifier/primary key contains at least one foreign key association. - * - * This flag is necessary because some code blocks require special treatment of this cases. - * - * @var boolean - */ - public $containsForeignIdentifier = false; - - /** - * READ-ONLY: The ID generator used for generating IDs for this class. - * - * @var \Doctrine\ORM\Id\AbstractIdGenerator - * - * @todo Remove! - */ - public $idGenerator; - - /** - * READ-ONLY: The definition of the sequence generator of this class. Only used for the - * SEQUENCE generation strategy. - * - * The definition has the following structure: - * - * array( - * 'sequenceName' => 'name', - * 'allocationSize' => 20, - * 'initialValue' => 1 - * ) - * - * - * @var array - * - * @todo Merge with tableGeneratorDefinition into generic generatorDefinition - */ - public $sequenceGeneratorDefinition; - - /** - * READ-ONLY: The definition of the table generator of this class. Only used for the - * TABLE generation strategy. - * - * @var array - * - * @todo Merge with tableGeneratorDefinition into generic generatorDefinition - */ - public $tableGeneratorDefinition; - - /** - * READ-ONLY: The policy used for change-tracking on entities of this class. - * - * @var integer - */ - public $changeTrackingPolicy = self::CHANGETRACKING_DEFERRED_IMPLICIT; - - /** - * READ-ONLY: A flag for whether or not instances of this class are to be versioned - * with optimistic locking. - * - * @var boolean - */ - public $isVersioned; - - /** - * READ-ONLY: The name of the field which is used for versioning in optimistic locking (if any). - * - * @var mixed - */ - public $versionField; - - /** - * @var array - */ - public $cache = null; - - /** - * The ReflectionClass instance of the mapped class. - * - * @var ReflectionClass - */ - public $reflClass; - - /** - * Is this entity marked as "read-only"? - * - * That means it is never considered for change-tracking in the UnitOfWork. It is a very helpful performance - * optimization for entities that are immutable, either in your domain or through the relation database - * (coming from a view, or a history table for example). - * - * @var bool - */ - public $isReadOnly = false; - - /** - * NamingStrategy determining the default column and table names. - * - * @var \Doctrine\ORM\Mapping\NamingStrategy - */ - protected $namingStrategy; - - /** - * The ReflectionProperty instances of the mapped class. - * - * @var \ReflectionProperty[] - */ - public $reflFields = []; - - /** - * @var \Doctrine\Instantiator\InstantiatorInterface|null - */ - private $instantiator; - - /** - * Initializes a new ClassMetadata instance that will hold the object-relational mapping - * metadata of the class with the given name. - * - * @param string $entityName The name of the entity class the new instance is used for. - * @param NamingStrategy|null $namingStrategy - */ - public function __construct($entityName, NamingStrategy $namingStrategy = null) - { - $this->name = $entityName; - $this->rootEntityName = $entityName; - $this->namingStrategy = $namingStrategy ?: new DefaultNamingStrategy(); - $this->instantiator = new Instantiator(); - } - - /** - * Gets the ReflectionProperties of the mapped class. - * - * @return array An array of ReflectionProperty instances. - */ - public function getReflectionProperties() - { - return $this->reflFields; - } - - /** - * Gets a ReflectionProperty for a specific field of the mapped class. - * - * @param string $name - * - * @return \ReflectionProperty - */ - public function getReflectionProperty($name) - { - return $this->reflFields[$name]; - } - - /** - * Gets the ReflectionProperty for the single identifier field. - * - * @return \ReflectionProperty - * - * @throws BadMethodCallException If the class has a composite identifier. - */ - public function getSingleIdReflectionProperty() - { - if ($this->isIdentifierComposite) { - throw new BadMethodCallException("Class " . $this->name . " has a composite identifier."); - } - - return $this->reflFields[$this->identifier[0]]; - } - - /** - * Extracts the identifier values of an entity of this class. - * - * For composite identifiers, the identifier values are returned as an array - * with the same order as the field order in {@link identifier}. - * - * @param object $entity - * - * @return array - */ - public function getIdentifierValues($entity) - { - if ($this->isIdentifierComposite) { - $id = []; - - foreach ($this->identifier as $idField) { - $value = $this->reflFields[$idField]->getValue($entity); - - if (null !== $value) { - $id[$idField] = $value; - } - } - - return $id; - } - - $id = $this->identifier[0]; - $value = $this->reflFields[$id]->getValue($entity); - - if (null === $value) { - return []; - } - - return [$id => $value]; - } - - /** - * Populates the entity identifier of an entity. - * - * @param object $entity - * @param array $id - * - * @return void - * - * @todo Rename to assignIdentifier() - */ - public function setIdentifierValues($entity, array $id) - { - foreach ($id as $idField => $idValue) { - $this->reflFields[$idField]->setValue($entity, $idValue); - } - } - - /** - * Sets the specified field to the specified value on the given entity. - * - * @param object $entity - * @param string $field - * @param mixed $value - * - * @return void - */ - public function setFieldValue($entity, $field, $value) - { - $this->reflFields[$field]->setValue($entity, $value); - } - - /** - * Gets the specified field's value off the given entity. - * - * @param object $entity - * @param string $field - * - * @return mixed - */ - public function getFieldValue($entity, $field) - { - return $this->reflFields[$field]->getValue($entity); - } - - /** - * Creates a string representation of this instance. - * - * @return string The string representation of this instance. - * - * @todo Construct meaningful string representation. - */ - public function __toString() - { - return __CLASS__ . '@' . spl_object_hash($this); - } - - /** - * Determines which fields get serialized. - * - * It is only serialized what is necessary for best unserialization performance. - * That means any metadata properties that are not set or empty or simply have - * their default value are NOT serialized. - * - * Parts that are also NOT serialized because they can not be properly unserialized: - * - reflClass (ReflectionClass) - * - reflFields (ReflectionProperty array) - * - * @return array The names of all the fields that should be serialized. - */ - public function __sleep() - { - // This metadata is always serialized/cached. - $serialized = [ - 'associationMappings', - 'columnNames', //TODO: 3.0 Remove this. Can use fieldMappings[$fieldName]['columnName'] - 'fieldMappings', - 'fieldNames', - 'embeddedClasses', - 'identifier', - 'isIdentifierComposite', // TODO: REMOVE - 'name', - 'namespace', // TODO: REMOVE - 'table', - 'rootEntityName', - 'idGenerator', //TODO: Does not really need to be serialized. Could be moved to runtime. - ]; - - // The rest of the metadata is only serialized if necessary. - if ($this->changeTrackingPolicy != self::CHANGETRACKING_DEFERRED_IMPLICIT) { - $serialized[] = 'changeTrackingPolicy'; - } - - if ($this->customRepositoryClassName) { - $serialized[] = 'customRepositoryClassName'; - } - - if ($this->inheritanceType != self::INHERITANCE_TYPE_NONE) { - $serialized[] = 'inheritanceType'; - $serialized[] = 'discriminatorColumn'; - $serialized[] = 'discriminatorValue'; - $serialized[] = 'discriminatorMap'; - $serialized[] = 'parentClasses'; - $serialized[] = 'subClasses'; - } - - if ($this->generatorType != self::GENERATOR_TYPE_NONE) { - $serialized[] = 'generatorType'; - if ($this->generatorType == self::GENERATOR_TYPE_SEQUENCE) { - $serialized[] = 'sequenceGeneratorDefinition'; - } - } - - if ($this->isMappedSuperclass) { - $serialized[] = 'isMappedSuperclass'; - } - - if ($this->isEmbeddedClass) { - $serialized[] = 'isEmbeddedClass'; - } - - if ($this->containsForeignIdentifier) { - $serialized[] = 'containsForeignIdentifier'; - } - - if ($this->isVersioned) { - $serialized[] = 'isVersioned'; - $serialized[] = 'versionField'; - } - - if ($this->lifecycleCallbacks) { - $serialized[] = 'lifecycleCallbacks'; - } - - if ($this->entityListeners) { - $serialized[] = 'entityListeners'; - } - - if ($this->namedQueries) { - $serialized[] = 'namedQueries'; - } - - if ($this->namedNativeQueries) { - $serialized[] = 'namedNativeQueries'; - } - - if ($this->sqlResultSetMappings) { - $serialized[] = 'sqlResultSetMappings'; - } - - if ($this->isReadOnly) { - $serialized[] = 'isReadOnly'; - } - - if ($this->customGeneratorDefinition) { - $serialized[] = "customGeneratorDefinition"; - } - - if ($this->cache) { - $serialized[] = 'cache'; - } - - return $serialized; - } - - /** - * Creates a new instance of the mapped class, without invoking the constructor. - * - * @return object - */ - public function newInstance() - { - return $this->instantiator->instantiate($this->name); - } - - /** - * Restores some state that can not be serialized/unserialized. - * - * @param \Doctrine\Common\Persistence\Mapping\ReflectionService $reflService - * - * @return void - */ - public function wakeupReflection($reflService) - { - // Restore ReflectionClass and properties - $this->reflClass = $reflService->getClass($this->name); - $this->instantiator = $this->instantiator ?: new Instantiator(); - - $parentReflFields = []; - - foreach ($this->embeddedClasses as $property => $embeddedClass) { - if (isset($embeddedClass['declaredField'])) { - $parentReflFields[$property] = new ReflectionEmbeddedProperty( - $parentReflFields[$embeddedClass['declaredField']], - $reflService->getAccessibleProperty( - $this->embeddedClasses[$embeddedClass['declaredField']]['class'], - $embeddedClass['originalField'] - ), - $this->embeddedClasses[$embeddedClass['declaredField']]['class'] - ); - - continue; - } - - $fieldRefl = $reflService->getAccessibleProperty( - isset($embeddedClass['declared']) ? $embeddedClass['declared'] : $this->name, - $property - ); - - $parentReflFields[$property] = $fieldRefl; - $this->reflFields[$property] = $fieldRefl; - } - - foreach ($this->fieldMappings as $field => $mapping) { - if (isset($mapping['declaredField']) && isset($parentReflFields[$mapping['declaredField']])) { - $this->reflFields[$field] = new ReflectionEmbeddedProperty( - $parentReflFields[$mapping['declaredField']], - $reflService->getAccessibleProperty($mapping['originalClass'], $mapping['originalField']), - $mapping['originalClass'] - ); - continue; - } - - $this->reflFields[$field] = isset($mapping['declared']) - ? $reflService->getAccessibleProperty($mapping['declared'], $field) - : $reflService->getAccessibleProperty($this->name, $field); - } - - foreach ($this->associationMappings as $field => $mapping) { - $this->reflFields[$field] = isset($mapping['declared']) - ? $reflService->getAccessibleProperty($mapping['declared'], $field) - : $reflService->getAccessibleProperty($this->name, $field); - } - } - - /** - * Initializes a new ClassMetadata instance that will hold the object-relational mapping - * metadata of the class with the given name. - * - * @param \Doctrine\Common\Persistence\Mapping\ReflectionService $reflService The reflection service. - * - * @return void - */ - public function initializeReflection($reflService) - { - $this->reflClass = $reflService->getClass($this->name); - $this->namespace = $reflService->getClassNamespace($this->name); - - if ($this->reflClass) { - $this->name = $this->rootEntityName = $this->reflClass->getName(); - } - - $this->table['name'] = $this->namingStrategy->classToTableName($this->name); - } - - /** - * Validates Identifier. - * - * @return void - * - * @throws MappingException - */ - public function validateIdentifier() - { - if ($this->isMappedSuperclass || $this->isEmbeddedClass) { - return; - } - - // Verify & complete identifier mapping - if ( ! $this->identifier) { - throw MappingException::identifierRequired($this->name); - } - - if ($this->usesIdGenerator() && $this->isIdentifierComposite) { - throw MappingException::compositeKeyAssignedIdGeneratorRequired($this->name); - } - } - - /** - * Validates association targets actually exist. - * - * @return void - * - * @throws MappingException - */ - public function validateAssociations() - { - foreach ($this->associationMappings as $mapping) { - if ( ! ClassLoader::classExists($mapping['targetEntity']) ) { - throw MappingException::invalidTargetEntityClass($mapping['targetEntity'], $this->name, $mapping['fieldName']); - } - } - } - - /** - * Validates lifecycle callbacks. - * - * @param \Doctrine\Common\Persistence\Mapping\ReflectionService $reflService - * - * @return void - * - * @throws MappingException - */ - public function validateLifecycleCallbacks($reflService) - { - foreach ($this->lifecycleCallbacks as $callbacks) { - foreach ($callbacks as $callbackFuncName) { - if ( ! $reflService->hasPublicMethod($this->name, $callbackFuncName)) { - throw MappingException::lifecycleCallbackMethodNotFound($this->name, $callbackFuncName); - } - } - } - } - - /** - * {@inheritDoc} - */ - public function getReflectionClass() - { - return $this->reflClass; - } - - /** - * @param array $cache - * - * @return void - */ - public function enableCache(array $cache) - { - if ( ! isset($cache['usage'])) { - $cache['usage'] = self::CACHE_USAGE_READ_ONLY; - } - - if ( ! isset($cache['region'])) { - $cache['region'] = strtolower(str_replace('\\', '_', $this->rootEntityName)); - } - - $this->cache = $cache; - } - - /** - * @param string $fieldName - * @param array $cache - * - * @return void - */ - public function enableAssociationCache($fieldName, array $cache) - { - $this->associationMappings[$fieldName]['cache'] = $this->getAssociationCacheDefaults($fieldName, $cache); - } - - /** - * @param string $fieldName - * @param array $cache - * - * @return array - */ - public function getAssociationCacheDefaults($fieldName, array $cache) - { - if ( ! isset($cache['usage'])) { - $cache['usage'] = isset($this->cache['usage']) - ? $this->cache['usage'] - : self::CACHE_USAGE_READ_ONLY; - } - - if ( ! isset($cache['region'])) { - $cache['region'] = strtolower(str_replace('\\', '_', $this->rootEntityName)) . '__' . $fieldName; - } - - return $cache; - } - - /** - * Sets the change tracking policy used by this class. - * - * @param integer $policy - * - * @return void - */ - public function setChangeTrackingPolicy($policy) - { - $this->changeTrackingPolicy = $policy; - } - - /** - * Whether the change tracking policy of this class is "deferred explicit". - * - * @return boolean - */ - public function isChangeTrackingDeferredExplicit() - { - return self::CHANGETRACKING_DEFERRED_EXPLICIT === $this->changeTrackingPolicy; - } - - /** - * Whether the change tracking policy of this class is "deferred implicit". - * - * @return boolean - */ - public function isChangeTrackingDeferredImplicit() - { - return self::CHANGETRACKING_DEFERRED_IMPLICIT === $this->changeTrackingPolicy; - } - - /** - * Whether the change tracking policy of this class is "notify". - * - * @return boolean - */ - public function isChangeTrackingNotify() - { - return self::CHANGETRACKING_NOTIFY === $this->changeTrackingPolicy; - } - - /** - * Checks whether a field is part of the identifier/primary key field(s). - * - * @param string $fieldName The field name. - * - * @return boolean TRUE if the field is part of the table identifier/primary key field(s), - * FALSE otherwise. - */ - public function isIdentifier($fieldName) - { - if ( ! $this->identifier) { - return false; - } - - if ( ! $this->isIdentifierComposite) { - return $fieldName === $this->identifier[0]; - } - - return in_array($fieldName, $this->identifier, true); - } - - /** - * Checks if the field is unique. - * - * @param string $fieldName The field name. - * - * @return boolean TRUE if the field is unique, FALSE otherwise. - */ - public function isUniqueField($fieldName) - { - $mapping = $this->getFieldMapping($fieldName); - - return false !== $mapping && isset($mapping['unique']) && $mapping['unique']; - } - - /** - * Checks if the field is not null. - * - * @param string $fieldName The field name. - * - * @return boolean TRUE if the field is not null, FALSE otherwise. - */ - public function isNullable($fieldName) - { - $mapping = $this->getFieldMapping($fieldName); - - return false !== $mapping && isset($mapping['nullable']) && $mapping['nullable']; - } - - /** - * Gets a column name for a field name. - * If the column name for the field cannot be found, the given field name - * is returned. - * - * @param string $fieldName The field name. - * - * @return string The column name. - */ - public function getColumnName($fieldName) - { - return isset($this->columnNames[$fieldName]) - ? $this->columnNames[$fieldName] - : $fieldName; - } - - /** - * Gets the mapping of a (regular) field that holds some data but not a - * reference to another object. - * - * @param string $fieldName The field name. - * - * @return array The field mapping. - * - * @throws MappingException - */ - public function getFieldMapping($fieldName) - { - if ( ! isset($this->fieldMappings[$fieldName])) { - throw MappingException::mappingNotFound($this->name, $fieldName); - } - - return $this->fieldMappings[$fieldName]; - } - - /** - * Gets the mapping of an association. - * - * @see ClassMetadataInfo::$associationMappings - * - * @param string $fieldName The field name that represents the association in - * the object model. - * - * @return array The mapping. - * - * @throws MappingException - */ - public function getAssociationMapping($fieldName) - { - if ( ! isset($this->associationMappings[$fieldName])) { - throw MappingException::mappingNotFound($this->name, $fieldName); - } - - return $this->associationMappings[$fieldName]; - } - - /** - * Gets all association mappings of the class. - * - * @return array - */ - public function getAssociationMappings() - { - return $this->associationMappings; - } - - /** - * Gets the field name for a column name. - * If no field name can be found the column name is returned. - * - * @param string $columnName The column name. - * - * @return string The column alias. - */ - public function getFieldName($columnName) - { - return isset($this->fieldNames[$columnName]) - ? $this->fieldNames[$columnName] - : $columnName; - } - - /** - * Gets the named query. - * - * @see ClassMetadataInfo::$namedQueries - * - * @param string $queryName The query name. - * - * @return string - * - * @throws MappingException - */ - public function getNamedQuery($queryName) - { - if ( ! isset($this->namedQueries[$queryName])) { - throw MappingException::queryNotFound($this->name, $queryName); - } - - return $this->namedQueries[$queryName]['dql']; - } - - /** - * Gets all named queries of the class. - * - * @return array - */ - public function getNamedQueries() - { - return $this->namedQueries; - } - - /** - * Gets the named native query. - * - * @see ClassMetadataInfo::$namedNativeQueries - * - * @param string $queryName The query name. - * - * @return array - * - * @throws MappingException - */ - public function getNamedNativeQuery($queryName) - { - if ( ! isset($this->namedNativeQueries[$queryName])) { - throw MappingException::queryNotFound($this->name, $queryName); - } - - return $this->namedNativeQueries[$queryName]; - } - - /** - * Gets all named native queries of the class. - * - * @return array - */ - public function getNamedNativeQueries() - { - return $this->namedNativeQueries; - } - - /** - * Gets the result set mapping. - * - * @see ClassMetadataInfo::$sqlResultSetMappings - * - * @param string $name The result set mapping name. - * - * @return array - * - * @throws MappingException - */ - public function getSqlResultSetMapping($name) - { - if ( ! isset($this->sqlResultSetMappings[$name])) { - throw MappingException::resultMappingNotFound($this->name, $name); - } - - return $this->sqlResultSetMappings[$name]; - } - - /** - * Gets all sql result set mappings of the class. - * - * @return array - */ - public function getSqlResultSetMappings() - { - return $this->sqlResultSetMappings; - } - - /** - * Validates & completes the given field mapping. - * - * @param array $mapping The field mapping to validate & complete. - * - * @return void - * - * @throws MappingException - */ - protected function _validateAndCompleteFieldMapping(array &$mapping) - { - // Check mandatory fields - if ( ! isset($mapping['fieldName']) || !$mapping['fieldName']) { - throw MappingException::missingFieldName($this->name); - } - - if ( ! isset($mapping['type'])) { - // Default to string - $mapping['type'] = 'string'; - } - - // Complete fieldName and columnName mapping - if ( ! isset($mapping['columnName'])) { - $mapping['columnName'] = $this->namingStrategy->propertyToColumnName($mapping['fieldName'], $this->name); - } - - if ('`' === $mapping['columnName'][0]) { - $mapping['columnName'] = trim($mapping['columnName'], '`'); - $mapping['quoted'] = true; - } - - $this->columnNames[$mapping['fieldName']] = $mapping['columnName']; - - if (isset($this->fieldNames[$mapping['columnName']]) || ($this->discriminatorColumn && $this->discriminatorColumn['name'] === $mapping['columnName'])) { - throw MappingException::duplicateColumnName($this->name, $mapping['columnName']); - } - - $this->fieldNames[$mapping['columnName']] = $mapping['fieldName']; - - // Complete id mapping - if (isset($mapping['id']) && true === $mapping['id']) { - if ($this->versionField == $mapping['fieldName']) { - throw MappingException::cannotVersionIdField($this->name, $mapping['fieldName']); - } - - if ( ! in_array($mapping['fieldName'], $this->identifier)) { - $this->identifier[] = $mapping['fieldName']; - } - - // Check for composite key - if ( ! $this->isIdentifierComposite && count($this->identifier) > 1) { - $this->isIdentifierComposite = true; - } - } - - if (Type::hasType($mapping['type']) && Type::getType($mapping['type'])->canRequireSQLConversion()) { - if (isset($mapping['id']) && true === $mapping['id']) { - throw MappingException::sqlConversionNotAllowedForIdentifiers($this->name, $mapping['fieldName'], $mapping['type']); - } - - $mapping['requireSQLConversion'] = true; - } - } - - /** - * Validates & completes the basic mapping information that is common to all - * association mappings (one-to-one, many-ot-one, one-to-many, many-to-many). - * - * @param array $mapping The mapping. - * - * @return array The updated mapping. - * - * @throws MappingException If something is wrong with the mapping. - */ - protected function _validateAndCompleteAssociationMapping(array $mapping) - { - if ( ! isset($mapping['mappedBy'])) { - $mapping['mappedBy'] = null; - } - - if ( ! isset($mapping['inversedBy'])) { - $mapping['inversedBy'] = null; - } - - $mapping['isOwningSide'] = true; // assume owning side until we hit mappedBy - - if (empty($mapping['indexBy'])) { - unset($mapping['indexBy']); - } - - // If targetEntity is unqualified, assume it is in the same namespace as - // the sourceEntity. - $mapping['sourceEntity'] = $this->name; - - if (isset($mapping['targetEntity'])) { - $mapping['targetEntity'] = $this->fullyQualifiedClassName($mapping['targetEntity']); - $mapping['targetEntity'] = ltrim($mapping['targetEntity'], '\\'); - } - - if (($mapping['type'] & self::MANY_TO_ONE) > 0 && isset($mapping['orphanRemoval']) && $mapping['orphanRemoval']) { - throw MappingException::illegalOrphanRemoval($this->name, $mapping['fieldName']); - } - - // Complete id mapping - if (isset($mapping['id']) && true === $mapping['id']) { - if (isset($mapping['orphanRemoval']) && $mapping['orphanRemoval']) { - throw MappingException::illegalOrphanRemovalOnIdentifierAssociation($this->name, $mapping['fieldName']); - } - - if ( ! in_array($mapping['fieldName'], $this->identifier)) { - if (isset($mapping['joinColumns']) && count($mapping['joinColumns']) >= 2) { - throw MappingException::cannotMapCompositePrimaryKeyEntitiesAsForeignId( - $mapping['targetEntity'], $this->name, $mapping['fieldName'] - ); - } - - $this->identifier[] = $mapping['fieldName']; - $this->containsForeignIdentifier = true; - } - - // Check for composite key - if ( ! $this->isIdentifierComposite && count($this->identifier) > 1) { - $this->isIdentifierComposite = true; - } - - if ($this->cache && !isset($mapping['cache'])) { - throw CacheException::nonCacheableEntityAssociation($this->name, $mapping['fieldName']); - } - } - - // Mandatory attributes for both sides - // Mandatory: fieldName, targetEntity - if ( ! isset($mapping['fieldName']) || !$mapping['fieldName']) { - throw MappingException::missingFieldName($this->name); - } - - if ( ! isset($mapping['targetEntity'])) { - throw MappingException::missingTargetEntity($mapping['fieldName']); - } - - // Mandatory and optional attributes for either side - if ( ! $mapping['mappedBy']) { - if (isset($mapping['joinTable']) && $mapping['joinTable']) { - if (isset($mapping['joinTable']['name']) && $mapping['joinTable']['name'][0] === '`') { - $mapping['joinTable']['name'] = trim($mapping['joinTable']['name'], '`'); - $mapping['joinTable']['quoted'] = true; - } - } - } else { - $mapping['isOwningSide'] = false; - } - - if (isset($mapping['id']) && true === $mapping['id'] && $mapping['type'] & self::TO_MANY) { - throw MappingException::illegalToManyIdentifierAssociation($this->name, $mapping['fieldName']); - } - - // Fetch mode. Default fetch mode to LAZY, if not set. - if ( ! isset($mapping['fetch'])) { - $mapping['fetch'] = self::FETCH_LAZY; - } - - // Cascades - $cascades = isset($mapping['cascade']) ? array_map('strtolower', $mapping['cascade']) : []; - - $allCascades = ['remove', 'persist', 'refresh', 'merge', 'detach']; - if (in_array('all', $cascades)) { - $cascades = $allCascades; - } elseif (count($cascades) !== count(array_intersect($cascades, $allCascades))) { - throw MappingException::invalidCascadeOption( - array_diff($cascades, $allCascades), - $this->name, - $mapping['fieldName'] - ); - } - - $mapping['cascade'] = $cascades; - $mapping['isCascadeRemove'] = in_array('remove', $cascades); - $mapping['isCascadePersist'] = in_array('persist', $cascades); - $mapping['isCascadeRefresh'] = in_array('refresh', $cascades); - $mapping['isCascadeMerge'] = in_array('merge', $cascades); - $mapping['isCascadeDetach'] = in_array('detach', $cascades); - - return $mapping; - } - - /** - * Validates & completes a one-to-one association mapping. - * - * @param array $mapping The mapping to validate & complete. - * - * @return array The validated & completed mapping. - * - * @throws RuntimeException - * @throws MappingException - */ - protected function _validateAndCompleteOneToOneMapping(array $mapping) - { - $mapping = $this->_validateAndCompleteAssociationMapping($mapping); - - if (isset($mapping['joinColumns']) && $mapping['joinColumns']) { - $mapping['isOwningSide'] = true; - } - - if ($mapping['isOwningSide']) { - if (empty($mapping['joinColumns'])) { - // Apply default join column - $mapping['joinColumns'] = [ - [ - 'name' => $this->namingStrategy->joinColumnName($mapping['fieldName'], $this->name), - 'referencedColumnName' => $this->namingStrategy->referenceColumnName() - ] - ]; - } - - $uniqueConstraintColumns = []; - - foreach ($mapping['joinColumns'] as &$joinColumn) { - if ($mapping['type'] === self::ONE_TO_ONE && ! $this->isInheritanceTypeSingleTable()) { - if (count($mapping['joinColumns']) === 1) { - if (empty($mapping['id'])) { - $joinColumn['unique'] = true; - } - } else { - $uniqueConstraintColumns[] = $joinColumn['name']; - } - } - - if (empty($joinColumn['name'])) { - $joinColumn['name'] = $this->namingStrategy->joinColumnName($mapping['fieldName'], $this->name); - } - - if (empty($joinColumn['referencedColumnName'])) { - $joinColumn['referencedColumnName'] = $this->namingStrategy->referenceColumnName(); - } - - if ($joinColumn['name'][0] === '`') { - $joinColumn['name'] = trim($joinColumn['name'], '`'); - $joinColumn['quoted'] = true; - } - - if ($joinColumn['referencedColumnName'][0] === '`') { - $joinColumn['referencedColumnName'] = trim($joinColumn['referencedColumnName'], '`'); - $joinColumn['quoted'] = true; - } - - $mapping['sourceToTargetKeyColumns'][$joinColumn['name']] = $joinColumn['referencedColumnName']; - $mapping['joinColumnFieldNames'][$joinColumn['name']] = isset($joinColumn['fieldName']) - ? $joinColumn['fieldName'] - : $joinColumn['name']; - } - - if ($uniqueConstraintColumns) { - if ( ! $this->table) { - throw new RuntimeException("ClassMetadataInfo::setTable() has to be called before defining a one to one relationship."); - } - - $this->table['uniqueConstraints'][$mapping['fieldName'] . "_uniq"] = [ - 'columns' => $uniqueConstraintColumns - ]; - } - - $mapping['targetToSourceKeyColumns'] = array_flip($mapping['sourceToTargetKeyColumns']); - } - - $mapping['orphanRemoval'] = isset($mapping['orphanRemoval']) && $mapping['orphanRemoval']; - $mapping['isCascadeRemove'] = $mapping['orphanRemoval'] || $mapping['isCascadeRemove']; - - if ($mapping['orphanRemoval']) { - unset($mapping['unique']); - } - - if (isset($mapping['id']) && $mapping['id'] === true && !$mapping['isOwningSide']) { - throw MappingException::illegalInverseIdentifierAssociation($this->name, $mapping['fieldName']); - } - - return $mapping; - } - - /** - * Validates & completes a one-to-many association mapping. - * - * @param array $mapping The mapping to validate and complete. - * - * @return array The validated and completed mapping. - * - * @throws MappingException - * @throws InvalidArgumentException - */ - protected function _validateAndCompleteOneToManyMapping(array $mapping) - { - $mapping = $this->_validateAndCompleteAssociationMapping($mapping); - - // OneToMany-side MUST be inverse (must have mappedBy) - if ( ! isset($mapping['mappedBy'])) { - throw MappingException::oneToManyRequiresMappedBy($mapping['fieldName']); - } - - $mapping['orphanRemoval'] = isset($mapping['orphanRemoval']) && $mapping['orphanRemoval']; - $mapping['isCascadeRemove'] = $mapping['orphanRemoval'] || $mapping['isCascadeRemove']; - - $this->assertMappingOrderBy($mapping); - - return $mapping; - } - - /** - * Validates & completes a many-to-many association mapping. - * - * @param array $mapping The mapping to validate & complete. - * - * @return array The validated & completed mapping. - * - * @throws \InvalidArgumentException - */ - protected function _validateAndCompleteManyToManyMapping(array $mapping) - { - $mapping = $this->_validateAndCompleteAssociationMapping($mapping); - - if ($mapping['isOwningSide']) { - // owning side MUST have a join table - if ( ! isset($mapping['joinTable']['name'])) { - $mapping['joinTable']['name'] = $this->namingStrategy->joinTableName($mapping['sourceEntity'], $mapping['targetEntity'], $mapping['fieldName']); - } - - $selfReferencingEntityWithoutJoinColumns = $mapping['sourceEntity'] == $mapping['targetEntity'] - && (! (isset($mapping['joinTable']['joinColumns']) || isset($mapping['joinTable']['inverseJoinColumns']))); - - if ( ! isset($mapping['joinTable']['joinColumns'])) { - $mapping['joinTable']['joinColumns'] = [ - [ - 'name' => $this->namingStrategy->joinKeyColumnName($mapping['sourceEntity'], $selfReferencingEntityWithoutJoinColumns ? 'source' : null), - 'referencedColumnName' => $this->namingStrategy->referenceColumnName(), - 'onDelete' => 'CASCADE' - ] - ]; - } - - if ( ! isset($mapping['joinTable']['inverseJoinColumns'])) { - $mapping['joinTable']['inverseJoinColumns'] = [ - [ - 'name' => $this->namingStrategy->joinKeyColumnName($mapping['targetEntity'], $selfReferencingEntityWithoutJoinColumns ? 'target' : null), - 'referencedColumnName' => $this->namingStrategy->referenceColumnName(), - 'onDelete' => 'CASCADE' - ] - ]; - } - - $mapping['joinTableColumns'] = []; - - foreach ($mapping['joinTable']['joinColumns'] as &$joinColumn) { - if (empty($joinColumn['name'])) { - $joinColumn['name'] = $this->namingStrategy->joinKeyColumnName($mapping['sourceEntity'], $joinColumn['referencedColumnName']); - } - - if (empty($joinColumn['referencedColumnName'])) { - $joinColumn['referencedColumnName'] = $this->namingStrategy->referenceColumnName(); - } - - if ($joinColumn['name'][0] === '`') { - $joinColumn['name'] = trim($joinColumn['name'], '`'); - $joinColumn['quoted'] = true; - } - - if ($joinColumn['referencedColumnName'][0] === '`') { - $joinColumn['referencedColumnName'] = trim($joinColumn['referencedColumnName'], '`'); - $joinColumn['quoted'] = true; - } - - if (isset($joinColumn['onDelete']) && strtolower($joinColumn['onDelete']) == 'cascade') { - $mapping['isOnDeleteCascade'] = true; - } - - $mapping['relationToSourceKeyColumns'][$joinColumn['name']] = $joinColumn['referencedColumnName']; - $mapping['joinTableColumns'][] = $joinColumn['name']; - } - - foreach ($mapping['joinTable']['inverseJoinColumns'] as &$inverseJoinColumn) { - if (empty($inverseJoinColumn['name'])) { - $inverseJoinColumn['name'] = $this->namingStrategy->joinKeyColumnName($mapping['targetEntity'], $inverseJoinColumn['referencedColumnName']); - } - - if (empty($inverseJoinColumn['referencedColumnName'])) { - $inverseJoinColumn['referencedColumnName'] = $this->namingStrategy->referenceColumnName(); - } - - if ($inverseJoinColumn['name'][0] === '`') { - $inverseJoinColumn['name'] = trim($inverseJoinColumn['name'], '`'); - $inverseJoinColumn['quoted'] = true; - } - - if ($inverseJoinColumn['referencedColumnName'][0] === '`') { - $inverseJoinColumn['referencedColumnName'] = trim($inverseJoinColumn['referencedColumnName'], '`'); - $inverseJoinColumn['quoted'] = true; - } - - if (isset($inverseJoinColumn['onDelete']) && strtolower($inverseJoinColumn['onDelete']) == 'cascade') { - $mapping['isOnDeleteCascade'] = true; - } - - $mapping['relationToTargetKeyColumns'][$inverseJoinColumn['name']] = $inverseJoinColumn['referencedColumnName']; - $mapping['joinTableColumns'][] = $inverseJoinColumn['name']; - } - } - - $mapping['orphanRemoval'] = isset($mapping['orphanRemoval']) && $mapping['orphanRemoval']; - - $this->assertMappingOrderBy($mapping); - - return $mapping; - } - - /** - * {@inheritDoc} - */ - public function getIdentifierFieldNames() - { - return $this->identifier; - } - - /** - * Gets the name of the single id field. Note that this only works on - * entity classes that have a single-field pk. - * - * @return string - * - * @throws MappingException If the class doesn't have an identifier or it has a composite primary key. - */ - public function getSingleIdentifierFieldName() - { - if ($this->isIdentifierComposite) { - throw MappingException::singleIdNotAllowedOnCompositePrimaryKey($this->name); - } - - if ( ! isset($this->identifier[0])) { - throw MappingException::noIdDefined($this->name); - } - - return $this->identifier[0]; - } - - /** - * Gets the column name of the single id column. Note that this only works on - * entity classes that have a single-field pk. - * - * @return string - * - * @throws MappingException If the class doesn't have an identifier or it has a composite primary key. - */ - public function getSingleIdentifierColumnName() - { - return $this->getColumnName($this->getSingleIdentifierFieldName()); - } - - /** - * INTERNAL: - * Sets the mapped identifier/primary key fields of this class. - * Mainly used by the ClassMetadataFactory to assign inherited identifiers. - * - * @param array $identifier - * - * @return void - */ - public function setIdentifier(array $identifier) - { - $this->identifier = $identifier; - $this->isIdentifierComposite = (count($this->identifier) > 1); - } - - /** - * {@inheritDoc} - */ - public function getIdentifier() - { - return $this->identifier; - } - - /** - * {@inheritDoc} - */ - public function hasField($fieldName) - { - return isset($this->fieldMappings[$fieldName]) || isset($this->embeddedClasses[$fieldName]); - } - - /** - * Gets an array containing all the column names. - * - * @param array|null $fieldNames - * - * @return array - */ - public function getColumnNames(array $fieldNames = null) - { - if (null === $fieldNames) { - return array_keys($this->fieldNames); - } - - return array_values(array_map([$this, 'getColumnName'], $fieldNames)); - } - - /** - * Returns an array with all the identifier column names. - * - * @return array - */ - public function getIdentifierColumnNames() - { - $columnNames = []; - - foreach ($this->identifier as $idProperty) { - if (isset($this->fieldMappings[$idProperty])) { - $columnNames[] = $this->fieldMappings[$idProperty]['columnName']; - - continue; - } - - // Association defined as Id field - $joinColumns = $this->associationMappings[$idProperty]['joinColumns']; - $assocColumnNames = array_map(function ($joinColumn) { return $joinColumn['name']; }, $joinColumns); - - $columnNames = array_merge($columnNames, $assocColumnNames); - } - - return $columnNames; - } - - /** - * Sets the type of Id generator to use for the mapped class. - * - * @param int $generatorType - * - * @return void - */ - public function setIdGeneratorType($generatorType) - { - $this->generatorType = $generatorType; - } - - /** - * Checks whether the mapped class uses an Id generator. - * - * @return boolean TRUE if the mapped class uses an Id generator, FALSE otherwise. - */ - public function usesIdGenerator() - { - return $this->generatorType != self::GENERATOR_TYPE_NONE; - } - - /** - * @return boolean - */ - public function isInheritanceTypeNone() - { - return $this->inheritanceType == self::INHERITANCE_TYPE_NONE; - } - - /** - * Checks whether the mapped class uses the JOINED inheritance mapping strategy. - * - * @return boolean TRUE if the class participates in a JOINED inheritance mapping, - * FALSE otherwise. - */ - public function isInheritanceTypeJoined() - { - return $this->inheritanceType == self::INHERITANCE_TYPE_JOINED; - } - - /** - * Checks whether the mapped class uses the SINGLE_TABLE inheritance mapping strategy. - * - * @return boolean TRUE if the class participates in a SINGLE_TABLE inheritance mapping, - * FALSE otherwise. - */ - public function isInheritanceTypeSingleTable() - { - return $this->inheritanceType == self::INHERITANCE_TYPE_SINGLE_TABLE; - } - - /** - * Checks whether the mapped class uses the TABLE_PER_CLASS inheritance mapping strategy. - * - * @return boolean TRUE if the class participates in a TABLE_PER_CLASS inheritance mapping, - * FALSE otherwise. - */ - public function isInheritanceTypeTablePerClass() - { - return $this->inheritanceType == self::INHERITANCE_TYPE_TABLE_PER_CLASS; - } - - /** - * Checks whether the class uses an identity column for the Id generation. - * - * @return boolean TRUE if the class uses the IDENTITY generator, FALSE otherwise. - */ - public function isIdGeneratorIdentity() - { - return $this->generatorType == self::GENERATOR_TYPE_IDENTITY; - } - - /** - * Checks whether the class uses a sequence for id generation. - * - * @return boolean TRUE if the class uses the SEQUENCE generator, FALSE otherwise. - */ - public function isIdGeneratorSequence() - { - return $this->generatorType == self::GENERATOR_TYPE_SEQUENCE; - } - - /** - * Checks whether the class uses a table for id generation. - * - * @return boolean TRUE if the class uses the TABLE generator, FALSE otherwise. - */ - public function isIdGeneratorTable() - { - return $this->generatorType == self::GENERATOR_TYPE_TABLE; - } - - /** - * Checks whether the class has a natural identifier/pk (which means it does - * not use any Id generator. - * - * @return boolean - */ - public function isIdentifierNatural() - { - return $this->generatorType == self::GENERATOR_TYPE_NONE; - } - - /** - * Checks whether the class use a UUID for id generation. - * - * @return boolean - */ - public function isIdentifierUuid() - { - return $this->generatorType == self::GENERATOR_TYPE_UUID; - } - - /** - * Gets the type of a field. - * - * @param string $fieldName - * - * @return \Doctrine\DBAL\Types\Type|string|null - * - * @todo 3.0 Remove this. PersisterHelper should fix it somehow - */ - public function getTypeOfField($fieldName) - { - return isset($this->fieldMappings[$fieldName]) - ? $this->fieldMappings[$fieldName]['type'] - : null; - } - - /** - * Gets the type of a column. - * - * @param string $columnName - * - * @return \Doctrine\DBAL\Types\Type|string|null - * - * @deprecated 3.0 remove this. this method is bogus and unreliable, since it cannot resolve the type of a column - * that is derived by a referenced field on a different entity. - */ - public function getTypeOfColumn($columnName) - { - return $this->getTypeOfField($this->getFieldName($columnName)); - } - - /** - * Gets the name of the primary table. - * - * @return string - */ - public function getTableName() - { - return $this->table['name']; - } - - /** - * Gets primary table's schema name. - * - * @return string|null - */ - public function getSchemaName() - { - return isset($this->table['schema']) ? $this->table['schema'] : null; - } - - /** - * Gets the table name to use for temporary identifier tables of this class. - * - * @return string - */ - public function getTemporaryIdTableName() - { - // replace dots with underscores because PostgreSQL creates temporary tables in a special schema - return str_replace('.', '_', $this->getTableName() . '_id_tmp'); - } - - /** - * Sets the mapped subclasses of this class. - * - * @param array $subclasses The names of all mapped subclasses. - * - * @return void - */ - public function setSubclasses(array $subclasses) - { - foreach ($subclasses as $subclass) { - $this->subClasses[] = $this->fullyQualifiedClassName($subclass); - } - } - - /** - * Sets the parent class names. - * Assumes that the class names in the passed array are in the order: - * directParent -> directParentParent -> directParentParentParent ... -> root. - * - * @param array $classNames - * - * @return void - */ - public function setParentClasses(array $classNames) - { - $this->parentClasses = $classNames; - - if (count($classNames) > 0) { - $this->rootEntityName = array_pop($classNames); - } - } - - /** - * Sets the inheritance type used by the class and its subclasses. - * - * @param integer $type - * - * @return void - * - * @throws MappingException - */ - public function setInheritanceType($type) - { - if ( ! $this->_isInheritanceType($type)) { - throw MappingException::invalidInheritanceType($this->name, $type); - } - - $this->inheritanceType = $type; - } - - /** - * Sets the association to override association mapping of property for an entity relationship. - * - * @param string $fieldName - * @param array $overrideMapping - * - * @return void - * - * @throws MappingException - */ - public function setAssociationOverride($fieldName, array $overrideMapping) - { - if ( ! isset($this->associationMappings[$fieldName])) { - throw MappingException::invalidOverrideFieldName($this->name, $fieldName); - } - - $mapping = $this->associationMappings[$fieldName]; - - if (isset($overrideMapping['joinColumns'])) { - $mapping['joinColumns'] = $overrideMapping['joinColumns']; - } - - if (isset($overrideMapping['inversedBy'])) { - $mapping['inversedBy'] = $overrideMapping['inversedBy']; - } - - if (isset($overrideMapping['joinTable'])) { - $mapping['joinTable'] = $overrideMapping['joinTable']; - } - - if (isset($overrideMapping['fetch'])) { - $mapping['fetch'] = $overrideMapping['fetch']; - } - - $mapping['joinColumnFieldNames'] = null; - $mapping['joinTableColumns'] = null; - $mapping['sourceToTargetKeyColumns'] = null; - $mapping['relationToSourceKeyColumns'] = null; - $mapping['relationToTargetKeyColumns'] = null; - - switch ($mapping['type']) { - case self::ONE_TO_ONE: - $mapping = $this->_validateAndCompleteOneToOneMapping($mapping); - break; - case self::ONE_TO_MANY: - $mapping = $this->_validateAndCompleteOneToManyMapping($mapping); - break; - case self::MANY_TO_ONE: - $mapping = $this->_validateAndCompleteOneToOneMapping($mapping); - break; - case self::MANY_TO_MANY: - $mapping = $this->_validateAndCompleteManyToManyMapping($mapping); - break; - } - - $this->associationMappings[$fieldName] = $mapping; - } - - /** - * Sets the override for a mapped field. - * - * @param string $fieldName - * @param array $overrideMapping - * - * @return void - * - * @throws MappingException - */ - public function setAttributeOverride($fieldName, array $overrideMapping) - { - if ( ! isset($this->fieldMappings[$fieldName])) { - throw MappingException::invalidOverrideFieldName($this->name, $fieldName); - } - - $mapping = $this->fieldMappings[$fieldName]; - - if (isset($mapping['id'])) { - $overrideMapping['id'] = $mapping['id']; - } - - if ( ! isset($overrideMapping['type'])) { - $overrideMapping['type'] = $mapping['type']; - } - - if ( ! isset($overrideMapping['fieldName'])) { - $overrideMapping['fieldName'] = $mapping['fieldName']; - } - - if ($overrideMapping['type'] !== $mapping['type']) { - throw MappingException::invalidOverrideFieldType($this->name, $fieldName); - } - - unset($this->fieldMappings[$fieldName]); - unset($this->fieldNames[$mapping['columnName']]); - unset($this->columnNames[$mapping['fieldName']]); - - $this->_validateAndCompleteFieldMapping($overrideMapping); - - $this->fieldMappings[$fieldName] = $overrideMapping; - } - - /** - * Checks whether a mapped field is inherited from an entity superclass. - * - * @param string $fieldName - * - * @return bool TRUE if the field is inherited, FALSE otherwise. - */ - public function isInheritedField($fieldName) - { - return isset($this->fieldMappings[$fieldName]['inherited']); - } - - /** - * Checks if this entity is the root in any entity-inheritance-hierarchy. - * - * @return bool - */ - public function isRootEntity() - { - return $this->name == $this->rootEntityName; - } - - /** - * Checks whether a mapped association field is inherited from a superclass. - * - * @param string $fieldName - * - * @return boolean TRUE if the field is inherited, FALSE otherwise. - */ - public function isInheritedAssociation($fieldName) - { - return isset($this->associationMappings[$fieldName]['inherited']); - } - - public function isInheritedEmbeddedClass($fieldName) - { - return isset($this->embeddedClasses[$fieldName]['inherited']); - } - - /** - * Sets the name of the primary table the class is mapped to. - * - * @param string $tableName The table name. - * - * @return void - * - * @deprecated Use {@link setPrimaryTable}. - */ - public function setTableName($tableName) - { - $this->table['name'] = $tableName; - } - - /** - * Sets the primary table definition. The provided array supports the - * following structure: - * - * name => (optional, defaults to class name) - * indexes => array of indexes (optional) - * uniqueConstraints => array of constraints (optional) - * - * If a key is omitted, the current value is kept. - * - * @param array $table The table description. - * - * @return void - */ - public function setPrimaryTable(array $table) - { - if (isset($table['name'])) { - // Split schema and table name from a table name like "myschema.mytable" - if (strpos($table['name'], '.') !== false) { - list($this->table['schema'], $table['name']) = explode('.', $table['name'], 2); - } - - if ($table['name'][0] === '`') { - $table['name'] = trim($table['name'], '`'); - $this->table['quoted'] = true; - } - - $this->table['name'] = $table['name']; - } - - if (isset($table['quoted'])) { - $this->table['quoted'] = $table['quoted']; - } - - if (isset($table['schema'])) { - $this->table['schema'] = $table['schema']; - } - - if (isset($table['indexes'])) { - $this->table['indexes'] = $table['indexes']; - } - - if (isset($table['uniqueConstraints'])) { - $this->table['uniqueConstraints'] = $table['uniqueConstraints']; - } - - if (isset($table['options'])) { - $this->table['options'] = $table['options']; - } - } - - /** - * Checks whether the given type identifies an inheritance type. - * - * @param integer $type - * - * @return boolean TRUE if the given type identifies an inheritance type, FALSe otherwise. - */ - private function _isInheritanceType($type) - { - return $type == self::INHERITANCE_TYPE_NONE || - $type == self::INHERITANCE_TYPE_SINGLE_TABLE || - $type == self::INHERITANCE_TYPE_JOINED || - $type == self::INHERITANCE_TYPE_TABLE_PER_CLASS; - } - - /** - * Adds a mapped field to the class. - * - * @param array $mapping The field mapping. - * - * @return void - * - * @throws MappingException - */ - public function mapField(array $mapping) - { - $this->_validateAndCompleteFieldMapping($mapping); - $this->assertFieldNotMapped($mapping['fieldName']); - - $this->fieldMappings[$mapping['fieldName']] = $mapping; - } - - /** - * INTERNAL: - * Adds an association mapping without completing/validating it. - * This is mainly used to add inherited association mappings to derived classes. - * - * @param array $mapping - * - * @return void - * - * @throws MappingException - */ - public function addInheritedAssociationMapping(array $mapping/*, $owningClassName = null*/) - { - if (isset($this->associationMappings[$mapping['fieldName']])) { - throw MappingException::duplicateAssociationMapping($this->name, $mapping['fieldName']); - } - $this->associationMappings[$mapping['fieldName']] = $mapping; - } - - /** - * INTERNAL: - * Adds a field mapping without completing/validating it. - * This is mainly used to add inherited field mappings to derived classes. - * - * @param array $fieldMapping - * - * @return void - */ - public function addInheritedFieldMapping(array $fieldMapping) - { - $this->fieldMappings[$fieldMapping['fieldName']] = $fieldMapping; - $this->columnNames[$fieldMapping['fieldName']] = $fieldMapping['columnName']; - $this->fieldNames[$fieldMapping['columnName']] = $fieldMapping['fieldName']; - } - - /** - * INTERNAL: - * Adds a named query to this class. - * - * @param array $queryMapping - * - * @return void - * - * @throws MappingException - */ - public function addNamedQuery(array $queryMapping) - { - if (!isset($queryMapping['name'])) { - throw MappingException::nameIsMandatoryForQueryMapping($this->name); - } - - if (isset($this->namedQueries[$queryMapping['name']])) { - throw MappingException::duplicateQueryMapping($this->name, $queryMapping['name']); - } - - if (!isset($queryMapping['query'])) { - throw MappingException::emptyQueryMapping($this->name, $queryMapping['name']); - } - - $name = $queryMapping['name']; - $query = $queryMapping['query']; - $dql = str_replace('__CLASS__', $this->name, $query); - - $this->namedQueries[$name] = [ - 'name' => $name, - 'query' => $query, - 'dql' => $dql, - ]; - } - - /** - * INTERNAL: - * Adds a named native query to this class. - * - * @param array $queryMapping - * - * @return void - * - * @throws MappingException - */ - public function addNamedNativeQuery(array $queryMapping) - { - if (!isset($queryMapping['name'])) { - throw MappingException::nameIsMandatoryForQueryMapping($this->name); - } - - if (isset($this->namedNativeQueries[$queryMapping['name']])) { - throw MappingException::duplicateQueryMapping($this->name, $queryMapping['name']); - } - - if (!isset($queryMapping['query'])) { - throw MappingException::emptyQueryMapping($this->name, $queryMapping['name']); - } - - if (!isset($queryMapping['resultClass']) && !isset($queryMapping['resultSetMapping'])) { - throw MappingException::missingQueryMapping($this->name, $queryMapping['name']); - } - - $queryMapping['isSelfClass'] = false; - - if (isset($queryMapping['resultClass'])) { - if ($queryMapping['resultClass'] === '__CLASS__') { - - $queryMapping['isSelfClass'] = true; - $queryMapping['resultClass'] = $this->name; - } - - $queryMapping['resultClass'] = $this->fullyQualifiedClassName($queryMapping['resultClass']); - $queryMapping['resultClass'] = ltrim($queryMapping['resultClass'], '\\'); - } - - $this->namedNativeQueries[$queryMapping['name']] = $queryMapping; - } - - /** - * INTERNAL: - * Adds a sql result set mapping to this class. - * - * @param array $resultMapping - * - * @return void - * - * @throws MappingException - */ - public function addSqlResultSetMapping(array $resultMapping) - { - if (!isset($resultMapping['name'])) { - throw MappingException::nameIsMandatoryForSqlResultSetMapping($this->name); - } - - if (isset($this->sqlResultSetMappings[$resultMapping['name']])) { - throw MappingException::duplicateResultSetMapping($this->name, $resultMapping['name']); - } - - if (isset($resultMapping['entities'])) { - foreach ($resultMapping['entities'] as $key => $entityResult) { - if (!isset($entityResult['entityClass'])) { - throw MappingException::missingResultSetMappingEntity($this->name, $resultMapping['name']); - } - - $entityResult['isSelfClass'] = false; - if ($entityResult['entityClass'] === '__CLASS__') { - - $entityResult['isSelfClass'] = true; - $entityResult['entityClass'] = $this->name; - - } - - $entityResult['entityClass'] = $this->fullyQualifiedClassName($entityResult['entityClass']); - - $resultMapping['entities'][$key]['entityClass'] = ltrim($entityResult['entityClass'], '\\'); - $resultMapping['entities'][$key]['isSelfClass'] = $entityResult['isSelfClass']; - - if (isset($entityResult['fields'])) { - foreach ($entityResult['fields'] as $k => $field) { - if (!isset($field['name'])) { - throw MappingException::missingResultSetMappingFieldName($this->name, $resultMapping['name']); - } - - if (!isset($field['column'])) { - $fieldName = $field['name']; - if (strpos($fieldName, '.')) { - list(, $fieldName) = explode('.', $fieldName); - } - - $resultMapping['entities'][$key]['fields'][$k]['column'] = $fieldName; - } - } - } - } - } - - $this->sqlResultSetMappings[$resultMapping['name']] = $resultMapping; - } - - /** - * Adds a one-to-one mapping. - * - * @param array $mapping The mapping. - * - * @return void - */ - public function mapOneToOne(array $mapping) - { - $mapping['type'] = self::ONE_TO_ONE; - - $mapping = $this->_validateAndCompleteOneToOneMapping($mapping); - - $this->_storeAssociationMapping($mapping); - } - - /** - * Adds a one-to-many mapping. - * - * @param array $mapping The mapping. - * - * @return void - */ - public function mapOneToMany(array $mapping) - { - $mapping['type'] = self::ONE_TO_MANY; - - $mapping = $this->_validateAndCompleteOneToManyMapping($mapping); - - $this->_storeAssociationMapping($mapping); - } - - /** - * Adds a many-to-one mapping. - * - * @param array $mapping The mapping. - * - * @return void - */ - public function mapManyToOne(array $mapping) - { - $mapping['type'] = self::MANY_TO_ONE; - - // A many-to-one mapping is essentially a one-one backreference - $mapping = $this->_validateAndCompleteOneToOneMapping($mapping); - - $this->_storeAssociationMapping($mapping); - } - - /** - * Adds a many-to-many mapping. - * - * @param array $mapping The mapping. - * - * @return void - */ - public function mapManyToMany(array $mapping) - { - $mapping['type'] = self::MANY_TO_MANY; - - $mapping = $this->_validateAndCompleteManyToManyMapping($mapping); - - $this->_storeAssociationMapping($mapping); - } - - /** - * Stores the association mapping. - * - * @param array $assocMapping - * - * @return void - * - * @throws MappingException - */ - protected function _storeAssociationMapping(array $assocMapping) - { - $sourceFieldName = $assocMapping['fieldName']; - - $this->assertFieldNotMapped($sourceFieldName); - - $this->associationMappings[$sourceFieldName] = $assocMapping; - } - - /** - * Registers a custom repository class for the entity class. - * - * @param string $repositoryClassName The class name of the custom mapper. - * - * @return void - */ - public function setCustomRepositoryClass($repositoryClassName) - { - $this->customRepositoryClassName = $this->fullyQualifiedClassName($repositoryClassName); - } - - /** - * Dispatches the lifecycle event of the given entity to the registered - * lifecycle callbacks and lifecycle listeners. - * - * @deprecated Deprecated since version 2.4 in favor of \Doctrine\ORM\Event\ListenersInvoker - * - * @param string $lifecycleEvent The lifecycle event. - * @param object $entity The Entity on which the event occurred. - * - * @return void - */ - public function invokeLifecycleCallbacks($lifecycleEvent, $entity) - { - foreach ($this->lifecycleCallbacks[$lifecycleEvent] as $callback) { - $entity->$callback(); - } - } - - /** - * Whether the class has any attached lifecycle listeners or callbacks for a lifecycle event. - * - * @param string $lifecycleEvent - * - * @return boolean - */ - public function hasLifecycleCallbacks($lifecycleEvent) - { - return isset($this->lifecycleCallbacks[$lifecycleEvent]); - } - - /** - * Gets the registered lifecycle callbacks for an event. - * - * @param string $event - * - * @return array - */ - public function getLifecycleCallbacks($event) - { - return isset($this->lifecycleCallbacks[$event]) ? $this->lifecycleCallbacks[$event] : []; - } - - /** - * Adds a lifecycle callback for entities of this class. - * - * @param string $callback - * @param string $event - * - * @return void - */ - public function addLifecycleCallback($callback, $event) - { - if (isset($this->lifecycleCallbacks[$event]) && in_array($callback, $this->lifecycleCallbacks[$event])) { - return; - } - - $this->lifecycleCallbacks[$event][] = $callback; - } - - /** - * Sets the lifecycle callbacks for entities of this class. - * Any previously registered callbacks are overwritten. - * - * @param array $callbacks - * - * @return void - */ - public function setLifecycleCallbacks(array $callbacks) - { - $this->lifecycleCallbacks = $callbacks; - } - - /** - * Adds a entity listener for entities of this class. - * - * @param string $eventName The entity lifecycle event. - * @param string $class The listener class. - * @param string $method The listener callback method. - * - * @throws \Doctrine\ORM\Mapping\MappingException - */ - public function addEntityListener($eventName, $class, $method) - { - $class = $this->fullyQualifiedClassName($class); - - $listener = [ - 'class' => $class, - 'method' => $method, - ]; - - if ( ! class_exists($class)) { - throw MappingException::entityListenerClassNotFound($class, $this->name); - } - - if ( ! method_exists($class, $method)) { - throw MappingException::entityListenerMethodNotFound($class, $method, $this->name); - } - - if (isset($this->entityListeners[$eventName]) && in_array($listener, $this->entityListeners[$eventName])) { - throw MappingException::duplicateEntityListener($class, $method, $this->name); - } - - $this->entityListeners[$eventName][] = $listener; - } - - /** - * Sets the discriminator column definition. - * - * @param array $columnDef - * - * @return void - * - * @throws MappingException - * - * @see getDiscriminatorColumn() - */ - public function setDiscriminatorColumn($columnDef) - { - if ($columnDef !== null) { - if ( ! isset($columnDef['name'])) { - throw MappingException::nameIsMandatoryForDiscriminatorColumns($this->name); - } - - if (isset($this->fieldNames[$columnDef['name']])) { - throw MappingException::duplicateColumnName($this->name, $columnDef['name']); - } - - if ( ! isset($columnDef['fieldName'])) { - $columnDef['fieldName'] = $columnDef['name']; - } - - if ( ! isset($columnDef['type'])) { - $columnDef['type'] = "string"; - } - - if (in_array($columnDef['type'], ["boolean", "array", "object", "datetime", "time", "date"])) { - throw MappingException::invalidDiscriminatorColumnType($this->name, $columnDef['type']); - } - - $this->discriminatorColumn = $columnDef; - } - } - - /** - * Sets the discriminator values used by this class. - * Used for JOINED and SINGLE_TABLE inheritance mapping strategies. - * - * @param array $map - * - * @return void - */ - public function setDiscriminatorMap(array $map) - { - foreach ($map as $value => $className) { - $this->addDiscriminatorMapClass($value, $className); - } - } - - /** - * Adds one entry of the discriminator map with a new class and corresponding name. - * - * @param string $name - * @param string $className - * - * @return void - * - * @throws MappingException - */ - public function addDiscriminatorMapClass($name, $className) - { - $className = $this->fullyQualifiedClassName($className); - $className = ltrim($className, '\\'); - - $this->discriminatorMap[$name] = $className; - - if ($this->name === $className) { - $this->discriminatorValue = $name; - - return; - } - - if ( ! (class_exists($className) || interface_exists($className))) { - throw MappingException::invalidClassInDiscriminatorMap($className, $this->name); - } - - if (is_subclass_of($className, $this->name) && ! in_array($className, $this->subClasses)) { - $this->subClasses[] = $className; - } - } - - /** - * Checks whether the class has a named query with the given query name. - * - * @param string $queryName - * - * @return boolean - */ - public function hasNamedQuery($queryName) - { - return isset($this->namedQueries[$queryName]); - } - - /** - * Checks whether the class has a named native query with the given query name. - * - * @param string $queryName - * - * @return boolean - */ - public function hasNamedNativeQuery($queryName) - { - return isset($this->namedNativeQueries[$queryName]); - } - - /** - * Checks whether the class has a named native query with the given query name. - * - * @param string $name - * - * @return boolean - */ - public function hasSqlResultSetMapping($name) - { - return isset($this->sqlResultSetMappings[$name]); - } - - /** - * {@inheritDoc} - */ - public function hasAssociation($fieldName) - { - return isset($this->associationMappings[$fieldName]); - } - - /** - * {@inheritDoc} - */ - public function isSingleValuedAssociation($fieldName) - { - return isset($this->associationMappings[$fieldName]) - && ($this->associationMappings[$fieldName]['type'] & self::TO_ONE); - } - - /** - * {@inheritDoc} - */ - public function isCollectionValuedAssociation($fieldName) - { - return isset($this->associationMappings[$fieldName]) - && ! ($this->associationMappings[$fieldName]['type'] & self::TO_ONE); - } - - /** - * Is this an association that only has a single join column? - * - * @param string $fieldName - * - * @return bool - */ - public function isAssociationWithSingleJoinColumn($fieldName) - { - return isset($this->associationMappings[$fieldName]) - && isset($this->associationMappings[$fieldName]['joinColumns'][0]) - && ! isset($this->associationMappings[$fieldName]['joinColumns'][1]); - } - - /** - * Returns the single association join column (if any). - * - * @param string $fieldName - * - * @return string - * - * @throws MappingException - */ - public function getSingleAssociationJoinColumnName($fieldName) - { - if ( ! $this->isAssociationWithSingleJoinColumn($fieldName)) { - throw MappingException::noSingleAssociationJoinColumnFound($this->name, $fieldName); - } - - return $this->associationMappings[$fieldName]['joinColumns'][0]['name']; - } - - /** - * Returns the single association referenced join column name (if any). - * - * @param string $fieldName - * - * @return string - * - * @throws MappingException - */ - public function getSingleAssociationReferencedJoinColumnName($fieldName) - { - if ( ! $this->isAssociationWithSingleJoinColumn($fieldName)) { - throw MappingException::noSingleAssociationJoinColumnFound($this->name, $fieldName); - } - - return $this->associationMappings[$fieldName]['joinColumns'][0]['referencedColumnName']; - } - - /** - * Used to retrieve a fieldname for either field or association from a given column. - * - * This method is used in foreign-key as primary-key contexts. - * - * @param string $columnName - * - * @return string - * - * @throws MappingException - */ - public function getFieldForColumn($columnName) - { - if (isset($this->fieldNames[$columnName])) { - return $this->fieldNames[$columnName]; - } - - foreach ($this->associationMappings as $assocName => $mapping) { - if ($this->isAssociationWithSingleJoinColumn($assocName) && - $this->associationMappings[$assocName]['joinColumns'][0]['name'] == $columnName) { - - return $assocName; - } - } - - throw MappingException::noFieldNameFoundForColumn($this->name, $columnName); - } - - /** - * Sets the ID generator used to generate IDs for instances of this class. - * - * @param \Doctrine\ORM\Id\AbstractIdGenerator $generator - * - * @return void - */ - public function setIdGenerator($generator) - { - $this->idGenerator = $generator; - } - - /** - * Sets definition. - * - * @param array $definition - * - * @return void - */ - public function setCustomGeneratorDefinition(array $definition) - { - $this->customGeneratorDefinition = $definition; - } - - /** - * Sets the definition of the sequence ID generator for this class. - * - * The definition must have the following structure: - * - * array( - * 'sequenceName' => 'name', - * 'allocationSize' => 20, - * 'initialValue' => 1 - * 'quoted' => 1 - * ) - * - * - * @param array $definition - * - * @return void - * - * @throws MappingException - */ - public function setSequenceGeneratorDefinition(array $definition) - { - if ( ! isset($definition['sequenceName'])) { - throw MappingException::missingSequenceName($this->name); - } - - if ($definition['sequenceName'][0] == '`') { - $definition['sequenceName'] = trim($definition['sequenceName'], '`'); - $definition['quoted'] = true; - } - - $this->sequenceGeneratorDefinition = $definition; - } - - /** - * Sets the version field mapping used for versioning. Sets the default - * value to use depending on the column type. - * - * @param array $mapping The version field mapping array. - * - * @return void - * - * @throws MappingException - */ - public function setVersionMapping(array &$mapping) - { - $this->isVersioned = true; - $this->versionField = $mapping['fieldName']; - - if ( ! isset($mapping['default'])) { - if (in_array($mapping['type'], ['integer', 'bigint', 'smallint'])) { - $mapping['default'] = 1; - } else if ($mapping['type'] == 'datetime') { - $mapping['default'] = 'CURRENT_TIMESTAMP'; - } else { - throw MappingException::unsupportedOptimisticLockingType($this->name, $mapping['fieldName'], $mapping['type']); - } - } - } - - /** - * Sets whether this class is to be versioned for optimistic locking. - * - * @param boolean $bool - * - * @return void - */ - public function setVersioned($bool) - { - $this->isVersioned = $bool; - } - - /** - * Sets the name of the field that is to be used for versioning if this class is - * versioned for optimistic locking. - * - * @param string $versionField - * - * @return void - */ - public function setVersionField($versionField) - { - $this->versionField = $versionField; - } - - /** - * Marks this class as read only, no change tracking is applied to it. - * - * @return void - */ - public function markReadOnly() - { - $this->isReadOnly = true; - } - - /** - * {@inheritDoc} - */ - public function getFieldNames() - { - return array_keys($this->fieldMappings); - } - - /** - * {@inheritDoc} - */ - public function getAssociationNames() - { - return array_keys($this->associationMappings); - } - - /** - * {@inheritDoc} - * - * @throws InvalidArgumentException - */ - public function getAssociationTargetClass($assocName) - { - if ( ! isset($this->associationMappings[$assocName])) { - throw new InvalidArgumentException("Association name expected, '" . $assocName ."' is not an association."); - } - - return $this->associationMappings[$assocName]['targetEntity']; - } - - /** - * {@inheritDoc} - */ - public function getName() - { - return $this->name; - } - - /** - * Gets the (possibly quoted) identifier column names for safe use in an SQL statement. - * - * @deprecated Deprecated since version 2.3 in favor of \Doctrine\ORM\Mapping\QuoteStrategy - * - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - * - * @return array - */ - public function getQuotedIdentifierColumnNames($platform) - { - $quotedColumnNames = []; - - foreach ($this->identifier as $idProperty) { - if (isset($this->fieldMappings[$idProperty])) { - $quotedColumnNames[] = isset($this->fieldMappings[$idProperty]['quoted']) - ? $platform->quoteIdentifier($this->fieldMappings[$idProperty]['columnName']) - : $this->fieldMappings[$idProperty]['columnName']; - - continue; - } - - // Association defined as Id field - $joinColumns = $this->associationMappings[$idProperty]['joinColumns']; - $assocQuotedColumnNames = array_map( - function ($joinColumn) use ($platform) { - return isset($joinColumn['quoted']) - ? $platform->quoteIdentifier($joinColumn['name']) - : $joinColumn['name']; - }, - $joinColumns - ); - - $quotedColumnNames = array_merge($quotedColumnNames, $assocQuotedColumnNames); - } - - return $quotedColumnNames; - } - - /** - * Gets the (possibly quoted) column name of a mapped field for safe use in an SQL statement. - * - * @deprecated Deprecated since version 2.3 in favor of \Doctrine\ORM\Mapping\QuoteStrategy - * - * @param string $field - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - * - * @return string - */ - public function getQuotedColumnName($field, $platform) - { - return isset($this->fieldMappings[$field]['quoted']) - ? $platform->quoteIdentifier($this->fieldMappings[$field]['columnName']) - : $this->fieldMappings[$field]['columnName']; - } - - /** - * Gets the (possibly quoted) primary table name of this class for safe use in an SQL statement. - * - * @deprecated Deprecated since version 2.3 in favor of \Doctrine\ORM\Mapping\QuoteStrategy - * - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - * - * @return string - */ - public function getQuotedTableName($platform) - { - return isset($this->table['quoted']) - ? $platform->quoteIdentifier($this->table['name']) - : $this->table['name']; - } - - /** - * Gets the (possibly quoted) name of the join table. - * - * @deprecated Deprecated since version 2.3 in favor of \Doctrine\ORM\Mapping\QuoteStrategy - * - * @param array $assoc - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - * - * @return string - */ - public function getQuotedJoinTableName(array $assoc, $platform) - { - return isset($assoc['joinTable']['quoted']) - ? $platform->quoteIdentifier($assoc['joinTable']['name']) - : $assoc['joinTable']['name']; - } - - /** - * {@inheritDoc} - */ - public function isAssociationInverseSide($fieldName) - { - return isset($this->associationMappings[$fieldName]) - && ! $this->associationMappings[$fieldName]['isOwningSide']; - } - - /** - * {@inheritDoc} - */ - public function getAssociationMappedByTargetField($fieldName) - { - return $this->associationMappings[$fieldName]['mappedBy']; - } - - /** - * @param string $targetClass - * - * @return array - */ - public function getAssociationsByTargetClass($targetClass) - { - $relations = []; - - foreach ($this->associationMappings as $mapping) { - if ($mapping['targetEntity'] == $targetClass) { - $relations[$mapping['fieldName']] = $mapping; - } - } - - return $relations; - } - - /** - * @param string|null $className - * - * @return string|null null if the input value is null - */ - public function fullyQualifiedClassName($className) - { - if (empty($className)) { - return $className; - } - - if ($className !== null && strpos($className, '\\') === false && $this->namespace) { - return $this->namespace . '\\' . $className; - } - - return $className; - } - - /** - * @param string $name - * - * @return mixed - */ - public function getMetadataValue($name) - { - - if (isset($this->$name)) { - return $this->$name; - } - - return null; - } - - /** - * Map Embedded Class - * - * @param array $mapping - * - * @throws MappingException - * @return void - */ - public function mapEmbedded(array $mapping) - { - $this->assertFieldNotMapped($mapping['fieldName']); - - $this->embeddedClasses[$mapping['fieldName']] = [ - 'class' => $this->fullyQualifiedClassName($mapping['class']), - 'columnPrefix' => $mapping['columnPrefix'], - 'declaredField' => isset($mapping['declaredField']) ? $mapping['declaredField'] : null, - 'originalField' => isset($mapping['originalField']) ? $mapping['originalField'] : null, - ]; - } - - /** - * Inline the embeddable class - * - * @param string $property - * @param ClassMetadataInfo $embeddable - */ - public function inlineEmbeddable($property, ClassMetadataInfo $embeddable) - { - foreach ($embeddable->fieldMappings as $fieldMapping) { - $fieldMapping['originalClass'] = isset($fieldMapping['originalClass']) - ? $fieldMapping['originalClass'] - : $embeddable->name; - $fieldMapping['declaredField'] = isset($fieldMapping['declaredField']) - ? $property . '.' . $fieldMapping['declaredField'] - : $property; - $fieldMapping['originalField'] = isset($fieldMapping['originalField']) - ? $fieldMapping['originalField'] - : $fieldMapping['fieldName']; - $fieldMapping['fieldName'] = $property . "." . $fieldMapping['fieldName']; - - if (! empty($this->embeddedClasses[$property]['columnPrefix'])) { - $fieldMapping['columnName'] = $this->embeddedClasses[$property]['columnPrefix'] . $fieldMapping['columnName']; - } elseif ($this->embeddedClasses[$property]['columnPrefix'] !== false) { - $fieldMapping['columnName'] = $this->namingStrategy - ->embeddedFieldToColumnName( - $property, - $fieldMapping['columnName'], - $this->reflClass->name, - $embeddable->reflClass->name - ); - } - - $this->mapField($fieldMapping); - } - } - - /** - * @param string $fieldName - * @throws MappingException - */ - private function assertFieldNotMapped($fieldName) - { - if (isset($this->fieldMappings[$fieldName]) || - isset($this->associationMappings[$fieldName]) || - isset($this->embeddedClasses[$fieldName])) { - - throw MappingException::duplicateFieldMapping($this->name, $fieldName); - } - } - - /** - * Gets the sequence name based on class metadata. - * - * @param AbstractPlatform $platform - * @return string - * - * @todo Sequence names should be computed in DBAL depending on the platform - */ - public function getSequenceName(AbstractPlatform $platform) - { - $sequencePrefix = $this->getSequencePrefix($platform); - $columnName = $this->getSingleIdentifierColumnName(); - $sequenceName = $sequencePrefix . '_' . $columnName . '_seq'; - - return $sequenceName; - } - - /** - * Gets the sequence name prefix based on class metadata. - * - * @param AbstractPlatform $platform - * @return string - * - * @todo Sequence names should be computed in DBAL depending on the platform - */ - public function getSequencePrefix(AbstractPlatform $platform) - { - $tableName = $this->getTableName(); - $sequencePrefix = $tableName; - - // Prepend the schema name to the table name if there is one - if ($schemaName = $this->getSchemaName()) { - $sequencePrefix = $schemaName . '.' . $tableName; - - if ( ! $platform->supportsSchemas() && $platform->canEmulateSchemas()) { - $sequencePrefix = $schemaName . '__' . $tableName; - } - } - - return $sequencePrefix; - } - - /** - * @param array $mapping - */ - private function assertMappingOrderBy(array $mapping) - { - if (isset($mapping['orderBy']) && !is_array($mapping['orderBy'])) { - throw new InvalidArgumentException("'orderBy' is expected to be an array, not " . gettype($mapping['orderBy'])); - } - } -} diff --git a/lib/Doctrine/ORM/Mapping/Column.php b/lib/Doctrine/ORM/Mapping/Column.php deleted file mode 100644 index 711590be672..00000000000 --- a/lib/Doctrine/ORM/Mapping/Column.php +++ /dev/null @@ -1,76 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target({"PROPERTY","ANNOTATION"}) - */ -final class Column implements Annotation -{ - /** - * @var string - */ - public $name; - - /** - * @var mixed - */ - public $type = 'string'; - - /** - * @var integer - */ - public $length; - - /** - * The precision for a decimal (exact numeric) column (Applies only for decimal column). - * - * @var integer - */ - public $precision = 0; - - /** - * The scale for a decimal (exact numeric) column (Applies only for decimal column). - * - * @var integer - */ - public $scale = 0; - - /** - * @var boolean - */ - public $unique = false; - - /** - * @var boolean - */ - public $nullable = false; - - /** - * @var array - */ - public $options = []; - - /** - * @var string - */ - public $columnDefinition; -} diff --git a/lib/Doctrine/ORM/Mapping/ColumnMetadata.php b/lib/Doctrine/ORM/Mapping/ColumnMetadata.php new file mode 100644 index 00000000000..dc883479c0f --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/ColumnMetadata.php @@ -0,0 +1,211 @@ + + */ +abstract class ColumnMetadata +{ + /** + * @var string|null + */ + protected $tableName; + + /** + * @var string|null + */ + protected $columnName; + + /** + * @var Type|null + */ + protected $type; + + /** + * @var string|null + */ + protected $columnDefinition; + + /** + * @var array + */ + protected $options = []; + + /** + * @var boolean + */ + protected $primaryKey = false; + + /** + * @var boolean + */ + protected $nullable = false; + + /** + * @var boolean + */ + protected $unique = false; + + /** + * ColumnMetadata constructor. + * + * @param string $columnName + * @param Type $type + * + * @todo Leverage this implementation instead of default, blank constructor + */ + /*public function __construct(string $columnName, Type $type) + { + $this->columnName = $columnName; + $this->type = $type; + }*/ + + /** + * @return string|null + */ + public function getTableName() : ?string + { + return $this->tableName; + } + + /** + * @todo Enable scalar typehint here + * + * @param string $tableName + */ + public function setTableName(/*string*/ $tableName) : void + { + $this->tableName = $tableName; + } + + /** + * @return string|null + */ + public function getColumnName() : ?string + { + return $this->columnName; + } + + /** + * @param string $columnName + */ + public function setColumnName(string $columnName) : void + { + $this->columnName = $columnName; + } + + /** + * @return Type|null + */ + public function getType() : ?Type + { + return $this->type; + } + + /** + * @param Type $type + */ + public function setType(Type $type) : void + { + $this->type = $type; + } + + /** + * @return string + */ + public function getTypeName() : string + { + return $this->type->getName(); + } + + /** + * @return string|null + */ + public function getColumnDefinition() : ?string + { + return $this->columnDefinition; + } + + /** + * @param string $columnDefinition + */ + public function setColumnDefinition(string $columnDefinition) : void + { + $this->columnDefinition = $columnDefinition; + } + + /** + * @return array + */ + public function getOptions() : array + { + return $this->options; + } + + /** + * @param array $options + */ + public function setOptions(array $options) : void + { + $this->options = $options; + } + + /** + * @param bool $isPrimaryKey + */ + public function setPrimaryKey(bool $isPrimaryKey) : void + { + $this->primaryKey = $isPrimaryKey; + } + + /** + * @return bool + */ + public function isPrimaryKey() : bool + { + return $this->primaryKey; + } + + /** + * @param bool $isNullable + */ + public function setNullable(bool $isNullable) : void + { + $this->nullable = $isNullable; + } + + /** + * @return bool + */ + public function isNullable() : bool + { + return $this->nullable; + } + + /** + * @param bool $isUnique + */ + public function setUnique(bool $isUnique) : void + { + $this->unique = $isUnique; + } + + /** + * @return bool + */ + public function isUnique() : bool + { + return $this->unique; + } +} diff --git a/lib/Doctrine/ORM/Mapping/ColumnResult.php b/lib/Doctrine/ORM/Mapping/ColumnResult.php deleted file mode 100644 index a164c85c0ee..00000000000 --- a/lib/Doctrine/ORM/Mapping/ColumnResult.php +++ /dev/null @@ -1,40 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * References name of a column in the SELECT clause of a SQL query. - * Scalar result types can be included in the query result by specifying this annotation in the metadata. - * - * @author Fabio B. Silva - * @since 2.3 - * - * @Annotation - * @Target("ANNOTATION") - */ -final class ColumnResult implements Annotation -{ - /** - * The name of a column in the SELECT clause of a SQL query. - * - * @var string - */ - public $name; -} diff --git a/lib/Doctrine/ORM/Mapping/ComponentMetadata.php b/lib/Doctrine/ORM/Mapping/ComponentMetadata.php new file mode 100644 index 00000000000..b85ec5fe458 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/ComponentMetadata.php @@ -0,0 +1,253 @@ +ComponentMetadata instance holds object-relational property mapping. + * + * @package Doctrine\ORM\Mapping + * @since 3.0 + * + * @author Guilherme Blanco + */ +abstract class ComponentMetadata +{ + /** + * @var string + */ + protected $className; + + /** + * @var ComponentMetadata|null + */ + protected $parent; + + /** + * The ReflectionClass instance of the component class. + * + * @var \ReflectionClass|null + */ + protected $reflectionClass; + + /** + * @var CacheMetadata|null + */ + protected $cache; + + /** + * @var array + */ + protected $declaredProperties = []; + + /** + * ComponentMetadata constructor. + * + * @param string $className + * @param ClassMetadataBuildingContext $metadataBuildingContext + */ + public function __construct(string $className, ClassMetadataBuildingContext $metadataBuildingContext) + { + $reflectionService = $metadataBuildingContext->getReflectionService(); + + $this->reflectionClass = $reflectionService->getClass($className); + $this->className = $this->reflectionClass ? $this->reflectionClass->getName() : $className; + } + + /** + * @return string + */ + public function getClassName() : string + { + return $this->className; + } + + /** + * @param ComponentMetadata $parent + */ + public function setParent(ComponentMetadata $parent) : void + { + $this->parent = $parent; + } + + /** + * @return ComponentMetadata|null + */ + public function getParent() : ?ComponentMetadata + { + return $this->parent; + } + + /** + * @return \ReflectionClass|null + */ + public function getReflectionClass() : ?\ReflectionClass + { + return $this->reflectionClass; + } + + /** + * @param CacheMetadata|null $cache + * + * @return void + */ + public function setCache(?CacheMetadata $cache = null) : void + { + $this->cache = $cache; + } + + /** + * @return CacheMetadata|null + */ + public function getCache(): ?CacheMetadata + { + return $this->cache; + } + + /** + * @return iterable + */ + public function getDeclaredPropertiesIterator() : iterable + { + foreach ($this->declaredProperties as $name => $property) { + yield $name => $property; + } + } + + /** + * @param Property $property + * + * @throws \ReflectionException + * @throws MappingException + */ + public function addDeclaredProperty(Property $property) : void + { + $className = $this->getClassName(); + $propertyName = $property->getName(); + + // @todo guilhermeblanco Switch to hasProperty once inherited properties are not being mapped on child classes + if ($this->hasDeclaredProperty($propertyName)) { + throw MappingException::duplicateProperty($className, $this->getProperty($propertyName)); + } + + $property->setDeclaringClass($this); + + if ($this->reflectionClass) { + $reflectionProperty = new \ReflectionProperty($className, $propertyName); + + if ($reflectionProperty->isPublic()) { + $reflectionProperty = new RuntimePublicReflectionProperty($className, $propertyName); + } + + $reflectionProperty->setAccessible(true); + + $property->setReflectionProperty($reflectionProperty); + } + + $this->declaredProperties[$propertyName] = $property; + } + + /** + * @param string $propertyName + * + * @return bool + */ + public function hasDeclaredProperty(string $propertyName) : bool + { + return isset($this->declaredProperties[$propertyName]); + } + + /** + * @return iterable + */ + public function getPropertiesIterator() : iterable + { + if ($this->parent) { + yield from $this->parent->getPropertiesIterator(); + } + + yield from $this->getDeclaredPropertiesIterator(); + } + + /** + * @param string $propertyName + * + * @return null|Property + */ + public function getProperty(string $propertyName) : ?Property + { + if (isset($this->declaredProperties[$propertyName])) { + return $this->declaredProperties[$propertyName]; + } + + if ($this->parent) { + return $this->parent->getProperty($propertyName); + } + + return null; + } + + /** + * @param string $propertyName + * + * @return bool + */ + public function hasProperty(string $propertyName) : bool + { + if (isset($this->declaredProperties[$propertyName])) { + return true; + } + + return $this->parent && $this->parent->hasProperty($propertyName); + } + + /** + * @return \ArrayIterator + */ + public function getColumnsIterator() : \ArrayIterator + { + $iterator = new \ArrayIterator(); + + // @todo guilhermeblanco Must be switched to getPropertiesIterator once class only has its declared properties + foreach ($this->getDeclaredPropertiesIterator() as $property) { + switch (true) { + case ($property instanceof FieldMetadata): + $iterator->offsetSet($property->getColumnName(), $property); + break; + + case ($property instanceof ToOneAssociationMetadata && $property->isOwningSide()): + foreach ($property->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $iterator->offsetSet($joinColumn->getColumnName(), $joinColumn); + } + + break; + } + } + + return $iterator; + } + + /** + * @param string|null $className + * + * @return string|null null if the input value is null + */ + public function fullyQualifiedClassName(?string $className) : ?string + { + if ($className === null || ! $this->reflectionClass) { + return $className; + } + + $namespaceName = $this->reflectionClass->getNamespaceName(); + $finalClassName = ($className !== null && strpos($className, '\\') === false && $namespaceName) + ? sprintf('%s\\%s', $namespaceName, $className) + : $className + ; + + return ltrim($finalClassName, '\\'); + } +} diff --git a/lib/Doctrine/ORM/Mapping/CustomIdGenerator.php b/lib/Doctrine/ORM/Mapping/CustomIdGenerator.php deleted file mode 100644 index 41e200e12a7..00000000000 --- a/lib/Doctrine/ORM/Mapping/CustomIdGenerator.php +++ /dev/null @@ -1,32 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("PROPERTY") - */ -final class CustomIdGenerator implements Annotation -{ - /** - * @var string - */ - public $class; -} diff --git a/lib/Doctrine/ORM/Mapping/DefaultEntityListenerResolver.php b/lib/Doctrine/ORM/Mapping/DefaultEntityListenerResolver.php index a8ee2dc783d..f1822528323 100644 --- a/lib/Doctrine/ORM/Mapping/DefaultEntityListenerResolver.php +++ b/lib/Doctrine/ORM/Mapping/DefaultEntityListenerResolver.php @@ -1,29 +1,16 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Mapping; /** * The default DefaultEntityListener * - * @since 2.4 + * @package Doctrine\ORM\Mapping + * @since 2.4 + * * @author Fabio B. Silva */ class DefaultEntityListenerResolver implements EntityListenerResolver diff --git a/lib/Doctrine/ORM/Mapping/DefaultQuoteStrategy.php b/lib/Doctrine/ORM/Mapping/DefaultQuoteStrategy.php deleted file mode 100644 index 6929edfe452..00000000000 --- a/lib/Doctrine/ORM/Mapping/DefaultQuoteStrategy.php +++ /dev/null @@ -1,163 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -use Doctrine\DBAL\Platforms\AbstractPlatform; - -/** - * A set of rules for determining the physical column, alias and table quotes - * - * @since 2.3 - * @author Fabio B. Silva - */ -class DefaultQuoteStrategy implements QuoteStrategy -{ - /** - * {@inheritdoc} - */ - public function getColumnName($fieldName, ClassMetadata $class, AbstractPlatform $platform) - { - return isset($class->fieldMappings[$fieldName]['quoted']) - ? $platform->quoteIdentifier($class->fieldMappings[$fieldName]['columnName']) - : $class->fieldMappings[$fieldName]['columnName']; - } - - /** - * {@inheritdoc} - * - * @todo Table names should be computed in DBAL depending on the platform - */ - public function getTableName(ClassMetadata $class, AbstractPlatform $platform) - { - $tableName = $class->table['name']; - - if ( ! empty($class->table['schema'])) { - $tableName = $class->table['schema'] . '.' . $class->table['name']; - - if ( ! $platform->supportsSchemas() && $platform->canEmulateSchemas()) { - $tableName = $class->table['schema'] . '__' . $class->table['name']; - } - } - - return isset($class->table['quoted']) - ? $platform->quoteIdentifier($tableName) - : $tableName; - } - - /** - * {@inheritdoc} - */ - public function getSequenceName(array $definition, ClassMetadata $class, AbstractPlatform $platform) - { - return isset($definition['quoted']) - ? $platform->quoteIdentifier($definition['sequenceName']) - : $definition['sequenceName']; - } - - /** - * {@inheritdoc} - */ - public function getJoinColumnName(array $joinColumn, ClassMetadata $class, AbstractPlatform $platform) - { - return isset($joinColumn['quoted']) - ? $platform->quoteIdentifier($joinColumn['name']) - : $joinColumn['name']; - } - - /** - * {@inheritdoc} - */ - public function getReferencedJoinColumnName(array $joinColumn, ClassMetadata $class, AbstractPlatform $platform) - { - return isset($joinColumn['quoted']) - ? $platform->quoteIdentifier($joinColumn['referencedColumnName']) - : $joinColumn['referencedColumnName']; - } - - /** - * {@inheritdoc} - */ - public function getJoinTableName(array $association, ClassMetadata $class, AbstractPlatform $platform) - { - $schema = ''; - - if (isset($association['joinTable']['schema'])) { - $schema = $association['joinTable']['schema'] . '.'; - } - - $tableName = $association['joinTable']['name']; - - if (isset($association['joinTable']['quoted'])) { - $tableName = $platform->quoteIdentifier($tableName); - } - - return $schema . $tableName; - } - - /** - * {@inheritdoc} - */ - public function getIdentifierColumnNames(ClassMetadata $class, AbstractPlatform $platform) - { - $quotedColumnNames = []; - - foreach ($class->identifier as $fieldName) { - if (isset($class->fieldMappings[$fieldName])) { - $quotedColumnNames[] = $this->getColumnName($fieldName, $class, $platform); - - continue; - } - - // Association defined as Id field - $joinColumns = $class->associationMappings[$fieldName]['joinColumns']; - $assocQuotedColumnNames = array_map( - function ($joinColumn) use ($platform) - { - return isset($joinColumn['quoted']) - ? $platform->quoteIdentifier($joinColumn['name']) - : $joinColumn['name']; - }, - $joinColumns - ); - - $quotedColumnNames = array_merge($quotedColumnNames, $assocQuotedColumnNames); - } - - return $quotedColumnNames; - } - - /** - * {@inheritdoc} - */ - public function getColumnAlias($columnName, $counter, AbstractPlatform $platform, ClassMetadata $class = null) - { - // 1 ) Concatenate column name and counter - // 2 ) Trim the column alias to the maximum identifier length of the platform. - // If the alias is to long, characters are cut off from the beginning. - // 3 ) Strip non alphanumeric characters - // 4 ) Prefix with "_" if the result its numeric - $columnName = $columnName . '_' . $counter; - $columnName = substr($columnName, -$platform->getMaxIdentifierLength()); - $columnName = preg_replace('/[^A-Za-z0-9_]/', '', $columnName); - $columnName = is_numeric($columnName) ? '_' . $columnName : $columnName; - - return $platform->getSQLResultCasing($columnName); - } -} diff --git a/lib/Doctrine/ORM/Mapping/DiscriminatorColumn.php b/lib/Doctrine/ORM/Mapping/DiscriminatorColumn.php deleted file mode 100644 index 97ca7e9b577..00000000000 --- a/lib/Doctrine/ORM/Mapping/DiscriminatorColumn.php +++ /dev/null @@ -1,54 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("CLASS") - */ -final class DiscriminatorColumn implements Annotation -{ - /** - * @var string - */ - public $name; - - /** - * @var string - */ - public $type; - - /** - * @var integer - */ - public $length; - - /** - * Field name used in non-object hydration (array/scalar). - * - * @var mixed - */ - public $fieldName; - - /** - * @var string - */ - public $columnDefinition; -} diff --git a/lib/Doctrine/ORM/Mapping/DiscriminatorColumnMetadata.php b/lib/Doctrine/ORM/Mapping/DiscriminatorColumnMetadata.php new file mode 100644 index 00000000000..7b652fde475 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/DiscriminatorColumnMetadata.php @@ -0,0 +1,18 @@ + + */ +final class DiscriminatorColumnMetadata extends LocalColumnMetadata +{ +} diff --git a/lib/Doctrine/ORM/Mapping/DiscriminatorMap.php b/lib/Doctrine/ORM/Mapping/DiscriminatorMap.php deleted file mode 100644 index 09d619465cd..00000000000 --- a/lib/Doctrine/ORM/Mapping/DiscriminatorMap.php +++ /dev/null @@ -1,32 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("CLASS") - */ -final class DiscriminatorMap implements Annotation -{ - /** - * @var array - */ - public $value; -} diff --git a/lib/Doctrine/ORM/Mapping/Driver/Annotation/AnnotationDriver.php b/lib/Doctrine/ORM/Mapping/Driver/Annotation/AnnotationDriver.php new file mode 100644 index 00000000000..d2aaee7c858 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Driver/Annotation/AnnotationDriver.php @@ -0,0 +1,1583 @@ + + * @author Guilherme Blanco + * @author Jonathan H. Wage + * @author Roman Borschel + */ +class AnnotationDriver implements Mapping\Driver\MappingDriver +{ + /** + * {@inheritdoc} + */ + protected $entityAnnotationClasses = [ + Annotation\Entity::class => 1, + Annotation\MappedSuperclass::class => 2, + Annotation\Embeddable::class => 3, + ]; + + /** + * The AnnotationReader. + * + * @var AnnotationReader + */ + protected $reader; + + /** + * The paths where to look for mapping files. + * + * @var array + */ + protected $paths = []; + + /** + * The paths excluded from path where to look for mapping files. + * + * @var array + */ + protected $excludePaths = []; + + /** + * The file extension of mapping documents. + * + * @var string + */ + protected $fileExtension = '.php'; + + /** + * Cache for AnnotationDriver#getAllClassNames(). + * + * @var array|null + */ + protected $classNames; + + /** + * Initializes a new AnnotationDriver that uses the given AnnotationReader for reading + * docblock annotations. + * + * @param AnnotationReader $reader The AnnotationReader to use, duck-typed. + * @param string|array|null $paths One or multiple paths where mapping classes can be found. + */ + public function __construct($reader, $paths = null) + { + $this->reader = $reader; + + if ($paths) { + $this->addPaths((array) $paths); + } + } + + /** + * Appends lookup paths to metadata driver. + * + * @param array $paths + * + * @return void + */ + public function addPaths(array $paths) + { + $this->paths = array_unique(array_merge($this->paths, $paths)); + } + + /** + * Retrieves the defined metadata lookup paths. + * + * @return array + */ + public function getPaths() + { + return $this->paths; + } + + /** + * Append exclude lookup paths to metadata driver. + * + * @param array $paths + */ + public function addExcludePaths(array $paths) + { + $this->excludePaths = array_unique(array_merge($this->excludePaths, $paths)); + } + + /** + * Retrieve the defined metadata lookup exclude paths. + * + * @return array + */ + public function getExcludePaths() + { + return $this->excludePaths; + } + + /** + * Retrieve the current annotation reader + * + * @return AnnotationReader + */ + public function getReader() + { + return $this->reader; + } + + /** + * Gets the file extension used to look for mapping files under. + * + * @return string + */ + public function getFileExtension() + { + return $this->fileExtension; + } + + /** + * Sets the file extension used to look for mapping files under. + * + * @param string $fileExtension The file extension to set. + * + * @return void + */ + public function setFileExtension($fileExtension) + { + $this->fileExtension = $fileExtension; + } + + /** + * Returns whether the class with the specified name is transient. Only non-transient + * classes, that is entities and mapped superclasses, should have their metadata loaded. + * + * A class is non-transient if it is annotated with an annotation + * from the {@see AnnotationDriver::entityAnnotationClasses}. + * + * @param string $className + * + * @return boolean + */ + public function isTransient($className) + { + $classAnnotations = $this->reader->getClassAnnotations(new \ReflectionClass($className)); + + foreach ($classAnnotations as $annot) { + if (isset($this->entityAnnotationClasses[get_class($annot)])) { + return false; + } + } + return true; + } + + /** + * {@inheritDoc} + */ + public function getAllClassNames() + { + if ($this->classNames !== null) { + return $this->classNames; + } + + if (!$this->paths) { + throw Mapping\MappingException::pathRequired(); + } + + $classes = []; + $includedFiles = []; + + foreach ($this->paths as $path) { + if ( ! is_dir($path)) { + throw Mapping\MappingException::fileMappingDriversRequireConfiguredDirectoryPath($path); + } + + $iterator = new \RegexIterator( + new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::LEAVES_ONLY + ), + '/^.+' . preg_quote($this->fileExtension) . '$/i', + \RecursiveRegexIterator::GET_MATCH + ); + + foreach ($iterator as $file) { + $sourceFile = $file[0]; + + if ( ! preg_match('(^phar:)i', $sourceFile)) { + $sourceFile = realpath($sourceFile); + } + + foreach ($this->excludePaths as $excludePath) { + $exclude = str_replace('\\', '/', realpath($excludePath)); + $current = str_replace('\\', '/', $sourceFile); + + if (strpos($current, $exclude) !== false) { + continue 2; + } + } + + require_once $sourceFile; + + $includedFiles[] = $sourceFile; + } + } + + $declared = get_declared_classes(); + + foreach ($declared as $className) { + $rc = new \ReflectionClass($className); + $sourceFile = $rc->getFileName(); + if (in_array($sourceFile, $includedFiles) && ! $this->isTransient($className)) { + $classes[] = $className; + } + } + + $this->classNames = $classes; + + return $classes; + } + + /** + * {@inheritdoc} + * + * @throws \UnexpectedValueException + * @throws \ReflectionException + * @throws Mapping\MappingException + */ + public function loadMetadataForClass( + string $className, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) : Mapping\ClassMetadata + { + $reflectionClass = $metadata->getReflectionClass(); + + if (! $reflectionClass) { + // this happens when running annotation driver in combination with + // static reflection services. This is not the nicest fix + $reflectionClass = new \ReflectionClass($metadata->getClassName()); + } + + $classAnnotations = $this->getClassAnnotations($reflectionClass); + $classMetadata = $this->convertClassAnnotationsToClassMetadata( + $reflectionClass, + $classAnnotations, + $metadata, + $metadataBuildingContext + ); + + // Evaluate @Cache annotation + if (isset($classAnnotations[Annotation\Cache::class])) { + $cacheAnnot = $classAnnotations[Annotation\Cache::class]; + $cache = $this->convertCacheAnnotationToCacheMetadata($cacheAnnot, $metadata); + + $classMetadata->setCache($cache); + } + + // Evaluate annotations on properties/fields + /* @var $reflProperty \ReflectionProperty */ + foreach ($reflectionClass->getProperties() as $reflectionProperty) { + if ($reflectionProperty->getDeclaringClass()->getName() !== $reflectionClass->getName()) { + continue; + } + + $propertyAnnotations = $this->getPropertyAnnotations($reflectionProperty); + $property = $this->convertPropertyAnnotationsToProperty( + $propertyAnnotations, + $reflectionProperty, + $classMetadata, + $metadataBuildingContext + ); + + if (! $property) { + continue; + } + + $metadata->addProperty($property); + } + + $this->attachPropertyOverrides($classAnnotations, $reflectionClass, $metadata, $metadataBuildingContext); + + return $classMetadata; + } + + /** + * @param \ReflectionClass $reflectionClass + * @param array $classAnnotations + * @param Mapping\ClassMetadata $metadata + * @param Mapping\ClassMetadataBuildingContext $metadataBuildingContext + * + * @return Mapping\ClassMetadata + * + * @throws \UnexpectedValueException + * @throws Mapping\MappingException + */ + private function convertClassAnnotationsToClassMetadata( + \ReflectionClass $reflectionClass, + array $classAnnotations, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) : Mapping\ClassMetadata + { + switch (true) { + case isset($classAnnotations[Annotation\Entity::class]): + $binder = new Binder\EntityClassMetadataBinder( + $reflectionClass, + $classAnnotations, + $metadata, + $metadataBuildingContext + ); + + break; + + case isset($classAnnotations[Annotation\MappedSuperclass::class]): + $binder = new Binder\MappedSuperClassMetadataBinder( + $reflectionClass, + $classAnnotations, + $metadata, + $metadataBuildingContext + ); + break; + + case isset($classAnnotations[Annotation\Embeddable::class]): + $binder = new Binder\EmbeddableClassMetadataBinder( + $reflectionClass, + $classAnnotations, + $metadata, + $metadataBuildingContext + ); + break; + + default: + throw Mapping\MappingException::classIsNotAValidEntityOrMappedSuperClass($reflectionClass->getName()); + } + + return $binder->bind(); + } + + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * @param Mapping\ClassMetadataBuildingContext $metadataBuildingContext + * + * @return Mapping\ClassMetadata + * + * @throws Mapping\MappingException + * @throws \UnexpectedValueException + */ + private function convertClassAnnotationsToEntityClassMetadata( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) + { + /** @var Annotation\Entity $entityAnnot */ + $entityAnnot = $classAnnotations[Annotation\Entity::class]; + + if ($entityAnnot->repositoryClass !== null) { + $metadata->setCustomRepositoryClassName( + $metadata->fullyQualifiedClassName($entityAnnot->repositoryClass) + ); + } + + if ($entityAnnot->readOnly) { + $metadata->asReadOnly(); + } + + $metadata->isMappedSuperclass = false; + $metadata->isEmbeddedClass = false; + + $this->attachTable($classAnnotations, $reflectionClass, $metadata, $metadataBuildingContext); + + // Evaluate @ChangeTrackingPolicy annotation + if (isset($classAnnotations[Annotation\ChangeTrackingPolicy::class])) { + $changeTrackingAnnot = $classAnnotations[Annotation\ChangeTrackingPolicy::class]; + + $metadata->setChangeTrackingPolicy( + constant(sprintf('%s::%s', Mapping\ChangeTrackingPolicy::class, $changeTrackingAnnot->value)) + ); + } + + // Evaluate @InheritanceType annotation + if (isset($classAnnotations[Annotation\InheritanceType::class])) { + $inheritanceTypeAnnot = $classAnnotations[Annotation\InheritanceType::class]; + + $metadata->setInheritanceType( + constant(sprintf('%s::%s', Mapping\InheritanceType::class, $inheritanceTypeAnnot->value)) + ); + + if ($metadata->inheritanceType !== Mapping\InheritanceType::NONE) { + $this->attachDiscriminatorColumn($classAnnotations, $reflectionClass, $metadata); + } + } + + $this->attachNamedQueries($classAnnotations, $reflectionClass, $metadata); + $this->attachNamedNativeQueries($classAnnotations, $reflectionClass, $metadata); + $this->attachLifecycleCallbacks($classAnnotations, $reflectionClass, $metadata); + $this->attachEntityListeners($classAnnotations, $reflectionClass, $metadata); + + return $metadata; + } + + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * @param Mapping\ClassMetadataBuildingContext $metadataBuildingContext + * + * @return Mapping\ClassMetadata + */ + private function convertClassAnnotationsToMappedSuperClassMetadata( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) : Mapping\ClassMetadata + { + /** @var Annotation\MappedSuperclass $mappedSuperclassAnnot */ + $mappedSuperclassAnnot = $classAnnotations[Annotation\MappedSuperclass::class]; + + if ($mappedSuperclassAnnot->repositoryClass !== null) { + $metadata->setCustomRepositoryClassName( + $metadata->fullyQualifiedClassName($mappedSuperclassAnnot->repositoryClass) + ); + } + + $metadata->isMappedSuperclass = true; + $metadata->isEmbeddedClass = false; + + $this->attachNamedQueries($classAnnotations, $reflectionClass, $metadata); + $this->attachNamedNativeQueries($classAnnotations, $reflectionClass, $metadata); + $this->attachLifecycleCallbacks($classAnnotations, $reflectionClass, $metadata); + $this->attachEntityListeners($classAnnotations, $reflectionClass, $metadata); + + return $metadata; + } + + /** + * @param array $propertyAnnotations + * @param \ReflectionProperty $reflectionProperty + * @param Mapping\ClassMetadata $metadata + * + * @todo guilhermeblanco Remove nullable typehint once embeddables are back + * + * @return Mapping\Property|null + * + * @throws Mapping\MappingException + */ + private function convertPropertyAnnotationsToProperty( + array $propertyAnnotations, + \ReflectionProperty $reflectionProperty, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) : ?Mapping\Property + { + switch (true) { + case isset($propertyAnnotations[Annotation\Column::class]): + return $this->convertReflectionPropertyToFieldMetadata( + $reflectionProperty, + $propertyAnnotations, + $metadata, + $metadataBuildingContext + ); + + case isset($propertyAnnotations[Annotation\OneToOne::class]): + return $this->convertReflectionPropertyToOneToOneAssociationMetadata( + $reflectionProperty, + $propertyAnnotations, + $metadata, + $metadataBuildingContext + ); + + case isset($propertyAnnotations[Annotation\ManyToOne::class]): + return $this->convertReflectionPropertyToManyToOneAssociationMetadata( + $reflectionProperty, + $propertyAnnotations, + $metadata, + $metadataBuildingContext + ); + + case isset($propertyAnnotations[Annotation\OneToMany::class]): + return $this->convertReflectionPropertyToOneToManyAssociationMetadata( + $reflectionProperty, + $propertyAnnotations, + $metadata, + $metadataBuildingContext + ); + + case isset($propertyAnnotations[Annotation\ManyToMany::class]): + return $this->convertReflectionPropertyToManyToManyAssociationMetadata( + $reflectionProperty, + $propertyAnnotations, + $metadata, + $metadataBuildingContext + ); + + case isset($propertyAnnotations[Annotation\Embedded::class]): + return null; + + default: + return new Mapping\TransientMetadata($reflectionProperty->getName()); + } + } + + /** + * @param \ReflectionProperty $reflProperty + * @param array $propertyAnnotations + * @param Mapping\ClassMetadata $metadata + * @param Mapping\ClassMetadataBuildingContext $metadataBuildingContext + * + * @return Mapping\FieldMetadata + * + * @throws Mapping\MappingException + */ + private function convertReflectionPropertyToFieldMetadata( + \ReflectionProperty $reflProperty, + array $propertyAnnotations, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) : Mapping\FieldMetadata + { + $className = $metadata->getClassName(); + $fieldName = $reflProperty->getName(); + $isVersioned = isset($propertyAnnotations[Annotation\Version::class]); + $columnAnnot = $propertyAnnotations[Annotation\Column::class]; + + if ($columnAnnot->type == null) { + throw Mapping\MappingException::propertyTypeIsRequired($className, $fieldName); + } + + $fieldMetadata = $this->convertColumnAnnotationToFieldMetadata($columnAnnot, $fieldName, $isVersioned); + + // Check for Id + if (isset($propertyAnnotations[Annotation\Id::class])) { + $fieldMetadata->setPrimaryKey(true); + } + + // Check for GeneratedValue strategy + if (isset($propertyAnnotations[Annotation\GeneratedValue::class])) { + $generatedValueAnnot = $propertyAnnotations[Annotation\GeneratedValue::class]; + $strategy = strtoupper($generatedValueAnnot->strategy); + $idGeneratorType = constant(sprintf('%s::%s', Mapping\GeneratorType::class, $strategy)); + + if ($idGeneratorType !== Mapping\GeneratorType::NONE) { + $idGeneratorDefinition = []; + + // Check for CustomGenerator/SequenceGenerator/TableGenerator definition + switch (true) { + case isset($propertyAnnotations[Annotation\SequenceGenerator::class]): + $seqGeneratorAnnot = $propertyAnnotations[Annotation\SequenceGenerator::class]; + + $idGeneratorDefinition = [ + 'sequenceName' => $seqGeneratorAnnot->sequenceName, + 'allocationSize' => $seqGeneratorAnnot->allocationSize, + ]; + + break; + + case isset($propertyAnnotations[Annotation\CustomIdGenerator::class]): + $customGeneratorAnnot = $propertyAnnotations[Annotation\CustomIdGenerator::class]; + + $idGeneratorDefinition = [ + 'class' => $customGeneratorAnnot->class, + 'arguments' => $customGeneratorAnnot->arguments, + ]; + + break; + + /* @todo If it is not supported, why does this exist? */ + case isset($propertyAnnotations['Doctrine\ORM\Mapping\TableGenerator']): + throw Mapping\MappingException::tableIdGeneratorNotImplemented($className); + } + + $fieldMetadata->setValueGenerator(new Mapping\ValueGeneratorMetadata($idGeneratorType, $idGeneratorDefinition)); + } + } + + return $fieldMetadata; + } + + /** + * @param \ReflectionProperty $reflectionProperty + * @param array $propertyAnnotations + * @param Mapping\ClassMetadata $metadata + * @param Mapping\ClassMetadataBuildingContext $metadataBuildingContext + * + * @return Mapping\OneToOneAssociationMetadata + */ + private function convertReflectionPropertyToOneToOneAssociationMetadata( + \ReflectionProperty $reflectionProperty, + array $propertyAnnotations, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) + { + $className = $metadata->getClassName(); + $fieldName = $reflectionProperty->getName(); + $oneToOneAnnot = $propertyAnnotations[Annotation\OneToOne::class]; + $assocMetadata = new Mapping\OneToOneAssociationMetadata($fieldName); + $targetEntity = $metadata->fullyQualifiedClassName($oneToOneAnnot->targetEntity); + + $assocMetadata->setTargetEntity($targetEntity); + $assocMetadata->setCascade($this->getCascade($className, $fieldName, $oneToOneAnnot->cascade)); + $assocMetadata->setOrphanRemoval($oneToOneAnnot->orphanRemoval); + $assocMetadata->setFetchMode($this->getFetchMode($className, $oneToOneAnnot->fetch)); + + if (! empty($oneToOneAnnot->mappedBy)) { + $assocMetadata->setMappedBy($oneToOneAnnot->mappedBy); + } + + if (! empty($oneToOneAnnot->inversedBy)) { + $assocMetadata->setInversedBy($oneToOneAnnot->inversedBy); + } + + // Check for Id + if (isset($propertyAnnotations[Annotation\Id::class])) { + $assocMetadata->setPrimaryKey(true); + } + + $this->attachAssociationPropertyCache($propertyAnnotations, $reflectionProperty, $assocMetadata, $metadata); + + // Check for JoinColumn/JoinColumns annotations + switch (true) { + case isset($propertyAnnotations[Annotation\JoinColumn::class]): + $joinColumnAnnot = $propertyAnnotations[Annotation\JoinColumn::class]; + + $assocMetadata->addJoinColumn( + $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot) + ); + + break; + + case isset($propertyAnnotations[Annotation\JoinColumns::class]): + $joinColumnsAnnot = $propertyAnnotations[Annotation\JoinColumns::class]; + + foreach ($joinColumnsAnnot->value as $joinColumnAnnot) { + $assocMetadata->addJoinColumn( + $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot) + ); + } + + break; + } + + return $assocMetadata; + } + + /** + * @param \ReflectionProperty $reflectionProperty + * @param array $propertyAnnotations + * @param Mapping\ClassMetadata $metadata + * @param Mapping\ClassMetadataBuildingContext $metadataBuildingContext + * + * @return Mapping\ManyToOneAssociationMetadata + */ + private function convertReflectionPropertyToManyToOneAssociationMetadata( + \ReflectionProperty $reflectionProperty, + array $propertyAnnotations, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) + { + $className = $metadata->getClassName(); + $fieldName = $reflectionProperty->getName(); + $manyToOneAnnot = $propertyAnnotations[Annotation\ManyToOne::class]; + $assocMetadata = new Mapping\ManyToOneAssociationMetadata($fieldName); + $targetEntity = $metadata->fullyQualifiedClassName($manyToOneAnnot->targetEntity); + + $assocMetadata->setTargetEntity($targetEntity); + $assocMetadata->setCascade($this->getCascade($className, $fieldName, $manyToOneAnnot->cascade)); + $assocMetadata->setFetchMode($this->getFetchMode($className, $manyToOneAnnot->fetch)); + + if (! empty($manyToOneAnnot->inversedBy)) { + $assocMetadata->setInversedBy($manyToOneAnnot->inversedBy); + } + + // Check for Id + if (isset($propertyAnnotations[Annotation\Id::class])) { + $assocMetadata->setPrimaryKey(true); + } + + $this->attachAssociationPropertyCache($propertyAnnotations, $reflectionProperty, $assocMetadata, $metadata); + + // Check for JoinColumn/JoinColumns annotations + switch (true) { + case isset($propertyAnnotations[Annotation\JoinColumn::class]): + $joinColumnAnnot = $propertyAnnotations[Annotation\JoinColumn::class]; + + $assocMetadata->addJoinColumn( + $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot) + ); + + break; + + case isset($propertyAnnotations[Annotation\JoinColumns::class]): + $joinColumnsAnnot = $propertyAnnotations[Annotation\JoinColumns::class]; + + foreach ($joinColumnsAnnot->value as $joinColumnAnnot) { + $assocMetadata->addJoinColumn( + $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot) + ); + } + + break; + } + + return $assocMetadata; + } + + /** + * @param \ReflectionProperty $reflectionProperty + * @param array $propertyAnnotations + * @param Mapping\ClassMetadata $metadata + * @param Mapping\ClassMetadataBuildingContext $metadataBuildingContext + * + * @return Mapping\OneToManyAssociationMetadata + * + * @throws Mapping\MappingException + */ + private function convertReflectionPropertyToOneToManyAssociationMetadata( + \ReflectionProperty $reflectionProperty, + array $propertyAnnotations, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) : Mapping\OneToManyAssociationMetadata + { + $className = $metadata->getClassName(); + $fieldName = $reflectionProperty->getName(); + $oneToManyAnnot = $propertyAnnotations[Annotation\OneToMany::class]; + $assocMetadata = new Mapping\OneToManyAssociationMetadata($fieldName); + $targetEntity = $metadata->fullyQualifiedClassName($oneToManyAnnot->targetEntity); + + $assocMetadata->setTargetEntity($targetEntity); + $assocMetadata->setCascade($this->getCascade($className, $fieldName, $oneToManyAnnot->cascade)); + $assocMetadata->setOrphanRemoval($oneToManyAnnot->orphanRemoval); + $assocMetadata->setFetchMode($this->getFetchMode($className, $oneToManyAnnot->fetch)); + + if (! empty($oneToManyAnnot->mappedBy)) { + $assocMetadata->setMappedBy($oneToManyAnnot->mappedBy); + } + + if (! empty($oneToManyAnnot->indexBy)) { + $assocMetadata->setIndexedBy($oneToManyAnnot->indexBy); + } + + // Check for OrderBy + if (isset($propertyAnnotations[Annotation\OrderBy::class])) { + $orderByAnnot = $propertyAnnotations[Annotation\OrderBy::class]; + + $assocMetadata->setOrderBy($orderByAnnot->value); + } + + // Check for Id + if (isset($propertyAnnotations[Annotation\Id::class])) { + throw Mapping\MappingException::illegalToManyIdentifierAssociation($className, $fieldName); + } + + $this->attachAssociationPropertyCache($propertyAnnotations, $reflectionProperty, $assocMetadata, $metadata); + + return $assocMetadata; + } + + /** + * @param \ReflectionProperty $reflectionProperty + * @param array $propertyAnnotations + * @param Mapping\ClassMetadata $metadata + * @param Mapping\ClassMetadataBuildingContext $metadataBuildingContext + * + * @return Mapping\ManyToManyAssociationMetadata + * + * @throws Mapping\MappingException + */ + private function convertReflectionPropertyToManyToManyAssociationMetadata( + \ReflectionProperty $reflectionProperty, + array $propertyAnnotations, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) : Mapping\ManyToManyAssociationMetadata + { + $className = $metadata->getClassName(); + $fieldName = $reflectionProperty->getName(); + $manyToManyAnnot = $propertyAnnotations[Annotation\ManyToMany::class]; + $assocMetadata = new Mapping\ManyToManyAssociationMetadata($fieldName); + $targetEntity = $metadata->fullyQualifiedClassName($manyToManyAnnot->targetEntity); + + $assocMetadata->setTargetEntity($targetEntity); + $assocMetadata->setCascade($this->getCascade($className, $fieldName, $manyToManyAnnot->cascade)); + $assocMetadata->setOrphanRemoval($manyToManyAnnot->orphanRemoval); + $assocMetadata->setFetchMode($this->getFetchMode($className, $manyToManyAnnot->fetch)); + + if (! empty($manyToManyAnnot->mappedBy)) { + $assocMetadata->setMappedBy($manyToManyAnnot->mappedBy); + } + + if (! empty($manyToManyAnnot->inversedBy)) { + $assocMetadata->setInversedBy($manyToManyAnnot->inversedBy); + } + + if (! empty($manyToManyAnnot->indexBy)) { + $assocMetadata->setIndexedBy($manyToManyAnnot->indexBy); + } + + // Check for JoinTable + if (isset($propertyAnnotations[Annotation\JoinTable::class])) { + $joinTableAnnot = $propertyAnnotations[Annotation\JoinTable::class]; + $joinTableMetadata = $this->convertJoinTableAnnotationToJoinTableMetadata($joinTableAnnot); + + $assocMetadata->setJoinTable($joinTableMetadata); + } + + // Check for OrderBy + if (isset($propertyAnnotations[Annotation\OrderBy::class])) { + $orderByAnnot = $propertyAnnotations[Annotation\OrderBy::class]; + + $assocMetadata->setOrderBy($orderByAnnot->value); + } + + // Check for Id + if (isset($propertyAnnotations[Annotation\Id::class])) { + throw Mapping\MappingException::illegalToManyIdentifierAssociation($className, $fieldName); + } + + $this->attachAssociationPropertyCache($propertyAnnotations, $reflectionProperty, $assocMetadata, $metadata); + + return $assocMetadata; + } + + /** + * Parse the given Column as FieldMetadata + * + * @param Annotation\Column $columnAnnot + * @param string $fieldName + * @param bool $isVersioned + * + * @return Mapping\FieldMetadata + */ + private function convertColumnAnnotationToFieldMetadata( + Annotation\Column $columnAnnot, + string $fieldName, + bool $isVersioned + ) : Mapping\FieldMetadata + { + $fieldMetadata = $isVersioned + ? new Mapping\VersionFieldMetadata($fieldName) + : new Mapping\FieldMetadata($fieldName) + ; + + $fieldMetadata->setType(Type::getType($columnAnnot->type)); + + if (! empty($columnAnnot->name)) { + $fieldMetadata->setColumnName($columnAnnot->name); + } + + if (! empty($columnAnnot->columnDefinition)) { + $fieldMetadata->setColumnDefinition($columnAnnot->columnDefinition); + } + + if (! empty($columnAnnot->length)) { + $fieldMetadata->setLength($columnAnnot->length); + } + + if ($columnAnnot->options) { + $fieldMetadata->setOptions($columnAnnot->options); + } + + $fieldMetadata->setScale($columnAnnot->scale); + $fieldMetadata->setPrecision($columnAnnot->precision); + $fieldMetadata->setNullable($columnAnnot->nullable); + $fieldMetadata->setUnique($columnAnnot->unique); + + return $fieldMetadata; + } + + /** + * Parse the given Table as TableMetadata + * + * @param Annotation\Table $tableAnnot + * @param Mapping\TableMetadata $table + * + * @return void + */ + private function convertTableAnnotationToTableMetadata( + Annotation\Table $tableAnnot, + Mapping\TableMetadata $table + ) : void + { + if (! empty($tableAnnot->name)) { + $table->setName($tableAnnot->name); + } + + if (! empty($tableAnnot->schema)) { + $table->setSchema($tableAnnot->schema); + } + + foreach ($tableAnnot->options as $optionName => $optionValue) { + $table->addOption($optionName, $optionValue); + } + + foreach ($tableAnnot->indexes as $indexAnnot) { + $table->addIndex([ + 'name' => $indexAnnot->name, + 'columns' => $indexAnnot->columns, + 'unique' => $indexAnnot->unique, + 'options' => $indexAnnot->options, + 'flags' => $indexAnnot->flags, + ]); + } + + foreach ($tableAnnot->uniqueConstraints as $uniqueConstraintAnnot) { + $table->addUniqueConstraint([ + 'name' => $uniqueConstraintAnnot->name, + 'columns' => $uniqueConstraintAnnot->columns, + 'options' => $uniqueConstraintAnnot->options, + 'flags' => $uniqueConstraintAnnot->flags, + ]); + } + + return $table; + } + + /** + * Parse the given JoinTable as JoinTableMetadata + * + * @param Annotation\JoinTable $joinTableAnnot + * + * @return Mapping\JoinTableMetadata + */ + private function convertJoinTableAnnotationToJoinTableMetadata( + Annotation\JoinTable $joinTableAnnot + ) : Mapping\JoinTableMetadata + { + $joinTable = new Mapping\JoinTableMetadata(); + + if (! empty($joinTableAnnot->name)) { + $joinTable->setName($joinTableAnnot->name); + } + + if (! empty($joinTableAnnot->schema)) { + $joinTable->setSchema($joinTableAnnot->schema); + } + + foreach ($joinTableAnnot->joinColumns as $joinColumnAnnot) { + $joinColumn = $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot); + + $joinTable->addJoinColumn($joinColumn); + } + + foreach ($joinTableAnnot->inverseJoinColumns as $joinColumnAnnot) { + $joinColumn = $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot); + + $joinTable->addInverseJoinColumn($joinColumn); + } + + return $joinTable; + } + + /** + * Parse the given JoinColumn as JoinColumnMetadata + * + * @param Annotation\JoinColumn $joinColumnAnnot + * + * @return Mapping\JoinColumnMetadata + */ + private function convertJoinColumnAnnotationToJoinColumnMetadata( + Annotation\JoinColumn $joinColumnAnnot + ) : Mapping\JoinColumnMetadata + { + $joinColumn = new Mapping\JoinColumnMetadata(); + + // @todo Remove conditionals for name and referencedColumnName once naming strategy is brought into drivers + if (! empty($joinColumnAnnot->name)) { + $joinColumn->setColumnName($joinColumnAnnot->name); + } + + if (! empty($joinColumnAnnot->referencedColumnName)) { + $joinColumn->setReferencedColumnName($joinColumnAnnot->referencedColumnName); + } + + $joinColumn->setNullable($joinColumnAnnot->nullable); + $joinColumn->setUnique($joinColumnAnnot->unique); + + if (! empty($joinColumnAnnot->fieldName)) { + $joinColumn->setAliasedName($joinColumnAnnot->fieldName); + } + + if (! empty($joinColumnAnnot->columnDefinition)) { + $joinColumn->setColumnDefinition($joinColumnAnnot->columnDefinition); + } + + if ($joinColumnAnnot->onDelete) { + $joinColumn->setOnDelete(strtoupper($joinColumnAnnot->onDelete)); + } + + return $joinColumn; + } + + /** + * Parse the given Cache as CacheMetadata + * + * @param Annotation\Cache $cacheAnnot + * @param Mapping\ClassMetadata $metadata + * @param null|string $fieldName + * + * @return Mapping\CacheMetadata + */ + private function convertCacheAnnotationToCacheMetadata( + Annotation\Cache $cacheAnnot, + Mapping\ClassMetadata $metadata, + $fieldName = null + ) : Mapping\CacheMetadata + { + $baseRegion = strtolower(str_replace('\\', '_', $metadata->getRootClassName())); + $defaultRegion = $baseRegion . ($fieldName ? '__' . $fieldName : ''); + + $usage = constant(sprintf('%s::%s', Mapping\CacheUsage::class, $cacheAnnot->usage)); + $region = $cacheAnnot->region ?: $defaultRegion; + + return new Mapping\CacheMetadata($usage, $region); + } + + /** + * @param Annotation\SqlResultSetMapping $resultSetMapping + * + * @return array + */ + private function convertSqlResultSetMapping(Annotation\SqlResultSetMapping $resultSetMapping) + { + $entities = []; + + foreach ($resultSetMapping->entities as $entityResultAnnot) { + $entityResult = [ + 'fields' => [], + 'entityClass' => $entityResultAnnot->entityClass, + 'discriminatorColumn' => $entityResultAnnot->discriminatorColumn, + ]; + + foreach ($entityResultAnnot->fields as $fieldResultAnnot) { + $entityResult['fields'][] = [ + 'name' => $fieldResultAnnot->name, + 'column' => $fieldResultAnnot->column + ]; + } + + $entities[] = $entityResult; + } + + $columns = []; + + foreach ($resultSetMapping->columns as $columnResultAnnot) { + $columns[] = [ + 'name' => $columnResultAnnot->name, + ]; + } + + return [ + 'name' => $resultSetMapping->name, + 'entities' => $entities, + 'columns' => $columns + ]; + } + + private function attachTable( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) : void + { + $parent = $metadata->getParent(); + + if ($parent->inheritanceType === InheritanceType::SINGLE_TABLE) { + $metadata->setTable($parent->table); + + return; + } + + $namingStrategy = $metadataBuildingContext->getNamingStrategy(); + $table = new Mapping\TableMetadata(); + + $table->setName($namingStrategy->classToTableName($metadata->getClassName())); + + // Evaluate @Table annotation + if (isset($classAnnotations[Annotation\Table::class])) { + $tableAnnot = $classAnnotations[Annotation\Table::class]; + + $this->convertTableAnnotationToTableMetadata($table, $tableAnnot); + } + + $metadata->setTable($table); + } + + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * + * @return void + * + * @throws Mapping\MappingException + */ + private function attachDiscriminatorColumn( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) : void + { + $discriminatorColumn = new Mapping\DiscriminatorColumnMetadata(); + + $discriminatorColumn->setTableName($metadata->getTableName()); + $discriminatorColumn->setColumnName('dtype'); + $discriminatorColumn->setType(Type::getType('string')); + $discriminatorColumn->setLength(255); + + // Evaluate DiscriminatorColumn annotation + if (isset($classAnnotations[Annotation\DiscriminatorColumn::class])) { + /** @var Annotation\DiscriminatorColumn $discriminatorColumnAnnotation */ + $discriminatorColumnAnnotation = $classAnnotations[Annotation\DiscriminatorColumn::class]; + $typeName = ! empty($discriminatorColumnAnnotation->type) + ? $discriminatorColumnAnnotation->type + : 'string'; + + $discriminatorColumn->setType(Type::getType($typeName)); + $discriminatorColumn->setColumnName($discriminatorColumnAnnotation->name); + + if (! empty($discriminatorColumnAnnotation->columnDefinition)) { + $discriminatorColumn->setColumnDefinition($discriminatorColumnAnnotation->columnDefinition); + } + + if (! empty($discriminatorColumnAnnotation->length)) { + $discriminatorColumn->setLength($discriminatorColumnAnnotation->length); + } + } + + $metadata->setDiscriminatorColumn($discriminatorColumn); + + // Evaluate DiscriminatorMap annotation + if (isset($classAnnotations[Annotation\DiscriminatorMap::class])) { + $discriminatorMapAnnotation = $classAnnotations[Annotation\DiscriminatorMap::class]; + $discriminatorMap = array_map( + function ($className) use ($metadata) { + return $metadata->fullyQualifiedClassName($className); + }, + $discriminatorMapAnnotation->value + ); + + $metadata->setDiscriminatorMap($discriminatorMap); + } + } + + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * + * @return void + * + * @throws \UnexpectedValueException + * @throws Mapping\MappingException + */ + private function attachNamedQueries( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata + ) : void + { + // Evaluate @NamedQueries annotation + if (isset($classAnnotations[Annotation\NamedQueries::class])) { + $namedQueriesAnnot = $classAnnotations[Annotation\NamedQueries::class]; + + if (! is_array($namedQueriesAnnot->value)) { + throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); + } + + foreach ($namedQueriesAnnot->value as $namedQuery) { + if (! ($namedQuery instanceof Annotation\NamedQuery)) { + throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); + } + + $metadata->addNamedQuery($namedQuery->name, $namedQuery->query); + } + } + } + + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * + * @return void + */ + private function attachNamedNativeQueries( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata + ) : void + { + // Evaluate @NamedNativeQueries annotation + if (isset($classAnnotations[Annotation\NamedNativeQueries::class])) { + $namedNativeQueriesAnnot = $classAnnotations[Annotation\NamedNativeQueries::class]; + + foreach ($namedNativeQueriesAnnot->value as $namedNativeQuery) { + $metadata->addNamedNativeQuery( + $namedNativeQuery->name, + $namedNativeQuery->query, + [ + 'resultClass' => $namedNativeQuery->resultClass, + 'resultSetMapping' => $namedNativeQuery->resultSetMapping, + ] + ); + } + } + + // Evaluate @SqlResultSetMappings annotation + if (isset($classAnnotations[Annotation\SqlResultSetMappings::class])) { + $sqlResultSetMappingsAnnot = $classAnnotations[Annotation\SqlResultSetMappings::class]; + + foreach ($sqlResultSetMappingsAnnot->value as $resultSetMapping) { + $sqlResultSetMapping = $this->convertSqlResultSetMapping($resultSetMapping); + + $metadata->addSqlResultSetMapping($sqlResultSetMapping); + } + } + } + + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * + * @return void + */ + private function attachLifecycleCallbacks( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata + ) : void + { + // Evaluate @HasLifecycleCallbacks annotation + if (isset($classAnnotations[Annotation\HasLifecycleCallbacks::class])) { + /* @var $method \ReflectionMethod */ + foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { + foreach ($this->getMethodCallbacks($method) as $callback) { + $metadata->addLifecycleCallback($method->getName(), $callback); + } + } + } + } + + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * + * @return void + * + * @throws \ReflectionException + * @throws Mapping\MappingException + */ + private function attachEntityListeners( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata + ) : void + { + // Evaluate @EntityListeners annotation + if (isset($classAnnotations[Annotation\EntityListeners::class])) { + /** @var Annotation\EntityListeners $entityListenersAnnot */ + $entityListenersAnnot = $classAnnotations[Annotation\EntityListeners::class]; + + foreach ($entityListenersAnnot->value as $item) { + $listenerClassName = $metadata->fullyQualifiedClassName($item); + + if (! class_exists($listenerClassName)) { + throw Mapping\MappingException::entityListenerClassNotFound( + $listenerClassName, + $metadata->getClassName() + ); + } + + $listenerClass = new \ReflectionClass($listenerClassName); + + /* @var $method \ReflectionMethod */ + foreach ($listenerClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { + foreach ($this->getMethodCallbacks($method) as $callback) { + $metadata->addEntityListener($callback, $listenerClassName, $method->getName()); + } + } + } + } + } + + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * + * @return void + * + * @throws Mapping\MappingException + */ + private function attachPropertyOverrides( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) : void + { + // Evaluate AssociationOverrides annotation + if (isset($classAnnotations[Annotation\AssociationOverrides::class])) { + $associationOverridesAnnot = $classAnnotations[Annotation\AssociationOverrides::class]; + + foreach ($associationOverridesAnnot->value as $associationOverride) { + $fieldName = $associationOverride->name; + $property = $metadata->getProperty($fieldName); + + if (! $property) { + throw Mapping\MappingException::invalidOverrideFieldName($metadata->getClassName(), $fieldName); + } + + $existingClass = get_class($property); + $override = new $existingClass($fieldName); + + // Check for JoinColumn/JoinColumns annotations + if ($associationOverride->joinColumns) { + $joinColumns = []; + + foreach ($associationOverride->joinColumns as $joinColumnAnnot) { + $joinColumns[] = $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot); + } + + $override->setJoinColumns($joinColumns); + } + + // Check for JoinTable annotations + if ($associationOverride->joinTable) { + $joinTableAnnot = $associationOverride->joinTable; + $joinTableMetadata = $this->convertJoinTableAnnotationToJoinTableMetadata($joinTableAnnot); + + $override->setJoinTable($joinTableMetadata); + } + + // Check for inversedBy + if ($associationOverride->inversedBy) { + $override->setInversedBy($associationOverride->inversedBy); + } + + // Check for fetch + if ($associationOverride->fetch) { + $override->setFetchMode( + constant(Mapping\FetchMode::class . '::' . $associationOverride->fetch) + ); + } + + $metadata->setPropertyOverride($override); + } + } + + // Evaluate AttributeOverrides annotation + if (isset($classAnnotations[Annotation\AttributeOverrides::class])) { + $attributeOverridesAnnot = $classAnnotations[Annotation\AttributeOverrides::class]; + + foreach ($attributeOverridesAnnot->value as $attributeOverrideAnnot) { + $fieldMetadata = $this->convertColumnAnnotationToFieldMetadata( + $attributeOverrideAnnot->column, + $attributeOverrideAnnot->name, + false + ); + + $metadata->setPropertyOverride($fieldMetadata); + } + } + } + + private function attachAssociationPropertyCache( + array $propertyAnnotations, + \ReflectionProperty $reflectionProperty, + Mapping\AssociationMetadata $assocMetadata, + Mapping\ClassMetadata $metadata + ) : void + { + // Check for Cache + if (isset($propertyAnnotations[Annotation\Cache::class])) { + $cacheAnnot = $propertyAnnotations[Annotation\Cache::class]; + $cacheMetadata = $this->convertCacheAnnotationToCacheMetadata( + $cacheAnnot, + $metadata, + $reflectionProperty->getName() + ); + + $assocMetadata->setCache($cacheMetadata); + } + } + + /** + * Attempts to resolve the cascade modes. + * + * @param string $className The class name. + * @param string $fieldName The field name. + * @param array $originalCascades The original unprocessed field cascades. + * + * @return array The processed field cascades. + * + * @throws Mapping\MappingException If a cascade option is not valid. + */ + private function getCascade(string $className, string $fieldName, array $originalCascades) : array + { + $cascadeTypes = ['remove', 'persist', 'refresh']; + $cascades = array_map('strtolower', $originalCascades); + + if (in_array('all', $cascades)) { + $cascades = $cascadeTypes; + } + + if (count($cascades) !== count(array_intersect($cascades, $cascadeTypes))) { + $diffCascades = array_diff($cascades, array_intersect($cascades, $cascadeTypes)); + + throw Mapping\MappingException::invalidCascadeOption($diffCascades, $className, $fieldName); + } + + return $cascades; + } + + /** + * Attempts to resolve the fetch mode. + * + * @param string $className The class name. + * @param string $fetchMode The fetch mode. + * + * @return string The fetch mode as defined in ClassMetadata. + * + * @throws Mapping\MappingException If the fetch mode is not valid. + */ + private function getFetchMode($className, $fetchMode) : string + { + $fetchModeConstant = sprintf('%s::%s', Mapping\FetchMode::class, $fetchMode); + + if (! defined($fetchModeConstant)) { + throw Mapping\MappingException::invalidFetchMode($className, $fetchMode); + } + + return constant($fetchModeConstant); + } + + /** + * Parses the given method. + * + * @param \ReflectionMethod $method + * + * @return array + */ + private function getMethodCallbacks(\ReflectionMethod $method) : array + { + $annotations = $this->getMethodAnnotations($method); + $events = [ + Events::prePersist => Annotation\PrePersist::class, + Events::postPersist => Annotation\PostPersist::class, + Events::preUpdate => Annotation\PreUpdate::class, + Events::postUpdate => Annotation\PostUpdate::class, + Events::preRemove => Annotation\PreRemove::class, + Events::postRemove => Annotation\PostRemove::class, + Events::postLoad => Annotation\PostLoad::class, + Events::preFlush => Annotation\PreFlush::class, + ]; + + // Check for callbacks + $callbacks = []; + + foreach ($events as $eventName => $annotationClassName) { + if (isset($annotations[$annotationClassName]) || $method->getName() === $eventName) { + $callbacks[] = $eventName; + } + } + + return $callbacks; + } + + /** + * @param \ReflectionClass $reflectionClass + * + * @return array + */ + private function getClassAnnotations(\ReflectionClass $reflectionClass) : array + { + $classAnnotations = $this->reader->getClassAnnotations($reflectionClass); + + foreach ($classAnnotations as $key => $annot) { + if (! is_numeric($key)) { + continue; + } + + $classAnnotations[get_class($annot)] = $annot; + } + + return $classAnnotations; + } + + /** + * @param \ReflectionProperty $reflectionProperty + * + * @return array + */ + private function getPropertyAnnotations(\ReflectionProperty $reflectionProperty) : array + { + $propertyAnnotations = $this->reader->getPropertyAnnotations($reflectionProperty); + + foreach ($propertyAnnotations as $key => $annot) { + if (! is_numeric($key)) { + continue; + } + + $propertyAnnotations[get_class($annot)] = $annot; + } + + return $propertyAnnotations; + } + + /** + * @param \ReflectionMethod $reflectionMethod + * + * @return array + */ + private function getMethodAnnotations(\ReflectionMethod $reflectionMethod) : array + { + $methodAnnotations = $this->reader->getMethodAnnotations($reflectionMethod); + + foreach ($methodAnnotations as $key => $annot) { + if (! is_numeric($key)) { + continue; + } + + $methodAnnotations[get_class($annot)] = $annot; + } + + return $methodAnnotations; + } + + /** + * Factory method for the Annotation Driver. + * + * @param array|string $paths + * @param AnnotationReader|null $reader + * + * @return AnnotationDriver + */ + static public function create($paths = [], AnnotationReader $reader = null) + { + if ($reader == null) { + $reader = new AnnotationReader(); + } + + return new self($reader, $paths); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Driver/Annotation/Binder/EmbeddableClassMetadataBinder.php b/lib/Doctrine/ORM/Mapping/Driver/Annotation/Binder/EmbeddableClassMetadataBinder.php new file mode 100644 index 00000000000..be9ef1633a7 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Driver/Annotation/Binder/EmbeddableClassMetadataBinder.php @@ -0,0 +1,91 @@ + + */ +class EmbeddableClassMetadataBinder +{ + /** + * @var Mapping\ClassMetadataBuildingContext + */ + private $metadataBuildingContext; + + /** + * @var \ReflectionClass + */ + private $reflectionClass; + + /** + * [dreaming] One day we would eliminate this and only do: $reflectionClass->getAnnotations() + * + * @var array + */ + private $classAnnotations; + + /** + * @todo guilhermeblanco This should disappear once we instantiation happens in the Driver + * + * @var Mapping\ClassMetadata + */ + private $classMetadata; + + /** + * ComponentMetadataBinder constructor. + * + * @param \ReflectionClass $reflectionClass + * @param array $classAnnotations + * @param Mapping\ClassMetadata $classMetadata + * @param Mapping\ClassMetadataBuildingContext $metadataBuildingContext + */ + public function __construct( + \ReflectionClass $reflectionClass, + array $classAnnotations, + Mapping\ClassMetadata $classMetadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) + { + $this->reflectionClass = $reflectionClass; + $this->classAnnotations = $classAnnotations; + $this->classMetadata = $classMetadata; + $this->metadataBuildingContext = $metadataBuildingContext; + } + + /** + * @return Mapping\ClassMetadata + */ + public function bind() : Mapping\ClassMetadata + { + $classMetadata = $this->classMetadata; + + $this->processEmbeddableAnnotation($classMetadata, $this->classMetadata[Annotation\Embeddable::class]); + + return $classMetadata; + } + + /** + * @param Mapping\ClassMetadata $classMetadata + * @param Annotation\Embeddable $embeddableAnnotation + * + * @return void + */ + private function processEmbeddableAnnotation( + Mapping\ClassMetadata $classMetadata, + Annotation\Embeddable $embeddableAnnotation + ) : void + { + $classMetadata->isMappedSuperclass = false; + $classMetadata->isEmbeddedClass = true; + } +} diff --git a/lib/Doctrine/ORM/Mapping/Driver/Annotation/Binder/EntityClassMetadataBinder.php b/lib/Doctrine/ORM/Mapping/Driver/Annotation/Binder/EntityClassMetadataBinder.php new file mode 100644 index 00000000000..2226f32e171 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Driver/Annotation/Binder/EntityClassMetadataBinder.php @@ -0,0 +1,101 @@ + + */ +class EntityClassMetadataBinder +{ + /** + * @var Mapping\ClassMetadataBuildingContext + */ + private $metadataBuildingContext; + + /** + * @var \ReflectionClass + */ + private $reflectionClass; + + /** + * [dreaming] One day we would eliminate this and only do: $reflectionClass->getAnnotations() + * + * @var array + */ + private $classAnnotations; + + /** + * @todo guilhermeblanco This should disappear once we instantiation happens in the Driver + * + * @var Mapping\ClassMetadata + */ + private $classMetadata; + + /** + * ComponentMetadataBinder constructor. + * + * @param \ReflectionClass $reflectionClass + * @param array $classAnnotations + * @param Mapping\ClassMetadata $classMetadata + * @param Mapping\ClassMetadataBuildingContext $metadataBuildingContext + */ + public function __construct( + \ReflectionClass $reflectionClass, + array $classAnnotations, + Mapping\ClassMetadata $classMetadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) + { + $this->reflectionClass = $reflectionClass; + $this->classAnnotations = $classAnnotations; + $this->classMetadata = $classMetadata; + $this->metadataBuildingContext = $metadataBuildingContext; + } + + /** + * @return Mapping\ClassMetadata + */ + public function bind() : Mapping\ClassMetadata + { + $classMetadata = $this->classMetadata; + + $this->processEntityAnnotation($classMetadata, $this->classAnnotations[Annotation\Entity::class]); + + return $classMetadata; + } + + /** + * @param Mapping\ClassMetadata $classMetadata + * @param Annotation\Entity $entityAnnotation + * + * @return void + */ + private function processEntityAnnotation( + Mapping\ClassMetadata $classMetadata, + Annotation\Entity $entityAnnotation + ) : void + { + if ($entityAnnotation->repositoryClass !== null) { + $repositoryClassName = $classMetadata->fullyQualifiedClassName($entityAnnotation->repositoryClass); + + $classMetadata->setCustomRepositoryClassName($repositoryClassName); + } + + if ($entityAnnotation->readOnly) { + $classMetadata->asReadOnly(); + } + + $classMetadata->isMappedSuperclass = false; + $classMetadata->isEmbeddedClass = false; + } +} diff --git a/lib/Doctrine/ORM/Mapping/Driver/Annotation/Binder/MappedSuperClassMetadataBinder.php b/lib/Doctrine/ORM/Mapping/Driver/Annotation/Binder/MappedSuperClassMetadataBinder.php new file mode 100644 index 00000000000..8ab895b7484 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Driver/Annotation/Binder/MappedSuperClassMetadataBinder.php @@ -0,0 +1,99 @@ + + */ +class MappedSuperClassMetadataBinder +{ + /** + * @var Mapping\ClassMetadataBuildingContext + */ + private $metadataBuildingContext; + + /** + * @var \ReflectionClass + */ + private $reflectionClass; + + /** + * [dreaming] One day we would eliminate this and only do: $reflectionClass->getAnnotations() + * + * @var array + */ + private $classAnnotations; + + /** + * @todo guilhermeblanco This should disappear once we instantiation happens in the Driver + * + * @var Mapping\ClassMetadata + */ + private $classMetadata; + + /** + * ComponentMetadataBinder constructor. + * + * @param \ReflectionClass $reflectionClass + * @param array $classAnnotations + * @param Mapping\ClassMetadata $classMetadata + * @param Mapping\ClassMetadataBuildingContext $metadataBuildingContext + */ + public function __construct( + \ReflectionClass $reflectionClass, + array $classAnnotations, + Mapping\ClassMetadata $classMetadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) + { + $this->reflectionClass = $reflectionClass; + $this->classAnnotations = $classAnnotations; + $this->classMetadata = $classMetadata; + $this->metadataBuildingContext = $metadataBuildingContext; + } + + /** + * @return Mapping\ClassMetadata + * + * @throws Mapping\MappingException + */ + public function bind() : Mapping\ClassMetadata + { + $classMetadata = $this->classMetadata; + + $this->processMappedSuperclassAnnotation($classMetadata, $this->classAnnotations[Annotation\MappedSuperclass::class]); + + return $classMetadata; + } + + /** + * @param Mapping\ClassMetadata $classMetadata + * @param Annotation\MappedSuperclass $mappedSuperclassAnnotation + * + * @return void + */ + private function processMappedSuperclassAnnotation( + Mapping\ClassMetadata $classMetadata, + Annotation\MappedSuperclass $mappedSuperclassAnnotation + ) : void + { + if ($mappedSuperclassAnnotation->repositoryClass !== null) { + $classMetadata->setCustomRepositoryClassName( + $classMetadata->fullyQualifiedClassName($mappedSuperclassAnnotation->repositoryClass) + ); + } + + $classMetadata->isMappedSuperclass = true; + $classMetadata->isEmbeddedClass = false; + } +} diff --git a/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php b/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php index d59fd3bb773..2c47e4de614 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php +++ b/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php @@ -1,31 +1,14 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Mapping\Driver; use Doctrine\Common\Annotations\AnnotationReader; -use Doctrine\Common\Persistence\Mapping\ClassMetadata; -use Doctrine\Common\Persistence\Mapping\Driver\AnnotationDriver as AbstractAnnotationDriver; +use Doctrine\DBAL\Types\Type; +use Doctrine\ORM\Annotation; use Doctrine\ORM\Events; use Doctrine\ORM\Mapping; -use Doctrine\ORM\Mapping\Builder\EntityListenerBuilder; -use Doctrine\ORM\Mapping\MappingException; /** * The AnnotationDriver reads the mapping metadata from docblock annotations. @@ -36,501 +19,1423 @@ * @author Jonathan H. Wage * @author Roman Borschel */ -class AnnotationDriver extends AbstractAnnotationDriver +class AnnotationDriver implements MappingDriver { /** - * {@inheritDoc} + * {@inheritDoc} + */ + protected $entityAnnotationClasses = [ + Annotation\Entity::class => 1, + Annotation\MappedSuperclass::class => 2, + ]; + + /** + * The AnnotationReader. + * + * @var AnnotationReader + */ + protected $reader; + + /** + * The paths where to look for mapping files. + * + * @var array + */ + protected $paths = []; + + /** + * The paths excluded from path where to look for mapping files. + * + * @var array + */ + protected $excludePaths = []; + + /** + * The file extension of mapping documents. + * + * @var string + */ + protected $fileExtension = '.php'; + + /** + * Cache for AnnotationDriver#getAllClassNames(). + * + * @var array|null + */ + protected $classNames; + + /** + * Initializes a new AnnotationDriver that uses the given AnnotationReader for reading + * docblock annotations. + * + * @param AnnotationReader $reader The AnnotationReader to use, duck-typed. + * @param string|array|null $paths One or multiple paths where mapping classes can be found. + */ + public function __construct($reader, $paths = null) + { + $this->reader = $reader; + if ($paths) { + $this->addPaths((array) $paths); + } + } + + /** + * Appends lookup paths to metadata driver. + * + * @param array $paths + * + * @return void + */ + public function addPaths(array $paths) + { + $this->paths = array_unique(array_merge($this->paths, $paths)); + } + + /** + * Retrieves the defined metadata lookup paths. + * + * @return array + */ + public function getPaths() + { + return $this->paths; + } + + /** + * Append exclude lookup paths to metadata driver. + * + * @param array $paths + */ + public function addExcludePaths(array $paths) + { + $this->excludePaths = array_unique(array_merge($this->excludePaths, $paths)); + } + + /** + * Retrieve the defined metadata lookup exclude paths. + * + * @return array + */ + public function getExcludePaths() + { + return $this->excludePaths; + } + + /** + * Retrieve the current annotation reader + * + * @return AnnotationReader + */ + public function getReader() + { + return $this->reader; + } + + /** + * Gets the file extension used to look for mapping files under. + * + * @return string + */ + public function getFileExtension() + { + return $this->fileExtension; + } + + /** + * Sets the file extension used to look for mapping files under. + * + * @param string $fileExtension The file extension to set. + * + * @return void + */ + public function setFileExtension($fileExtension) + { + $this->fileExtension = $fileExtension; + } + + /** + * Returns whether the class with the specified name is transient. Only non-transient + * classes, that is entities and mapped superclasses, should have their metadata loaded. + * + * A class is non-transient if it is annotated with an annotation + * from the {@see AnnotationDriver::entityAnnotationClasses}. + * + * @param string $className + * + * @return boolean + */ + public function isTransient($className) + { + $classAnnotations = $this->reader->getClassAnnotations(new \ReflectionClass($className)); + + foreach ($classAnnotations as $annot) { + if (isset($this->entityAnnotationClasses[get_class($annot)])) { + return false; + } + } + return true; + } + + /** + * {@inheritDoc} + */ + public function getAllClassNames() + { + if ($this->classNames !== null) { + return $this->classNames; + } + + if (!$this->paths) { + throw Mapping\MappingException::pathRequired(); + } + + $classes = []; + $includedFiles = []; + + foreach ($this->paths as $path) { + if ( ! is_dir($path)) { + throw Mapping\MappingException::fileMappingDriversRequireConfiguredDirectoryPath($path); + } + + $iterator = new \RegexIterator( + new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::LEAVES_ONLY + ), + '/^.+' . preg_quote($this->fileExtension) . '$/i', + \RecursiveRegexIterator::GET_MATCH + ); + + foreach ($iterator as $file) { + $sourceFile = $file[0]; + + if ( ! preg_match('(^phar:)i', $sourceFile)) { + $sourceFile = realpath($sourceFile); + } + + foreach ($this->excludePaths as $excludePath) { + $exclude = str_replace('\\', '/', realpath($excludePath)); + $current = str_replace('\\', '/', $sourceFile); + + if (strpos($current, $exclude) !== false) { + continue 2; + } + } + + require_once $sourceFile; + + $includedFiles[] = $sourceFile; + } + } + + $declared = get_declared_classes(); + + foreach ($declared as $className) { + $rc = new \ReflectionClass($className); + $sourceFile = $rc->getFileName(); + if (in_array($sourceFile, $includedFiles) && ! $this->isTransient($className)) { + $classes[] = $className; + } + } + + $this->classNames = $classes; + + return $classes; + } + + /** + * {@inheritDoc} + */ + public function loadMetadataForClass( + string $className, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) : Mapping\ClassMetadata + { + $reflectionClass = $metadata->getReflectionClass(); + + if (! $reflectionClass) { + // this happens when running annotation driver in combination with + // static reflection services. This is not the nicest fix + $reflectionClass = new \ReflectionClass($metadata->getClassName()); + } + + $classAnnotations = $this->getClassAnnotations($reflectionClass); + $classMetadata = $this->convertClassAnnotationsToClassMetadata( + $classAnnotations, + $reflectionClass, + $metadata, + $metadataBuildingContext + ); + + // Evaluate @Cache annotation + if (isset($classAnnotations[Annotation\Cache::class])) { + $cacheAnnot = $classAnnotations[Annotation\Cache::class]; + $cache = $this->convertCacheAnnotationToCacheMetadata($cacheAnnot, $metadata); + + $classMetadata->setCache($cache); + } + + // Evaluate annotations on properties/fields + /* @var $reflProperty \ReflectionProperty */ + foreach ($reflectionClass->getProperties() as $reflectionProperty) { + if ($reflectionProperty->getDeclaringClass()->getName() !== $reflectionClass->getName()) { + continue; + } + + $propertyAnnotations = $this->getPropertyAnnotations($reflectionProperty); + $property = $this->convertPropertyAnnotationsToProperty( + $propertyAnnotations, + $reflectionProperty, + $classMetadata + ); + + if (! $property) { + continue; + } + + $metadata->addProperty($property); + } + + $this->attachPropertyOverrides($classAnnotations, $reflectionClass, $metadata); + + return $classMetadata; + } + + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * @param Mapping\ClassMetadataBuildingContext $metadataBuildingContext + * + * @return Mapping\ClassMetadata + * + * @throws Mapping\MappingException + */ + private function convertClassAnnotationsToClassMetadata( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) : Mapping\ClassMetadata + { + switch (true) { + case isset($classAnnotations[Annotation\Entity::class]): + return $this->convertClassAnnotationsToEntityClassMetadata( + $classAnnotations, + $reflectionClass, + $metadata, + $metadataBuildingContext + ); + + break; + + case isset($classAnnotations[Annotation\MappedSuperclass::class]): + return $this->convertClassAnnotationsToMappedSuperClassMetadata( + $classAnnotations, + $reflectionClass, + $metadata + ); + + case isset($classAnnotations[Annotation\Embeddable::class]): + return $this->convertClassAnnotationsToEmbeddableClassMetadata( + $classAnnotations, + $reflectionClass, + $metadata + ); + + default: + throw Mapping\MappingException::classIsNotAValidEntityOrMappedSuperClass($reflectionClass->getName()); + } + } + + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * @param Mapping\ClassMetadataBuildingContext $metadataBuildingContext + * + * @return Mapping\ClassMetadata + * + * @throws Mapping\MappingException + * @throws \UnexpectedValueException + */ + private function convertClassAnnotationsToEntityClassMetadata( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) + { + /** @var Annotation\Entity $entityAnnot */ + $entityAnnot = $classAnnotations[Annotation\Entity::class]; + + if ($entityAnnot->repositoryClass !== null) { + $metadata->setCustomRepositoryClassName( + $metadata->fullyQualifiedClassName($entityAnnot->repositoryClass) + ); + } + + if ($entityAnnot->readOnly) { + $metadata->asReadOnly(); + } + + $metadata->isMappedSuperclass = false; + $metadata->isEmbeddedClass = false; + + $this->attachTable($classAnnotations, $reflectionClass, $metadata, $metadataBuildingContext); + + // Evaluate @ChangeTrackingPolicy annotation + if (isset($classAnnotations[Annotation\ChangeTrackingPolicy::class])) { + $changeTrackingAnnot = $classAnnotations[Annotation\ChangeTrackingPolicy::class]; + + $metadata->setChangeTrackingPolicy( + constant(sprintf('%s::%s', Mapping\ChangeTrackingPolicy::class, $changeTrackingAnnot->value)) + ); + } + + // Evaluate @InheritanceType annotation + if (isset($classAnnotations[Annotation\InheritanceType::class])) { + $inheritanceTypeAnnot = $classAnnotations[Annotation\InheritanceType::class]; + + $metadata->setInheritanceType( + constant(sprintf('%s::%s', Mapping\InheritanceType::class, $inheritanceTypeAnnot->value)) + ); + + if ($metadata->inheritanceType !== Mapping\InheritanceType::NONE) { + $this->attachDiscriminatorColumn($classAnnotations, $reflectionClass, $metadata); + } + } + + $this->attachNamedQueries($classAnnotations, $reflectionClass, $metadata); + $this->attachNamedNativeQueries($classAnnotations, $reflectionClass, $metadata); + $this->attachLifecycleCallbacks($classAnnotations, $reflectionClass, $metadata); + $this->attachEntityListeners($classAnnotations, $reflectionClass, $metadata); + + return $metadata; + } + + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * + * @return Mapping\ClassMetadata + */ + private function convertClassAnnotationsToMappedSuperClassMetadata( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata + ) : Mapping\ClassMetadata + { + /** @var Annotation\MappedSuperclass $mappedSuperclassAnnot */ + $mappedSuperclassAnnot = $classAnnotations[Annotation\MappedSuperclass::class]; + + if ($mappedSuperclassAnnot->repositoryClass !== null) { + $metadata->setCustomRepositoryClassName( + $metadata->fullyQualifiedClassName($mappedSuperclassAnnot->repositoryClass) + ); + } + + $metadata->isMappedSuperclass = true; + $metadata->isEmbeddedClass = false; + + $this->attachNamedQueries($classAnnotations, $reflectionClass, $metadata); + $this->attachNamedNativeQueries($classAnnotations, $reflectionClass, $metadata); + $this->attachLifecycleCallbacks($classAnnotations, $reflectionClass, $metadata); + $this->attachEntityListeners($classAnnotations, $reflectionClass, $metadata); + + return $metadata; + } + + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * + * @return Mapping\ClassMetadata + */ + private function convertClassAnnotationsToEmbeddableClassMetadata( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata + ) : Mapping\ClassMetadata + { + $metadata->isMappedSuperclass = false; + $metadata->isEmbeddedClass = true; + + return $metadata; + } + + /** + * @param array $propertyAnnotations + * @param \ReflectionProperty $reflectionProperty + * @param Mapping\ClassMetadata $metadata + * + * @todo guilhermeblanco Remove nullable typehint once embeddables are back + * + * @return Mapping\Property|null + */ + private function convertPropertyAnnotationsToProperty( + array $propertyAnnotations, + \ReflectionProperty $reflectionProperty, + Mapping\ClassMetadata $metadata + ) : ?Mapping\Property + { + switch (true) { + case isset($propertyAnnotations[Annotation\Column::class]): + return $this->convertReflectionPropertyToFieldMetadata( + $reflectionProperty, + $propertyAnnotations, + $metadata + ); + + case isset($propertyAnnotations[Annotation\OneToOne::class]): + return $this->convertReflectionPropertyToOneToOneAssociationMetadata( + $reflectionProperty, + $propertyAnnotations, + $metadata + ); + + case isset($propertyAnnotations[Annotation\ManyToOne::class]): + return $this->convertReflectionPropertyToManyToOneAssociationMetadata( + $reflectionProperty, + $propertyAnnotations, + $metadata + ); + + case isset($propertyAnnotations[Annotation\OneToMany::class]): + return $this->convertReflectionPropertyToOneToManyAssociationMetadata( + $reflectionProperty, + $propertyAnnotations, + $metadata + ); + + case isset($propertyAnnotations[Annotation\ManyToMany::class]): + return $this->convertReflectionPropertyToManyToManyAssociationMetadata( + $reflectionProperty, + $propertyAnnotations, + $metadata + ); + + case isset($propertyAnnotations[Annotation\Embedded::class]): + return null; + + default: + return new Mapping\TransientMetadata($reflectionProperty->getName()); + } + } + + /** + * @param \ReflectionProperty $reflProperty + * @param array $propertyAnnotations + * @param Mapping\ClassMetadata $metadata + * + * @return Mapping\FieldMetadata + * + * @throws Mapping\MappingException + */ + private function convertReflectionPropertyToFieldMetadata( + \ReflectionProperty $reflProperty, + array $propertyAnnotations, + Mapping\ClassMetadata $metadata + ) : Mapping\FieldMetadata + { + $className = $metadata->getClassName(); + $fieldName = $reflProperty->getName(); + $isVersioned = isset($propertyAnnotations[Annotation\Version::class]); + $columnAnnot = $propertyAnnotations[Annotation\Column::class]; + + if ($columnAnnot->type == null) { + throw Mapping\MappingException::propertyTypeIsRequired($className, $fieldName); + } + + $fieldMetadata = $this->convertColumnAnnotationToFieldMetadata($columnAnnot, $fieldName, $isVersioned); + + // Check for Id + if (isset($propertyAnnotations[Annotation\Id::class])) { + $fieldMetadata->setPrimaryKey(true); + } + + // Check for GeneratedValue strategy + if (isset($propertyAnnotations[Annotation\GeneratedValue::class])) { + $generatedValueAnnot = $propertyAnnotations[Annotation\GeneratedValue::class]; + $strategy = strtoupper($generatedValueAnnot->strategy); + $idGeneratorType = constant(sprintf('%s::%s', Mapping\GeneratorType::class, $strategy)); + + if ($idGeneratorType !== Mapping\GeneratorType::NONE) { + $idGeneratorDefinition = []; + + // Check for CustomGenerator/SequenceGenerator/TableGenerator definition + switch (true) { + case isset($propertyAnnotations[Annotation\SequenceGenerator::class]): + $seqGeneratorAnnot = $propertyAnnotations[Annotation\SequenceGenerator::class]; + + $idGeneratorDefinition = [ + 'sequenceName' => $seqGeneratorAnnot->sequenceName, + 'allocationSize' => $seqGeneratorAnnot->allocationSize, + ]; + + break; + + case isset($propertyAnnotations[Annotation\CustomIdGenerator::class]): + $customGeneratorAnnot = $propertyAnnotations[Annotation\CustomIdGenerator::class]; + + $idGeneratorDefinition = [ + 'class' => $customGeneratorAnnot->class, + 'arguments' => $customGeneratorAnnot->arguments, + ]; + + break; + + /* @todo If it is not supported, why does this exist? */ + case isset($propertyAnnotations['Doctrine\ORM\Mapping\TableGenerator']): + throw Mapping\MappingException::tableIdGeneratorNotImplemented($className); + } + + $fieldMetadata->setValueGenerator(new Mapping\ValueGeneratorMetadata($idGeneratorType, $idGeneratorDefinition)); + } + } + + return $fieldMetadata; + } + + /** + * @param \ReflectionProperty $reflectionProperty + * @param array $propertyAnnotations + * @param Mapping\ClassMetadata $metadata + * + * @return Mapping\OneToOneAssociationMetadata + */ + private function convertReflectionPropertyToOneToOneAssociationMetadata( + \ReflectionProperty $reflectionProperty, + array $propertyAnnotations, + Mapping\ClassMetadata $metadata + ) + { + $className = $metadata->getClassName(); + $fieldName = $reflectionProperty->getName(); + $oneToOneAnnot = $propertyAnnotations[Annotation\OneToOne::class]; + $assocMetadata = new Mapping\OneToOneAssociationMetadata($fieldName); + $targetEntity = $metadata->fullyQualifiedClassName($oneToOneAnnot->targetEntity); + + $assocMetadata->setTargetEntity($targetEntity); + $assocMetadata->setCascade($this->getCascade($className, $fieldName, $oneToOneAnnot->cascade)); + $assocMetadata->setOrphanRemoval($oneToOneAnnot->orphanRemoval); + $assocMetadata->setFetchMode($this->getFetchMode($className, $oneToOneAnnot->fetch)); + + if (! empty($oneToOneAnnot->mappedBy)) { + $assocMetadata->setMappedBy($oneToOneAnnot->mappedBy); + } + + if (! empty($oneToOneAnnot->inversedBy)) { + $assocMetadata->setInversedBy($oneToOneAnnot->inversedBy); + } + + // Check for Id + if (isset($propertyAnnotations[Annotation\Id::class])) { + $assocMetadata->setPrimaryKey(true); + } + + $this->attachAssociationPropertyCache($propertyAnnotations, $reflectionProperty, $assocMetadata, $metadata); + + // Check for JoinColumn/JoinColumns annotations + switch (true) { + case isset($propertyAnnotations[Annotation\JoinColumn::class]): + $joinColumnAnnot = $propertyAnnotations[Annotation\JoinColumn::class]; + + $assocMetadata->addJoinColumn( + $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot) + ); + + break; + + case isset($propertyAnnotations[Annotation\JoinColumns::class]): + $joinColumnsAnnot = $propertyAnnotations[Annotation\JoinColumns::class]; + + foreach ($joinColumnsAnnot->value as $joinColumnAnnot) { + $assocMetadata->addJoinColumn( + $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot) + ); + } + + break; + } + + return $assocMetadata; + } + + /** + * @param \ReflectionProperty $reflectionProperty + * @param array $propertyAnnotations + * @param Mapping\ClassMetadata $metadata + * + * @return Mapping\ManyToOneAssociationMetadata + */ + private function convertReflectionPropertyToManyToOneAssociationMetadata( + \ReflectionProperty $reflectionProperty, + array $propertyAnnotations, + Mapping\ClassMetadata $metadata + ) + { + $className = $metadata->getClassName(); + $fieldName = $reflectionProperty->getName(); + $manyToOneAnnot = $propertyAnnotations[Annotation\ManyToOne::class]; + $assocMetadata = new Mapping\ManyToOneAssociationMetadata($fieldName); + $targetEntity = $metadata->fullyQualifiedClassName($manyToOneAnnot->targetEntity); + + $assocMetadata->setTargetEntity($targetEntity); + $assocMetadata->setCascade($this->getCascade($className, $fieldName, $manyToOneAnnot->cascade)); + $assocMetadata->setFetchMode($this->getFetchMode($className, $manyToOneAnnot->fetch)); + + if (! empty($manyToOneAnnot->inversedBy)) { + $assocMetadata->setInversedBy($manyToOneAnnot->inversedBy); + } + + // Check for Id + if (isset($propertyAnnotations[Annotation\Id::class])) { + $assocMetadata->setPrimaryKey(true); + } + + $this->attachAssociationPropertyCache($propertyAnnotations, $reflectionProperty, $assocMetadata, $metadata); + + // Check for JoinColumn/JoinColumns annotations + switch (true) { + case isset($propertyAnnotations[Annotation\JoinColumn::class]): + $joinColumnAnnot = $propertyAnnotations[Annotation\JoinColumn::class]; + + $assocMetadata->addJoinColumn( + $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot) + ); + + break; + + case isset($propertyAnnotations[Annotation\JoinColumns::class]): + $joinColumnsAnnot = $propertyAnnotations[Annotation\JoinColumns::class]; + + foreach ($joinColumnsAnnot->value as $joinColumnAnnot) { + $assocMetadata->addJoinColumn( + $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot) + ); + } + + break; + } + + return $assocMetadata; + } + + /** + * @param \ReflectionProperty $reflectionProperty + * @param array $propertyAnnotations + * @param Mapping\ClassMetadata $metadata + * + * @return Mapping\OneToManyAssociationMetadata + * + * @throws Mapping\MappingException + */ + private function convertReflectionPropertyToOneToManyAssociationMetadata( + \ReflectionProperty $reflectionProperty, + array $propertyAnnotations, + Mapping\ClassMetadata $metadata + ) : Mapping\OneToManyAssociationMetadata + { + $className = $metadata->getClassName(); + $fieldName = $reflectionProperty->getName(); + $oneToManyAnnot = $propertyAnnotations[Annotation\OneToMany::class]; + $assocMetadata = new Mapping\OneToManyAssociationMetadata($fieldName); + $targetEntity = $metadata->fullyQualifiedClassName($oneToManyAnnot->targetEntity); + + $assocMetadata->setTargetEntity($targetEntity); + $assocMetadata->setCascade($this->getCascade($className, $fieldName, $oneToManyAnnot->cascade)); + $assocMetadata->setOrphanRemoval($oneToManyAnnot->orphanRemoval); + $assocMetadata->setFetchMode($this->getFetchMode($className, $oneToManyAnnot->fetch)); + + if (! empty($oneToManyAnnot->mappedBy)) { + $assocMetadata->setMappedBy($oneToManyAnnot->mappedBy); + } + + if (! empty($oneToManyAnnot->indexBy)) { + $assocMetadata->setIndexedBy($oneToManyAnnot->indexBy); + } + + // Check for OrderBy + if (isset($propertyAnnotations[Annotation\OrderBy::class])) { + $orderByAnnot = $propertyAnnotations[Annotation\OrderBy::class]; + + $assocMetadata->setOrderBy($orderByAnnot->value); + } + + // Check for Id + if (isset($propertyAnnotations[Annotation\Id::class])) { + throw Mapping\MappingException::illegalToManyIdentifierAssociation($className, $fieldName); + } + + $this->attachAssociationPropertyCache($propertyAnnotations, $reflectionProperty, $assocMetadata, $metadata); + + return $assocMetadata; + } + + /** + * @param \ReflectionProperty $reflectionProperty + * @param array $propertyAnnotations + * @param Mapping\ClassMetadata $metadata + * + * @return Mapping\ManyToManyAssociationMetadata + * + * @throws Mapping\MappingException + */ + private function convertReflectionPropertyToManyToManyAssociationMetadata( + \ReflectionProperty $reflectionProperty, + array $propertyAnnotations, + Mapping\ClassMetadata $metadata + ) : Mapping\ManyToManyAssociationMetadata + { + $className = $metadata->getClassName(); + $fieldName = $reflectionProperty->getName(); + $manyToManyAnnot = $propertyAnnotations[Annotation\ManyToMany::class]; + $assocMetadata = new Mapping\ManyToManyAssociationMetadata($fieldName); + $targetEntity = $metadata->fullyQualifiedClassName($manyToManyAnnot->targetEntity); + + $assocMetadata->setTargetEntity($targetEntity); + $assocMetadata->setCascade($this->getCascade($className, $fieldName, $manyToManyAnnot->cascade)); + $assocMetadata->setOrphanRemoval($manyToManyAnnot->orphanRemoval); + $assocMetadata->setFetchMode($this->getFetchMode($className, $manyToManyAnnot->fetch)); + + if (! empty($manyToManyAnnot->mappedBy)) { + $assocMetadata->setMappedBy($manyToManyAnnot->mappedBy); + } + + if (! empty($manyToManyAnnot->inversedBy)) { + $assocMetadata->setInversedBy($manyToManyAnnot->inversedBy); + } + + if (! empty($manyToManyAnnot->indexBy)) { + $assocMetadata->setIndexedBy($manyToManyAnnot->indexBy); + } + + // Check for JoinTable + if (isset($propertyAnnotations[Annotation\JoinTable::class])) { + $joinTableAnnot = $propertyAnnotations[Annotation\JoinTable::class]; + $joinTableMetadata = $this->convertJoinTableAnnotationToJoinTableMetadata($joinTableAnnot); + + $assocMetadata->setJoinTable($joinTableMetadata); + } + + // Check for OrderBy + if (isset($propertyAnnotations[Annotation\OrderBy::class])) { + $orderByAnnot = $propertyAnnotations[Annotation\OrderBy::class]; + + $assocMetadata->setOrderBy($orderByAnnot->value); + } + + // Check for Id + if (isset($propertyAnnotations[Annotation\Id::class])) { + throw Mapping\MappingException::illegalToManyIdentifierAssociation($className, $fieldName); + } + + $this->attachAssociationPropertyCache($propertyAnnotations, $reflectionProperty, $assocMetadata, $metadata); + + return $assocMetadata; + } + + /** + * Parse the given Column as FieldMetadata + * + * @param Annotation\Column $columnAnnot + * @param string $fieldName + * @param bool $isVersioned + * + * @return Mapping\FieldMetadata + */ + private function convertColumnAnnotationToFieldMetadata( + Annotation\Column $columnAnnot, + string $fieldName, + bool $isVersioned + ) : Mapping\FieldMetadata + { + $fieldMetadata = $isVersioned + ? new Mapping\VersionFieldMetadata($fieldName) + : new Mapping\FieldMetadata($fieldName) + ; + + $fieldMetadata->setType(Type::getType($columnAnnot->type)); + + if (! empty($columnAnnot->name)) { + $fieldMetadata->setColumnName($columnAnnot->name); + } + + if (! empty($columnAnnot->columnDefinition)) { + $fieldMetadata->setColumnDefinition($columnAnnot->columnDefinition); + } + + if (! empty($columnAnnot->length)) { + $fieldMetadata->setLength($columnAnnot->length); + } + + if ($columnAnnot->options) { + $fieldMetadata->setOptions($columnAnnot->options); + } + + $fieldMetadata->setScale($columnAnnot->scale); + $fieldMetadata->setPrecision($columnAnnot->precision); + $fieldMetadata->setNullable($columnAnnot->nullable); + $fieldMetadata->setUnique($columnAnnot->unique); + + return $fieldMetadata; + } + + /** + * Parse the given Table as TableMetadata + * + * @param Annotation\Table $tableAnnot + * @param Mapping\TableMetadata $tableMetadata + * + * @return void */ - protected $entityAnnotationClasses = [ - Mapping\Entity::class => 1, - Mapping\MappedSuperclass::class => 2, - ]; + private function convertTableAnnotationToTableMetadata( + Annotation\Table $tableAnnot, + Mapping\TableMetadata $tableMetadata + ) : void + { + if (! empty($tableAnnot->name)) { + $tableMetadata->setName($tableAnnot->name); + } + + if (! empty($tableAnnot->schema)) { + $tableMetadata->setSchema($tableAnnot->schema); + } + + foreach ($tableAnnot->options as $optionName => $optionValue) { + $tableMetadata->addOption($optionName, $optionValue); + } + + foreach ($tableAnnot->indexes as $indexAnnot) { + $tableMetadata->addIndex([ + 'name' => $indexAnnot->name, + 'columns' => $indexAnnot->columns, + 'unique' => $indexAnnot->unique, + 'options' => $indexAnnot->options, + 'flags' => $indexAnnot->flags, + ]); + } + + foreach ($tableAnnot->uniqueConstraints as $uniqueConstraintAnnot) { + $tableMetadata->addUniqueConstraint([ + 'name' => $uniqueConstraintAnnot->name, + 'columns' => $uniqueConstraintAnnot->columns, + 'options' => $uniqueConstraintAnnot->options, + 'flags' => $uniqueConstraintAnnot->flags, + ]); + } + } /** - * {@inheritDoc} + * Parse the given JoinTable as JoinTableMetadata + * + * @param Annotation\JoinTable $joinTableAnnot + * + * @return Mapping\JoinTableMetadata */ - public function loadMetadataForClass($className, ClassMetadata $metadata) + private function convertJoinTableAnnotationToJoinTableMetadata( + Annotation\JoinTable $joinTableAnnot + ) : Mapping\JoinTableMetadata { - /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadataInfo */ - $class = $metadata->getReflectionClass(); + $joinTable = new Mapping\JoinTableMetadata(); - if ( ! $class) { - // this happens when running annotation driver in combination with - // static reflection services. This is not the nicest fix - $class = new \ReflectionClass($metadata->name); + if (! empty($joinTableAnnot->name)) { + $joinTable->setName($joinTableAnnot->name); } - $classAnnotations = $this->reader->getClassAnnotations($class); + if (! empty($joinTableAnnot->schema)) { + $joinTable->setSchema($joinTableAnnot->schema); + } - if ($classAnnotations) { - foreach ($classAnnotations as $key => $annot) { - if ( ! is_numeric($key)) { - continue; - } + foreach ($joinTableAnnot->joinColumns as $joinColumnAnnot) { + $joinColumn = $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot); - $classAnnotations[get_class($annot)] = $annot; - } + $joinTable->addJoinColumn($joinColumn); } - // Evaluate Entity annotation - if (isset($classAnnotations[Mapping\Entity::class])) { - $entityAnnot = $classAnnotations[Mapping\Entity::class]; - if ($entityAnnot->repositoryClass !== null) { - $metadata->setCustomRepositoryClass($entityAnnot->repositoryClass); - } - - if ($entityAnnot->readOnly) { - $metadata->markReadOnly(); - } - } else if (isset($classAnnotations[Mapping\MappedSuperclass::class])) { - $mappedSuperclassAnnot = $classAnnotations[Mapping\MappedSuperclass::class]; - - $metadata->setCustomRepositoryClass($mappedSuperclassAnnot->repositoryClass); - $metadata->isMappedSuperclass = true; - } else if (isset($classAnnotations[Mapping\Embeddable::class])) { - $metadata->isEmbeddedClass = true; - } else { - throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className); - } - - // Evaluate Table annotation - if (isset($classAnnotations[Mapping\Table::class])) { - $tableAnnot = $classAnnotations[Mapping\Table::class]; - $primaryTable = [ - 'name' => $tableAnnot->name, - 'schema' => $tableAnnot->schema - ]; + foreach ($joinTableAnnot->inverseJoinColumns as $joinColumnAnnot) { + $joinColumn = $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot); - if ($tableAnnot->indexes !== null) { - foreach ($tableAnnot->indexes as $indexAnnot) { - $index = ['columns' => $indexAnnot->columns]; + $joinTable->addInverseJoinColumn($joinColumn); + } - if ( ! empty($indexAnnot->flags)) { - $index['flags'] = $indexAnnot->flags; - } + return $joinTable; + } - if ( ! empty($indexAnnot->options)) { - $index['options'] = $indexAnnot->options; - } + /** + * Parse the given JoinColumn as JoinColumnMetadata + * + * @param Annotation\JoinColumn $joinColumnAnnot + * + * @return Mapping\JoinColumnMetadata + */ + private function convertJoinColumnAnnotationToJoinColumnMetadata( + Annotation\JoinColumn $joinColumnAnnot + ) : Mapping\JoinColumnMetadata + { + $joinColumn = new Mapping\JoinColumnMetadata(); - if ( ! empty($indexAnnot->name)) { - $primaryTable['indexes'][$indexAnnot->name] = $index; - } else { - $primaryTable['indexes'][] = $index; - } - } - } + // @todo Remove conditionals for name and referencedColumnName once naming strategy is brought into drivers + if (! empty($joinColumnAnnot->name)) { + $joinColumn->setColumnName($joinColumnAnnot->name); + } - if ($tableAnnot->uniqueConstraints !== null) { - foreach ($tableAnnot->uniqueConstraints as $uniqueConstraintAnnot) { - $uniqueConstraint = ['columns' => $uniqueConstraintAnnot->columns]; + if (! empty($joinColumnAnnot->referencedColumnName)) { + $joinColumn->setReferencedColumnName($joinColumnAnnot->referencedColumnName); + } - if ( ! empty($uniqueConstraintAnnot->options)) { - $uniqueConstraint['options'] = $uniqueConstraintAnnot->options; - } + $joinColumn->setNullable($joinColumnAnnot->nullable); + $joinColumn->setUnique($joinColumnAnnot->unique); - if ( ! empty($uniqueConstraintAnnot->name)) { - $primaryTable['uniqueConstraints'][$uniqueConstraintAnnot->name] = $uniqueConstraint; - } else { - $primaryTable['uniqueConstraints'][] = $uniqueConstraint; - } - } - } + if (! empty($joinColumnAnnot->fieldName)) { + $joinColumn->setAliasedName($joinColumnAnnot->fieldName); + } - if ($tableAnnot->options) { - $primaryTable['options'] = $tableAnnot->options; - } + if (! empty($joinColumnAnnot->columnDefinition)) { + $joinColumn->setColumnDefinition($joinColumnAnnot->columnDefinition); + } - $metadata->setPrimaryTable($primaryTable); + if ($joinColumnAnnot->onDelete) { + $joinColumn->setOnDelete(strtoupper($joinColumnAnnot->onDelete)); } - // Evaluate @Cache annotation - if (isset($classAnnotations[Mapping\Cache::class])) { - $cacheAnnot = $classAnnotations[Mapping\Cache::class]; - $cacheMap = [ - 'region' => $cacheAnnot->region, - 'usage' => constant('Doctrine\ORM\Mapping\ClassMetadata::CACHE_USAGE_' . $cacheAnnot->usage), + return $joinColumn; + } + + /** + * Parse the given Cache as CacheMetadata + * + * @param Annotation\Cache $cacheAnnot + * @param Mapping\ClassMetadata $metadata + * @param null|string $fieldName + * + * @return Mapping\CacheMetadata + */ + private function convertCacheAnnotationToCacheMetadata( + Annotation\Cache $cacheAnnot, + Mapping\ClassMetadata $metadata, + $fieldName = null + ) : Mapping\CacheMetadata + { + $baseRegion = strtolower(str_replace('\\', '_', $metadata->getRootClassName())); + $defaultRegion = $baseRegion . ($fieldName ? '__' . $fieldName : ''); + + $usage = constant(sprintf('%s::%s', Mapping\CacheUsage::class, $cacheAnnot->usage)); + $region = $cacheAnnot->region ?: $defaultRegion; + + return new Mapping\CacheMetadata($usage, $region); + } + + /** + * @param Annotation\SqlResultSetMapping $resultSetMapping + * + * @return array + */ + private function convertSqlResultSetMapping(Annotation\SqlResultSetMapping $resultSetMapping) + { + $entities = []; + + foreach ($resultSetMapping->entities as $entityResultAnnot) { + $entityResult = [ + 'fields' => [], + 'entityClass' => $entityResultAnnot->entityClass, + 'discriminatorColumn' => $entityResultAnnot->discriminatorColumn, ]; - $metadata->enableCache($cacheMap); + foreach ($entityResultAnnot->fields as $fieldResultAnnot) { + $entityResult['fields'][] = [ + 'name' => $fieldResultAnnot->name, + 'column' => $fieldResultAnnot->column + ]; + } + + $entities[] = $entityResult; } - // Evaluate NamedNativeQueries annotation - if (isset($classAnnotations[Mapping\NamedNativeQueries::class])) { - $namedNativeQueriesAnnot = $classAnnotations[Mapping\NamedNativeQueries::class]; + $columns = []; - foreach ($namedNativeQueriesAnnot->value as $namedNativeQuery) { - $metadata->addNamedNativeQuery( - [ - 'name' => $namedNativeQuery->name, - 'query' => $namedNativeQuery->query, - 'resultClass' => $namedNativeQuery->resultClass, - 'resultSetMapping' => $namedNativeQuery->resultSetMapping, - ] - ); - } + foreach ($resultSetMapping->columns as $columnResultAnnot) { + $columns[] = [ + 'name' => $columnResultAnnot->name, + ]; } - // Evaluate SqlResultSetMappings annotation - if (isset($classAnnotations[Mapping\SqlResultSetMappings::class])) { - $sqlResultSetMappingsAnnot = $classAnnotations[Mapping\SqlResultSetMappings::class]; + return [ + 'name' => $resultSetMapping->name, + 'entities' => $entities, + 'columns' => $columns + ]; + } - foreach ($sqlResultSetMappingsAnnot->value as $resultSetMapping) { - $entities = []; - $columns = []; - foreach ($resultSetMapping->entities as $entityResultAnnot) { - $entityResult = [ - 'fields' => [], - 'entityClass' => $entityResultAnnot->entityClass, - 'discriminatorColumn' => $entityResultAnnot->discriminatorColumn, - ]; - - foreach ($entityResultAnnot->fields as $fieldResultAnnot) { - $entityResult['fields'][] = [ - 'name' => $fieldResultAnnot->name, - 'column' => $fieldResultAnnot->column - ]; - } + private function attachTable( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) : void + { + $parent = $metadata->getParent(); - $entities[] = $entityResult; - } + if ($parent && $parent->inheritanceType === Mapping\InheritanceType::SINGLE_TABLE) { + // Handle the case where a middle mapped super class inherits from a single table inheritance tree. + do { + if (! $parent->isMappedSuperclass) { + $metadata->setTable($parent->table); - foreach ($resultSetMapping->columns as $columnResultAnnot) { - $columns[] = [ - 'name' => $columnResultAnnot->name, - ]; + break; } + } while (($parent = $parent->getParent()) !== null); - $metadata->addSqlResultSetMapping( - [ - 'name' => $resultSetMapping->name, - 'entities' => $entities, - 'columns' => $columns - ] - ); - } + return; } - // Evaluate NamedQueries annotation - if (isset($classAnnotations[Mapping\NamedQueries::class])) { - $namedQueriesAnnot = $classAnnotations[Mapping\NamedQueries::class]; + $namingStrategy = $metadataBuildingContext->getNamingStrategy(); + $tableMetadata = new Mapping\TableMetadata(); - if ( ! is_array($namedQueriesAnnot->value)) { - throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); + $tableMetadata->setName($namingStrategy->classToTableName($metadata->getClassName())); + + // Evaluate @Table annotation + if (isset($classAnnotations[Annotation\Table::class])) { + $tableAnnot = $classAnnotations[Annotation\Table::class]; + + $this->convertTableAnnotationToTableMetadata($tableAnnot, $tableMetadata); + } + + $metadata->setTable($tableMetadata); + } + + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * + * @return void + * + * @throws Mapping\MappingException + */ + private function attachDiscriminatorColumn( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata + ) : void + { + $discriminatorColumn = new Mapping\DiscriminatorColumnMetadata(); + + $discriminatorColumn->setTableName($metadata->getTableName()); + $discriminatorColumn->setColumnName('dtype'); + $discriminatorColumn->setType(Type::getType('string')); + $discriminatorColumn->setLength(255); + + // Evaluate DiscriminatorColumn annotation + if (isset($classAnnotations[Annotation\DiscriminatorColumn::class])) { + /** @var Annotation\DiscriminatorColumn $discriminatorColumnAnnotation */ + $discriminatorColumnAnnotation = $classAnnotations[Annotation\DiscriminatorColumn::class]; + $typeName = ! empty($discriminatorColumnAnnotation->type) + ? $discriminatorColumnAnnotation->type + : 'string'; + + $discriminatorColumn->setType(Type::getType($typeName)); + $discriminatorColumn->setColumnName($discriminatorColumnAnnotation->name); + + if (! empty($discriminatorColumnAnnotation->columnDefinition)) { + $discriminatorColumn->setColumnDefinition($discriminatorColumnAnnotation->columnDefinition); } - foreach ($namedQueriesAnnot->value as $namedQuery) { - if ( ! ($namedQuery instanceof Mapping\NamedQuery)) { - throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); - } - $metadata->addNamedQuery( - [ - 'name' => $namedQuery->name, - 'query' => $namedQuery->query - ] - ); + if (! empty($discriminatorColumnAnnotation->length)) { + $discriminatorColumn->setLength($discriminatorColumnAnnotation->length); } } - // Evaluate InheritanceType annotation - if (isset($classAnnotations[Mapping\InheritanceType::class])) { - $inheritanceTypeAnnot = $classAnnotations[Mapping\InheritanceType::class]; + $metadata->setDiscriminatorColumn($discriminatorColumn); - $metadata->setInheritanceType( - constant('Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_' . $inheritanceTypeAnnot->value) + // Evaluate DiscriminatorMap annotation + if (isset($classAnnotations[Annotation\DiscriminatorMap::class])) { + $discriminatorMapAnnotation = $classAnnotations[Annotation\DiscriminatorMap::class]; + $discriminatorMap = array_map( + function ($className) use ($metadata) { + return $metadata->fullyQualifiedClassName($className); + }, + $discriminatorMapAnnotation->value ); - if ($metadata->inheritanceType != Mapping\ClassMetadata::INHERITANCE_TYPE_NONE) { - // Evaluate DiscriminatorColumn annotation - if (isset($classAnnotations[Mapping\DiscriminatorColumn::class])) { - $discrColumnAnnot = $classAnnotations[Mapping\DiscriminatorColumn::class]; - - $metadata->setDiscriminatorColumn( - [ - 'name' => $discrColumnAnnot->name, - 'type' => $discrColumnAnnot->type ?: 'string', - 'length' => $discrColumnAnnot->length ?: 255, - 'columnDefinition' => $discrColumnAnnot->columnDefinition, - ] - ); - } else { - $metadata->setDiscriminatorColumn(['name' => 'dtype', 'type' => 'string', 'length' => 255]); - } - - // Evaluate DiscriminatorMap annotation - if (isset($classAnnotations[Mapping\DiscriminatorMap::class])) { - $discrMapAnnot = $classAnnotations[Mapping\DiscriminatorMap::class]; - $metadata->setDiscriminatorMap($discrMapAnnot->value); - } - } + $metadata->setDiscriminatorMap($discriminatorMap); } + } + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * + * @return void + * + * @throws \UnexpectedValueException + * @throws Mapping\MappingException + */ + private function attachNamedQueries( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata + ) : void + { + // Evaluate @NamedQueries annotation + if (isset($classAnnotations[Annotation\NamedQueries::class])) { + $namedQueriesAnnot = $classAnnotations[Annotation\NamedQueries::class]; - // Evaluate DoctrineChangeTrackingPolicy annotation - if (isset($classAnnotations[Mapping\ChangeTrackingPolicy::class])) { - $changeTrackingAnnot = $classAnnotations[Mapping\ChangeTrackingPolicy::class]; - $metadata->setChangeTrackingPolicy(constant('Doctrine\ORM\Mapping\ClassMetadata::CHANGETRACKING_' . $changeTrackingAnnot->value)); - } + if (! is_array($namedQueriesAnnot->value)) { + throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); + } - // Evaluate annotations on properties/fields - /* @var $property \ReflectionProperty */ - foreach ($class->getProperties() as $property) { - if ($metadata->isMappedSuperclass && ! $property->isPrivate() - || - $metadata->isInheritedField($property->name) - || - $metadata->isInheritedAssociation($property->name) - || - $metadata->isInheritedEmbeddedClass($property->name)) { - continue; + foreach ($namedQueriesAnnot->value as $namedQuery) { + if (! ($namedQuery instanceof Annotation\NamedQuery)) { + throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); + } + + $metadata->addNamedQuery($namedQuery->name, $namedQuery->query); } + } + } - $mapping = []; - $mapping['fieldName'] = $property->getName(); + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * + * @return void + */ + private function attachNamedNativeQueries( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata + ) : void + { + // Evaluate @NamedNativeQueries annotation + if (isset($classAnnotations[Annotation\NamedNativeQueries::class])) { + $namedNativeQueriesAnnot = $classAnnotations[Annotation\NamedNativeQueries::class]; - // Evaluate @Cache annotation - if (($cacheAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Cache::class)) !== null) { - $mapping['cache'] = $metadata->getAssociationCacheDefaults( - $mapping['fieldName'], + foreach ($namedNativeQueriesAnnot->value as $namedNativeQuery) { + $metadata->addNamedNativeQuery( + $namedNativeQuery->name, + $namedNativeQuery->query, [ - 'usage' => constant('Doctrine\ORM\Mapping\ClassMetadata::CACHE_USAGE_' . $cacheAnnot->usage), - 'region' => $cacheAnnot->region, + 'resultClass' => $namedNativeQuery->resultClass, + 'resultSetMapping' => $namedNativeQuery->resultSetMapping, ] ); } - // Check for JoinColumn/JoinColumns annotations - $joinColumns = []; - - if ($joinColumnAnnot = $this->reader->getPropertyAnnotation($property, Mapping\JoinColumn::class)) { - $joinColumns[] = $this->joinColumnToArray($joinColumnAnnot); - } else if ($joinColumnsAnnot = $this->reader->getPropertyAnnotation($property, Mapping\JoinColumns::class)) { - foreach ($joinColumnsAnnot->value as $joinColumn) { - $joinColumns[] = $this->joinColumnToArray($joinColumn); - } - } + } - // Field can only be annotated with one of: - // @Column, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany - if ($columnAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Column::class)) { - if ($columnAnnot->type == null) { - throw MappingException::propertyTypeIsRequired($className, $property->getName()); - } + // Evaluate @SqlResultSetMappings annotation + if (isset($classAnnotations[Annotation\SqlResultSetMappings::class])) { + $sqlResultSetMappingsAnnot = $classAnnotations[Annotation\SqlResultSetMappings::class]; - $mapping = $this->columnToArray($property->getName(), $columnAnnot); + foreach ($sqlResultSetMappingsAnnot->value as $resultSetMapping) { + $sqlResultSetMapping = $this->convertSqlResultSetMapping($resultSetMapping); - if ($idAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Id::class)) { - $mapping['id'] = true; - } + $metadata->addSqlResultSetMapping($sqlResultSetMapping); + } + } + } - if ($generatedValueAnnot = $this->reader->getPropertyAnnotation($property, Mapping\GeneratedValue::class)) { - $metadata->setIdGeneratorType(constant('Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_' . $generatedValueAnnot->strategy)); + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * + * @return void + */ + private function attachLifecycleCallbacks( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata + ) : void + { + // Evaluate @HasLifecycleCallbacks annotation + if (isset($classAnnotations[Annotation\HasLifecycleCallbacks::class])) { + /* @var $method \ReflectionMethod */ + foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { + foreach ($this->getMethodCallbacks($method) as $callback) { + $metadata->addLifecycleCallback($method->getName(), $callback); } + } + } + } - if ($this->reader->getPropertyAnnotation($property, Mapping\Version::class)) { - $metadata->setVersionMapping($mapping); - } + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * + * @return void + * + * @throws \ReflectionException + * @throws Mapping\MappingException + */ + private function attachEntityListeners( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata + ) : void + { + // Evaluate @EntityListeners annotation + if (isset($classAnnotations[Annotation\EntityListeners::class])) { + /** @var Annotation\EntityListeners $entityListenersAnnot */ + $entityListenersAnnot = $classAnnotations[Annotation\EntityListeners::class]; - $metadata->mapField($mapping); + foreach ($entityListenersAnnot->value as $item) { + $listenerClassName = $metadata->fullyQualifiedClassName($item); - // Check for SequenceGenerator/TableGenerator definition - if ($seqGeneratorAnnot = $this->reader->getPropertyAnnotation($property, Mapping\SequenceGenerator::class)) { - $metadata->setSequenceGeneratorDefinition( - [ - 'sequenceName' => $seqGeneratorAnnot->sequenceName, - 'allocationSize' => $seqGeneratorAnnot->allocationSize, - 'initialValue' => $seqGeneratorAnnot->initialValue - ] - ); - } else if ($this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\TableGenerator')) { - throw MappingException::tableIdGeneratorNotImplemented($className); - } else if ($customGeneratorAnnot = $this->reader->getPropertyAnnotation($property, Mapping\CustomIdGenerator::class)) { - $metadata->setCustomGeneratorDefinition( - [ - 'class' => $customGeneratorAnnot->class - ] + if (! class_exists($listenerClassName)) { + throw Mapping\MappingException::entityListenerClassNotFound( + $listenerClassName, + $metadata->getClassName() ); } - } else if ($oneToOneAnnot = $this->reader->getPropertyAnnotation($property, Mapping\OneToOne::class)) { - if ($idAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Id::class)) { - $mapping['id'] = true; - } - - $mapping['targetEntity'] = $oneToOneAnnot->targetEntity; - $mapping['joinColumns'] = $joinColumns; - $mapping['mappedBy'] = $oneToOneAnnot->mappedBy; - $mapping['inversedBy'] = $oneToOneAnnot->inversedBy; - $mapping['cascade'] = $oneToOneAnnot->cascade; - $mapping['orphanRemoval'] = $oneToOneAnnot->orphanRemoval; - $mapping['fetch'] = $this->getFetchMode($className, $oneToOneAnnot->fetch); - $metadata->mapOneToOne($mapping); - } else if ($oneToManyAnnot = $this->reader->getPropertyAnnotation($property, Mapping\OneToMany::class)) { - $mapping['mappedBy'] = $oneToManyAnnot->mappedBy; - $mapping['targetEntity'] = $oneToManyAnnot->targetEntity; - $mapping['cascade'] = $oneToManyAnnot->cascade; - $mapping['indexBy'] = $oneToManyAnnot->indexBy; - $mapping['orphanRemoval'] = $oneToManyAnnot->orphanRemoval; - $mapping['fetch'] = $this->getFetchMode($className, $oneToManyAnnot->fetch); - - if ($orderByAnnot = $this->reader->getPropertyAnnotation($property, Mapping\OrderBy::class)) { - $mapping['orderBy'] = $orderByAnnot->value; - } - - $metadata->mapOneToMany($mapping); - } else if ($manyToOneAnnot = $this->reader->getPropertyAnnotation($property, Mapping\ManyToOne::class)) { - if ($idAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Id::class)) { - $mapping['id'] = true; - } - $mapping['joinColumns'] = $joinColumns; - $mapping['cascade'] = $manyToOneAnnot->cascade; - $mapping['inversedBy'] = $manyToOneAnnot->inversedBy; - $mapping['targetEntity'] = $manyToOneAnnot->targetEntity; - $mapping['fetch'] = $this->getFetchMode($className, $manyToOneAnnot->fetch); - $metadata->mapManyToOne($mapping); - } else if ($manyToManyAnnot = $this->reader->getPropertyAnnotation($property, Mapping\ManyToMany::class)) { - $joinTable = []; - - if ($joinTableAnnot = $this->reader->getPropertyAnnotation($property, Mapping\JoinTable::class)) { - $joinTable = [ - 'name' => $joinTableAnnot->name, - 'schema' => $joinTableAnnot->schema - ]; - - foreach ($joinTableAnnot->joinColumns as $joinColumn) { - $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumn); - } + $listenerClass = new \ReflectionClass($listenerClassName); - foreach ($joinTableAnnot->inverseJoinColumns as $joinColumn) { - $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumn); + /* @var $method \ReflectionMethod */ + foreach ($listenerClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { + foreach ($this->getMethodCallbacks($method) as $callback) { + $metadata->addEntityListener($callback, $listenerClassName, $method->getName()); } } - - $mapping['joinTable'] = $joinTable; - $mapping['targetEntity'] = $manyToManyAnnot->targetEntity; - $mapping['mappedBy'] = $manyToManyAnnot->mappedBy; - $mapping['inversedBy'] = $manyToManyAnnot->inversedBy; - $mapping['cascade'] = $manyToManyAnnot->cascade; - $mapping['indexBy'] = $manyToManyAnnot->indexBy; - $mapping['orphanRemoval'] = $manyToManyAnnot->orphanRemoval; - $mapping['fetch'] = $this->getFetchMode($className, $manyToManyAnnot->fetch); - - if ($orderByAnnot = $this->reader->getPropertyAnnotation($property, Mapping\OrderBy::class)) { - $mapping['orderBy'] = $orderByAnnot->value; - } - - $metadata->mapManyToMany($mapping); - } else if ($embeddedAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Embedded::class)) { - $mapping['class'] = $embeddedAnnot->class; - $mapping['columnPrefix'] = $embeddedAnnot->columnPrefix; - - $metadata->mapEmbedded($mapping); } } + } + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $metadata + * + * @return void + * + * @throws Mapping\MappingException + */ + private function attachPropertyOverrides( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $metadata + ) : void + { // Evaluate AssociationOverrides annotation - if (isset($classAnnotations[Mapping\AssociationOverrides::class])) { - $associationOverridesAnnot = $classAnnotations[Mapping\AssociationOverrides::class]; + if (isset($classAnnotations[Annotation\AssociationOverrides::class])) { + $associationOverridesAnnot = $classAnnotations[Annotation\AssociationOverrides::class]; foreach ($associationOverridesAnnot->value as $associationOverride) { - $override = []; - $fieldName = $associationOverride->name; + $fieldName = $associationOverride->name; + $property = $metadata->getProperty($fieldName); + + if (! $property) { + throw Mapping\MappingException::invalidOverrideFieldName($metadata->getClassName(), $fieldName); + } + + $existingClass = get_class($property); + $override = new $existingClass($fieldName); // Check for JoinColumn/JoinColumns annotations if ($associationOverride->joinColumns) { $joinColumns = []; - foreach ($associationOverride->joinColumns as $joinColumn) { - $joinColumns[] = $this->joinColumnToArray($joinColumn); + foreach ($associationOverride->joinColumns as $joinColumnAnnot) { + $joinColumns[] = $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot); } - $override['joinColumns'] = $joinColumns; + $override->setJoinColumns($joinColumns); } // Check for JoinTable annotations if ($associationOverride->joinTable) { - $joinTableAnnot = $associationOverride->joinTable; - $joinTable = [ - 'name' => $joinTableAnnot->name, - 'schema' => $joinTableAnnot->schema - ]; - - foreach ($joinTableAnnot->joinColumns as $joinColumn) { - $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumn); - } - - foreach ($joinTableAnnot->inverseJoinColumns as $joinColumn) { - $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumn); - } + $joinTableAnnot = $associationOverride->joinTable; + $joinTableMetadata = $this->convertJoinTableAnnotationToJoinTableMetadata($joinTableAnnot); - $override['joinTable'] = $joinTable; + $override->setJoinTable($joinTableMetadata); } // Check for inversedBy if ($associationOverride->inversedBy) { - $override['inversedBy'] = $associationOverride->inversedBy; + $override->setInversedBy($associationOverride->inversedBy); } - // Check for `fetch` + // Check for fetch if ($associationOverride->fetch) { - $override['fetch'] = constant(Mapping\ClassMetadata::class . '::FETCH_' . $associationOverride->fetch); + $override->setFetchMode( + constant(Mapping\FetchMode::class . '::' . $associationOverride->fetch) + ); } - $metadata->setAssociationOverride($fieldName, $override); + $metadata->setPropertyOverride($override); } } // Evaluate AttributeOverrides annotation - if (isset($classAnnotations[Mapping\AttributeOverrides::class])) { - $attributeOverridesAnnot = $classAnnotations[Mapping\AttributeOverrides::class]; + if (isset($classAnnotations[Annotation\AttributeOverrides::class])) { + $attributeOverridesAnnot = $classAnnotations[Annotation\AttributeOverrides::class]; foreach ($attributeOverridesAnnot->value as $attributeOverrideAnnot) { - $attributeOverride = $this->columnToArray($attributeOverrideAnnot->name, $attributeOverrideAnnot->column); + $fieldMetadata = $this->convertColumnAnnotationToFieldMetadata( + $attributeOverrideAnnot->column, + $attributeOverrideAnnot->name, + false + ); - $metadata->setAttributeOverride($attributeOverrideAnnot->name, $attributeOverride); + $metadata->setPropertyOverride($fieldMetadata); } } + } - // Evaluate EntityListeners annotation - if (isset($classAnnotations[Mapping\EntityListeners::class])) { - $entityListenersAnnot = $classAnnotations[Mapping\EntityListeners::class]; - - foreach ($entityListenersAnnot->value as $item) { - $listenerClassName = $metadata->fullyQualifiedClassName($item); + private function attachAssociationPropertyCache( + array $propertyAnnotations, + \ReflectionProperty $reflectionProperty, + Mapping\AssociationMetadata $assocMetadata, + Mapping\ClassMetadata $metadata + ) : void + { + // Check for Cache + if (isset($propertyAnnotations[Annotation\Cache::class])) { + $cacheAnnot = $propertyAnnotations[Annotation\Cache::class]; + $cacheMetadata = $this->convertCacheAnnotationToCacheMetadata( + $cacheAnnot, + $metadata, + $reflectionProperty->getName() + ); - if ( ! class_exists($listenerClassName)) { - throw MappingException::entityListenerClassNotFound($listenerClassName, $className); - } + $assocMetadata->setCache($cacheMetadata); + } + } - $hasMapping = false; - $listenerClass = new \ReflectionClass($listenerClassName); + /** + * Attempts to resolve the cascade modes. + * + * @param string $className The class name. + * @param string $fieldName The field name. + * @param array $originalCascades The original unprocessed field cascades. + * + * @return array The processed field cascades. + * + * @throws Mapping\MappingException If a cascade option is not valid. + */ + private function getCascade(string $className, string $fieldName, array $originalCascades) + { + $cascadeTypes = ['remove', 'persist', 'refresh']; + $cascades = array_map('strtolower', $originalCascades); - /* @var $method \ReflectionMethod */ - foreach ($listenerClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { - // find method callbacks. - $callbacks = $this->getMethodCallbacks($method); - $hasMapping = $hasMapping ?: ( ! empty($callbacks)); + if (in_array('all', $cascades)) { + $cascades = $cascadeTypes; + } - foreach ($callbacks as $value) { - $metadata->addEntityListener($value[1], $listenerClassName, $value[0]); - } - } + if (count($cascades) !== count(array_intersect($cascades, $cascadeTypes))) { + $diffCascades = array_diff($cascades, array_intersect($cascades, $cascadeTypes)); - // Evaluate the listener using naming convention. - if ( ! $hasMapping ) { - EntityListenerBuilder::bindEntityListener($metadata, $listenerClassName); - } - } + throw Mapping\MappingException::invalidCascadeOption($diffCascades, $className, $fieldName); } - // Evaluate @HasLifecycleCallbacks annotation - if (isset($classAnnotations[Mapping\HasLifecycleCallbacks::class])) { - /* @var $method \ReflectionMethod */ - foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { - foreach ($this->getMethodCallbacks($method) as $value) { - $metadata->addLifecycleCallback($value[0], $value[1]); - } - } - } + return $cascades; } /** @@ -539,17 +1444,19 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) * @param string $className The class name. * @param string $fetchMode The fetch mode. * - * @return integer The fetch mode as defined in ClassMetadata. + * @return string The fetch mode as defined in ClassMetadata. * - * @throws MappingException If the fetch mode is not valid. + * @throws Mapping\MappingException If the fetch mode is not valid. */ - private function getFetchMode($className, $fetchMode) + private function getFetchMode($className, $fetchMode) : string { - if ( ! defined('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $fetchMode)) { - throw MappingException::invalidFetchMode($className, $fetchMode); + $fetchModeConstant = sprintf('%s::%s', Mapping\FetchMode::class, $fetchMode); + + if ( ! defined($fetchModeConstant)) { + throw Mapping\MappingException::invalidFetchMode($className, $fetchMode); } - return constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $fetchMode); + return constant($fetchModeConstant); } /** @@ -559,99 +1466,90 @@ private function getFetchMode($className, $fetchMode) * * @return array */ - private function getMethodCallbacks(\ReflectionMethod $method) + private function getMethodCallbacks(\ReflectionMethod $method) : array { - $callbacks = []; - $annotations = $this->reader->getMethodAnnotations($method); - - foreach ($annotations as $annot) { - if ($annot instanceof Mapping\PrePersist) { - $callbacks[] = [$method->name, Events::prePersist]; - } - - if ($annot instanceof Mapping\PostPersist) { - $callbacks[] = [$method->name, Events::postPersist]; - } + $annotations = $this->getMethodAnnotations($method); + $events = [ + Events::prePersist => Annotation\PrePersist::class, + Events::postPersist => Annotation\PostPersist::class, + Events::preUpdate => Annotation\PreUpdate::class, + Events::postUpdate => Annotation\PostUpdate::class, + Events::preRemove => Annotation\PreRemove::class, + Events::postRemove => Annotation\PostRemove::class, + Events::postLoad => Annotation\PostLoad::class, + Events::preFlush => Annotation\PreFlush::class, + ]; - if ($annot instanceof Mapping\PreUpdate) { - $callbacks[] = [$method->name, Events::preUpdate]; - } + // Check for callbacks + $callbacks = []; - if ($annot instanceof Mapping\PostUpdate) { - $callbacks[] = [$method->name, Events::postUpdate]; + foreach ($events as $eventName => $annotationClassName) { + if (isset($annotations[$annotationClassName]) || $method->getName() === $eventName) { + $callbacks[] = $eventName; } + } - if ($annot instanceof Mapping\PreRemove) { - $callbacks[] = [$method->name, Events::preRemove]; - } + return $callbacks; + } - if ($annot instanceof Mapping\PostRemove) { - $callbacks[] = [$method->name, Events::postRemove]; - } + /** + * @param \ReflectionClass $reflectionClass + * + * @return array + */ + private function getClassAnnotations(\ReflectionClass $reflectionClass) : array + { + $classAnnotations = $this->reader->getClassAnnotations($reflectionClass); - if ($annot instanceof Mapping\PostLoad) { - $callbacks[] = [$method->name, Events::postLoad]; + foreach ($classAnnotations as $key => $annot) { + if (! is_numeric($key)) { + continue; } - if ($annot instanceof Mapping\PreFlush) { - $callbacks[] = [$method->name, Events::preFlush]; - } + $classAnnotations[get_class($annot)] = $annot; } - return $callbacks; + return $classAnnotations; } /** - * Parse the given JoinColumn as array + * @param \ReflectionProperty $reflectionProperty * - * @param Mapping\JoinColumn $joinColumn * @return array */ - private function joinColumnToArray(Mapping\JoinColumn $joinColumn) + private function getPropertyAnnotations(\ReflectionProperty $reflectionProperty) : array { - return [ - 'name' => $joinColumn->name, - 'unique' => $joinColumn->unique, - 'nullable' => $joinColumn->nullable, - 'onDelete' => $joinColumn->onDelete, - 'columnDefinition' => $joinColumn->columnDefinition, - 'referencedColumnName' => $joinColumn->referencedColumnName, - ]; + $propertyAnnotations = $this->reader->getPropertyAnnotations($reflectionProperty); + + foreach ($propertyAnnotations as $key => $annot) { + if (! is_numeric($key)) { + continue; + } + + $propertyAnnotations[get_class($annot)] = $annot; + } + + return $propertyAnnotations; } /** - * Parse the given Column as array - * - * @param string $fieldName - * @param Mapping\Column $column + * @param \ReflectionMethod $reflectionMethod * * @return array */ - private function columnToArray($fieldName, Mapping\Column $column) + private function getMethodAnnotations(\ReflectionMethod $reflectionMethod) : array { - $mapping = [ - 'fieldName' => $fieldName, - 'type' => $column->type, - 'scale' => $column->scale, - 'length' => $column->length, - 'unique' => $column->unique, - 'nullable' => $column->nullable, - 'precision' => $column->precision - ]; - - if ($column->options) { - $mapping['options'] = $column->options; - } + $methodAnnotations = $this->reader->getMethodAnnotations($reflectionMethod); - if (isset($column->name)) { - $mapping['columnName'] = $column->name; - } + foreach ($methodAnnotations as $key => $annot) { + if (! is_numeric($key)) { + continue; + } - if (isset($column->columnDefinition)) { - $mapping['columnDefinition'] = $column->columnDefinition; + $methodAnnotations[get_class($annot)] = $annot; } - return $mapping; + return $methodAnnotations; } /** diff --git a/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php b/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php index 756399f6d43..c2d13340d68 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php +++ b/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php @@ -1,34 +1,17 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Mapping\Driver; -use Doctrine\Common\Persistence\Mapping\Driver\MappingDriver; -use Doctrine\Common\Persistence\Mapping\ClassMetadata; use Doctrine\Common\Util\Inflector; use Doctrine\DBAL\Schema\AbstractSchemaManager; +use Doctrine\DBAL\Schema\Index; use Doctrine\DBAL\Schema\SchemaException; use Doctrine\DBAL\Schema\Table; use Doctrine\DBAL\Schema\Column; use Doctrine\DBAL\Types\Type; -use Doctrine\ORM\Mapping\ClassMetadataInfo; -use Doctrine\ORM\Mapping\MappingException; +use Doctrine\ORM\Mapping; /** * The DatabaseDriver reverse engineers the mapping metadata from a database. @@ -44,7 +27,7 @@ class DatabaseDriver implements MappingDriver /** * @var AbstractSchemaManager */ - private $_sm; + private $sm; /** * @var array|null @@ -83,7 +66,7 @@ class DatabaseDriver implements MappingDriver */ public function __construct(AbstractSchemaManager $schemaManager) { - $this->_sm = $schemaManager; + $this->sm = $schemaManager; } /** @@ -170,7 +153,11 @@ public function setTables($entityTables, $manyToManyTables) /** * {@inheritDoc} */ - public function loadMetadataForClass($className, ClassMetadata $metadata) + public function loadMetadataForClass( + string $className, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) { $this->reverseEngineerMappingFromDatabase(); @@ -178,28 +165,29 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) throw new \InvalidArgumentException("Unknown class " . $className); } - $tableName = $this->classToTableNames[$className]; - - $metadata->name = $className; - $metadata->table['name'] = $tableName; + // @todo guilhermeblanco This should somehow disappear... =) + $metadata->setClassName($className); - $this->buildIndexes($metadata); + $this->buildTable($metadata); $this->buildFieldMappings($metadata); $this->buildToOneAssociationMappings($metadata); + $loweredTableName = strtolower($metadata->getTableName()); + foreach ($this->manyToManyTables as $manyTable) { foreach ($manyTable->getForeignKeys() as $foreignKey) { // foreign key maps to the table of the current entity, many to many association probably exists - if ( ! (strtolower($tableName) === strtolower($foreignKey->getForeignTableName()))) { + if ( ! ($loweredTableName === strtolower($foreignKey->getForeignTableName()))) { continue; } $myFk = $foreignKey; $otherFk = null; - foreach ($manyTable->getForeignKeys() as $foreignKey) { - if ($foreignKey != $myFk) { - $otherFk = $foreignKey; + foreach ($manyTable->getForeignKeys() as $manyTableForeignKey) { + if ($manyTableForeignKey !== $myFk) { + $otherFk = $manyTableForeignKey; + break; } } @@ -216,38 +204,41 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $associationMapping['fieldName'] = $this->getFieldNameForColumn($manyTable->getName(), current($otherFk->getColumns()), true); $associationMapping['targetEntity'] = $this->getClassNameForTable($otherFk->getForeignTableName()); - if (current($manyTable->getColumns())->getName() == $localColumn) { + if (current($manyTable->getColumns())->getName() === $localColumn) { $associationMapping['inversedBy'] = $this->getFieldNameForColumn($manyTable->getName(), current($myFk->getColumns()), true); - $associationMapping['joinTable'] = [ - 'name' => strtolower($manyTable->getName()), - 'joinColumns' => [], - 'inverseJoinColumns' => [], - ]; + $associationMapping['joinTable'] = new Mapping\JoinTableMetadata(); + + $joinTable = $associationMapping['joinTable']; + $joinTable->setName(strtolower($manyTable->getName())); $fkCols = $myFk->getForeignColumns(); - $cols = $myFk->getColumns(); + $cols = $myFk->getColumns(); - for ($i = 0, $colsCount = count($cols); $i < $colsCount; $i++) { - $associationMapping['joinTable']['joinColumns'][] = [ - 'name' => $cols[$i], - 'referencedColumnName' => $fkCols[$i], - ]; + for ($i = 0, $l = count($cols); $i < $l; $i++) { + $joinColumn = new Mapping\JoinColumnMetadata(); + + $joinColumn->setColumnName($cols[$i]); + $joinColumn->setReferencedColumnName($fkCols[$i]); + + $joinTable->addJoinColumn($joinColumn); } $fkCols = $otherFk->getForeignColumns(); $cols = $otherFk->getColumns(); - for ($i = 0, $colsCount = count($cols); $i < $colsCount; $i++) { - $associationMapping['joinTable']['inverseJoinColumns'][] = [ - 'name' => $cols[$i], - 'referencedColumnName' => $fkCols[$i], - ]; + for ($i = 0, $l = count($cols); $i < $l; $i++) { + $joinColumn = new Mapping\JoinColumnMetadata(); + + $joinColumn->setColumnName($cols[$i]); + $joinColumn->setReferencedColumnName($fkCols[$i]); + + $joinTable->addInverseJoinColumn($joinColumn); } } else { $associationMapping['mappedBy'] = $this->getFieldNameForColumn($manyTable->getName(), current($myFk->getColumns()), true); } - $metadata->mapManyToMany($associationMapping); + $metadata->addProperty($associationMapping); break; } @@ -257,7 +248,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) /** * @return void * - * @throws \Doctrine\ORM\Mapping\MappingException + * @throws Mapping\MappingException */ private function reverseEngineerMappingFromDatabase() { @@ -267,14 +258,14 @@ private function reverseEngineerMappingFromDatabase() $tables = []; - foreach ($this->_sm->listTableNames() as $tableName) { - $tables[$tableName] = $this->_sm->listTableDetails($tableName); + foreach ($this->sm->listTableNames() as $tableName) { + $tables[$tableName] = $this->sm->listTableDetails($tableName); } $this->tables = $this->manyToManyTables = $this->classToTableNames = []; foreach ($tables as $tableName => $table) { - $foreignKeys = ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) + $foreignKeys = ($this->sm->getDatabasePlatform()->supportsForeignKeyConstraints()) ? $table->getForeignKeys() : []; @@ -285,7 +276,7 @@ private function reverseEngineerMappingFromDatabase() } if ( ! $table->hasPrimaryKey()) { - throw new MappingException( + throw new Mapping\MappingException( "Table " . $table->getName() . " has no primary key. Doctrine does not ". "support reverse engineering from tables that don't have a primary key." ); @@ -310,38 +301,44 @@ private function reverseEngineerMappingFromDatabase() } /** - * Build indexes from a class metadata. + * Build table from a class metadata. * - * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata + * @param Mapping\ClassMetadata $metadata */ - private function buildIndexes(ClassMetadataInfo $metadata) + private function buildTable(Mapping\ClassMetadata $metadata) { - $tableName = $metadata->table['name']; - $indexes = $this->tables[$tableName]->getIndexes(); + $tableName = $this->classToTableNames[$metadata->getClassName()]; + $indexes = $this->tables[$tableName]->getIndexes(); + $tableMetadata = new Mapping\TableMetadata(); + + $tableMetadata->setName($this->classToTableNames[$metadata->getClassName()]); foreach ($indexes as $index) { + /** @var Index $index */ if ($index->isPrimary()) { continue; } - $indexName = $index->getName(); - $indexColumns = $index->getColumns(); - $constraintType = $index->isUnique() - ? 'uniqueConstraints' - : 'indexes'; - - $metadata->table[$constraintType][$indexName]['columns'] = $indexColumns; + $tableMetadata->addIndex([ + 'name' => $index->getName(), + 'columns' => $index->getColumns(), + 'unique' => $index->isUnique(), + 'options' => $index->getOptions(), + 'flags' => $index->getFlags(), + ]); } + + $metadata->setTable($tableMetadata); } /** * Build field mapping from class metadata. * - * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata + * @param Mapping\ClassMetadata $metadata */ - private function buildFieldMappings(ClassMetadataInfo $metadata) + private function buildFieldMappings(Mapping\ClassMetadata $metadata) { - $tableName = $metadata->table['name']; + $tableName = $metadata->getTableName(); $columns = $this->tables[$tableName]->getColumns(); $primaryKeys = $this->getTablePrimaryKeys($this->tables[$tableName]); $foreignKeys = $this->getTableForeignKeys($this->tables[$tableName]); @@ -351,53 +348,51 @@ private function buildFieldMappings(ClassMetadataInfo $metadata) $allForeignKeys = array_merge($allForeignKeys, $foreignKey->getLocalColumns()); } - $ids = []; - $fieldMappings = []; + $ids = []; foreach ($columns as $column) { if (in_array($column->getName(), $allForeignKeys)) { continue; } - $fieldMapping = $this->buildFieldMapping($tableName, $column); + $fieldName = $this->getFieldNameForColumn($tableName, $column->getName(), false); + $fieldMetadata = $this->convertColumnAnnotationToFieldMetadata($tableName, $column, $fieldName); if ($primaryKeys && in_array($column->getName(), $primaryKeys)) { - $fieldMapping['id'] = true; - $ids[] = $fieldMapping; + $fieldMetadata->setPrimaryKey(true); + + $ids[] = $fieldMetadata; } - $fieldMappings[] = $fieldMapping; + $metadata->addProperty($fieldMetadata); } // We need to check for the columns here, because we might have associations as id as well. - if ($ids && count($primaryKeys) == 1) { - $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); - } - - foreach ($fieldMappings as $fieldMapping) { - $metadata->mapField($fieldMapping); + if ($ids && count($primaryKeys) === 1) { + $ids[0]->setValueGenerator(new Mapping\ValueGeneratorMetadata(Mapping\GeneratorType::AUTO)); } } /** - * Build field mapping from a schema column definition + * Parse the given Column as FieldMetadata * - * @param string $tableName - * @param \Doctrine\DBAL\Schema\Column $column + * @param string $tableName + * @param Column $column + * @param string $fieldName * - * @return array + * @return Mapping\FieldMetadata */ - private function buildFieldMapping($tableName, Column $column) + private function convertColumnAnnotationToFieldMetadata(string $tableName, Column $column, string $fieldName) { - $fieldMapping = [ - 'fieldName' => $this->getFieldNameForColumn($tableName, $column->getName(), false), - 'columnName' => $column->getName(), - 'type' => $column->getType()->getName(), - 'nullable' => ( ! $column->getNotnull()), - ]; + $options = []; + $fieldMetadata = new Mapping\FieldMetadata($fieldName); + + $fieldMetadata->setType($column->getType()); + $fieldMetadata->setTableName($tableName); + $fieldMetadata->setColumnName($column->getName()); // Type specific elements - switch ($fieldMapping['type']) { + switch ($column->getType()->getName()) { case Type::TARRAY: case Type::BLOB: case Type::GUID: @@ -406,44 +401,49 @@ private function buildFieldMapping($tableName, Column $column) case Type::SIMPLE_ARRAY: case Type::STRING: case Type::TEXT: - $fieldMapping['length'] = $column->getLength(); - $fieldMapping['options']['fixed'] = $column->getFixed(); + if ($column->getLength()) { + $fieldMetadata->setLength($column->getLength()); + } + + $options['fixed'] = $column->getFixed(); break; case Type::DECIMAL: case Type::FLOAT: - $fieldMapping['precision'] = $column->getPrecision(); - $fieldMapping['scale'] = $column->getScale(); + $fieldMetadata->setScale($column->getScale()); + $fieldMetadata->setPrecision($column->getPrecision()); break; case Type::INTEGER: case Type::BIGINT: case Type::SMALLINT: - $fieldMapping['options']['unsigned'] = $column->getUnsigned(); + $options['unsigned'] = $column->getUnsigned(); break; } // Comment if (($comment = $column->getComment()) !== null) { - $fieldMapping['options']['comment'] = $comment; + $options['comment'] = $comment; } // Default if (($default = $column->getDefault()) !== null) { - $fieldMapping['options']['default'] = $default; + $options['default'] = $default; } - return $fieldMapping; + $fieldMetadata->setOptions($options); + + return $fieldMetadata; } /** * Build to one (one to one, many to one) association mapping from class metadata. * - * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata + * @param Mapping\ClassMetadata $metadata */ - private function buildToOneAssociationMappings(ClassMetadataInfo $metadata) + private function buildToOneAssociationMappings(Mapping\ClassMetadata $metadata) { - $tableName = $metadata->table['name']; + $tableName = $metadata->getTableName(); $primaryKeys = $this->getTablePrimaryKeys($this->tables[$tableName]); $foreignKeys = $this->getTableForeignKeys($this->tables[$tableName]); @@ -457,7 +457,7 @@ private function buildToOneAssociationMappings(ClassMetadataInfo $metadata) 'targetEntity' => $this->getClassNameForTable($foreignTableName), ]; - if (isset($metadata->fieldMappings[$associationMapping['fieldName']])) { + if ($metadata->getProperty($associationMapping['fieldName'])) { $associationMapping['fieldName'] .= '2'; // "foo" => "foo2" } @@ -465,18 +465,20 @@ private function buildToOneAssociationMappings(ClassMetadataInfo $metadata) $associationMapping['id'] = true; } - for ($i = 0, $fkColumnsCount = count($fkColumns); $i < $fkColumnsCount; $i++) { - $associationMapping['joinColumns'][] = [ - 'name' => $fkColumns[$i], - 'referencedColumnName' => $fkForeignColumns[$i], - ]; + for ($i = 0, $l = count($fkColumns); $i < $l; $i++) { + $joinColumn = new Mapping\JoinColumnMetadata(); + + $joinColumn->setColumnName($fkColumns[$i]); + $joinColumn->setReferencedColumnName($fkForeignColumns[$i]); + + $associationMapping['joinColumns'][] = $joinColumn; } // Here we need to check if $fkColumns are the same as $primaryKeys if ( ! array_diff($fkColumns, $primaryKeys)) { - $metadata->mapOneToOne($associationMapping); + $metadata->addProperty($associationMapping); } else { - $metadata->mapManyToOne($associationMapping); + $metadata->addProperty($associationMapping); } } } @@ -490,7 +492,7 @@ private function buildToOneAssociationMappings(ClassMetadataInfo $metadata) */ private function getTableForeignKeys(Table $table) { - return ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) + return ($this->sm->getDatabasePlatform()->supportsForeignKeyConstraints()) ? $table->getForeignKeys() : []; } diff --git a/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php b/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php deleted file mode 100644 index 8f4a34c0ef4..00000000000 --- a/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php +++ /dev/null @@ -1,69 +0,0 @@ -. - */ - -require_once __DIR__.'/../Annotation.php'; -require_once __DIR__.'/../Entity.php'; -require_once __DIR__.'/../Embeddable.php'; -require_once __DIR__.'/../Embedded.php'; -require_once __DIR__.'/../MappedSuperclass.php'; -require_once __DIR__.'/../InheritanceType.php'; -require_once __DIR__.'/../DiscriminatorColumn.php'; -require_once __DIR__.'/../DiscriminatorMap.php'; -require_once __DIR__.'/../Id.php'; -require_once __DIR__.'/../GeneratedValue.php'; -require_once __DIR__.'/../Version.php'; -require_once __DIR__.'/../JoinColumn.php'; -require_once __DIR__.'/../JoinColumns.php'; -require_once __DIR__.'/../Column.php'; -require_once __DIR__.'/../OneToOne.php'; -require_once __DIR__.'/../OneToMany.php'; -require_once __DIR__.'/../ManyToOne.php'; -require_once __DIR__.'/../ManyToMany.php'; -require_once __DIR__.'/../Table.php'; -require_once __DIR__.'/../UniqueConstraint.php'; -require_once __DIR__.'/../Index.php'; -require_once __DIR__.'/../JoinTable.php'; -require_once __DIR__.'/../SequenceGenerator.php'; -require_once __DIR__.'/../CustomIdGenerator.php'; -require_once __DIR__.'/../ChangeTrackingPolicy.php'; -require_once __DIR__.'/../OrderBy.php'; -require_once __DIR__.'/../NamedQueries.php'; -require_once __DIR__.'/../NamedQuery.php'; -require_once __DIR__.'/../HasLifecycleCallbacks.php'; -require_once __DIR__.'/../PrePersist.php'; -require_once __DIR__.'/../PostPersist.php'; -require_once __DIR__.'/../PreUpdate.php'; -require_once __DIR__.'/../PostUpdate.php'; -require_once __DIR__.'/../PreRemove.php'; -require_once __DIR__.'/../PostRemove.php'; -require_once __DIR__.'/../PostLoad.php'; -require_once __DIR__.'/../PreFlush.php'; -require_once __DIR__.'/../FieldResult.php'; -require_once __DIR__.'/../ColumnResult.php'; -require_once __DIR__.'/../EntityResult.php'; -require_once __DIR__.'/../NamedNativeQuery.php'; -require_once __DIR__.'/../NamedNativeQueries.php'; -require_once __DIR__.'/../SqlResultSetMapping.php'; -require_once __DIR__.'/../SqlResultSetMappings.php'; -require_once __DIR__.'/../AssociationOverride.php'; -require_once __DIR__.'/../AssociationOverrides.php'; -require_once __DIR__.'/../AttributeOverride.php'; -require_once __DIR__.'/../AttributeOverrides.php'; -require_once __DIR__.'/../EntityListeners.php'; -require_once __DIR__.'/../Cache.php'; diff --git a/lib/Doctrine/ORM/Mapping/Driver/DriverChain.php b/lib/Doctrine/ORM/Mapping/Driver/DriverChain.php index f4cd8cd6081..848636ae90b 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/DriverChain.php +++ b/lib/Doctrine/ORM/Mapping/Driver/DriverChain.php @@ -1,4 +1,5 @@ . */ +declare(strict_types=1); + namespace Doctrine\ORM\Mapping\Driver; -use Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain; +use Doctrine\ORM\Mapping; /** - * {@inheritDoc} + * The DriverChain allows you to add multiple other mapping drivers for + * certain namespaces. * - * @deprecated this driver will be removed. Use Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain instead + * @since 2.2 + * @author Benjamin Eberlei + * @author Guilherme Blanco + * @author Jonathan H. Wage + * @author Roman Borschel */ -class DriverChain extends MappingDriverChain +class DriverChain implements MappingDriver { + /** + * The default driver. + * + * @var MappingDriver|null + */ + private $defaultDriver; + + /** + * @var array + */ + private $drivers = []; + + /** + * Gets the default driver. + * + * @return MappingDriver|null + */ + public function getDefaultDriver() + { + return $this->defaultDriver; + } + + /** + * Set the default driver. + * + * @param MappingDriver $driver + * + * @return void + */ + public function setDefaultDriver(MappingDriver $driver) + { + $this->defaultDriver = $driver; + } + + /** + * Adds a nested driver. + * + * @param MappingDriver $nestedDriver + * @param string $namespace + * + * @return void + */ + public function addDriver(MappingDriver $nestedDriver, $namespace) + { + $this->drivers[$namespace] = $nestedDriver; + } + + /** + * Gets the array of nested drivers. + * + * @return array $drivers + */ + public function getDrivers() + { + return $this->drivers; + } + + /** + * {@inheritDoc} + */ + public function loadMetadataForClass( + string $className, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) + { + /* @var $driver MappingDriver */ + foreach ($this->drivers as $namespace => $driver) { + if (strpos($className, $namespace) === 0) { + $driver->loadMetadataForClass($className, $metadata, $metadataBuildingContext); + return; + } + } + + if (null !== $this->defaultDriver) { + $this->defaultDriver->loadMetadataForClass($className, $metadata, $metadataBuildingContext); + return; + } + + throw Mapping\MappingException::classNotFoundInNamespaces($className, array_keys($this->drivers)); + } + + /** + * {@inheritDoc} + */ + public function getAllClassNames() + { + $classNames = []; + $driverClasses = []; + + /* @var $driver MappingDriver */ + foreach ($this->drivers AS $namespace => $driver) { + $oid = spl_object_hash($driver); + + if (!isset($driverClasses[$oid])) { + $driverClasses[$oid] = $driver->getAllClassNames(); + } + + foreach ($driverClasses[$oid] AS $className) { + if (strpos($className, $namespace) === 0) { + $classNames[$className] = true; + } + } + } + + if (null !== $this->defaultDriver) { + foreach ($this->defaultDriver->getAllClassNames() as $className) { + $classNames[$className] = true; + } + } + + return array_keys($classNames); + } + + /** + * {@inheritDoc} + */ + public function isTransient($className) + { + /* @var $driver MappingDriver */ + foreach ($this->drivers AS $namespace => $driver) { + if (strpos($className, $namespace) === 0) { + return $driver->isTransient($className); + } + } + + if ($this->defaultDriver !== null) { + return $this->defaultDriver->isTransient($className); + } + + return true; + } } diff --git a/lib/Doctrine/ORM/Mapping/Driver/FileDriver.php b/lib/Doctrine/ORM/Mapping/Driver/FileDriver.php new file mode 100644 index 00000000000..5811d9397e6 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Driver/FileDriver.php @@ -0,0 +1,203 @@ + + * @author Guilherme Blanco + * @author Jonathan H. Wage + * @author Roman Borschel + */ +abstract class FileDriver implements MappingDriver +{ + /** + * @var FileLocator + */ + protected $locator; + + /** + * @var array|null + */ + protected $classCache; + + /** + * @var string|null + */ + protected $globalBasename; + + /** + * Initializes a new FileDriver that looks in the given path(s) for mapping + * documents and operates in the specified operating mode. + * + * @param string|array|FileLocator $locator A FileLocator or one/multiple paths + * where mapping documents can be found. + * @param string|null $fileExtension + */ + public function __construct($locator, $fileExtension = null) + { + if ($locator instanceof FileLocator) { + $this->locator = $locator; + } else { + $this->locator = new DefaultFileLocator((array)$locator, $fileExtension); + } + } + + /** + * Retrieves the locator used to discover mapping files by className. + * + * @return FileLocator + */ + public function getLocator() + { + return $this->locator; + } + + /** + * Sets the locator used to discover mapping files by className. + * + * @param FileLocator $locator + */ + public function setLocator(FileLocator $locator) + { + $this->locator = $locator; + } + + /** + * Sets the global basename. + * + * @param string $file + * + * @return void + */ + public function setGlobalBasename($file) + { + $this->globalBasename = $file; + } + + /** + * Retrieves the global basename. + * + * @return string|null + */ + public function getGlobalBasename() + { + return $this->globalBasename; + } + + /** + * Gets the element of schema meta data for the class from the mapping file. + * This will lazily load the mapping file if it is not loaded yet. + * + * @param string $className + * + * @return array The element of schema meta data. + * + * @throws MappingException + */ + public function getElement($className) + { + if ($this->classCache === null) { + $this->initialize(); + } + + if (isset($this->classCache[$className])) { + return $this->classCache[$className]; + } + + $result = $this->loadMappingFile($this->locator->findMappingFile($className)); + if (!isset($result[$className])) { + throw MappingException::invalidMappingFile($className, str_replace('\\', '.', $className) . $this->locator->getFileExtension()); + } + + $this->classCache[$className] = $result[$className]; + + return $result[$className]; + } + + /** + * {@inheritDoc} + */ + public function isTransient($className) + { + if ($this->classCache === null) { + $this->initialize(); + } + + if (isset($this->classCache[$className])) { + return false; + } + + return !$this->locator->fileExists($className); + } + + /** + * {@inheritDoc} + */ + public function getAllClassNames() + { + if ($this->classCache === null) { + $this->initialize(); + } + + if (! $this->classCache) { + return (array) $this->locator->getAllClassNames($this->globalBasename); + } + + return array_merge( + array_keys($this->classCache), + (array) $this->locator->getAllClassNames($this->globalBasename) + ); + } + + /** + * Loads a mapping file with the given name and returns a map + * from class/entity names to their corresponding file driver elements. + * + * @param string $file The mapping file to load. + * + * @return array + */ + abstract protected function loadMappingFile($file); + + /** + * Initializes the class cache from all the global files. + * + * Using this feature adds a substantial performance hit to file drivers as + * more metadata has to be loaded into memory than might actually be + * necessary. This may not be relevant to scenarios where caching of + * metadata is in place, however hits very hard in scenarios where no + * caching is used. + * + * @return void + */ + protected function initialize() + { + $this->classCache = []; + if (null !== $this->globalBasename) { + foreach ($this->locator->getPaths() as $path) { + $file = $path.'/'.$this->globalBasename.$this->locator->getFileExtension(); + if (is_file($file)) { + $this->classCache = array_merge( + $this->classCache, + $this->loadMappingFile($file) + ); + } + } + } + } +} diff --git a/lib/Doctrine/ORM/Mapping/Driver/MappingDriver.php b/lib/Doctrine/ORM/Mapping/Driver/MappingDriver.php new file mode 100644 index 00000000000..89c55b1238d --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Driver/MappingDriver.php @@ -0,0 +1,52 @@ + + * @author Jonathan H. Wage + */ +interface MappingDriver +{ + /** + * Loads the metadata for the specified class into the provided container. + * + * @param string $className + * @param ClassMetadata $metadata + * @param ClassMetadataBuildingContext $metadataBuildingContext + * + * @return void + */ + public function loadMetadataForClass( + string $className, + ClassMetadata $metadata, // ComponentMetadata $parent + ClassMetadataBuildingContext $metadataBuildingContext + ); // : ComponentMetadata + + /** + * Gets the names of all mapped classes known to this driver. + * + * @return array The names of all mapped classes known to this driver. + */ + public function getAllClassNames(); + + /** + * Returns whether the class with the specified name should have its metadata loaded. + * This is only the case if it is either mapped as an Entity or a MappedSuperclass. + * + * @param string $className + * + * @return boolean + */ + public function isTransient($className); +} diff --git a/lib/Doctrine/ORM/Mapping/Driver/NewAnnotationDriver.php b/lib/Doctrine/ORM/Mapping/Driver/NewAnnotationDriver.php new file mode 100644 index 00000000000..562d3118569 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Driver/NewAnnotationDriver.php @@ -0,0 +1,1205 @@ + 1, + Annotation\MappedSuperclass::class => 2, + ]; + + /** + * The Annotation reader. + * + * @var AnnotationReader + */ + protected $reader; + + /** + * The file locator. + * + * @var FileLocator + */ + protected $locator; + + /** + * @var Factory\NamingStrategy + */ + protected $namingStrategy; + + /** + * Cache for AnnotationDriver#getAllClassNames(). + * + * @var array|null + */ + private $classNames; + + /** + * Initializes a new AnnotationDriver that uses the given AnnotationReader for reading docblock annotations. + * + * @param AnnotationReader $reader The AnnotationReader to use, duck-typed. + * @param FileLocator $locator A FileLocator or one/multiple paths where mapping documents can be found. + * @param Factory\NamingStrategy $namingStrategy The NamingStrategy to use. + */ + public function __construct(AnnotationReader $reader, FileLocator $locator, Factory\NamingStrategy $namingStrategy) + { + $this->reader = $reader; + $this->locator = $locator; + $this->namingStrategy = $namingStrategy; + } + + /** + * {@inheritdoc} + * + * @return Mapping\ClassMetadata + * + * @throws Mapping\MappingException + */ + public function loadMetadataForClass( + string $className, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) + { + // IMPORTANT: We're handling $metadata as "parent" metadata here, while building the $className ClassMetadata. + $reflectionClass = new \ReflectionClass($className); + + // Evaluate annotations on class metadata + $classAnnotations = $this->getClassAnnotations($reflectionClass); + $classMetadata = $this->convertClassAnnotationsToClassMetadata( + $classAnnotations, + $reflectionClass, + $metadata + ); + + // Evaluate @Cache annotation + if (isset($classAnnotations[Annotation\Cache::class])) { + $cacheAnnot = $classAnnotations[Annotation\Cache::class]; + $cache = $this->convertCacheAnnotationToCacheMetadata($cacheAnnot, $classMetadata); + + $classMetadata->setCache($cache); + } + + // Evaluate annotations on properties/fields + /* @var \ReflectionProperty $reflectionProperty */ + foreach ($reflectionClass->getProperties() as $reflectionProperty) { + if ($reflectionProperty->getDeclaringClass()->getClassName() !== $reflectionClass->getName()) { + continue; + } + + $propertyAnnotations = $this->getPropertyAnnotations($reflectionProperty); + $property = $this->convertReflectionPropertyAnnotationsToProperty( + $reflectionProperty, + $propertyAnnotations, + $classMetadata + ); + + $classMetadata->addDeclaredProperty($property); + } + + return $classMetadata; + } + + /** + * {@inheritdoc} + */ + public function getAllClassNames() + { + if ($this->classNames !== null) { + return $this->classNames; + } + + $classNames = array_filter( + $this->locator->getAllClassNames(null), + function ($className) { + return ! $this->isTransient($className); + } + ); + + $this->classNames = $classNames; + + return $classNames; + } + + /** + * {@inheritdoc} + */ + public function isTransient($className) + { + $reflectionClass = new \ReflectionClass($className); + $classAnnotations = $this->reader->getClassAnnotations($reflectionClass); + + foreach ($classAnnotations as $annotation) { + if (isset(self::$entityAnnotationClasses[get_class($annotation)])) { + return false; + } + } + + return true; + } + + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $parent + * + * @return Mapping\ClassMetadata|Mapping\ComponentMetadata + * + * @throws Mapping\MappingException + */ + private function convertClassAnnotationsToClassMetadata( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $parent + ) + { + switch (true) { + case isset($classAnnotations[Annotation\Entity::class]): + return $this->convertClassAnnotationsToEntityClassMetadata( + $classAnnotations, + $reflectionClass, + $parent + ); + + break; + + case isset($classAnnotations[Annotation\MappedSuperclass::class]): + return $this->convertClassAnnotationsToMappedSuperClassMetadata( + $classAnnotations, + $reflectionClass, + $parent + ); + + case isset($classAnnotations[Annotation\Embeddable::class]): + return $this->convertClassAnnotationsToEntityClassMetadata( + $classAnnotations, + $reflectionClass, + $parent + ); + + default: + throw Mapping\MappingException::classIsNotAValidEntityOrMappedSuperClass($reflectionClass->getName()); + } + } + + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $parent + * + * @return Mapping\ClassMetadata + * + * @throws Mapping\MappingException + * @throws \UnexpectedValueException + */ + private function convertClassAnnotationsToEntityClassMetadata( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $parent + ) + { + /** @var Annotation\Entity $entityAnnot */ + $entityAnnot = $classAnnotations[Annotation\Entity::class]; + $classMetadata = new Mapping\ClassMetadata($reflectionClass->getName(), $parent); + + if ($entityAnnot->repositoryClass !== null) { + $classMetadata->setCustomRepositoryClassName( + $classMetadata->fullyQualifiedClassName($entityAnnot->repositoryClass) + ); + } + + if ($entityAnnot->readOnly) { + $classMetadata->asReadOnly(); + } + + // Evaluate @Table annotation + if (isset($classAnnotations[Annotation\Table::class])) { + /** @var Annotation\Table $tableAnnot */ + $tableAnnot = $classAnnotations[Annotation\Table::class]; + $table = $this->convertTableAnnotationToTableMetadata($tableAnnot); + + $classMetadata->setTable($table); + } + + // Evaluate @ChangeTrackingPolicy annotation + if (isset($classAnnotations[Annotation\ChangeTrackingPolicy::class])) { + /** @var Annotation\ChangeTrackingPolicy $changeTrackingAnnot */ + $changeTrackingAnnot = $classAnnotations[Annotation\ChangeTrackingPolicy::class]; + + $classMetadata->setChangeTrackingPolicy( + constant(sprintf('%s::%s', Mapping\ChangeTrackingPolicy::class, $changeTrackingAnnot->value)) + ); + } + + // Evaluate @NamedNativeQueries annotation + if (isset($classAnnotations[Annotation\NamedNativeQueries::class])) { + /** @var Annotation\NamedNativeQueries $namedNativeQueriesAnnot */ + $namedNativeQueriesAnnot = $classAnnotations[Annotation\NamedNativeQueries::class]; + + foreach ($namedNativeQueriesAnnot->value as $namedNativeQuery) { + $classMetadata->addNamedNativeQuery( + $namedNativeQuery->name, + $namedNativeQuery->query, + [ + 'resultClass' => $namedNativeQuery->resultClass, + 'resultSetMapping' => $namedNativeQuery->resultSetMapping, + ] + ); + } + } + + // Evaluate @SqlResultSetMappings annotation + if (isset($classAnnotations[Annotation\SqlResultSetMappings::class])) { + /** @var Annotation\SqlResultSetMappings $sqlResultSetMappingsAnnot */ + $sqlResultSetMappingsAnnot = $classAnnotations[Annotation\SqlResultSetMappings::class]; + + foreach ($sqlResultSetMappingsAnnot->value as $resultSetMapping) { + $sqlResultSetMapping = $this->convertSqlResultSetMapping($resultSetMapping); + + $classMetadata->addSqlResultSetMapping($sqlResultSetMapping); + } + } + + // Evaluate @NamedQueries annotation + if (isset($classAnnotations[Annotation\NamedQueries::class])) { + /** @var Annotation\NamedQueries $namedQueriesAnnot */ + $namedQueriesAnnot = $classAnnotations[Annotation\NamedQueries::class]; + + if (! is_array($namedQueriesAnnot->value)) { + throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); + } + + foreach ($namedQueriesAnnot->value as $namedQuery) { + if (! ($namedQuery instanceof Annotation\NamedQuery)) { + throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); + } + + $classMetadata->addNamedQuery($namedQuery->name, $namedQuery->query); + } + } + + // Evaluate @EntityListeners annotation + if (isset($classAnnotations[Annotation\EntityListeners::class])) { + /** @var Annotation\EntityListeners $entityListenersAnnot */ + $entityListenersAnnot = $classAnnotations[Annotation\EntityListeners::class]; + + foreach ($entityListenersAnnot->value as $item) { + $listenerClassName = $classMetadata->fullyQualifiedClassName($item); + + if (! class_exists($listenerClassName)) { + throw Mapping\MappingException::entityListenerClassNotFound( + $listenerClassName, + $reflectionClass->getName() + ); + } + + $listenerClass = new \ReflectionClass($listenerClassName); + + /* @var $method \ReflectionMethod */ + foreach ($listenerClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { + foreach ($this->getMethodCallbacks($method) as $callback) { + $classMetadata->addEntityListener($callback, $listenerClassName, $method->getName()); + } + } + } + } + + // Evaluate @HasLifecycleCallbacks annotation + if (isset($classAnnotations[Annotation\HasLifecycleCallbacks::class])) { + /* @var $method \ReflectionMethod */ + foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { + foreach ($this->getMethodCallbacks($method) as $callback) { + $classMetadata->addLifecycleCallback($method->getName(), $callback); + } + } + } + + // Evaluate @InheritanceType annotation + if (isset($classAnnotations[Annotation\InheritanceType::class])) { + /** @var Annotation\InheritanceType $inheritanceTypeAnnot */ + $inheritanceTypeAnnot = $classAnnotations[Annotation\InheritanceType::class]; + + $classMetadata->setInheritanceType( + constant(sprintf('%s::%s', Mapping\InheritanceType::class, $inheritanceTypeAnnot->value)) + ); + + if ($classMetadata->inheritanceType !== Mapping\InheritanceType::NONE) { + $discriminatorColumn = new Mapping\DiscriminatorColumnMetadata(); + + // Evaluate @DiscriminatorColumn annotation + if (isset($classAnnotations[Annotation\DiscriminatorColumn::class])) { + /** @var Annotation\DiscriminatorColumn $discriminatorColumnAnnot */ + $discriminatorColumnAnnot = $classAnnotations[Annotation\DiscriminatorColumn::class]; + + $discriminatorColumn->setColumnName($discriminatorColumnAnnot->name); + + if (! empty($discriminatorColumnAnnot->columnDefinition)) { + $discriminatorColumn->setColumnDefinition($discriminatorColumnAnnot->columnDefinition); + } + + if (! empty($discriminatorColumnAnnot->type)) { + $discriminatorColumn->setType(Type::getType($discriminatorColumnAnnot->type)); + } + + if (! empty($discriminatorColumnAnnot->length)) { + $discriminatorColumn->setLength($discriminatorColumnAnnot->length); + } + } + + if (empty($discriminatorColumn->getColumnName())) { + throw Mapping\MappingException::nameIsMandatoryForDiscriminatorColumns($reflectionClass->getName()); + } + + $classMetadata->setDiscriminatorColumn($discriminatorColumn); + + // Evaluate @DiscriminatorMap annotation + if (isset($classAnnotations[Annotation\DiscriminatorMap::class])) { + /** @var Annotation\DiscriminatorMap $discriminatorMapAnnotation */ + $discriminatorMapAnnotation = $classAnnotations[Annotation\DiscriminatorMap::class]; + $discriminatorMap = array_map( + function ($className) use ($classMetadata) { + return $classMetadata->fullyQualifiedClassName($className); + }, + $discriminatorMapAnnotation->value + ); + + $classMetadata->setDiscriminatorMap($discriminatorMap); + } + } + } + + return $classMetadata; + } + + /** + * @param array $classAnnotations + * @param \ReflectionClass $reflectionClass + * @param Mapping\ClassMetadata $parent + * + * @return Mapping\MappedSuperClassMetadata + */ + private function convertClassAnnotationsToMappedSuperClassMetadata( + array $classAnnotations, + \ReflectionClass $reflectionClass, + Mapping\ClassMetadata $parent + ) + { + /** @var Annotation\MappedSuperclass $mappedSuperclassAnnot */ + $mappedSuperclassAnnot = $classAnnotations[Annotation\MappedSuperclass::class]; + $classMetadata = new Mapping\MappedSuperClassMetadata($reflectionClass->getName(), $parent); + + if ($mappedSuperclassAnnot->repositoryClass !== null) { + $classMetadata->setCustomRepositoryClassName( + $classMetadata->fullyQualifiedClassName($mappedSuperclassAnnot->repositoryClass) + ); + } + + return $classMetadata; + } + + /** + * Parse the given Table as TableMetadata + * + * @param Annotation\Table $tableAnnot + * + * @return Mapping\TableMetadata + */ + private function convertTableAnnotationToTableMetadata(Annotation\Table $tableAnnot) + { + $table = new Mapping\TableMetadata(); + + if (! empty($tableAnnot->name)) { + $table->setName($tableAnnot->name); + } + + if (! empty($tableAnnot->schema)) { + $table->setSchema($tableAnnot->schema); + } + + foreach ($tableAnnot->options as $optionName => $optionValue) { + $table->addOption($optionName, $optionValue); + } + + foreach ($tableAnnot->indexes as $indexAnnot) { + $table->addIndex([ + 'name' => $indexAnnot->name, + 'columns' => $indexAnnot->columns, + 'unique' => $indexAnnot->unique, + 'options' => $indexAnnot->options, + 'flags' => $indexAnnot->flags, + ]); + } + + foreach ($tableAnnot->uniqueConstraints as $uniqueConstraintAnnot) { + $table->addUniqueConstraint([ + 'name' => $uniqueConstraintAnnot->name, + 'columns' => $uniqueConstraintAnnot->columns, + 'options' => $uniqueConstraintAnnot->options, + 'flags' => $uniqueConstraintAnnot->flags, + ]); + } + + return $table; + } + + /** + * @param Annotation\SqlResultSetMapping $resultSetMapping + * + * @return array + */ + private function convertSqlResultSetMapping(Annotation\SqlResultSetMapping $resultSetMapping) + { + $entities = []; + + foreach ($resultSetMapping->entities as $entityResultAnnot) { + $entityResult = [ + 'fields' => [], + 'entityClass' => $entityResultAnnot->entityClass, + 'discriminatorColumn' => $entityResultAnnot->discriminatorColumn, + ]; + + foreach ($entityResultAnnot->fields as $fieldResultAnnot) { + $entityResult['fields'][] = [ + 'name' => $fieldResultAnnot->name, + 'column' => $fieldResultAnnot->column + ]; + } + + $entities[] = $entityResult; + } + + $columns = []; + + foreach ($resultSetMapping->columns as $columnResultAnnot) { + $columns[] = [ + 'name' => $columnResultAnnot->name, + ]; + } + + return [ + 'name' => $resultSetMapping->name, + 'entities' => $entities, + 'columns' => $columns + ]; + } + + /** + * Parse the given Cache as CacheMetadata + * + * @param Annotation\Cache $cacheAnnot + * @param Mapping\ClassMetadata $metadata + * @param null|string $fieldName + * + * @return Mapping\CacheMetadata + */ + private function convertCacheAnnotationToCacheMetadata( + Annotation\Cache $cacheAnnot, + Mapping\ClassMetadata $metadata, + $fieldName = null + ) + { + $usage = constant(sprintf('%s::%s', Mapping\CacheUsage::class, $cacheAnnot->usage)); + $baseRegion = strtolower(str_replace('\\', '_', $metadata->getRootClassName())); + $defaultRegion = $baseRegion . ($fieldName ? '__' . $fieldName : ''); + + return new Mapping\CacheMetadata($usage, $cacheAnnot->region ?: $defaultRegion); + } + + /** + * @param \ReflectionProperty $reflectionProperty + * @param array $propertyAnnotations + * @param Mapping\ClassMetadata $classMetadata + * + * @return Mapping\Property + * + * @throws Mapping\MappingException + */ + private function convertReflectionPropertyAnnotationsToProperty( + \ReflectionProperty $reflectionProperty, + array $propertyAnnotations, + Mapping\ClassMetadata $classMetadata + ) + { + // Field can only be annotated with one of: + // @Column, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany, @Embedded + switch (true) { + case isset($propertyAnnotations[Annotation\Column::class]): + return $this->convertReflectionPropertyToFieldMetadata( + $reflectionProperty, + $propertyAnnotations, + $classMetadata + ); + + case isset($propertyAnnotations[Annotation\OneToOne::class]): + return $this->convertReflectionPropertyToOneToOneAssociationMetadata( + $reflectionProperty, + $propertyAnnotations, + $classMetadata + ); + + case isset($propertyAnnotations[Annotation\ManyToOne::class]): + return $this->convertReflectionPropertyToManyToOneAssociationMetadata( + $reflectionProperty, + $propertyAnnotations, + $classMetadata + ); + + case isset($propertyAnnotations[Annotation\OneToMany::class]): + return $this->convertReflectionPropertyToOneToManyAssociationMetadata( + $reflectionProperty, + $propertyAnnotations, + $classMetadata + ); + + case isset($propertyAnnotations[Annotation\ManyToMany::class]): + return $this->convertReflectionPropertyToManyToManyAssociationMetadata( + $reflectionProperty, + $propertyAnnotations, + $classMetadata + ); + + case isset($propertyAnnotations[Annotation\Embedded::class]): + // @todo guilhermeblanco Implement later... =) + break; + + default: + return new Mapping\TransientMetadata($reflectionProperty->getName()); + } + } + + /** + * @param \ReflectionProperty $reflectionProperty + * @param array $propertyAnnotations + * @param Mapping\ClassMetadata $classMetadata + * + * @return Mapping\FieldMetadata + * + * @throws Mapping\MappingException + */ + private function convertReflectionPropertyToFieldMetadata( + \ReflectionProperty $reflectionProperty, + array $propertyAnnotations, + Mapping\ClassMetadata $classMetadata + ) + { + $className = $classMetadata->getClassName(); + $fieldName = $reflectionProperty->getName(); + $columnAnnot = $propertyAnnotations[Annotation\Column::class]; + $isVersioned = isset($propertyAnnotations[Annotation\Version::class]); + $isPrimaryKey = isset($propertyAnnotations[Annotation\Id::class]); + + if ($columnAnnot->type === null) { + throw Mapping\MappingException::propertyTypeIsRequired($className, $fieldName); + } + + if ($isVersioned && $isPrimaryKey) { + throw Mapping\MappingException::cannotVersionIdField($className, $fieldName); + } + + $columnName = empty($columnAnnot->name) + ? $this->namingStrategy->propertyToColumnName($fieldName, $className) + : $columnAnnot->name + ; + + $fieldMetadata = $isVersioned + ? new Mapping\VersionFieldMetadata($fieldName) + : new Mapping\FieldMetadata($fieldName) + ; + + $fieldMetadata->setType(Type::getType($columnAnnot->type)); + $fieldMetadata->setColumnName($columnName); + $fieldMetadata->setScale($columnAnnot->scale); + $fieldMetadata->setPrecision($columnAnnot->precision); + $fieldMetadata->setNullable($columnAnnot->nullable); + $fieldMetadata->setUnique($columnAnnot->unique); + + // Check for Id + if ($isPrimaryKey) { + if ($fieldMetadata->getType()->canRequireSQLConversion()) { + throw Mapping\MappingException::sqlConversionNotAllowedForPrimaryKeyProperties($className, $fieldMetadata); + }; + + $fieldMetadata->setPrimaryKey(true); + } + + if (! empty($columnAnnot->columnDefinition)) { + $fieldMetadata->setColumnDefinition($columnAnnot->columnDefinition); + } + + if (! empty($columnAnnot->length)) { + $fieldMetadata->setLength($columnAnnot->length); + } + + // Assign default options + $customOptions = $columnAnnot->options ?? []; + $defaultOptions = []; + + if ($isVersioned) { + switch ($fieldMetadata->getTypeName()) { + case 'integer': + case 'bigint': + case 'smallint': + $defaultOptions['default'] = 1; + break; + + case 'datetime': + $defaultOptions['default'] = 'CURRENT_TIMESTAMP'; + break; + + default: + if (! isset($customOptions['default'])) { + throw Mapping\MappingException::unsupportedOptimisticLockingType($fieldMetadata->getType()); + } + } + } + + $fieldMetadata->setOptions(array_merge($defaultOptions, $customOptions)); + + return $fieldMetadata; + } + + /** + * @param \ReflectionProperty $reflectionProperty + * @param array $propertyAnnotations + * @param Mapping\ClassMetadata $classMetadata + * + * @return Mapping\OneToOneAssociationMetadata + */ + private function convertReflectionPropertyToOneToOneAssociationMetadata( + \ReflectionProperty $reflectionProperty, + array $propertyAnnotations, + Mapping\ClassMetadata $classMetadata + ) + { + $className = $classMetadata->getClassName(); + $fieldName = $reflectionProperty->getName(); + $oneToOneAnnot = $propertyAnnotations[Annotation\OneToOne::class]; + + if ($oneToOneAnnot->targetEntity === null) { + throw Mapping\MappingException::missingTargetEntity($fieldName); + } + + $assocMetadata = new Mapping\OneToOneAssociationMetadata($fieldName); + $targetEntity = $classMetadata->fullyQualifiedClassName($oneToOneAnnot->targetEntity); + + $assocMetadata->setSourceEntity($className); + $assocMetadata->setTargetEntity($targetEntity); + $assocMetadata->setCascade($this->getCascade($className, $fieldName, $oneToOneAnnot->cascade)); + $assocMetadata->setOrphanRemoval($oneToOneAnnot->orphanRemoval); + $assocMetadata->setFetchMode($this->getFetchMode($className, $oneToOneAnnot->fetch)); + + if (! empty($oneToOneAnnot->mappedBy)) { + $assocMetadata->setMappedBy($oneToOneAnnot->mappedBy); + } + + if (! empty($oneToOneAnnot->inversedBy)) { + $assocMetadata->setInversedBy($oneToOneAnnot->inversedBy); + } + + // Check for Id + if (isset($propertyAnnotations[Annotation\Id::class])) { + $assocMetadata->setPrimaryKey(true); + } + + // Check for Cache + if (isset($propertyAnnotations[Annotation\Cache::class])) { + $cacheAnnot = $propertyAnnotations[Annotation\Cache::class]; + $cacheMetadata = $this->convertCacheAnnotationToCacheMetadata($cacheAnnot, $classMetadata, $fieldName); + + $assocMetadata->setCache($cacheMetadata); + } + + // Check for JoinColumn/JoinColumns annotations + switch (true) { + case isset($propertyAnnotations[Annotation\JoinColumn::class]): + $joinColumnAnnot = $propertyAnnotations[Annotation\JoinColumn::class]; + $joinColumn = $this->convertJoinColumnAnnotationToJoinColumnMetadata( + $reflectionProperty, + $joinColumnAnnot, + $classMetadata + ); + + $assocMetadata->addJoinColumn($joinColumn); + + break; + + case isset($propertyAnnotations[Annotation\JoinColumns::class]): + $joinColumnsAnnot = $propertyAnnotations[Annotation\JoinColumns::class]; + + foreach ($joinColumnsAnnot->value as $joinColumnAnnot) { + $joinColumn = $this->convertJoinColumnAnnotationToJoinColumnMetadata( + $reflectionProperty, + $joinColumnAnnot, + $classMetadata + ); + + $assocMetadata->addJoinColumn($joinColumn); + } + + break; + } + + return $assocMetadata; + } + + /** + * @param \ReflectionProperty $reflectionProperty + * @param array $propertyAnnotations + * @param Mapping\ClassMetadata $classMetadata + * + * @return Mapping\ManyToOneAssociationMetadata + */ + private function convertReflectionPropertyToManyToOneAssociationMetadata( + \ReflectionProperty $reflectionProperty, + array $propertyAnnotations, + Mapping\ClassMetadata $classMetadata + ) + { + $className = $classMetadata->getClassName(); + $fieldName = $reflectionProperty->getName(); + $manyToOneAnnot = $propertyAnnotations[Annotation\ManyToOne::class]; + + if ($manyToOneAnnot->targetEntity === null) { + throw Mapping\MappingException::missingTargetEntity($fieldName); + } + + $assocMetadata = new Mapping\ManyToOneAssociationMetadata($fieldName); + $targetEntity = $classMetadata->fullyQualifiedClassName($manyToOneAnnot->targetEntity); + + $assocMetadata->setSourceEntity($className); + $assocMetadata->setTargetEntity($targetEntity); + $assocMetadata->setCascade($this->getCascade($className, $fieldName, $manyToOneAnnot->cascade)); + $assocMetadata->setFetchMode($this->getFetchMode($className, $manyToOneAnnot->fetch)); + + if (! empty($manyToOneAnnot->inversedBy)) { + $assocMetadata->setInversedBy($manyToOneAnnot->inversedBy); + } + + // Check for Id + if (isset($propertyAnnotations[Annotation\Id::class])) { + $assocMetadata->setPrimaryKey(true); + } + + // Check for Cache + if (isset($propertyAnnotations[Annotation\Cache::class])) { + $cacheAnnot = $propertyAnnotations[Annotation\Cache::class]; + $cacheMetadata = $this->convertCacheAnnotationToCacheMetadata($cacheAnnot, $classMetadata, $fieldName); + + $assocMetadata->setCache($cacheMetadata); + } + + // Check for JoinColumn/JoinColumns annotations + switch (true) { + case isset($propertyAnnotations[Annotation\JoinColumn::class]): + $joinColumnAnnot = $propertyAnnotations[Annotation\JoinColumn::class]; + $joinColumn = $this->convertJoinColumnAnnotationToJoinColumnMetadata( + $reflectionProperty, + $joinColumnAnnot, + $classMetadata + ); + + $assocMetadata->addJoinColumn($joinColumn); + + break; + + case isset($propertyAnnotations[Annotation\JoinColumns::class]): + $joinColumnsAnnot = $propertyAnnotations[Annotation\JoinColumns::class]; + + foreach ($joinColumnsAnnot->value as $joinColumnAnnot) { + $joinColumn = $this->convertJoinColumnAnnotationToJoinColumnMetadata( + $reflectionProperty, + $joinColumnAnnot, + $classMetadata + ); + + $assocMetadata->addJoinColumn($joinColumn); + } + + break; + } + + return $assocMetadata; + } + + /** + * @param \ReflectionProperty $reflectionProperty + * @param array $propertyAnnotations + * @param Mapping\ClassMetadata $classMetadata + * + * @return Mapping\OneToManyAssociationMetadata + */ + private function convertReflectionPropertyToOneToManyAssociationMetadata( + \ReflectionProperty $reflectionProperty, + array $propertyAnnotations, + Mapping\ClassMetadata $classMetadata + ) + { + $className = $classMetadata->getClassName(); + $fieldName = $reflectionProperty->getName(); + $oneToManyAnnot = $propertyAnnotations[Annotation\OneToMany::class]; + + if ($oneToManyAnnot->targetEntity === null) { + throw Mapping\MappingException::missingTargetEntity($fieldName); + } + + $assocMetadata = new Mapping\OneToManyAssociationMetadata($fieldName); + $targetEntity = $classMetadata->fullyQualifiedClassName($oneToManyAnnot->targetEntity); + + $assocMetadata->setSourceEntity($className); + $assocMetadata->setTargetEntity($targetEntity); + $assocMetadata->setCascade($this->getCascade($className, $fieldName, $oneToManyAnnot->cascade)); + $assocMetadata->setOrphanRemoval($oneToManyAnnot->orphanRemoval); + $assocMetadata->setFetchMode($this->getFetchMode($className, $oneToManyAnnot->fetch)); + + if (! empty($oneToManyAnnot->mappedBy)) { + $assocMetadata->setMappedBy($oneToManyAnnot->mappedBy); + } + + if (! empty($oneToManyAnnot->indexBy)) { + $assocMetadata->setIndexedBy($oneToManyAnnot->indexBy); + } + + // Check for OrderBy + if (isset($propertyAnnotations[Annotation\OrderBy::class])) { + $orderByAnnot = $propertyAnnotations[Annotation\OrderBy::class]; + + $assocMetadata->setOrderBy($orderByAnnot->value); + } + + // Check for Id + if (isset($propertyAnnotations[Annotation\Id::class])) { + $assocMetadata->setPrimaryKey(true); + } + + // Check for Cache + if (isset($propertyAnnotations[Annotation\Cache::class])) { + $cacheAnnot = $propertyAnnotations[Annotation\Cache::class]; + $cacheMetadata = $this->convertCacheAnnotationToCacheMetadata($cacheAnnot, $classMetadata, $fieldName); + + $assocMetadata->setCache($cacheMetadata); + } + + return $assocMetadata; + } + + /** + * @param \ReflectionProperty $reflectionProperty + * @param array $propertyAnnotations + * @param Mapping\ClassMetadata $classMetadata + * + * @return Mapping\ManyToManyAssociationMetadata + */ + private function convertReflectionPropertyToManyToManyAssociationMetadata( + \ReflectionProperty $reflectionProperty, + array $propertyAnnotations, + Mapping\ClassMetadata $classMetadata + ) + { + $className = $classMetadata->getClassName(); + $fieldName = $reflectionProperty->getName(); + $manyToManyAnnot = $propertyAnnotations[Annotation\ManyToMany::class]; + + if ($manyToManyAnnot->targetEntity === null) { + throw Mapping\MappingException::missingTargetEntity($fieldName); + } + + $assocMetadata = new Mapping\ManyToManyAssociationMetadata($fieldName); + $targetEntity = $classMetadata->fullyQualifiedClassName($manyToManyAnnot->targetEntity); + + $assocMetadata->setSourceEntity($className); + $assocMetadata->setTargetEntity($targetEntity); + $assocMetadata->setCascade($this->getCascade($className, $fieldName, $manyToManyAnnot->cascade)); + $assocMetadata->setOrphanRemoval($manyToManyAnnot->orphanRemoval); + $assocMetadata->setFetchMode($this->getFetchMode($className, $manyToManyAnnot->fetch)); + + if (! empty($manyToManyAnnot->mappedBy)) { + $assocMetadata->setMappedBy($manyToManyAnnot->mappedBy); + } + + if (! empty($manyToManyAnnot->inversedBy)) { + $assocMetadata->setInversedBy($manyToManyAnnot->inversedBy); + } + + if (! empty($manyToManyAnnot->indexBy)) { + $assocMetadata->setIndexedBy($manyToManyAnnot->indexBy); + } + + // Check for JoinTable + if (isset($propertyAnnotations[Annotation\JoinTable::class])) { + $joinTableAnnot = $propertyAnnotations[Annotation\JoinTable::class]; + $joinTableMetadata = $this->convertJoinTableAnnotationToJoinTableMetadata( + $reflectionProperty, + $joinTableAnnot, + $classMetadata + ); + + $assocMetadata->setJoinTable($joinTableMetadata); + } + + // Check for OrderBy + if (isset($propertyAnnotations[Annotation\OrderBy::class])) { + $orderByAnnot = $propertyAnnotations[Annotation\OrderBy::class]; + + $assocMetadata->setOrderBy($orderByAnnot->value); + } + + // Check for Id + if (isset($propertyAnnotations[Annotation\Id::class])) { + $assocMetadata->setPrimaryKey(true); + } + + // Check for Cache + if (isset($propertyAnnotations[Annotation\Cache::class])) { + $cacheAnnot = $propertyAnnotations[Annotation\Cache::class]; + $cacheMetadata = $this->convertCacheAnnotationToCacheMetadata($cacheAnnot, $classMetadata, $fieldName); + + $assocMetadata->setCache($cacheMetadata); + } + + return $assocMetadata; + } + + /** + * Parse the given JoinTable as JoinTableMetadata + * + * @param \ReflectionProperty $reflectionProperty + * @param Annotation\JoinTable $joinTableAnnot + * @param Mapping\ClassMetadata $classMetadata + * + * @return Mapping\JoinTableMetadata + */ + private function convertJoinTableAnnotationToJoinTableMetadata( + \ReflectionProperty $reflectionProperty, + Annotation\JoinTable $joinTableAnnot, + Mapping\ClassMetadata $classMetadata + ) + { + $joinTable = new Mapping\JoinTableMetadata(); + + if (! empty($joinTableAnnot->name)) { + $joinTable->setName($joinTableAnnot->name); + } + + if (! empty($joinTableAnnot->schema)) { + $joinTable->setSchema($joinTableAnnot->schema); + } + + foreach ($joinTableAnnot->joinColumns as $joinColumnAnnot) { + $joinColumn = $this->convertJoinColumnAnnotationToJoinColumnMetadata( + $reflectionProperty, + $joinColumnAnnot, + $classMetadata + ); + + $joinTable->addJoinColumn($joinColumn); + } + + foreach ($joinTableAnnot->inverseJoinColumns as $joinColumnAnnot) { + $joinColumn = $this->convertJoinColumnAnnotationToJoinColumnMetadata( + $reflectionProperty, + $joinColumnAnnot, + $classMetadata + ); + + $joinTable->addInverseJoinColumn($joinColumn); + } + + return $joinTable; + } + + /** + * Parse the given JoinColumn as JoinColumnMetadata + * + * @param Annotation\JoinColumn $joinColumnAnnot + * + * @return Mapping\JoinColumnMetadata + */ + private function convertJoinColumnAnnotationToJoinColumnMetadata( + \ReflectionProperty $reflectionProperty, + Annotation\JoinColumn $joinColumnAnnot, + Mapping\ClassMetadata $classMetadata + ) + { + $fieldName = $reflectionProperty->getName(); + $joinColumn = new Mapping\JoinColumnMetadata(); + $columnName = empty($joinColumnAnnot->name) + ? $this->namingStrategy->propertyToColumnName($fieldName, $classMetadata->getClassName()) + : $joinColumnAnnot->name + ; + $referencedColumnName = empty($joinColumnAnnot->referencedColumnName) + ? $this->namingStrategy->referenceColumnName() + : $joinColumnAnnot->referencedColumnName + ; + + $joinColumn->setColumnName($columnName); + $joinColumn->setReferencedColumnName($referencedColumnName); + $joinColumn->setNullable($joinColumnAnnot->nullable); + $joinColumn->setUnique($joinColumnAnnot->unique); + + if (! empty($joinColumnAnnot->fieldName)) { + $joinColumn->setAliasedName($joinColumnAnnot->fieldName); + } + + if (! empty($joinColumnAnnot->columnDefinition)) { + $joinColumn->setColumnDefinition($joinColumnAnnot->columnDefinition); + } + + if ($joinColumnAnnot->onDelete) { + $joinColumn->setOnDelete(strtoupper($joinColumnAnnot->onDelete)); + } + + return $joinColumn; + } + + /** + * Parses the given method. + * + * @param \ReflectionMethod $method + * + * @return array + */ + private function getMethodCallbacks(\ReflectionMethod $method) + { + $annotations = $this->getMethodAnnotations($method); + $events = [ + Events::prePersist => Annotation\PrePersist::class, + Events::postPersist => Annotation\PostPersist::class, + Events::preUpdate => Annotation\PreUpdate::class, + Events::postUpdate => Annotation\PostUpdate::class, + Events::preRemove => Annotation\PreRemove::class, + Events::postRemove => Annotation\PostRemove::class, + Events::postLoad => Annotation\PostLoad::class, + Events::preFlush => Annotation\PreFlush::class, + ]; + + // Check for callbacks + $callbacks = []; + + foreach ($events as $eventName => $annotationClassName) { + if (isset($annotations[$annotationClassName]) || $method->getName() === $eventName) { + $callbacks[] = $eventName; + } + } + + return $callbacks; + } + + /** + * Attempts to resolve the fetch mode. + * + * @param string $className The class name. + * @param string $fetchMode The fetch mode. + * + * @return integer The fetch mode as defined in ClassMetadata. + * + * @throws Mapping\MappingException If the fetch mode is not valid. + */ + private function getFetchMode($className, $fetchMode) + { + $fetchModeConstant = sprintf('%s::%s', Mapping\FetchMode::class, $fetchMode); + + if (! defined($fetchModeConstant)) { + throw Mapping\MappingException::invalidFetchMode($className, $fetchMode); + } + + return constant($fetchModeConstant); + } + + /** + * @param string $className The class name. + * @param string $fieldName The field name. + * @param array $originalCascades The original unprocessed field cascades. + * + * @return array The processed field cascades. + * + * @throws Mapping\MappingException If a cascade option is not valid. + */ + private function getCascade(string $className, string $fieldName, array $originalCascades) + { + $cascadeTypes = ['remove', 'persist', 'refresh']; + $cascades = array_map('strtolower', $originalCascades); + + if (in_array('all', $cascades)) { + $cascades = $cascadeTypes; + } + + if (count($cascades) !== count(array_intersect($cascades, $cascadeTypes))) { + $diffCascades = array_diff($cascades, array_intersect($cascades, $cascadeTypes)); + + throw Mapping\MappingException::invalidCascadeOption($diffCascades, $className, $fieldName); + } + + return $cascades; + } + + /** + * @param \ReflectionClass $reflectionClass + * + * @return array + */ + private function getClassAnnotations(\ReflectionClass $reflectionClass) + { + $classAnnotations = $this->reader->getClassAnnotations($reflectionClass); + + foreach ($classAnnotations as $key => $annot) { + if (! is_numeric($key)) { + continue; + } + + $classAnnotations[get_class($annot)] = $annot; + } + + return $classAnnotations; + } + + /** + * @param \ReflectionProperty $reflectionProperty + * + * @return array + */ + private function getPropertyAnnotations(\ReflectionProperty $reflectionProperty) + { + $propertyAnnotations = $this->reader->getPropertyAnnotations($reflectionProperty); + + foreach ($propertyAnnotations as $key => $annot) { + if (! is_numeric($key)) { + continue; + } + + $propertyAnnotations[get_class($annot)] = $annot; + } + + return $propertyAnnotations; + } + + /** + * @param \ReflectionMethod $reflectionMethod + * + * @return array + */ + private function getMethodAnnotations(\ReflectionMethod $reflectionMethod) + { + $methodAnnotations = $this->reader->getMethodAnnotations($reflectionMethod); + + foreach ($methodAnnotations as $key => $annot) { + if (! is_numeric($key)) { + continue; + } + + $methodAnnotations[get_class($annot)] = $annot; + } + + return $methodAnnotations; + } +} diff --git a/lib/Doctrine/ORM/Mapping/Driver/PHPDriver.php b/lib/Doctrine/ORM/Mapping/Driver/PHPDriver.php deleted file mode 100644 index 28e2dbea22f..00000000000 --- a/lib/Doctrine/ORM/Mapping/Driver/PHPDriver.php +++ /dev/null @@ -1,31 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping\Driver; - -use Doctrine\Common\Persistence\Mapping\Driver\PHPDriver as CommonPHPDriver; - -/** - * {@inheritDoc} - * - * @deprecated this driver will be removed. Use Doctrine\Common\Persistence\Mapping\Driver\PHPDriver instead - */ -class PHPDriver extends CommonPHPDriver -{ -} diff --git a/lib/Doctrine/ORM/Mapping/Driver/SimplifiedXmlDriver.php b/lib/Doctrine/ORM/Mapping/Driver/SimplifiedXmlDriver.php index 9bfd84cae38..11f65aae819 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/SimplifiedXmlDriver.php +++ b/lib/Doctrine/ORM/Mapping/Driver/SimplifiedXmlDriver.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Mapping\Driver; @@ -38,6 +23,7 @@ class SimplifiedXmlDriver extends XmlDriver public function __construct($prefixes, $fileExtension = self::DEFAULT_FILE_EXTENSION) { $locator = new SymfonyFileLocator((array) $prefixes, $fileExtension); + parent::__construct($locator, $fileExtension); } } diff --git a/lib/Doctrine/ORM/Mapping/Driver/SimplifiedYamlDriver.php b/lib/Doctrine/ORM/Mapping/Driver/SimplifiedYamlDriver.php deleted file mode 100644 index 8f38784f4e6..00000000000 --- a/lib/Doctrine/ORM/Mapping/Driver/SimplifiedYamlDriver.php +++ /dev/null @@ -1,43 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping\Driver; - -use Doctrine\Common\Persistence\Mapping\Driver\SymfonyFileLocator; - -/** - * YamlDriver that additionally looks for mapping information in a global file. - * - * @author Fabien Potencier - * @author Benjamin Eberlei - * @license MIT - */ -class SimplifiedYamlDriver extends YamlDriver -{ - const DEFAULT_FILE_EXTENSION = '.orm.yml'; - - /** - * {@inheritDoc} - */ - public function __construct($prefixes, $fileExtension = self::DEFAULT_FILE_EXTENSION) - { - $locator = new SymfonyFileLocator((array) $prefixes, $fileExtension); - parent::__construct($locator, $fileExtension); - } -} diff --git a/lib/Doctrine/ORM/Mapping/Driver/StaticPHPDriver.php b/lib/Doctrine/ORM/Mapping/Driver/StaticPHPDriver.php deleted file mode 100644 index d6c6ead853c..00000000000 --- a/lib/Doctrine/ORM/Mapping/Driver/StaticPHPDriver.php +++ /dev/null @@ -1,31 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping\Driver; - -use Doctrine\Common\Persistence\Mapping\Driver\StaticPHPDriver as CommonStaticPHPDriver; - -/** - * {@inheritDoc} - * - * @deprecated this driver will be removed. Use Doctrine\Common\Persistence\Mapping\Driver\StaticPHPDriver instead - */ -class StaticPHPDriver extends CommonStaticPHPDriver -{ -} diff --git a/lib/Doctrine/ORM/Mapping/Driver/XmlDriver.php b/lib/Doctrine/ORM/Mapping/Driver/XmlDriver.php index 39af412c9f2..6736c681f5d 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/XmlDriver.php +++ b/lib/Doctrine/ORM/Mapping/Driver/XmlDriver.php @@ -1,30 +1,13 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Mapping\Driver; +use Doctrine\DBAL\Types\Type; +use Doctrine\ORM\Events; +use Doctrine\ORM\Mapping; use SimpleXMLElement; -use Doctrine\Common\Persistence\Mapping\Driver\FileDriver; -use Doctrine\ORM\Mapping\Builder\EntityListenerBuilder; -use Doctrine\Common\Persistence\Mapping\ClassMetadata; -use Doctrine\ORM\Mapping\MappingException; -use Doctrine\ORM\Mapping\ClassMetadata as Metadata; /** * XmlDriver is a metadata driver that enables mapping through XML files. @@ -52,57 +35,118 @@ public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENS /** * {@inheritDoc} */ - public function loadMetadataForClass($className, ClassMetadata $metadata) + public function loadMetadataForClass( + string $className, + Mapping\ClassMetadata $metadata, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) { - /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadataInfo */ - /* @var $xmlRoot SimpleXMLElement */ + /* @var \SimpleXMLElement $xmlRoot */ $xmlRoot = $this->getElement($className); - if ($xmlRoot->getName() == 'entity') { + if ($xmlRoot->getName() === 'entity') { if (isset($xmlRoot['repository-class'])) { - $metadata->setCustomRepositoryClass((string) $xmlRoot['repository-class']); + $metadata->setCustomRepositoryClassName( + $metadata->fullyQualifiedClassName((string) $xmlRoot['repository-class']) + ); } + if (isset($xmlRoot['read-only']) && $this->evaluateBoolean($xmlRoot['read-only'])) { - $metadata->markReadOnly(); + $metadata->asReadOnly(); } - } else if ($xmlRoot->getName() == 'mapped-superclass') { - $metadata->setCustomRepositoryClass( - isset($xmlRoot['repository-class']) ? (string) $xmlRoot['repository-class'] : null - ); + } else if ($xmlRoot->getName() === 'mapped-superclass') { + if (isset($xmlRoot['repository-class'])) { + $metadata->setCustomRepositoryClassName( + $metadata->fullyQualifiedClassName((string) $xmlRoot['repository-class']) + ); + } + $metadata->isMappedSuperclass = true; - } else if ($xmlRoot->getName() == 'embeddable') { + } else if ($xmlRoot->getName() === 'embeddable') { $metadata->isEmbeddedClass = true; } else { - throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className); + throw Mapping\MappingException::classIsNotAValidEntityOrMappedSuperClass($className); } - // Evaluate attributes - $primaryTable = []; + // Process table information + $parent = $metadata->getParent(); - if (isset($xmlRoot['table'])) { - $primaryTable['name'] = (string) $xmlRoot['table']; - } + if ($parent && $parent->inheritanceType === Mapping\InheritanceType::SINGLE_TABLE) { + $metadata->setTable($parent->table); + } else { + $namingStrategy = $metadataBuildingContext->getNamingStrategy(); + $tableMetadata = new Mapping\TableMetadata(); - if (isset($xmlRoot['schema'])) { - $primaryTable['schema'] = (string) $xmlRoot['schema']; - } + $tableMetadata->setName($namingStrategy->classToTableName($metadata->getClassName())); + + // Evaluate attributes + if (isset($xmlRoot['table'])) { + $tableMetadata->setName((string) $xmlRoot['table']); + } + + if (isset($xmlRoot['schema'])) { + $tableMetadata->setSchema((string) $xmlRoot['schema']); + } + + if (isset($xmlRoot->options)) { + $options = $this->parseOptions($xmlRoot->options->children()); + + foreach ($options as $optionName => $optionValue) { + $tableMetadata->addOption($optionName, $optionValue); + } + } + + // Evaluate + if (isset($xmlRoot->indexes)) { + foreach ($xmlRoot->indexes->index as $indexXml) { + $indexName = isset($indexXml['name']) ? (string) $indexXml['name'] : null; + $columns = explode(',', (string) $indexXml['columns']); + $isUnique = isset($indexXml['unique']) && $indexXml['unique']; + $options = isset($indexXml->options) ? $this->parseOptions($indexXml->options->children()) : []; + $flags = isset($indexXml['flags']) ? explode(',', (string) $indexXml['flags']) : []; + + $tableMetadata->addIndex([ + 'name' => $indexName, + 'columns' => $columns, + 'unique' => $isUnique, + 'options' => $options, + 'flags' => $flags, + ]); + } + } + + // Evaluate - $metadata->setPrimaryTable($primaryTable); + if (isset($xmlRoot->{'unique-constraints'})) { + foreach ($xmlRoot->{'unique-constraints'}->{'unique-constraint'} as $uniqueXml) { + $indexName = isset($uniqueXml['name']) ? (string) $uniqueXml['name'] : null; + $columns = explode(',', (string) $uniqueXml['columns']); + $options = isset($uniqueXml->options) ? $this->parseOptions($uniqueXml->options->children()) : []; + $flags = isset($uniqueXml['flags']) ? explode(',', (string) $uniqueXml['flags']) : []; + + $tableMetadata->addUniqueConstraint([ + 'name' => $indexName, + 'columns' => $columns, + 'options' => $options, + 'flags' => $flags, + ]); + } + } + + $metadata->setTable($tableMetadata); + } // Evaluate second level cache if (isset($xmlRoot->cache)) { - $metadata->enableCache($this->cacheToArray($xmlRoot->cache)); + $cache = $this->convertCacheElementToCacheMetadata($xmlRoot->cache, $metadata); + + $metadata->setCache($cache); } // Evaluate named queries if (isset($xmlRoot->{'named-queries'})) { foreach ($xmlRoot->{'named-queries'}->{'named-query'} as $namedQueryElement) { - $metadata->addNamedQuery( - [ - 'name' => (string) $namedQueryElement['name'], - 'query' => (string) $namedQueryElement['query'] - ] - ); + $metadata->addNamedQuery((string) $namedQueryElement['name'], (string) $namedQueryElement['query']); } } @@ -110,11 +154,11 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($xmlRoot->{'named-native-queries'})) { foreach ($xmlRoot->{'named-native-queries'}->{'named-native-query'} as $nativeQueryElement) { $metadata->addNamedNativeQuery( + isset($nativeQueryElement['name']) ? (string) $nativeQueryElement['name'] : null, + isset($nativeQueryElement->query) ? (string) $nativeQueryElement->query : null, [ - 'name' => isset($nativeQueryElement['name']) ? (string) $nativeQueryElement['name'] : null, - 'query' => isset($nativeQueryElement->query) ? (string) $nativeQueryElement->query : null, - 'resultClass' => isset($nativeQueryElement['result-class']) ? (string) $nativeQueryElement['result-class'] : null, - 'resultSetMapping' => isset($nativeQueryElement['result-set-mapping']) ? (string) $nativeQueryElement['result-set-mapping'] : null, + 'resultClass' => isset($nativeQueryElement['result-class']) ? (string) $nativeQueryElement['result-class'] : null, + 'resultSetMapping' => isset($nativeQueryElement['result-set-mapping']) ? (string) $nativeQueryElement['result-set-mapping'] : null, ] ); } @@ -125,6 +169,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) foreach ($xmlRoot->{'sql-result-set-mappings'}->{'sql-result-set-mapping'} as $rsmElement) { $entities = []; $columns = []; + foreach ($rsmElement as $entityElement) { // if (isset($entityElement['entity-class'])) { @@ -163,31 +208,49 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } if (isset($xmlRoot['inheritance-type'])) { - $inheritanceType = (string) $xmlRoot['inheritance-type']; - $metadata->setInheritanceType(constant('Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_' . $inheritanceType)); + $inheritanceType = strtoupper((string) $xmlRoot['inheritance-type']); + + $metadata->setInheritanceType( + constant(sprintf('%s::%s', Mapping\InheritanceType::class, $inheritanceType)) + ); + + if ($metadata->inheritanceType !== Mapping\InheritanceType::NONE) { + $discriminatorColumn = new Mapping\DiscriminatorColumnMetadata(); + + $discriminatorColumn->setTableName($metadata->getTableName()); + $discriminatorColumn->setColumnName('dtype'); + $discriminatorColumn->setType(Type::getType('string')); + $discriminatorColumn->setLength(255); - if ($metadata->inheritanceType != Metadata::INHERITANCE_TYPE_NONE) { // Evaluate if (isset($xmlRoot->{'discriminator-column'})) { - $discrColumn = $xmlRoot->{'discriminator-column'}; - $metadata->setDiscriminatorColumn( - [ - 'name' => isset($discrColumn['name']) ? (string) $discrColumn['name'] : null, - 'type' => isset($discrColumn['type']) ? (string) $discrColumn['type'] : 'string', - 'length' => isset($discrColumn['length']) ? (string) $discrColumn['length'] : 255, - 'columnDefinition' => isset($discrColumn['column-definition']) ? (string) $discrColumn['column-definition'] : null - ] - ); - } else { - $metadata->setDiscriminatorColumn(['name' => 'dtype', 'type' => 'string', 'length' => 255]); + $discriminatorColumnMapping = $xmlRoot->{'discriminator-column'}; + $typeName = isset($discriminatorColumnMapping['type']) + ? (string) $discriminatorColumnMapping['type'] + : 'string'; + + $discriminatorColumn->setType(Type::getType($typeName)); + $discriminatorColumn->setColumnName((string) $discriminatorColumnMapping['name']); + + if (isset($discriminatorColumnMapping['column-definition'])) { + $discriminatorColumn->setColumnDefinition((string) $discriminatorColumnMapping['column-definition']); + } + + if (isset($discriminatorColumnMapping['length'])) { + $discriminatorColumn->setLength((int) $discriminatorColumnMapping['length']); + } } + $metadata->setDiscriminatorColumn($discriminatorColumn); + // Evaluate if (isset($xmlRoot->{'discriminator-map'})) { $map = []; + foreach ($xmlRoot->{'discriminator-map'}->{'discriminator-mapping'} as $discrMapElement) { - $map[(string) $discrMapElement['value']] = (string) $discrMapElement['class']; + $map[(string) $discrMapElement['value']] = $metadata->fullyQualifiedClassName((string) $discrMapElement['class']); } + $metadata->setDiscriminatorMap($map); } } @@ -196,68 +259,21 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate if (isset($xmlRoot['change-tracking-policy'])) { - $metadata->setChangeTrackingPolicy(constant('Doctrine\ORM\Mapping\ClassMetadata::CHANGETRACKING_' - . strtoupper((string) $xmlRoot['change-tracking-policy']))); - } - - // Evaluate - if (isset($xmlRoot->indexes)) { - $metadata->table['indexes'] = []; - foreach ($xmlRoot->indexes->index as $indexXml) { - $index = ['columns' => explode(',', (string) $indexXml['columns'])]; + $changeTrackingPolicy = strtoupper((string) $xmlRoot['change-tracking-policy']); - if (isset($indexXml['flags'])) { - $index['flags'] = explode(',', (string) $indexXml['flags']); - } - - if (isset($indexXml->options)) { - $index['options'] = $this->_parseOptions($indexXml->options->children()); - } - - if (isset($indexXml['name'])) { - $metadata->table['indexes'][(string) $indexXml['name']] = $index; - } else { - $metadata->table['indexes'][] = $index; - } - } - } - - // Evaluate - if (isset($xmlRoot->{'unique-constraints'})) { - $metadata->table['uniqueConstraints'] = []; - foreach ($xmlRoot->{'unique-constraints'}->{'unique-constraint'} as $uniqueXml) { - $unique = ['columns' => explode(',', (string) $uniqueXml['columns'])]; - - if (isset($uniqueXml->options)) { - $unique['options'] = $this->_parseOptions($uniqueXml->options->children()); - } - - if (isset($uniqueXml['name'])) { - $metadata->table['uniqueConstraints'][(string) $uniqueXml['name']] = $unique; - } else { - $metadata->table['uniqueConstraints'][] = $unique; - } - } - } - - if (isset($xmlRoot->options)) { - $metadata->table['options'] = $this->_parseOptions($xmlRoot->options->children()); + $metadata->setChangeTrackingPolicy( + constant(sprintf('%s::%s', Mapping\ChangeTrackingPolicy::class, $changeTrackingPolicy)) + ); } - // The mapping assignment is done in 2 times as a bug might occurs on some php/xml lib versions - // The internal SimpleXmlIterator get resetted, to this generate a duplicate field exception - $mappings = []; // Evaluate mappings if (isset($xmlRoot->field)) { - foreach ($xmlRoot->field as $fieldMapping) { - $mapping = $this->columnToArray($fieldMapping); - - if (isset($mapping['version'])) { - $metadata->setVersionMapping($mapping); - unset($mapping['version']); - } + foreach ($xmlRoot->field as $fieldElement) { + $fieldName = (string) $fieldElement['name']; + $isFieldVersioned = isset($fieldElement['version']) && $fieldElement['version']; + $fieldMetadata = $this->convertFieldElementToFieldMetadata($fieldElement, $fieldName, $isFieldVersioned); - $metadata->mapField($mapping); + $metadata->addProperty($fieldMetadata); } } @@ -281,287 +297,320 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } } - foreach ($mappings as $mapping) { - if (isset($mapping['version'])) { - $metadata->setVersionMapping($mapping); - } - - $metadata->mapField($mapping); - } - // Evaluate mappings $associationIds = []; + foreach ($xmlRoot->id as $idElement) { + $fieldName = (string) $idElement['name']; + if (isset($idElement['association-key']) && $this->evaluateBoolean($idElement['association-key'])) { - $associationIds[(string) $idElement['name']] = true; + $associationIds[$fieldName] = true; + continue; } - $mapping = [ - 'id' => true, - 'fieldName' => (string) $idElement['name'] - ]; + $fieldMetadata = $this->convertFieldElementToFieldMetadata($idElement, $fieldName, false); - if (isset($idElement['type'])) { - $mapping['type'] = (string) $idElement['type']; - } + $fieldMetadata->setPrimaryKey(true); - if (isset($idElement['length'])) { - $mapping['length'] = (string) $idElement['length']; - } + if (isset($idElement->generator)) { + $strategy = isset($idElement->generator['strategy']) + ? (string) $idElement->generator['strategy'] + : 'AUTO'; - if (isset($idElement['column'])) { - $mapping['columnName'] = (string) $idElement['column']; - } + $idGeneratorType = constant(sprintf('%s::%s', Mapping\GeneratorType::class, strtoupper($strategy))); - if (isset($idElement['column-definition'])) { - $mapping['columnDefinition'] = (string) $idElement['column-definition']; - } + if ($idGeneratorType !== Mapping\GeneratorType::NONE) { + $idGeneratorDefinition = []; - if (isset($idElement->options)) { - $mapping['options'] = $this->_parseOptions($idElement->options->children()); - } + // Check for SequenceGenerator/TableGenerator definition + if (isset($idElement->{'sequence-generator'})) { + $seqGenerator = $idElement->{'sequence-generator'}; + $idGeneratorDefinition = [ + 'sequenceName' => (string) $seqGenerator['sequence-name'], + 'allocationSize' => (string) $seqGenerator['allocation-size'], + ]; + } elseif (isset($idElement->{'custom-id-generator'})) { + $customGenerator = $idElement->{'custom-id-generator'}; - $metadata->mapField($mapping); + $idGeneratorDefinition = [ + 'class' => (string) $customGenerator['class'], + 'arguments' => [], + ]; + } elseif (isset($idElement->{'table-generator'})) { + throw Mapping\MappingException::tableIdGeneratorNotImplemented($className); + } - if (isset($idElement->generator)) { - $strategy = isset($idElement->generator['strategy']) ? - (string) $idElement->generator['strategy'] : 'AUTO'; - $metadata->setIdGeneratorType(constant('Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_' - . $strategy)); + $fieldMetadata->setValueGenerator(new Mapping\ValueGeneratorMetadata($idGeneratorType, $idGeneratorDefinition)); + } } - // Check for SequenceGenerator/TableGenerator definition - if (isset($idElement->{'sequence-generator'})) { - $seqGenerator = $idElement->{'sequence-generator'}; - $metadata->setSequenceGeneratorDefinition( - [ - 'sequenceName' => (string) $seqGenerator['sequence-name'], - 'allocationSize' => (string) $seqGenerator['allocation-size'], - 'initialValue' => (string) $seqGenerator['initial-value'] - ] - ); - } else if (isset($idElement->{'custom-id-generator'})) { - $customGenerator = $idElement->{'custom-id-generator'}; - $metadata->setCustomGeneratorDefinition( - [ - 'class' => (string) $customGenerator['class'] - ] - ); - } else if (isset($idElement->{'table-generator'})) { - throw MappingException::tableIdGeneratorNotImplemented($className); - } + $metadata->addProperty($fieldMetadata); } // Evaluate mappings if (isset($xmlRoot->{'one-to-one'})) { foreach ($xmlRoot->{'one-to-one'} as $oneToOneElement) { - $mapping = [ - 'fieldName' => (string) $oneToOneElement['field'], - 'targetEntity' => (string) $oneToOneElement['target-entity'] - ]; + $association = new Mapping\OneToOneAssociationMetadata((string) $oneToOneElement['field']); + $targetEntity = $metadata->fullyQualifiedClassName((string) $oneToOneElement['target-entity']); + + $association->setTargetEntity($targetEntity); - if (isset($associationIds[$mapping['fieldName']])) { - $mapping['id'] = true; + if (isset($associationIds[$association->getName()])) { + $association->setPrimaryKey(true); } if (isset($oneToOneElement['fetch'])) { - $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . (string) $oneToOneElement['fetch']); + $association->setFetchMode( + constant(sprintf('%s::%s', Mapping\FetchMode::class, (string) $oneToOneElement['fetch'])) + ); } if (isset($oneToOneElement['mapped-by'])) { - $mapping['mappedBy'] = (string) $oneToOneElement['mapped-by']; + $association->setMappedBy((string) $oneToOneElement['mapped-by']); } else { if (isset($oneToOneElement['inversed-by'])) { - $mapping['inversedBy'] = (string) $oneToOneElement['inversed-by']; + $association->setInversedBy((string) $oneToOneElement['inversed-by']); } + $joinColumns = []; if (isset($oneToOneElement->{'join-column'})) { - $joinColumns[] = $this->joinColumnToArray($oneToOneElement->{'join-column'}); + $joinColumns[] = $this->convertJoinColumnElementToJoinColumnMetadata($oneToOneElement->{'join-column'}); } else if (isset($oneToOneElement->{'join-columns'})) { foreach ($oneToOneElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { - $joinColumns[] = $this->joinColumnToArray($joinColumnElement); + $joinColumns[] = $this->convertJoinColumnElementToJoinColumnMetadata($joinColumnElement); } } - $mapping['joinColumns'] = $joinColumns; + $association->setJoinColumns($joinColumns); } if (isset($oneToOneElement->cascade)) { - $mapping['cascade'] = $this->_getCascadeMappings($oneToOneElement->cascade); + $association->setCascade($this->getCascadeMappings($oneToOneElement->cascade)); } if (isset($oneToOneElement['orphan-removal'])) { - $mapping['orphanRemoval'] = $this->evaluateBoolean($oneToOneElement['orphan-removal']); + $association->setOrphanRemoval($this->evaluateBoolean($oneToOneElement['orphan-removal'])); } // Evaluate second level cache if (isset($oneToOneElement->cache)) { - $mapping['cache'] = $metadata->getAssociationCacheDefaults($mapping['fieldName'], $this->cacheToArray($oneToOneElement->cache)); + $association->setCache( + $this->convertCacheElementToCacheMetadata( + $oneToOneElement->cache, + $metadata, + $association->getName() + ) + ); } - $metadata->mapOneToOne($mapping); + $metadata->addProperty($association); } } // Evaluate mappings if (isset($xmlRoot->{'one-to-many'})) { foreach ($xmlRoot->{'one-to-many'} as $oneToManyElement) { - $mapping = [ - 'fieldName' => (string) $oneToManyElement['field'], - 'targetEntity' => (string) $oneToManyElement['target-entity'], - 'mappedBy' => (string) $oneToManyElement['mapped-by'] - ]; + $association = new Mapping\OneToManyAssociationMetadata((string) $oneToManyElement['field']); + $targetEntity = $metadata->fullyQualifiedClassName((string) $oneToManyElement['target-entity']); + + $association->setTargetEntity($targetEntity); + $association->setMappedBy((string) $oneToManyElement['mapped-by']); + + if (isset($associationIds[$association->getName()])) { + throw Mapping\MappingException::illegalToManyIdentifierAssociation($className, $association->getName()); + } if (isset($oneToManyElement['fetch'])) { - $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . (string) $oneToManyElement['fetch']); + $association->setFetchMode( + constant(sprintf('%s::%s', Mapping\FetchMode::class, (string) $oneToManyElement['fetch'])) + ); } if (isset($oneToManyElement->cascade)) { - $mapping['cascade'] = $this->_getCascadeMappings($oneToManyElement->cascade); + $association->setCascade($this->getCascadeMappings($oneToManyElement->cascade)); } if (isset($oneToManyElement['orphan-removal'])) { - $mapping['orphanRemoval'] = $this->evaluateBoolean($oneToManyElement['orphan-removal']); + $association->setOrphanRemoval($this->evaluateBoolean($oneToManyElement['orphan-removal'])); } if (isset($oneToManyElement->{'order-by'})) { $orderBy = []; + foreach ($oneToManyElement->{'order-by'}->{'order-by-field'} as $orderByField) { $orderBy[(string) $orderByField['name']] = (string) $orderByField['direction']; } - $mapping['orderBy'] = $orderBy; + + $association->setOrderBy($orderBy); } if (isset($oneToManyElement['index-by'])) { - $mapping['indexBy'] = (string) $oneToManyElement['index-by']; + $association->setIndexedBy((string) $oneToManyElement['index-by']); } else if (isset($oneToManyElement->{'index-by'})) { throw new \InvalidArgumentException(" is not a valid tag"); } // Evaluate second level cache if (isset($oneToManyElement->cache)) { - $mapping['cache'] = $metadata->getAssociationCacheDefaults($mapping['fieldName'], $this->cacheToArray($oneToManyElement->cache)); + $association->setCache( + $this->convertCacheElementToCacheMetadata( + $oneToManyElement->cache, + $metadata, + $association->getName() + ) + ); } - $metadata->mapOneToMany($mapping); + $metadata->addProperty($association); } } // Evaluate mappings if (isset($xmlRoot->{'many-to-one'})) { foreach ($xmlRoot->{'many-to-one'} as $manyToOneElement) { - $mapping = [ - 'fieldName' => (string) $manyToOneElement['field'], - 'targetEntity' => (string) $manyToOneElement['target-entity'] - ]; + $association = new Mapping\ManyToOneAssociationMetadata((string) $manyToOneElement['field']); + $targetEntity = $metadata->fullyQualifiedClassName((string) $manyToOneElement['target-entity']); - if (isset($associationIds[$mapping['fieldName']])) { - $mapping['id'] = true; + $association->setTargetEntity($targetEntity); + + if (isset($associationIds[$association->getName()])) { + $association->setPrimaryKey(true); } if (isset($manyToOneElement['fetch'])) { - $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . (string) $manyToOneElement['fetch']); + $association->setFetchMode( + constant('Doctrine\ORM\Mapping\FetchMode::' . (string) $manyToOneElement['fetch']) + ); } if (isset($manyToOneElement['inversed-by'])) { - $mapping['inversedBy'] = (string) $manyToOneElement['inversed-by']; + $association->setInversedBy((string) $manyToOneElement['inversed-by']); } $joinColumns = []; if (isset($manyToOneElement->{'join-column'})) { - $joinColumns[] = $this->joinColumnToArray($manyToOneElement->{'join-column'}); + $joinColumns[] = $this->convertJoinColumnElementToJoinColumnMetadata($manyToOneElement->{'join-column'}); } else if (isset($manyToOneElement->{'join-columns'})) { foreach ($manyToOneElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { - $joinColumns[] = $this->joinColumnToArray($joinColumnElement); + $joinColumns[] = $this->convertJoinColumnElementToJoinColumnMetadata($joinColumnElement); } } - $mapping['joinColumns'] = $joinColumns; + $association->setJoinColumns($joinColumns); if (isset($manyToOneElement->cascade)) { - $mapping['cascade'] = $this->_getCascadeMappings($manyToOneElement->cascade); + $association->setCascade($this->getCascadeMappings($manyToOneElement->cascade)); } // Evaluate second level cache if (isset($manyToOneElement->cache)) { - $mapping['cache'] = $metadata->getAssociationCacheDefaults($mapping['fieldName'], $this->cacheToArray($manyToOneElement->cache)); + $association->setCache( + $this->convertCacheElementToCacheMetadata( + $manyToOneElement->cache, + $metadata, + $association->getName() + ) + ); } - $metadata->mapManyToOne($mapping); - + $metadata->addProperty($association); } } // Evaluate mappings if (isset($xmlRoot->{'many-to-many'})) { foreach ($xmlRoot->{'many-to-many'} as $manyToManyElement) { - $mapping = [ - 'fieldName' => (string) $manyToManyElement['field'], - 'targetEntity' => (string) $manyToManyElement['target-entity'] - ]; + $association = new Mapping\ManyToManyAssociationMetadata((string) $manyToManyElement['field']); + $targetEntity = $metadata->fullyQualifiedClassName((string) $manyToManyElement['target-entity']); + + $association->setTargetEntity($targetEntity); + + if (isset($associationIds[$association->getName()])) { + throw Mapping\MappingException::illegalToManyIdentifierAssociation($className, $association->getName()); + } if (isset($manyToManyElement['fetch'])) { - $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . (string) $manyToManyElement['fetch']); + $association->setFetchMode( + constant(sprintf('%s::%s', Mapping\FetchMode::class, (string) $manyToManyElement['fetch'])) + ); } if (isset($manyToManyElement['orphan-removal'])) { - $mapping['orphanRemoval'] = $this->evaluateBoolean($manyToManyElement['orphan-removal']); + $association->setOrphanRemoval($this->evaluateBoolean($manyToManyElement['orphan-removal'])); } if (isset($manyToManyElement['mapped-by'])) { - $mapping['mappedBy'] = (string) $manyToManyElement['mapped-by']; + $association->setMappedBy((string) $manyToManyElement['mapped-by']); } else if (isset($manyToManyElement->{'join-table'})) { if (isset($manyToManyElement['inversed-by'])) { - $mapping['inversedBy'] = (string) $manyToManyElement['inversed-by']; + $association->setInversedBy((string) $manyToManyElement['inversed-by']); } $joinTableElement = $manyToManyElement->{'join-table'}; - $joinTable = [ - 'name' => (string) $joinTableElement['name'] - ]; + $joinTable = new Mapping\JoinTableMetadata(); + + if (isset($joinTableElement['name'])) { + $joinTable->setName((string) $joinTableElement['name']); + } if (isset($joinTableElement['schema'])) { - $joinTable['schema'] = (string) $joinTableElement['schema']; + $joinTable->setSchema((string) $joinTableElement['schema']); } - foreach ($joinTableElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { - $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumnElement); + if (isset($joinTableElement->{'join-columns'})) { + foreach ($joinTableElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { + $joinColumn = $this->convertJoinColumnElementToJoinColumnMetadata($joinColumnElement); + + $joinTable->addJoinColumn($joinColumn); + } } - foreach ($joinTableElement->{'inverse-join-columns'}->{'join-column'} as $joinColumnElement) { - $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumnElement); + if (isset($joinTableElement->{'inverse-join-columns'})) { + foreach ($joinTableElement->{'inverse-join-columns'}->{'join-column'} as $joinColumnElement) { + $joinColumn = $this->convertJoinColumnElementToJoinColumnMetadata($joinColumnElement); + + $joinTable->addInverseJoinColumn($joinColumn); + } } - $mapping['joinTable'] = $joinTable; + $association->setJoinTable($joinTable); } if (isset($manyToManyElement->cascade)) { - $mapping['cascade'] = $this->_getCascadeMappings($manyToManyElement->cascade); + $association->setCascade($this->getCascadeMappings($manyToManyElement->cascade)); } if (isset($manyToManyElement->{'order-by'})) { $orderBy = []; + foreach ($manyToManyElement->{'order-by'}->{'order-by-field'} as $orderByField) { $orderBy[(string) $orderByField['name']] = (string) $orderByField['direction']; } - $mapping['orderBy'] = $orderBy; + + $association->setOrderBy($orderBy); } if (isset($manyToManyElement['index-by'])) { - $mapping['indexBy'] = (string) $manyToManyElement['index-by']; + $association->setIndexedBy((string) $manyToManyElement['index-by']); } else if (isset($manyToManyElement->{'index-by'})) { throw new \InvalidArgumentException(" is not a valid tag"); } // Evaluate second level cache if (isset($manyToManyElement->cache)) { - $mapping['cache'] = $metadata->getAssociationCacheDefaults($mapping['fieldName'], $this->cacheToArray($manyToManyElement->cache)); + $association->setCache( + $this->convertCacheElementToCacheMetadata( + $manyToManyElement->cache, + $metadata, + $association->getName() + ) + ); } - $metadata->mapManyToMany($mapping); + $metadata->addProperty($association); } } @@ -569,10 +618,11 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($xmlRoot->{'attribute-overrides'})) { foreach ($xmlRoot->{'attribute-overrides'}->{'attribute-override'} as $overrideElement) { $fieldName = (string) $overrideElement['name']; - foreach ($overrideElement->field as $field) { - $mapping = $this->columnToArray($field); - $mapping['fieldName'] = $fieldName; - $metadata->setAttributeOverride($fieldName, $mapping); + + foreach ($overrideElement->field as $fieldElement) { + $fieldMetadata = $this->convertFieldElementToFieldMetadata($fieldElement, $fieldName, false); + + $metadata->setPropertyOverride($fieldMetadata); } } } @@ -580,71 +630,107 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate association-overrides if (isset($xmlRoot->{'association-overrides'})) { foreach ($xmlRoot->{'association-overrides'}->{'association-override'} as $overrideElement) { - $fieldName = (string) $overrideElement['name']; - $override = []; + $fieldName = (string) $overrideElement['name']; + $property = $metadata->getProperty($fieldName); + + if (! $property) { + throw Mapping\MappingException::invalidOverrideFieldName($metadata->getClassName(), $fieldName); + } + + $existingClass = get_class($property); + $override = new $existingClass($fieldName); // Check for join-columns if (isset($overrideElement->{'join-columns'})) { $joinColumns = []; + foreach ($overrideElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { - $joinColumns[] = $this->joinColumnToArray($joinColumnElement); + $joinColumns[] = $this->convertJoinColumnElementToJoinColumnMetadata($joinColumnElement); } - $override['joinColumns'] = $joinColumns; + + $override->setJoinColumns($joinColumns); } // Check for join-table if ($overrideElement->{'join-table'}) { - $joinTable = null; $joinTableElement = $overrideElement->{'join-table'}; + $joinTable = new Mapping\JoinTableMetadata(); - $joinTable = [ - 'name' => (string) $joinTableElement['name'], - 'schema' => (string) $joinTableElement['schema'] - ]; + if (isset($joinTableElement['name'])) { + $joinTable->setName((string) $joinTableElement['name']); + } + + if (isset($joinTableElement['schema'])) { + $joinTable->setSchema((string) $joinTableElement['schema']); + } if (isset($joinTableElement->{'join-columns'})) { foreach ($joinTableElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { - $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumnElement); + $joinColumn = $this->convertJoinColumnElementToJoinColumnMetadata($joinColumnElement); + + $joinTable->addJoinColumn($joinColumn); } } if (isset($joinTableElement->{'inverse-join-columns'})) { foreach ($joinTableElement->{'inverse-join-columns'}->{'join-column'} as $joinColumnElement) { - $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumnElement); + $joinColumn = $this->convertJoinColumnElementToJoinColumnMetadata($joinColumnElement); + + $joinTable->addInverseJoinColumn($joinColumn); } } - $override['joinTable'] = $joinTable; + $override->setJoinTable($joinTable); } // Check for inversed-by if (isset($overrideElement->{'inversed-by'})) { - $override['inversedBy'] = (string) $overrideElement->{'inversed-by'}['name']; + $override->setInversedBy((string) $overrideElement->{'inversed-by'}['name']); } - // Check for `fetch` + // Check for fetch if (isset($overrideElement['fetch'])) { - $override['fetch'] = constant(Metadata::class . '::FETCH_' . (string) $overrideElement['fetch']); + $override->setFetchMode( + constant('Doctrine\ORM\Mapping\FetchMode::' . (string) $overrideElement['fetch']) + ); } - $metadata->setAssociationOverride($fieldName, $override); + $metadata->setPropertyOverride($override); } } // Evaluate if (isset($xmlRoot->{'lifecycle-callbacks'})) { foreach ($xmlRoot->{'lifecycle-callbacks'}->{'lifecycle-callback'} as $lifecycleCallback) { - $metadata->addLifecycleCallback((string) $lifecycleCallback['method'], constant('Doctrine\ORM\Events::' . (string) $lifecycleCallback['type'])); + $eventName = constant(Events::class . '::' . (string) $lifecycleCallback['type']); + $methodName = (string) $lifecycleCallback['method']; + + $metadata->addLifecycleCallback($methodName, $eventName); } } // Evaluate entity listener if (isset($xmlRoot->{'entity-listeners'})) { foreach ($xmlRoot->{'entity-listeners'}->{'entity-listener'} as $listenerElement) { - $className = (string) $listenerElement['class']; + $listenerClassName = $metadata->fullyQualifiedClassName((string) $listenerElement['class']); + + if (! class_exists($listenerClassName)) { + throw Mapping\MappingException::entityListenerClassNotFound( + $listenerClassName, + $metadata->getClassName() + ); + } + + $listenerClass = new \ReflectionClass($listenerClassName); + // Evaluate the listener using naming convention. if ($listenerElement->count() === 0) { - EntityListenerBuilder::bindEntityListener($metadata, $className); + /* @var $method \ReflectionMethod */ + foreach ($listenerClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { + foreach ($this->getMethodCallbacks($method) as $callback) { + $metadata->addEntityListener($callback, $listenerClassName, $method->getName()); + } + } continue; } @@ -653,7 +739,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $eventName = (string) $callbackElement['type']; $methodName = (string) $callbackElement['method']; - $metadata->addEntityListener($eventName, $className, $methodName); + $metadata->addEntityListener($eventName, $listenerClassName, $methodName); } } } @@ -666,14 +752,14 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) * * @return array The options array. */ - private function _parseOptions(SimpleXMLElement $options) + private function parseOptions(SimpleXMLElement $options) { $array = []; /* @var $option SimpleXMLElement */ foreach ($options as $option) { if ($option->count()) { - $value = $this->_parseOptions($option->children()); + $value = $this->parseOptions($option->children()); } else { $value = (string) $option; } @@ -688,125 +774,155 @@ private function _parseOptions(SimpleXMLElement $options) } else { $array[] = $value; } + } return $array; } /** - * Constructs a joinColumn mapping array based on the information - * found in the given SimpleXMLElement. + * @param SimpleXMLElement $fieldElement + * @param string $fieldName + * @param bool $isVersioned * - * @param SimpleXMLElement $joinColumnElement The XML element. - * - * @return array The mapping array. + * @return Mapping\FieldMetadata */ - private function joinColumnToArray(SimpleXMLElement $joinColumnElement) + private function convertFieldElementToFieldMetadata(SimpleXMLElement $fieldElement, string $fieldName, bool $isVersioned) { - $joinColumn = [ - 'name' => (string) $joinColumnElement['name'], - 'referencedColumnName' => (string) $joinColumnElement['referenced-column-name'] - ]; + $fieldMetadata = $isVersioned + ? new Mapping\VersionFieldMetadata($fieldName) + : new Mapping\FieldMetadata($fieldName) + ; - if (isset($joinColumnElement['unique'])) { - $joinColumn['unique'] = $this->evaluateBoolean($joinColumnElement['unique']); - } + $fieldMetadata->setType(Type::getType('string')); - if (isset($joinColumnElement['nullable'])) { - $joinColumn['nullable'] = $this->evaluateBoolean($joinColumnElement['nullable']); + if (isset($fieldElement['type'])) { + $fieldMetadata->setType(Type::getType((string) $fieldElement['type'])); } - if (isset($joinColumnElement['on-delete'])) { - $joinColumn['onDelete'] = (string) $joinColumnElement['on-delete']; + if (isset($fieldElement['column'])) { + $fieldMetadata->setColumnName((string) $fieldElement['column']); } - if (isset($joinColumnElement['column-definition'])) { - $joinColumn['columnDefinition'] = (string) $joinColumnElement['column-definition']; + if (isset($fieldElement['length'])) { + $fieldMetadata->setLength((int) $fieldElement['length']); } - return $joinColumn; - } - - /** - * Parses the given field as array. - * - * @param SimpleXMLElement $fieldMapping - * - * @return array - */ - private function columnToArray(SimpleXMLElement $fieldMapping) - { - $mapping = [ - 'fieldName' => (string) $fieldMapping['name'], - ]; + if (isset($fieldElement['precision'])) { + $fieldMetadata->setPrecision((int) $fieldElement['precision']); + } - if (isset($fieldMapping['type'])) { - $mapping['type'] = (string) $fieldMapping['type']; + if (isset($fieldElement['scale'])) { + $fieldMetadata->setScale((int) $fieldElement['scale']); } - if (isset($fieldMapping['column'])) { - $mapping['columnName'] = (string) $fieldMapping['column']; + if (isset($fieldElement['unique'])) { + $fieldMetadata->setUnique($this->evaluateBoolean($fieldElement['unique'])); } - if (isset($fieldMapping['length'])) { - $mapping['length'] = (int) $fieldMapping['length']; + if (isset($fieldElement['nullable'])) { + $fieldMetadata->setNullable($this->evaluateBoolean($fieldElement['nullable'])); } - if (isset($fieldMapping['precision'])) { - $mapping['precision'] = (int) $fieldMapping['precision']; + if (isset($fieldElement['column-definition'])) { + $fieldMetadata->setColumnDefinition((string) $fieldElement['column-definition']); } - if (isset($fieldMapping['scale'])) { - $mapping['scale'] = (int) $fieldMapping['scale']; + if (isset($fieldElement->options)) { + $fieldMetadata->setOptions($this->parseOptions($fieldElement->options->children())); } - if (isset($fieldMapping['unique'])) { - $mapping['unique'] = $this->evaluateBoolean($fieldMapping['unique']); + return $fieldMetadata; + } + + /** + * Constructs a joinColumn mapping array based on the information + * found in the given SimpleXMLElement. + * + * @param SimpleXMLElement $joinColumnElement The XML element. + * + * @return Mapping\JoinColumnMetadata + */ + private function convertJoinColumnElementToJoinColumnMetadata(SimpleXMLElement $joinColumnElement) + { + $joinColumnMetadata = new Mapping\JoinColumnMetadata(); + + $joinColumnMetadata->setColumnName((string) $joinColumnElement['name']); + $joinColumnMetadata->setReferencedColumnName((string) $joinColumnElement['referenced-column-name']); + + if (isset($joinColumnElement['column-definition'])) { + $joinColumnMetadata->setColumnDefinition((string) $joinColumnElement['column-definition']); } - if (isset($fieldMapping['nullable'])) { - $mapping['nullable'] = $this->evaluateBoolean($fieldMapping['nullable']); + if (isset($joinColumnElement['field-name'])) { + $joinColumnMetadata->setAliasedName((string) $joinColumnElement['field-name']); } - if (isset($fieldMapping['version']) && $fieldMapping['version']) { - $mapping['version'] = $this->evaluateBoolean($fieldMapping['version']); + if (isset($joinColumnElement['nullable'])) { + $joinColumnMetadata->setNullable($this->evaluateBoolean($joinColumnElement['nullable'])); } - if (isset($fieldMapping['column-definition'])) { - $mapping['columnDefinition'] = (string) $fieldMapping['column-definition']; + if (isset($joinColumnElement['unique'])) { + $joinColumnMetadata->setUnique($this->evaluateBoolean($joinColumnElement['unique'])); } - if (isset($fieldMapping->options)) { - $mapping['options'] = $this->_parseOptions($fieldMapping->options->children()); + if (isset($joinColumnElement['on-delete'])) { + $joinColumnMetadata->setOnDelete(strtoupper((string) $joinColumnElement['on-delete'])); } - return $mapping; + return $joinColumnMetadata; } /** - * Parse / Normalize the cache configuration + * Parse the given Cache as CacheMetadata * - * @param SimpleXMLElement $cacheMapping + * @param \SimpleXMLElement $cacheMapping + * @param Mapping\ClassMetadata $metadata + * @param null|string $fieldName * - * @return array + * @return Mapping\CacheMetadata */ - private function cacheToArray(SimpleXMLElement $cacheMapping) + private function convertCacheElementToCacheMetadata( + SimpleXMLElement $cacheMapping, + Mapping\ClassMetadata $metadata, + $fieldName = null + ) { - $region = isset($cacheMapping['region']) ? (string) $cacheMapping['region'] : null; - $usage = isset($cacheMapping['usage']) ? strtoupper($cacheMapping['usage']) : null; + $baseRegion = strtolower(str_replace('\\', '_', $metadata->getRootClassName())); + $defaultRegion = $baseRegion . ($fieldName ? '__' . $fieldName : ''); - if ($usage && ! defined('Doctrine\ORM\Mapping\ClassMetadata::CACHE_USAGE_' . $usage)) { - throw new \InvalidArgumentException(sprintf('Invalid cache usage "%s"', $usage)); - } + $region = isset($cacheMapping['region']) ? (string) $cacheMapping['region'] : $defaultRegion; + $usage = isset($cacheMapping['usage']) + ? constant(sprintf('%s::%s', Mapping\CacheUsage::class, strtoupper((string) $cacheMapping['usage']))) + : Mapping\CacheUsage::READ_ONLY + ; - if ($usage) { - $usage = constant('Doctrine\ORM\Mapping\ClassMetadata::CACHE_USAGE_' . $usage); - } + return new Mapping\CacheMetadata($usage, $region); + } - return [ - 'usage' => $usage, - 'region' => $region, + /** + * Parses the given method. + * + * @param \ReflectionMethod $method + * + * @return array + */ + private function getMethodCallbacks(\ReflectionMethod $method) + { + $events = [ + Events::prePersist, + Events::postPersist, + Events::preUpdate, + Events::postUpdate, + Events::preRemove, + Events::postRemove, + Events::postLoad, + Events::preFlush, ]; + + return array_filter($events, function ($eventName) use ($method) { + return $eventName === $method->getName(); + }); } /** @@ -816,16 +932,17 @@ private function cacheToArray(SimpleXMLElement $cacheMapping) * * @return array The list of cascade options. */ - private function _getCascadeMappings(SimpleXMLElement $cascadeElement) + private function getCascadeMappings(SimpleXMLElement $cascadeElement) { $cascades = []; + /* @var $action SimpleXmlElement */ foreach ($cascadeElement->children() as $action) { // According to the JPA specifications, XML uses "cascade-persist" - // instead of "persist". Here, both variations - // are supported because both YAML and Annotation use "persist" - // and we want to make sure that this driver doesn't need to know - // anything about the supported cascading actions + // instead of "persist". Here, both variations are supported + // because Annotation use "persist" and we want to make sure that + // this driver doesn't need to know anything about the supported + // cascading actions $cascades[] = str_replace('cascade-', '', $action->getName()); } diff --git a/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php b/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php deleted file mode 100644 index c4fb45ecedd..00000000000 --- a/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php +++ /dev/null @@ -1,815 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping\Driver; - -use Doctrine\Common\Persistence\Mapping\ClassMetadata; -use Doctrine\ORM\Mapping\Builder\EntityListenerBuilder; -use Doctrine\Common\Persistence\Mapping\Driver\FileDriver; -use Doctrine\ORM\Mapping\ClassMetadata as Metadata; -use Doctrine\ORM\Mapping\MappingException; -use Symfony\Component\Yaml\Yaml; - -/** - * The YamlDriver reads the mapping metadata from yaml schema files. - * - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan H. Wage - * @author Roman Borschel - */ -class YamlDriver extends FileDriver -{ - const DEFAULT_FILE_EXTENSION = '.dcm.yml'; - - /** - * {@inheritDoc} - */ - public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENSION) - { - parent::__construct($locator, $fileExtension); - } - - /** - * {@inheritDoc} - */ - public function loadMetadataForClass($className, ClassMetadata $metadata) - { - /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadataInfo */ - $element = $this->getElement($className); - - if ($element['type'] == 'entity') { - if (isset($element['repositoryClass'])) { - $metadata->setCustomRepositoryClass($element['repositoryClass']); - } - if (isset($element['readOnly']) && $element['readOnly'] == true) { - $metadata->markReadOnly(); - } - } else if ($element['type'] == 'mappedSuperclass') { - $metadata->setCustomRepositoryClass( - isset($element['repositoryClass']) ? $element['repositoryClass'] : null - ); - $metadata->isMappedSuperclass = true; - } else if ($element['type'] == 'embeddable') { - $metadata->isEmbeddedClass = true; - } else { - throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className); - } - - // Evaluate root level properties - $primaryTable = []; - - if (isset($element['table'])) { - $primaryTable['name'] = $element['table']; - } - - if (isset($element['schema'])) { - $primaryTable['schema'] = $element['schema']; - } - - // Evaluate second level cache - if (isset($element['cache'])) { - $metadata->enableCache($this->cacheToArray($element['cache'])); - } - - $metadata->setPrimaryTable($primaryTable); - - // Evaluate named queries - if (isset($element['namedQueries'])) { - foreach ($element['namedQueries'] as $name => $queryMapping) { - if (is_string($queryMapping)) { - $queryMapping = ['query' => $queryMapping]; - } - - if ( ! isset($queryMapping['name'])) { - $queryMapping['name'] = $name; - } - - $metadata->addNamedQuery($queryMapping); - } - } - - // Evaluate named native queries - if (isset($element['namedNativeQueries'])) { - foreach ($element['namedNativeQueries'] as $name => $mappingElement) { - if (!isset($mappingElement['name'])) { - $mappingElement['name'] = $name; - } - $metadata->addNamedNativeQuery( - [ - 'name' => $mappingElement['name'], - 'query' => isset($mappingElement['query']) ? $mappingElement['query'] : null, - 'resultClass' => isset($mappingElement['resultClass']) ? $mappingElement['resultClass'] : null, - 'resultSetMapping' => isset($mappingElement['resultSetMapping']) ? $mappingElement['resultSetMapping'] : null, - ] - ); - } - } - - // Evaluate sql result set mappings - if (isset($element['sqlResultSetMappings'])) { - foreach ($element['sqlResultSetMappings'] as $name => $resultSetMapping) { - if (!isset($resultSetMapping['name'])) { - $resultSetMapping['name'] = $name; - } - - $entities = []; - $columns = []; - if (isset($resultSetMapping['entityResult'])) { - foreach ($resultSetMapping['entityResult'] as $entityResultElement) { - $entityResult = [ - 'fields' => [], - 'entityClass' => isset($entityResultElement['entityClass']) ? $entityResultElement['entityClass'] : null, - 'discriminatorColumn' => isset($entityResultElement['discriminatorColumn']) ? $entityResultElement['discriminatorColumn'] : null, - ]; - - if (isset($entityResultElement['fieldResult'])) { - foreach ($entityResultElement['fieldResult'] as $fieldResultElement) { - $entityResult['fields'][] = [ - 'name' => isset($fieldResultElement['name']) ? $fieldResultElement['name'] : null, - 'column' => isset($fieldResultElement['column']) ? $fieldResultElement['column'] : null, - ]; - } - } - - $entities[] = $entityResult; - } - } - - - if (isset($resultSetMapping['columnResult'])) { - foreach ($resultSetMapping['columnResult'] as $columnResultAnnot) { - $columns[] = [ - 'name' => isset($columnResultAnnot['name']) ? $columnResultAnnot['name'] : null, - ]; - } - } - - $metadata->addSqlResultSetMapping( - [ - 'name' => $resultSetMapping['name'], - 'entities' => $entities, - 'columns' => $columns - ] - ); - } - } - - if (isset($element['inheritanceType'])) { - $metadata->setInheritanceType(constant('Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_' . strtoupper($element['inheritanceType']))); - - if ($metadata->inheritanceType != Metadata::INHERITANCE_TYPE_NONE) { - // Evaluate discriminatorColumn - if (isset($element['discriminatorColumn'])) { - $discrColumn = $element['discriminatorColumn']; - $metadata->setDiscriminatorColumn( - [ - 'name' => isset($discrColumn['name']) ? (string) $discrColumn['name'] : null, - 'type' => isset($discrColumn['type']) ? (string) $discrColumn['type'] : 'string', - 'length' => isset($discrColumn['length']) ? (string) $discrColumn['length'] : 255, - 'columnDefinition' => isset($discrColumn['columnDefinition']) ? (string) $discrColumn['columnDefinition'] : null - ] - ); - } else { - $metadata->setDiscriminatorColumn(['name' => 'dtype', 'type' => 'string', 'length' => 255]); - } - - // Evaluate discriminatorMap - if (isset($element['discriminatorMap'])) { - $metadata->setDiscriminatorMap($element['discriminatorMap']); - } - } - } - - - // Evaluate changeTrackingPolicy - if (isset($element['changeTrackingPolicy'])) { - $metadata->setChangeTrackingPolicy(constant('Doctrine\ORM\Mapping\ClassMetadata::CHANGETRACKING_' - . strtoupper($element['changeTrackingPolicy']))); - } - - // Evaluate indexes - if (isset($element['indexes'])) { - foreach ($element['indexes'] as $name => $indexYml) { - if ( ! isset($indexYml['name'])) { - $indexYml['name'] = $name; - } - - if (is_string($indexYml['columns'])) { - $index = ['columns' => array_map('trim', explode(',', $indexYml['columns']))]; - } else { - $index = ['columns' => $indexYml['columns']]; - } - - if (isset($indexYml['flags'])) { - if (is_string($indexYml['flags'])) { - $index['flags'] = array_map('trim', explode(',', $indexYml['flags'])); - } else { - $index['flags'] = $indexYml['flags']; - } - } - - if (isset($indexYml['options'])) { - $index['options'] = $indexYml['options']; - } - - $metadata->table['indexes'][$indexYml['name']] = $index; - } - } - - // Evaluate uniqueConstraints - if (isset($element['uniqueConstraints'])) { - foreach ($element['uniqueConstraints'] as $name => $uniqueYml) { - if ( ! isset($uniqueYml['name'])) { - $uniqueYml['name'] = $name; - } - - if (is_string($uniqueYml['columns'])) { - $unique = ['columns' => array_map('trim', explode(',', $uniqueYml['columns']))]; - } else { - $unique = ['columns' => $uniqueYml['columns']]; - } - - if (isset($uniqueYml['options'])) { - $unique['options'] = $uniqueYml['options']; - } - - $metadata->table['uniqueConstraints'][$uniqueYml['name']] = $unique; - } - } - - if (isset($element['options'])) { - $metadata->table['options'] = $element['options']; - } - - $associationIds = []; - if (isset($element['id'])) { - // Evaluate identifier settings - foreach ($element['id'] as $name => $idElement) { - if (isset($idElement['associationKey']) && $idElement['associationKey'] == true) { - $associationIds[$name] = true; - continue; - } - - $mapping = [ - 'id' => true, - 'fieldName' => $name - ]; - - if (isset($idElement['type'])) { - $mapping['type'] = $idElement['type']; - } - - if (isset($idElement['column'])) { - $mapping['columnName'] = $idElement['column']; - } - - if (isset($idElement['length'])) { - $mapping['length'] = $idElement['length']; - } - - if (isset($idElement['columnDefinition'])) { - $mapping['columnDefinition'] = $idElement['columnDefinition']; - } - - if (isset($idElement['options'])) { - $mapping['options'] = $idElement['options']; - } - - $metadata->mapField($mapping); - - if (isset($idElement['generator'])) { - $metadata->setIdGeneratorType(constant('Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_' - . strtoupper($idElement['generator']['strategy']))); - } - // Check for SequenceGenerator/TableGenerator definition - if (isset($idElement['sequenceGenerator'])) { - $metadata->setSequenceGeneratorDefinition($idElement['sequenceGenerator']); - } else if (isset($idElement['customIdGenerator'])) { - $customGenerator = $idElement['customIdGenerator']; - $metadata->setCustomGeneratorDefinition( - [ - 'class' => (string) $customGenerator['class'] - ] - ); - } else if (isset($idElement['tableGenerator'])) { - throw MappingException::tableIdGeneratorNotImplemented($className); - } - } - } - - // Evaluate fields - if (isset($element['fields'])) { - foreach ($element['fields'] as $name => $fieldMapping) { - - $mapping = $this->columnToArray($name, $fieldMapping); - - if (isset($fieldMapping['id'])) { - $mapping['id'] = true; - if (isset($fieldMapping['generator']['strategy'])) { - $metadata->setIdGeneratorType(constant('Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_' - . strtoupper($fieldMapping['generator']['strategy']))); - } - } - - if (isset($mapping['version'])) { - $metadata->setVersionMapping($mapping); - unset($mapping['version']); - } - - $metadata->mapField($mapping); - } - } - - if (isset($element['embedded'])) { - foreach ($element['embedded'] as $name => $embeddedMapping) { - $mapping = [ - 'fieldName' => $name, - 'class' => $embeddedMapping['class'], - 'columnPrefix' => isset($embeddedMapping['columnPrefix']) ? $embeddedMapping['columnPrefix'] : null, - ]; - $metadata->mapEmbedded($mapping); - } - } - - // Evaluate oneToOne relationships - if (isset($element['oneToOne'])) { - foreach ($element['oneToOne'] as $name => $oneToOneElement) { - $mapping = [ - 'fieldName' => $name, - 'targetEntity' => $oneToOneElement['targetEntity'] - ]; - - if (isset($associationIds[$mapping['fieldName']])) { - $mapping['id'] = true; - } - - if (isset($oneToOneElement['fetch'])) { - $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $oneToOneElement['fetch']); - } - - if (isset($oneToOneElement['mappedBy'])) { - $mapping['mappedBy'] = $oneToOneElement['mappedBy']; - } else { - if (isset($oneToOneElement['inversedBy'])) { - $mapping['inversedBy'] = $oneToOneElement['inversedBy']; - } - - $joinColumns = []; - - if (isset($oneToOneElement['joinColumn'])) { - $joinColumns[] = $this->joinColumnToArray($oneToOneElement['joinColumn']); - } else if (isset($oneToOneElement['joinColumns'])) { - foreach ($oneToOneElement['joinColumns'] as $joinColumnName => $joinColumnElement) { - if ( ! isset($joinColumnElement['name'])) { - $joinColumnElement['name'] = $joinColumnName; - } - - $joinColumns[] = $this->joinColumnToArray($joinColumnElement); - } - } - - $mapping['joinColumns'] = $joinColumns; - } - - if (isset($oneToOneElement['cascade'])) { - $mapping['cascade'] = $oneToOneElement['cascade']; - } - - if (isset($oneToOneElement['orphanRemoval'])) { - $mapping['orphanRemoval'] = (bool) $oneToOneElement['orphanRemoval']; - } - - // Evaluate second level cache - if (isset($oneToOneElement['cache'])) { - $mapping['cache'] = $metadata->getAssociationCacheDefaults($mapping['fieldName'], $this->cacheToArray($oneToOneElement['cache'])); - } - - $metadata->mapOneToOne($mapping); - } - } - - // Evaluate oneToMany relationships - if (isset($element['oneToMany'])) { - foreach ($element['oneToMany'] as $name => $oneToManyElement) { - $mapping = [ - 'fieldName' => $name, - 'targetEntity' => $oneToManyElement['targetEntity'], - 'mappedBy' => $oneToManyElement['mappedBy'] - ]; - - if (isset($oneToManyElement['fetch'])) { - $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $oneToManyElement['fetch']); - } - - if (isset($oneToManyElement['cascade'])) { - $mapping['cascade'] = $oneToManyElement['cascade']; - } - - if (isset($oneToManyElement['orphanRemoval'])) { - $mapping['orphanRemoval'] = (bool) $oneToManyElement['orphanRemoval']; - } - - if (isset($oneToManyElement['orderBy'])) { - $mapping['orderBy'] = $oneToManyElement['orderBy']; - } - - if (isset($oneToManyElement['indexBy'])) { - $mapping['indexBy'] = $oneToManyElement['indexBy']; - } - - - // Evaluate second level cache - if (isset($oneToManyElement['cache'])) { - $mapping['cache'] = $metadata->getAssociationCacheDefaults($mapping['fieldName'], $this->cacheToArray($oneToManyElement['cache'])); - } - - $metadata->mapOneToMany($mapping); - } - } - - // Evaluate manyToOne relationships - if (isset($element['manyToOne'])) { - foreach ($element['manyToOne'] as $name => $manyToOneElement) { - $mapping = [ - 'fieldName' => $name, - 'targetEntity' => $manyToOneElement['targetEntity'] - ]; - - if (isset($associationIds[$mapping['fieldName']])) { - $mapping['id'] = true; - } - - if (isset($manyToOneElement['fetch'])) { - $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $manyToOneElement['fetch']); - } - - if (isset($manyToOneElement['inversedBy'])) { - $mapping['inversedBy'] = $manyToOneElement['inversedBy']; - } - - $joinColumns = []; - - if (isset($manyToOneElement['joinColumn'])) { - $joinColumns[] = $this->joinColumnToArray($manyToOneElement['joinColumn']); - } else if (isset($manyToOneElement['joinColumns'])) { - foreach ($manyToOneElement['joinColumns'] as $joinColumnName => $joinColumnElement) { - if ( ! isset($joinColumnElement['name'])) { - $joinColumnElement['name'] = $joinColumnName; - } - - $joinColumns[] = $this->joinColumnToArray($joinColumnElement); - } - } - - $mapping['joinColumns'] = $joinColumns; - - if (isset($manyToOneElement['cascade'])) { - $mapping['cascade'] = $manyToOneElement['cascade']; - } - - // Evaluate second level cache - if (isset($manyToOneElement['cache'])) { - $mapping['cache'] = $metadata->getAssociationCacheDefaults($mapping['fieldName'], $this->cacheToArray($manyToOneElement['cache'])); - } - - $metadata->mapManyToOne($mapping); - } - } - - // Evaluate manyToMany relationships - if (isset($element['manyToMany'])) { - foreach ($element['manyToMany'] as $name => $manyToManyElement) { - $mapping = [ - 'fieldName' => $name, - 'targetEntity' => $manyToManyElement['targetEntity'] - ]; - - if (isset($manyToManyElement['fetch'])) { - $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $manyToManyElement['fetch']); - } - - if (isset($manyToManyElement['mappedBy'])) { - $mapping['mappedBy'] = $manyToManyElement['mappedBy']; - } else if (isset($manyToManyElement['joinTable'])) { - - $joinTableElement = $manyToManyElement['joinTable']; - $joinTable = [ - 'name' => $joinTableElement['name'] - ]; - - if (isset($joinTableElement['schema'])) { - $joinTable['schema'] = $joinTableElement['schema']; - } - - if (isset($joinTableElement['joinColumns'])) { - foreach ($joinTableElement['joinColumns'] as $joinColumnName => $joinColumnElement) { - if ( ! isset($joinColumnElement['name'])) { - $joinColumnElement['name'] = $joinColumnName; - } - $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumnElement); - } - } - - if (isset($joinTableElement['inverseJoinColumns'])) { - foreach ($joinTableElement['inverseJoinColumns'] as $joinColumnName => $joinColumnElement) { - if ( ! isset($joinColumnElement['name'])) { - $joinColumnElement['name'] = $joinColumnName; - } - $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumnElement); - } - } - - $mapping['joinTable'] = $joinTable; - } - - if (isset($manyToManyElement['inversedBy'])) { - $mapping['inversedBy'] = $manyToManyElement['inversedBy']; - } - - if (isset($manyToManyElement['cascade'])) { - $mapping['cascade'] = $manyToManyElement['cascade']; - } - - if (isset($manyToManyElement['orderBy'])) { - $mapping['orderBy'] = $manyToManyElement['orderBy']; - } - - if (isset($manyToManyElement['indexBy'])) { - $mapping['indexBy'] = $manyToManyElement['indexBy']; - } - - if (isset($manyToManyElement['orphanRemoval'])) { - $mapping['orphanRemoval'] = (bool) $manyToManyElement['orphanRemoval']; - } - - // Evaluate second level cache - if (isset($manyToManyElement['cache'])) { - $mapping['cache'] = $metadata->getAssociationCacheDefaults($mapping['fieldName'], $this->cacheToArray($manyToManyElement['cache'])); - } - - $metadata->mapManyToMany($mapping); - } - } - - // Evaluate associationOverride - if (isset($element['associationOverride']) && is_array($element['associationOverride'])) { - - foreach ($element['associationOverride'] as $fieldName => $associationOverrideElement) { - $override = []; - - // Check for joinColumn - if (isset($associationOverrideElement['joinColumn'])) { - $joinColumns = []; - foreach ($associationOverrideElement['joinColumn'] as $name => $joinColumnElement) { - if ( ! isset($joinColumnElement['name'])) { - $joinColumnElement['name'] = $name; - } - $joinColumns[] = $this->joinColumnToArray($joinColumnElement); - } - $override['joinColumns'] = $joinColumns; - } - - // Check for joinTable - if (isset($associationOverrideElement['joinTable'])) { - - $joinTableElement = $associationOverrideElement['joinTable']; - $joinTable = [ - 'name' => $joinTableElement['name'] - ]; - - if (isset($joinTableElement['schema'])) { - $joinTable['schema'] = $joinTableElement['schema']; - } - - foreach ($joinTableElement['joinColumns'] as $name => $joinColumnElement) { - if ( ! isset($joinColumnElement['name'])) { - $joinColumnElement['name'] = $name; - } - - $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumnElement); - } - - foreach ($joinTableElement['inverseJoinColumns'] as $name => $joinColumnElement) { - if ( ! isset($joinColumnElement['name'])) { - $joinColumnElement['name'] = $name; - } - - $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumnElement); - } - - $override['joinTable'] = $joinTable; - } - - // Check for inversedBy - if (isset($associationOverrideElement['inversedBy'])) { - $override['inversedBy'] = (string) $associationOverrideElement['inversedBy']; - } - - // Check for `fetch` - if (isset($associationOverrideElement['fetch'])) { - $override['fetch'] = constant(Metadata::class . '::FETCH_' . $associationOverrideElement['fetch']); - } - - $metadata->setAssociationOverride($fieldName, $override); - } - } - - // Evaluate associationOverride - if (isset($element['attributeOverride']) && is_array($element['attributeOverride'])) { - - foreach ($element['attributeOverride'] as $fieldName => $attributeOverrideElement) { - $mapping = $this->columnToArray($fieldName, $attributeOverrideElement); - $metadata->setAttributeOverride($fieldName, $mapping); - } - } - - // Evaluate lifeCycleCallbacks - if (isset($element['lifecycleCallbacks'])) { - foreach ($element['lifecycleCallbacks'] as $type => $methods) { - foreach ($methods as $method) { - $metadata->addLifecycleCallback($method, constant('Doctrine\ORM\Events::' . $type)); - } - } - } - - // Evaluate entityListeners - if (isset($element['entityListeners'])) { - foreach ($element['entityListeners'] as $className => $entityListener) { - // Evaluate the listener using naming convention. - if (empty($entityListener)) { - EntityListenerBuilder::bindEntityListener($metadata, $className); - - continue; - } - - foreach ($entityListener as $eventName => $callbackElement) { - foreach ($callbackElement as $methodName) { - $metadata->addEntityListener($eventName, $className, $methodName); - } - } - } - } - } - - /** - * Constructs a joinColumn mapping array based on the information - * found in the given join column element. - * - * @param array $joinColumnElement The array join column element. - * - * @return array The mapping array. - */ - private function joinColumnToArray($joinColumnElement) - { - $joinColumn = []; - if (isset($joinColumnElement['referencedColumnName'])) { - $joinColumn['referencedColumnName'] = (string) $joinColumnElement['referencedColumnName']; - } - - if (isset($joinColumnElement['name'])) { - $joinColumn['name'] = (string) $joinColumnElement['name']; - } - - if (isset($joinColumnElement['fieldName'])) { - $joinColumn['fieldName'] = (string) $joinColumnElement['fieldName']; - } - - if (isset($joinColumnElement['unique'])) { - $joinColumn['unique'] = (bool) $joinColumnElement['unique']; - } - - if (isset($joinColumnElement['nullable'])) { - $joinColumn['nullable'] = (bool) $joinColumnElement['nullable']; - } - - if (isset($joinColumnElement['onDelete'])) { - $joinColumn['onDelete'] = $joinColumnElement['onDelete']; - } - - if (isset($joinColumnElement['columnDefinition'])) { - $joinColumn['columnDefinition'] = $joinColumnElement['columnDefinition']; - } - - return $joinColumn; - } - - /** - * Parses the given column as array. - * - * @param string $fieldName - * @param array $column - * - * @return array - */ - private function columnToArray($fieldName, $column) - { - $mapping = [ - 'fieldName' => $fieldName - ]; - - if (isset($column['type'])) { - $params = explode('(', $column['type']); - - $column['type'] = $params[0]; - $mapping['type'] = $column['type']; - - if (isset($params[1])) { - $column['length'] = (integer) substr($params[1], 0, strlen($params[1]) - 1); - } - } - - if (isset($column['column'])) { - $mapping['columnName'] = $column['column']; - } - - if (isset($column['length'])) { - $mapping['length'] = $column['length']; - } - - if (isset($column['precision'])) { - $mapping['precision'] = $column['precision']; - } - - if (isset($column['scale'])) { - $mapping['scale'] = $column['scale']; - } - - if (isset($column['unique'])) { - $mapping['unique'] = (bool) $column['unique']; - } - - if (isset($column['options'])) { - $mapping['options'] = $column['options']; - } - - if (isset($column['nullable'])) { - $mapping['nullable'] = $column['nullable']; - } - - if (isset($column['version']) && $column['version']) { - $mapping['version'] = $column['version']; - } - - if (isset($column['columnDefinition'])) { - $mapping['columnDefinition'] = $column['columnDefinition']; - } - - return $mapping; - } - - /** - * Parse / Normalize the cache configuration - * - * @param array $cacheMapping - * - * @return array - */ - private function cacheToArray($cacheMapping) - { - $region = isset($cacheMapping['region']) ? (string) $cacheMapping['region'] : null; - $usage = isset($cacheMapping['usage']) ? strtoupper($cacheMapping['usage']) : null; - - if ($usage && ! defined('Doctrine\ORM\Mapping\ClassMetadata::CACHE_USAGE_' . $usage)) { - throw new \InvalidArgumentException(sprintf('Invalid cache usage "%s"', $usage)); - } - - if ($usage) { - $usage = constant('Doctrine\ORM\Mapping\ClassMetadata::CACHE_USAGE_' . $usage); - } - - return [ - 'usage' => $usage, - 'region' => $region, - ]; - } - - /** - * {@inheritDoc} - */ - protected function loadMappingFile($file) - { - if (defined(Yaml::class . '::PARSE_KEYS_AS_STRINGS')) { - return Yaml::parse(file_get_contents($file), Yaml::PARSE_KEYS_AS_STRINGS); - } - - return Yaml::parse(file_get_contents($file)); - } -} diff --git a/lib/Doctrine/ORM/Mapping/Embeddable.php b/lib/Doctrine/ORM/Mapping/Embeddable.php deleted file mode 100644 index f14bfac82a6..00000000000 --- a/lib/Doctrine/ORM/Mapping/Embeddable.php +++ /dev/null @@ -1,28 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("CLASS") - */ -final class Embeddable implements Annotation -{ -} diff --git a/lib/Doctrine/ORM/Mapping/Embedded.php b/lib/Doctrine/ORM/Mapping/Embedded.php deleted file mode 100644 index 37339108bc9..00000000000 --- a/lib/Doctrine/ORM/Mapping/Embedded.php +++ /dev/null @@ -1,38 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("PROPERTY") - */ -final class Embedded implements Annotation -{ - /** - * @Required - * @var string - */ - public $class; - - /** - * @var mixed - */ - public $columnPrefix; -} diff --git a/lib/Doctrine/ORM/Mapping/EmbeddedClassMetadata.php b/lib/Doctrine/ORM/Mapping/EmbeddedClassMetadata.php new file mode 100644 index 00000000000..d3196461824 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/EmbeddedClassMetadata.php @@ -0,0 +1,129 @@ + + * + * @property MappedSuperClassMetadata $parent + */ +class EmbeddedClassMetadata extends ComponentMetadata implements Property +{ + /** @var ClassMetadata */ + private $declaringClass; + + /** @var \ReflectionProperty */ + private $reflection; + + /** @var string */ + private $name; + + /** @var boolean */ + protected $primaryKey = false; + + /** + * EmbeddedClassMetadata constructor. + * + * @param string $name + * @param string $className + * @param MappedSuperClassMetadata|null $parent + */ + public function __construct(string $name, string $className, ?MappedSuperClassMetadata $parent = null) + { + parent::__construct($className, $parent); + + $this->name = $name; + } + + /** + * {@inheritdoc} + */ + public function getDeclaringClass() : ComponentMetadata + { + return $this->declaringClass; + } + + /** + * @param ComponentMetadata $declaringClass + */ + public function setDeclaringClass(ComponentMetadata $declaringClass) : void + { + $this->declaringClass = $declaringClass; + } + + /** + * {@inheritdoc} + */ + public function getName() : string + { + return $this->name; + } + + /** + * {@inheritdoc} + */ + public function setName($name) : void + { + $this->name = $name; + } + + /** + * @param bool $isPrimaryKey + */ + public function setPrimaryKey(bool $isPrimaryKey) : void + { + $this->primaryKey = $isPrimaryKey; + } + + /** + * @return bool + */ + public function isPrimaryKey() : bool + { + return $this->primaryKey; + } + + /** + * {@inheritdoc} + */ + public function setValue($object, $value) : void + { + $this->reflection->setValue($object, $value); + } + + /** + * {@inheritdoc} + */ + public function getValue($object) + { + return $this->reflection->getValue($object); + } + + /** + * {@inheritdoc} + */ + public function setReflectionProperty(\ReflectionProperty $reflectionProperty) : void + { + $this->reflection = $reflectionProperty; + } + + /** + * {@inheritdoc} + */ + public function wakeupReflection(ReflectionService $reflectionService) : void + { + $this->setReflectionProperty( + $reflectionService->getAccessibleProperty($this->declaringClass->getClassName(), $this->name) + ); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Entity.php b/lib/Doctrine/ORM/Mapping/Entity.php deleted file mode 100644 index edf6ad5a4be..00000000000 --- a/lib/Doctrine/ORM/Mapping/Entity.php +++ /dev/null @@ -1,37 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("CLASS") - */ -final class Entity implements Annotation -{ - /** - * @var string - */ - public $repositoryClass; - - /** - * @var boolean - */ - public $readOnly = false; -} diff --git a/lib/Doctrine/ORM/Mapping/EntityClassMetadata.php b/lib/Doctrine/ORM/Mapping/EntityClassMetadata.php new file mode 100644 index 00000000000..57bb4133c32 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/EntityClassMetadata.php @@ -0,0 +1,392 @@ + + */ +abstract class EntityClassMetadata extends ComponentMetadata +{ + /** @var string The name of the Entity */ + protected $entityName; + + /** + * @var null|string The name of the custom repository class used for the entity class. + */ + protected $customRepositoryClassName; + + /** + * @var null|Property The field which is used for versioning in optimistic locking (if any). + */ + protected $declaredVersion = null; + + /** + * Whether this class describes the mapping of a read-only class. + * That means it is never considered for change-tracking in the UnitOfWork. + * It is a very helpful performance optimization for entities that are immutable, + * either in your domain or through the relation database (coming from a view, + * or a history table for example). + * + * @var boolean + */ + protected $readOnly = false; + + /** + * List of all sub-classes (descendants) metadata. + * + * @var array + */ + protected $subClasses = []; + + /** + * The named queries allowed to be called directly from Repository. + * + * @var array + */ + protected $namedQueries = []; + + /** + * READ-ONLY: The named native queries allowed to be called directly from Repository. + * + * A native SQL named query definition has the following structure: + *
+     * array(
+     *     'name'               => ,
+     *     'query'              => ,
+     *     'resultClass'        => ,
+     *     'resultSetMapping'   => 
+     * )
+     * 
+ * + * @var array + */ + protected $namedNativeQueries = []; + + /** + * READ-ONLY: The mappings of the results of native SQL queries. + * + * A native result mapping definition has the following structure: + *
+     * array(
+     *     'name'               => ,
+     *     'entities'           => array(),
+     *     'columns'            => array()
+     * )
+     * 
+ * + * @var array + */ + protected $sqlResultSetMappings = []; + + /** + * READ-ONLY: The registered lifecycle callbacks for entities of this class. + * + * @var array + */ + protected $lifecycleCallbacks = []; + + /** + * READ-ONLY: The registered entity listeners. + * + * @var array + */ + protected $entityListeners = []; + + /** + * READ-ONLY: The field names of all fields that are part of the identifier/primary key + * of the mapped entity class. + * + * @var array + */ + protected $identifier = []; + + /** + * READ-ONLY: The primary table metadata. + * + * @var TableMetadata + */ + protected $table; + + /** + * MappedSuperClassMetadata constructor. + * + * @param string $className + * @param ClassMetadataBuildingContext $metadataBuildingContext + */ + public function __construct(string $className, ClassMetadataBuildingContext $metadataBuildingContext) + { + parent::__construct($className); + + $this->entityName = $className; + } + + /** + * @return string + */ + public function getEntityName() : string + { + return $this->entityName; + } + + /** + * @param string $entityName + */ + public function setEntityName(string $entityName) : void + { + $this->entityName = $entityName; + } + + /** + * @return null|string + */ + public function getCustomRepositoryClassName() : ?string + { + return $this->customRepositoryClassName; + } + + /** + * @param null|string customRepositoryClassName + */ + public function setCustomRepositoryClassName(?string $customRepositoryClassName) : void + { + $this->customRepositoryClassName = $customRepositoryClassName; + } + + /** + * @return Property|null + */ + public function getDeclaredVersion() : ?Property + { + return $this->declaredVersion; + } + + /** + * @param Property $property + */ + public function setDeclaredVersion(Property $property) : void + { + $this->declaredVersion = $property; + } + + /** + * @return Property|null + */ + public function getVersion() : ?Property + { + /** @var ComponentMetadata|null $parent */ + $parent = $this->parent; + $version = $this->declaredVersion; + + if ($parent && ! $version) { + $version = $parent->getVersion(); + } + + return $version; + } + + /** + * @return bool + */ + public function isVersioned() : bool + { + return $this->getVersion() !== null; + } + + /** + * @param bool $readOnly + */ + public function setReadOnly(bool $readOnly) : void + { + $this->readOnly = $readOnly; + } + + /** + * @return bool + */ + public function isReadOnly() : bool + { + return $this->readOnly; + } + + /** + * @param SubClassMetadata $subClassMetadata + * + * @throws MappingException + */ + public function addSubClass(SubClassMetadata $subClassMetadata) : void + { + $superClassMetadata = $this->getSuperClass(); + + while ($superClassMetadata !== null) { + if ($superClassMetadata->entityName === $subClassMetadata->entityName) { + throw new MappingException( + sprintf( + 'Circular inheritance mapping detected: "%s" have itself as superclass when extending "%s".', + $subClassMetadata->entityName, + $superClassMetadata->entityName + ) + ); + } + + $superClassMetadata->subClasses[] = $subClassMetadata; + + $superClassMetadata = $superClassMetadata->parent; + } + + $this->subClasses[] = $subClassMetadata; + } + + /** + * @return bool + */ + public function hasSubClasses() : bool + { + return (bool) $this->subClasses; + } + + /** + * @return \Iterator + */ + public function getSubClassIterator() : \Iterator + { + $iterator = new \AppendIterator(); + + foreach ($this->subClasses as $subClassMetadata) { + $iterator->append($subClassMetadata->getSubClassIterator()); + } + + $iterator->append(new \ArrayIterator($this->subClasses)); + + return $iterator; + } + + /** + * Adds a named query. + * + * @param string $name + * @param string $dqlQuery + * + * @throws MappingException + */ + public function addNamedQuery(string $name, string $dqlQuery) : void + { + if (isset($this->namedQueries[$name])) { + throw MappingException::duplicateQueryMapping($this->entityName, $name); + } + + $this->namedQueries[$name] = $dqlQuery; + } + + /** + * Gets a named query. + * + * @param string $queryName The query name. + * + * @return string + * + * @throws MappingException + */ + public function getNamedQuery($queryName) : string + { + if (! isset($this->namedQueries[$queryName])) { + throw MappingException::queryNotFound($this->entityName, $queryName); + } + + return $this->namedQueries[$queryName]; + } + + /** + * Gets all named queries of the class. + * + * @return array + */ + public function getNamedQueries() : array + { + return $this->namedQueries; + } + + /** + * Gets a named native query. + * + * @param string $queryName The native query name. + * + * @return array + * + * @throws MappingException + * + * @todo guilhermeblanco This should return an object instead + */ + public function getNamedNativeQuery($queryName) : array + { + if (! isset($this->namedNativeQueries[$queryName])) { + throw MappingException::queryNotFound($this->entityName, $queryName); + } + + return $this->namedNativeQueries[$queryName]; + } + + /** + * Gets all named native queries of the class. + * + * @return array + */ + public function getNamedNativeQueries() : array + { + return $this->namedNativeQueries; + } + + /** + * Gets the result set mapping. + * + * @param string $name The result set mapping name. + * + * @return array + * + * @throws MappingException + * + * @todo guilhermeblanco This should return an object instead + */ + public function getSqlResultSetMapping($name) : array + { + if (! isset($this->sqlResultSetMappings[$name])) { + throw MappingException::resultMappingNotFound($this->entityName, $name); + } + + return $this->sqlResultSetMappings[$name]; + } + + /** + * Gets all sql result set mappings of the class. + * + * @return array + */ + public function getSqlResultSetMappings() : array + { + return $this->sqlResultSetMappings; + } + + /** + * {@inheritdoc} + */ + public function addDeclaredProperty(Property $property) : void + { + parent::addDeclaredProperty($property); + + if ($property instanceof VersionFieldMetadata) { + $this->setDeclaredVersion($property); + } + } + + /** + * @return RootClassMetadata + */ + abstract public function getRootClass() : RootClassMetadata; +} diff --git a/lib/Doctrine/ORM/Mapping/EntityListenerResolver.php b/lib/Doctrine/ORM/Mapping/EntityListenerResolver.php index b0c62c8c3a3..273326de86a 100644 --- a/lib/Doctrine/ORM/Mapping/EntityListenerResolver.php +++ b/lib/Doctrine/ORM/Mapping/EntityListenerResolver.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Mapping; @@ -35,7 +20,7 @@ interface EntityListenerResolver * * @return void */ - function clear($className = null); + public function clear($className = null); /** * Returns a entity listener instance for the given class name. @@ -44,12 +29,12 @@ function clear($className = null); * * @return object An entity listener */ - function resolve($className); + public function resolve($className); /** * Register a entity listener instance. * * @param object $object An entity listener */ - function register($object); + public function register($object); } diff --git a/lib/Doctrine/ORM/Mapping/EntityListeners.php b/lib/Doctrine/ORM/Mapping/EntityListeners.php deleted file mode 100644 index ae6c9126bd7..00000000000 --- a/lib/Doctrine/ORM/Mapping/EntityListeners.php +++ /dev/null @@ -1,41 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * The EntityListeners annotation specifies the callback listener classes to be used for an entity or mapped superclass. - * The EntityListeners annotation may be applied to an entity class or mapped superclass. - * - * @author Fabio B. Silva - * @since 2.4 - * - * @Annotation - * @Target("CLASS") - */ -final class EntityListeners implements Annotation -{ - /** - * Specifies the names of the entity listeners. - * - * @var array - */ - public $value = []; -} diff --git a/lib/Doctrine/ORM/Mapping/EntityResult.php b/lib/Doctrine/ORM/Mapping/EntityResult.php deleted file mode 100644 index d8b05730ae5..00000000000 --- a/lib/Doctrine/ORM/Mapping/EntityResult.php +++ /dev/null @@ -1,56 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * References an entity in the SELECT clause of a SQL query. - * If this annotation is used, the SQL statement should select all of the columns that are mapped to the entity object. - * This should include foreign key columns to related entities. - * The results obtained when insufficient data is available are undefined. - * - * @author Fabio B. Silva - * @since 2.3 - * - * @Annotation - * @Target("ANNOTATION") - */ -final class EntityResult implements Annotation -{ - /** - * The class of the result. - * - * @var string - */ - public $entityClass; - - /** - * Maps the columns specified in the SELECT list of the query to the properties or fields of the entity class. - * - * @var array<\Doctrine\ORM\Mapping\FieldResult> - */ - public $fields = []; - - /** - * Specifies the column name of the column in the SELECT list that is used to determine the type of the entity instance. - * - * @var string - */ - public $discriminatorColumn; -} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/AssociationMetadataExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/AssociationMetadataExporter.php new file mode 100644 index 00000000000..1915bfc904d --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/AssociationMetadataExporter.php @@ -0,0 +1,73 @@ +resolveCascade($value->getCascade()); + $lines = []; + + $lines[] = $objectReference . ' = ' . $this->exportInstantiation($value); + + if (! empty($value->getCache())) { + $lines[] = $cacheExporter->export($value->getCache(), $indentationLevel); + $lines[] = null; + $lines[] = $objectReference . '->setCache(' . $cacheExporter::VARIABLE . ');'; + } + + if (! empty($value->getMappedBy())) { + $lines[] = $objectReference . '->setMappedBy("' . $value->getMappedBy() . '");'; + } + + if (! empty($value->getInversedBy())) { + $lines[] = $objectReference . '->setInversedBy("' . $value->getInversedBy() . '");'; + } + + $lines[] = $objectReference . '->setSourceEntity("' . $value->getSourceEntity() . '");'; + $lines[] = $objectReference . '->setTargetEntity("' . $value->getTargetEntity() . '");'; + $lines[] = $objectReference . '->setFetchMode(Mapping\FetchMode::' . strtoupper($value->getFetchMode()) . '");'; + $lines[] = $objectReference . '->setCascade(' . $variableExporter->export($cascade, $indentationLevel + 1) . ');'; + $lines[] = $objectReference . '->setOwningSide(' . $variableExporter->export($value->isOwningSide(), $indentationLevel + 1) . ');'; + $lines[] = $objectReference . '->setOrphanRemoval(' . $variableExporter->export($value->isOrphanRemoval(), $indentationLevel + 1) . ');'; + $lines[] = $objectReference . '->setPrimaryKey(' . $variableExporter->export($value->isPrimaryKey(), $indentationLevel + 1) . ');'; + + + return implode(PHP_EOL, $lines); + } + + /** + * @param string[] $cascade + * + * @return string[] + */ + private function resolveCascade(array $cascade) : array + { + return array_diff(['remove', 'persist', 'refresh'], $cascade) + ? $cascade + : ['all']; + } + + /** + * @param AssociationMetadata $metadata + * + * @return string + */ + abstract protected function exportInstantiation(AssociationMetadata $metadata) : string; +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/CacheMetadataExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/CacheMetadataExporter.php new file mode 100644 index 00000000000..ca54a77d222 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/CacheMetadataExporter.php @@ -0,0 +1,42 @@ +exportInstantiation($value); + + return implode(PHP_EOL, $lines); + } + + /** + * @param CacheMetadata $metadata + * + * @return string + */ + protected function exportInstantiation(CacheMetadata $metadata) : string + { + return sprintf( + 'new Mapping\CacheMetadata(Mapping\CacheUsage::%s, "%s");', + strtoupper($metadata->getUsage()), + $metadata->getRegion() + ); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/ClassMetadataExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/ClassMetadataExporter.php new file mode 100644 index 00000000000..c84a43dad2a --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/ClassMetadataExporter.php @@ -0,0 +1,293 @@ +getReflectionClass(); + $namespace = $reflectionClass->getNamespaceName(); + $lines = []; + + $lines[] = 'exportClass($value, $indentationLevel); + $lines[] = null; + + return implode(PHP_EOL, $lines); + } + + /** + * @param Mapping\ClassMetadata $metadata + * @param int $indentationLevel + * + * @return string + */ + private function exportClass(Mapping\ClassMetadata $metadata, int $indentationLevel) : string + { + $reflectionClass = $metadata->getReflectionClass(); + $shortClassName = $reflectionClass->getShortName(); + $extendedClassName = ($metadata instanceof Mapping\MappedSuperClassMetadata) + ? 'MappedSuperClassMetadata' + : 'EntityClassMetadata' + ; + + $lines[] = sprintf('class %sClassMetadata extends Mapping\%s', $shortClassName, $extendedClassName); + $lines[] = '{'; + $lines[] = $this->exportConstructor($metadata, $indentationLevel + 1); + $lines[] = '}'; + $lines[] = null; + + return implode(PHP_EOL, $lines); + } + + /** + * @param Mapping\ClassMetadata $metadata + * @param int $indentationLevel + * + * @return string + */ + private function exportConstructor(Mapping\ClassMetadata $metadata, int $indentationLevel) : string + { + $indentation = str_repeat(self::INDENTATION, $indentationLevel); + $bodyIndentation = str_repeat(self::INDENTATION, $indentationLevel + 1); + $objectReference = $bodyIndentation . static::VARIABLE; + $lines = []; + + $lines[] = $indentation . 'public function __construct('; + $lines[] = $bodyIndentation . 'ClassMetadataBuildingContext $metadataBuildingContext,'; + $lines[] = $bodyIndentation . '?ClassMetadata $parent = null'; + $lines[] = $indentation . ')'; + $lines[] = $indentation . '{'; + $lines[] = $bodyIndentation . 'parent::__construct("' . $metadata->getClassName() . '", $parent);'; + + if ($metadata->getCustomRepositoryClassName()) { + $lines[] = null; + $lines[] = $objectReference . '->setCustomRepositoryClassName("' . $metadata->getCustomRepositoryClassName() . '");'; + } + + if ($metadata->changeTrackingPolicy) { + $lines[] = null; + $lines[] = $objectReference . '->setChangeTrackingPolicy(Mapping\ChangeTrackingPolicy::' . strtoupper($metadata->changeTrackingPolicy) . ');'; + } + + $lines[] = $this->exportInheritance($metadata, $indentationLevel); + $lines[] = $this->exportTable($metadata, $indentationLevel); + $lines[] = $this->exportProperties($metadata, $indentationLevel); + $lines[] = $this->exportLifecycleCallbacks($metadata, $indentationLevel); + $lines[] = $indentation . '}'; + + return implode(PHP_EOL, $lines); + } + + /** + * @param Mapping\ClassMetadata $metadata + * @param int $indentationLevel + * + * @return string + */ + private function exportInheritance(Mapping\ClassMetadata $metadata, int $indentationLevel) : string + { + $bodyIndentation = str_repeat(self::INDENTATION, $indentationLevel + 1); + $objectReference = $bodyIndentation . static::VARIABLE; + $lines = []; + + if ($metadata->inheritanceType) { + $lines[] = null; + $lines[] = $objectReference . '->setInheritanceType(Mapping\InheritanceType::' . strtoupper($metadata->inheritanceType) . ');'; + } + + if ($metadata->discriminatorColumn) { + $lines[] = null; + $lines[] = $bodyIndentation . '// Discriminator mapping'; + $lines[] = $this->exportDiscriminatorMetadata($metadata, $indentationLevel + 1); + } + + return implode(PHP_EOL, $lines); + } + + /** + * @param Mapping\ClassMetadata $metadata + * @param int $indentationLevel + * + * @return string + */ + private function exportTable(Mapping\ClassMetadata $metadata, int $indentationLevel) : string + { + $bodyIndentation = str_repeat(self::INDENTATION, $indentationLevel + 1); + $lines = []; + + if ($metadata->table) { + $lines[] = null; + $lines[] = $bodyIndentation . '// Table'; + $lines[] = $this->exportTableMetadata($metadata->table, $indentationLevel + 1); + } + + return implode(PHP_EOL, $lines); + } + + /** + * @param Mapping\ClassMetadata $metadata + * @param int $indentationLevel + * + * @return string + */ + private function exportProperties(Mapping\ClassMetadata $metadata, int $indentationLevel) : string + { + $bodyIndentation = str_repeat(self::INDENTATION, $indentationLevel + 1); + $lines = []; + + foreach ($metadata->getDeclaredPropertiesIterator() as $name => $property) { + $lines[] = null; + $lines[] = $bodyIndentation . '// Property: ' . $name; + $lines[] = $this->exportProperty($property, $indentationLevel + 1); + } + + return implode(PHP_EOL, $lines); + } + + /** + * @param Mapping\ClassMetadata $metadata + * @param int $indentationLevel + * + * @return string + */ + private function exportLifecycleCallbacks(Mapping\ClassMetadata $metadata, int $indentationLevel) : string + { + $bodyIndentation = str_repeat(self::INDENTATION, $indentationLevel + 1); + $objectReference = $bodyIndentation . static::VARIABLE; + $lines = []; + + if ($metadata->lifecycleCallbacks) { + $lines[] = null; + $lines[] = $bodyIndentation . '// Lifecycle callbacks'; + + foreach ($metadata->lifecycleCallbacks as $event => $callbacks) { + foreach ($callbacks as $callback) { + $lines[] = $objectReference . '->addLifecycleCallback("' . $callback . '", "' . $event . '");'; + } + } + } + + return implode(PHP_EOL, $lines); + } + + /** + * @param Mapping\ClassMetadata $metadata + * @param int $indentationLevel + * + * @return string + */ + private function exportDiscriminatorMetadata(Mapping\ClassMetadata $metadata, int $indentationLevel) : string + { + $variableExporter = new VariableExporter(); + $discriminatorExporter = new DiscriminatorColumnMetadataExporter(); + $indentation = str_repeat(self::INDENTATION, $indentationLevel); + $objectReference = $indentation . static::VARIABLE; + $lines = []; + + $lines[] = $discriminatorExporter->export($metadata->discriminatorColumn, $indentationLevel); + $lines[] = null; + $lines[] = $objectReference . '->setDiscriminatorColumn(' . $discriminatorExporter::VARIABLE . ');'; + + if ($metadata->discriminatorMap) { + $discriminatorMap = $variableExporter->export($metadata->discriminatorMap, $indentationLevel + 1); + + $lines[] = $objectReference . '->setDiscriminatorMap(' . $discriminatorMap . ');'; + } + + return implode(PHP_EOL, $lines); + } + + /** + * @param Mapping\TableMetadata $table + * @param int $indentationLevel + * + * @return string + */ + private function exportTableMetadata(Mapping\TableMetadata $table, int $indentationLevel) : string + { + $tableExporter = new TableMetadataExporter(); + $indentation = str_repeat(self::INDENTATION, $indentationLevel); + $objectReference = $indentation . static::VARIABLE; + $lines = []; + + $lines[] = $tableExporter->export($table, $indentationLevel); + $lines[] = null; + $lines[] = $objectReference . '->setTable(' . $tableExporter::VARIABLE . ');'; + + return implode(PHP_EOL, $lines); + } + + /** + * @param Mapping\Property $property + * @param int $indentationLevel + * + * @return string + */ + private function exportProperty(Mapping\Property $property, int $indentationLevel) : string + { + $indentation = str_repeat(self::INDENTATION, $indentationLevel); + $objectReference = $indentation . static::VARIABLE; + $lines = []; + + switch (true) { + case ($property instanceof Mapping\VersionFieldMetadata): + $propertyExporter = new VersionFieldMetadataExporter(); + break; + + case ($property instanceof Mapping\FieldMetadata): + $propertyExporter = new FieldMetadataExporter(); + break; + + case ($property instanceof Mapping\OneToOneAssociationMetadata): + $propertyExporter = new OneToOneAssociationMetadataExporter(); + break; + + case ($property instanceof Mapping\OneToManyAssociationMetadata): + $propertyExporter = new OneToManyAssociationMetadataExporter(); + break; + + case ($property instanceof Mapping\ManyToOneAssociationMetadata): + $propertyExporter = new ManyToOneAssociationMetadataExporter(); + break; + + case ($property instanceof Mapping\ManyToManyAssociationMetadata): + $propertyExporter = new ManyToManyAssociationMetadataExporter(); + break; + + default: + $propertyExporter = new TransientMetadataExporter(); + break; + } + + $lines[] = $propertyExporter->export($property, $indentationLevel); + $lines[] = null; + $lines[] = $objectReference . '->addProperty(' . $propertyExporter::VARIABLE . ');'; + + return implode(PHP_EOL, $lines); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/ColumnMetadataExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/ColumnMetadataExporter.php new file mode 100644 index 00000000000..241c4d5b96c --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/ColumnMetadataExporter.php @@ -0,0 +1,46 @@ +exportInstantiation($value); + + if (! empty($value->getColumnDefinition())) { + $lines[] = $objectReference. '->setColumnDefinition("' . $value->getColumnDefinition() . '");'; + } + + $lines[] = $objectReference . '->setTableName("' . $value->getTableName() . '");'; + $lines[] = $objectReference . '->setOptions(' . ltrim($variableExporter->export($value->getOptions(), $indentationLevel + 1)) . ');'; + $lines[] = $objectReference . '->setPrimaryKey(' . ltrim($variableExporter->export($value->isPrimaryKey(), $indentationLevel + 1)) . ');'; + $lines[] = $objectReference . '->setNullable(' . ltrim($variableExporter->export($value->isNullable(), $indentationLevel + 1)) . ');'; + $lines[] = $objectReference . '->setUnique(' . ltrim($variableExporter->export($value->isUnique(), $indentationLevel + 1)) . ');'; + + return implode(PHP_EOL, $lines); + } + + /** + * @param ColumnMetadata $metadata + * + * @return string + */ + abstract protected function exportInstantiation(ColumnMetadata $metadata) : string; +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/DiscriminatorColumnMetadataExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/DiscriminatorColumnMetadataExporter.php new file mode 100644 index 00000000000..1da566fa661 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/DiscriminatorColumnMetadataExporter.php @@ -0,0 +1,27 @@ +getColumnName(), + $metadata->getTypeName() + ); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/Exporter.php b/lib/Doctrine/ORM/Mapping/Exporter/Exporter.php new file mode 100644 index 00000000000..902fe89d2c9 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/Exporter.php @@ -0,0 +1,19 @@ +getName(), + $metadata->getColumnName(), + $metadata->getTypeName() + ); + + return implode(PHP_EOL, $lines); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/JoinColumnMetadataExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/JoinColumnMetadataExporter.php new file mode 100644 index 00000000000..8ff2e39fc43 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/JoinColumnMetadataExporter.php @@ -0,0 +1,45 @@ +setReferencedColumnName("' . $value->getReferencedColumnName() . '");'; + $lines[] = $objectReference . '->setAliasedName("' . $value->getAliasedName() . '");'; + $lines[] = $objectReference . '->setOnDelete("' . $value->getOnDelete() . '");'; + + return implode(PHP_EOL, $lines); + } + + /** + * @param JoinColumnMetadata $metadata + * + * @return string + */ + protected function exportInstantiation(JoinColumnMetadata $metadata) : string + { + return sprintf( + 'new Mapping\JoinColumnMetadata("%s", Type::getType("%s"));', + $metadata->getColumnName(), + $metadata->getTypeName() + ); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/JoinTableMetadataExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/JoinTableMetadataExporter.php new file mode 100644 index 00000000000..173cd76060c --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/JoinTableMetadataExporter.php @@ -0,0 +1,52 @@ +getJoinColumns() as $joinColumn) { + $lines[] = $joinColumnExporter->export($joinColumn, $indentationLevel); + $lines[] = $objectReference . '->addJoinColumn(' . $joinColumnExporter::VARIABLE . ');'; + } + + foreach ($value->getInverseJoinColumns() as $inverseJoinColumn) { + $lines[] = $joinColumnExporter->export($inverseJoinColumn, $indentationLevel); + $lines[] = $objectReference . '->addInverseJoinColumn(' . $joinColumnExporter::VARIABLE . ');'; + } + + return implode(PHP_EOL, $lines); + } + + /** + * @param JoinTableMetadata $metadata + * + * @return string + */ + protected function exportInstantiation(JoinTableMetadata $metadata) : string + { + return sprintf( + 'new Mapping\JoinTableMetadata("%s");', + $metadata->getName() + ); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/LocalColumnMetadataExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/LocalColumnMetadataExporter.php new file mode 100644 index 00000000000..19ff4affbe4 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/LocalColumnMetadataExporter.php @@ -0,0 +1,38 @@ +setLength(' . $value->getLength() . ');'; + $lines[] = $objectReference . '->setScale(' . $value->getScale() . ');'; + $lines[] = $objectReference . '->setPrecision(' . $value->getPrecision() . ');'; + + if ($value->hasValueGenerator()) { + $lines[] = sprintf( + $objectReference . '->setValueGenerator(new ValueGenerator(%s, %s));', + var_export($value->getValueGenerator()->getType(), true), + var_export($value->getValueGenerator()->getDefinition(), true) + ); + } + + return implode(PHP_EOL, $lines); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/ManyToManyAssociationMetadataExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/ManyToManyAssociationMetadataExporter.php new file mode 100644 index 00000000000..c3d8591c034 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/ManyToManyAssociationMetadataExporter.php @@ -0,0 +1,46 @@ +getJoinTable()) { + $joinTableExporter = new JoinColumnMetadataExporter(); + + $lines[] = null; + $lines[] = $joinTableExporter->export($value->getJoinTable(), $indentationLevel); + $lines[] = null; + $lines[] = $objectReference . '->setJoinTable(' . $joinTableExporter::VARIABLE . ');'; + } + + return implode(PHP_EOL, $lines); + } + + /** + * {@inheritdoc} + */ + protected function exportInstantiation(ManyToManyAssociationMetadata $metadata) : string + { + return sprintf( + 'new Mapping\ManyToManyAssociationMetadata("%s");', + $metadata->getName() + ); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/ManyToOneAssociationMetadataExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/ManyToOneAssociationMetadataExporter.php new file mode 100644 index 00000000000..7653fae8fda --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/ManyToOneAssociationMetadataExporter.php @@ -0,0 +1,22 @@ +getName() + ); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/OneToManyAssociationMetadataExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/OneToManyAssociationMetadataExporter.php new file mode 100644 index 00000000000..beca3f29e83 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/OneToManyAssociationMetadataExporter.php @@ -0,0 +1,22 @@ +getName() + ); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/OneToOneAssociationMetadataExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/OneToOneAssociationMetadataExporter.php new file mode 100644 index 00000000000..52eb46da7b1 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/OneToOneAssociationMetadataExporter.php @@ -0,0 +1,22 @@ +getName() + ); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/TableMetadataExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/TableMetadataExporter.php new file mode 100644 index 00000000000..efd75e54b15 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/TableMetadataExporter.php @@ -0,0 +1,56 @@ +exportInstantiation($value); + + if (! empty($value->getSchema())) { + $lines[] = $objectReference . '->setSchema("' . $value->getSchema() . '");'; + } + + foreach ($value->getIndexes() as $index) { + $lines[] = $objectReference . '->addIndex(' . ltrim($variableExporter->export($index, $indentationLevel + 1)) . ');'; + } + + foreach ($value->getUniqueConstraints() as $uniqueConstraint) { + $lines[] = $objectReference . '->addUniqueConstraint(' . ltrim($variableExporter->export($uniqueConstraint, $indentationLevel + 1)) . ');'; + } + + $lines[] = $objectReference . '->setOptions(' . ltrim($variableExporter->export($value->getOptions(), $indentationLevel + 1)) . ');'; + + return implode(PHP_EOL, $lines); + } + + /** + * @param TableMetadata $metadata + * + * @return string + */ + protected function exportInstantiation(TableMetadata $metadata) : string + { + return sprintf( + 'new Mapping\TableMetadata("%s");', + $metadata->getName() + ); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/ToManyAssociationMetadataExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/ToManyAssociationMetadataExporter.php new file mode 100644 index 00000000000..3e374f426a3 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/ToManyAssociationMetadataExporter.php @@ -0,0 +1,33 @@ +getIndexedBy())) { + $lines[] = $objectReference . '->setIndexedBy("' . $value->getIndexedBy() . '"");'; + } + + $lines[] = $objectReference . '->setOderBy(' . $variableExporter->export($value->getOrderBy(), $indentationLevel + 1) . ');'; + + return implode(PHP_EOL, $lines); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/ToOneAssociationMetadataExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/ToOneAssociationMetadataExporter.php new file mode 100644 index 00000000000..b8c2337c116 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/ToOneAssociationMetadataExporter.php @@ -0,0 +1,34 @@ +getJoinColumns() as $joinColumn) { + $lines[] = null; + $lines[] = $joinColumnExporter->export($joinColumn, $indentationLevel); + $lines[] = null; + $lines[] = $objectReference . '->addJoinColumn(' . $joinColumnExporter::VARIABLE . ');'; + } + + return implode(PHP_EOL, $lines); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/TransientMetadataExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/TransientMetadataExporter.php new file mode 100644 index 00000000000..8b6de1a3750 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/TransientMetadataExporter.php @@ -0,0 +1,38 @@ +exportInstantiation($value); + } + + /** + * @param TransientMetadata $metadata + * + * @return string + */ + protected function exportInstantiation(TransientMetadata $metadata) : string + { + return sprintf( + 'new Mapping\TransientMetadata("%s");', + $metadata->getName() + ); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/VariableExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/VariableExporter.php new file mode 100644 index 00000000000..65554133c97 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/VariableExporter.php @@ -0,0 +1,43 @@ + strlen((string) $v) ? $k : $v); + }); + $maxKeyLength = strlen($longestKey) + (is_numeric($longestKey) ? 0 : 2); + + $lines = []; + + $lines[] = $indentation . '['; + + foreach ($value as $entryKey => $entryValue) { + $lines[] = sprintf('%s%s => %s,', + $indentation . self::INDENTATION, + str_pad(var_export($entryKey, true), $maxKeyLength), + ltrim($this->export($entryValue, $indentationLevel + 1)) + ); + } + + $lines[] = $indentation . ']'; + + return implode(PHP_EOL, $lines); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Exporter/VersionFieldMetadataExporter.php b/lib/Doctrine/ORM/Mapping/Exporter/VersionFieldMetadataExporter.php new file mode 100644 index 00000000000..45de02bb5d2 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Exporter/VersionFieldMetadataExporter.php @@ -0,0 +1,28 @@ +getName(), + $metadata->getColumnName(), + $metadata->getTypeName() + ); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Factory/AbstractClassMetadataFactory.php b/lib/Doctrine/ORM/Mapping/Factory/AbstractClassMetadataFactory.php new file mode 100644 index 00000000000..f072b20d2e5 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Factory/AbstractClassMetadataFactory.php @@ -0,0 +1,216 @@ + + */ +abstract class AbstractClassMetadataFactory implements ClassMetadataFactory +{ + /** + * Never autogenerate a class metadata and rely that it was generated by some process before deployment. + * + * @var int + */ + const AUTOGENERATE_NEVER = 0; + + /** + * Always generates a new class metadata in every request. This is only sane during development. + * + * @var int + */ + const AUTOGENERATE_ALWAYS = 1; + + /** + * Autogenerate the class metadata when the file does not exist. + * This strategy causes a file exists call whenever any metadata is used the first time in a request. + * + * @var int + */ + const AUTOGENERATE_FILE_NOT_EXISTS = 2; + + /** + * @var ClassMetadataDefinitionFactory + */ + protected $definitionFactory; + + /** + * @var MappingDriver + */ + protected $mappingDriver; + + /** + * @var array + */ + private $definitions = []; + + /** + * @var array + */ + private $loaded = []; + + /** + * ClassMetadataFactory constructor. + * + * @param MetadataConfiguration $configuration + */ + public function __construct(MetadataConfiguration $configuration) + { + $mappingDriver = $configuration->getMappingDriver(); + $resolver = $configuration->getResolver(); + //$autoGenerate = $configuration->getAutoGenerate(); + $generator = new ClassMetadataGenerator($mappingDriver); + $generatorStrategy = new ConditionalFileWriterClassMetadataGeneratorStrategy($generator); + $definitionFactory = new ClassMetadataDefinitionFactory($resolver, $generatorStrategy); + + $this->mappingDriver = $mappingDriver; + $this->definitionFactory = $definitionFactory; + } + + /** + * {@inheritdoc} + */ + public function getAllMetadata() + { + $metadata = []; + + foreach ($this->mappingDriver->getAllClassNames() as $className) { + $metadata[] = $this->getMetadataFor($className); + } + + return $metadata; + } + + /** + * {@inheritdoc} + */ + public function getMetadataFor($className) + { + $entityClassName = ClassUtils::getRealClass($className); + + if (isset($this->loaded[$entityClassName])) { + return $this->loaded[$entityClassName]; + } + + $metadataBuildingContext = new ClassMetadataBuildingContext($this); + $parentClassNameList = $this->getParentClassNameList($entityClassName); + $parentClassNameList[] = $entityClassName; + $parent = null; + + foreach ($parentClassNameList as $parentClassName) { + if (isset($this->loaded[$parentClassName])) { + $parent = $this->loaded[$parentClassName]; + + continue; + } + + $definition = $this->getOrCreateClassMetadataDefinition($parentClassName, $parent); + + $parent = $this->loaded[$parentClassName] = $this->createClassMetadata($definition); + } + + $metadataBuildingContext->validate(); + + return $this->loaded[$entityClassName]; + } + + /** + * {@inheritdoc} + */ + public function hasMetadataFor($className) + { + return isset($this->loaded[$className]); + } + + /** + * {@inheritdoc} + */ + public function setMetadataFor($className, $class) + { + $this->loaded[$className] = $class; + } + + /** + * {@inheritdoc} + */ + public function isTransient($className) + { + return $this->mappingDriver->isTransient($className); + } + + /** + * @param ClassMetadataDefinition $definition + * + * @return ClassMetadata + */ + protected function createClassMetadata(ClassMetadataDefinition $definition) : ClassMetadata + { + /** @var ClassMetadata $classMetadata */ + $metadataFqcn = $definition->metadataClassName; + $classMetadata = new $metadataFqcn($definition->parentClassMetadata); + + $classMetadata->wakeupReflection($this->getReflectionService()); + + return $classMetadata; + } + + /** + * Create a class metadata definition for the given class name. + * + * @param string $className + * @param ClassMetadata|null $parent + * + * @return ClassMetadataDefinition + */ + private function getOrCreateClassMetadataDefinition(string $className, ?ClassMetadata $parent) : ClassMetadataDefinition + { + if (! isset($this->definitions[$className])) { + $this->definitions[$className] = $this->definitionFactory->build($className, $parent); + } + + return $this->definitions[$className]; + } + + /** + * @param string $className + * + * @return array + */ + private function getParentClassNameList(string $className) : array + { + $reflectionService = $this->getReflectionService(); + $parentClassNameList = []; + + foreach (array_reverse($reflectionService->getParentClasses($className)) as $parentClassName) { + if ($this->mappingDriver->isTransient($parentClassName)) { + continue; + } + + $parentClassNameList[] = $parentClassName; + } + + return $parentClassNameList; + } + + /** + * @return ReflectionService + */ + abstract protected function getReflectionService(); +} diff --git a/lib/Doctrine/ORM/Mapping/Factory/Autoloader.php b/lib/Doctrine/ORM/Mapping/Factory/Autoloader.php new file mode 100644 index 00000000000..1f476066494 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Factory/Autoloader.php @@ -0,0 +1,87 @@ + + */ +class ClassMetadataBuildingContext +{ + private $classMetadataFactory; + + /** + * @var array + */ + protected $secondPassList = []; + + /** + * @var bool + */ + private $inSecondPass = false; + + /** + * ClassMetadataBuildingContext constructor. + * + * @param AbstractClassMetadataFactory $classMetadataFactory + */ + public function __construct(AbstractClassMetadataFactory $classMetadataFactory) + { + $this->classMetadataFactory = $classMetadataFactory; + } + + /** + * @return AbstractClassMetadataFactory + */ + public function getClassMetadataFactory() : AbstractClassMetadataFactory + { + return $this->classMetadataFactory; + } + + /** + * @param SecondPass $secondPass + * + * @return void + */ + public function addSecondPass(SecondPass $secondPass) : void + { + $this->secondPassList[] = $secondPass; + } + + /** + * @return bool + */ + public function isInSecondPass() : bool + { + return $this->inSecondPass; + } + + /** + * @return void + */ + public function validate() : void + { + $this->inSecondPass = true; + + foreach ($this->secondPassList as $secondPass) { + /** @var SecondPass $secondPass */ + $secondPass->process($this); + } + + $this->inSecondPass = false; + } +} diff --git a/lib/Doctrine/ORM/Mapping/Factory/ClassMetadataDefinition.php b/lib/Doctrine/ORM/Mapping/Factory/ClassMetadataDefinition.php new file mode 100644 index 00000000000..ee5b2ee5bd0 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Factory/ClassMetadataDefinition.php @@ -0,0 +1,44 @@ +entityClassName = $entityClassName; + $this->metadataClassName = $metadataClassName; + $this->parentClassMetadata = $parentMetadata; + } +} diff --git a/lib/Doctrine/ORM/Mapping/Factory/ClassMetadataDefinitionFactory.php b/lib/Doctrine/ORM/Mapping/Factory/ClassMetadataDefinitionFactory.php new file mode 100644 index 00000000000..f7db480b1d3 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Factory/ClassMetadataDefinitionFactory.php @@ -0,0 +1,66 @@ +resolver = $resolver; + $this->generatorStrategy = $generatorStrategy; + } + + /** + * @param string $className + * @param ClassMetadata|null $parentMetadata + * + * @return ClassMetadataDefinition + */ + public function build(string $className, ?ClassMetadata $parentMetadata) : ClassMetadataDefinition + { + $definition = $this->createDefinition($className, $parentMetadata); + + if (! class_exists($definition->metadataClassName, false)) { + $metadataClassPath = $this->resolver->resolveMetadataClassPath($className); + + $this->generatorStrategy->generate($metadataClassPath, $definition); + } + + return $definition; + } + + /** + * @param string $className + * @param ClassMetadata|null $parentMetadata + * + * @return ClassMetadataDefinition + */ + private function createDefinition(string $className, ?ClassMetadata $parentMetadata) : ClassMetadataDefinition + { + $metadataClassName = $this->resolver->resolveMetadataClassName($className); + + return new ClassMetadataDefinition($className, $metadataClassName, $parentMetadata); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Factory/ClassMetadataGenerator.php b/lib/Doctrine/ORM/Mapping/Factory/ClassMetadataGenerator.php new file mode 100644 index 00000000000..5e1ce7bf009 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Factory/ClassMetadataGenerator.php @@ -0,0 +1,59 @@ + + */ +class ClassMetadataGenerator +{ + /** + * @var MappingDriver + */ + protected $mappingDriver; + + /** + * @var ClassMetadataExporter + */ + private $metadataExporter; + + /** + * @param MappingDriver $mappingDriver + * @param ClassMetadataExporter|null $metadataExporter + */ + public function __construct( + MappingDriver $mappingDriver, + ClassMetadataExporter $metadataExporter = null + ) + { + $this->mappingDriver = $mappingDriver; + $this->metadataExporter = $metadataExporter ?: new ClassMetadataExporter(); + } + + /** + * Generates class metadata code. + * + * @param ClassMetadataDefinition $definition + * + * @return string + */ + public function generate(ClassMetadataDefinition $definition) : string + { + $metadata = $this->mappingDriver->loadMetadataForClass( + $definition->entityClassName, + $definition->parentClassMetadata + ); + + return $this->metadataExporter->export($metadata); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Factory/ClassMetadataResolver.php b/lib/Doctrine/ORM/Mapping/Factory/ClassMetadataResolver.php new file mode 100644 index 00000000000..7fa5536502f --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Factory/ClassMetadataResolver.php @@ -0,0 +1,31 @@ + + */ +interface ClassMetadataResolver +{ + /** + * @param string $className + * + * @return string + */ + public function resolveMetadataClassName(string $className) : string; + + /** + * @param string $className + * + * @return string + */ + public function resolveMetadataClassPath(string $className) : string; +} diff --git a/lib/Doctrine/ORM/Mapping/Factory/DefaultClassMetadataResolver.php b/lib/Doctrine/ORM/Mapping/Factory/DefaultClassMetadataResolver.php new file mode 100644 index 00000000000..1f07fc9ea7f --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Factory/DefaultClassMetadataResolver.php @@ -0,0 +1,54 @@ +namespace = ltrim($namespace, '\\'); + $this->directory = rtrim($this->directory, DIRECTORY_SEPARATOR); + } + + /** + * {@inheritdoc} + */ + public function resolveMetadataClassName(string $className) : string + { + return sprintf('%s\%s\%s', $this->namespace, self::MARKER, ltrim($className, '\\')); + } + + /** + * {@inheritdoc} + */ + public function resolveMetadataClassPath(string $className) : string + { + return sprintf('%s/%s/%s.php', $this->directory, self::MARKER, str_replace('\\', '.', $className)); + } +} diff --git a/lib/Doctrine/ORM/Mapping/DefaultNamingStrategy.php b/lib/Doctrine/ORM/Mapping/Factory/DefaultNamingStrategy.php similarity index 62% rename from lib/Doctrine/ORM/Mapping/DefaultNamingStrategy.php rename to lib/Doctrine/ORM/Mapping/Factory/DefaultNamingStrategy.php index ef7f76b1e92..14b2192beaf 100644 --- a/lib/Doctrine/ORM/Mapping/DefaultNamingStrategy.php +++ b/lib/Doctrine/ORM/Mapping/Factory/DefaultNamingStrategy.php @@ -1,24 +1,9 @@ . - */ -namespace Doctrine\ORM\Mapping; +declare(strict_types=1); + +namespace Doctrine\ORM\Mapping\Factory; /** * The default NamingStrategy diff --git a/lib/Doctrine/ORM/Mapping/NamingStrategy.php b/lib/Doctrine/ORM/Mapping/Factory/NamingStrategy.php similarity index 52% rename from lib/Doctrine/ORM/Mapping/NamingStrategy.php rename to lib/Doctrine/ORM/Mapping/Factory/NamingStrategy.php index 9960f949f16..37b7bb42991 100644 --- a/lib/Doctrine/ORM/Mapping/NamingStrategy.php +++ b/lib/Doctrine/ORM/Mapping/Factory/NamingStrategy.php @@ -1,29 +1,14 @@ . - */ -namespace Doctrine\ORM\Mapping; +declare(strict_types=1); + +namespace Doctrine\ORM\Mapping\Factory; /** * A set of rules for determining the physical column and table names * - * + * * @link www.doctrine-project.org * @since 2.3 * @author Fabio B. Silva @@ -37,7 +22,7 @@ interface NamingStrategy * * @return string A table name. */ - function classToTableName($className); + public function classToTableName($className); /** * Returns a column name for a property. @@ -47,7 +32,7 @@ function classToTableName($className); * * @return string A column name. */ - function propertyToColumnName($propertyName, $className = null); + public function propertyToColumnName($propertyName, $className = null); /** * Returns a column name for an embedded property. @@ -59,23 +44,24 @@ function propertyToColumnName($propertyName, $className = null); * * @return string */ - function embeddedFieldToColumnName($propertyName, $embeddedColumnName, $className = null, $embeddedClassName = null); + public function embeddedFieldToColumnName($propertyName, $embeddedColumnName, $className = null, $embeddedClassName = null); /** * Returns the default reference column name. * * @return string A column name. */ - function referenceColumnName(); + public function referenceColumnName(); /** * Returns a join column name for a property. * - * @param string $propertyName A property name. + * @param string $propertyName A property name. + * @param string|null $className The fully-qualified class name. * * @return string A join column name. */ - function joinColumnName($propertyName); + public function joinColumnName($propertyName, $className = null); /** * Returns a join table name. @@ -86,7 +72,7 @@ function joinColumnName($propertyName); * * @return string A join table name. */ - function joinTableName($sourceEntity, $targetEntity, $propertyName = null); + public function joinTableName($sourceEntity, $targetEntity, $propertyName = null); /** * Returns the foreign key column name for the given parameters. @@ -96,5 +82,5 @@ function joinTableName($sourceEntity, $targetEntity, $propertyName = null); * * @return string A join column name. */ - function joinKeyColumnName($entityName, $referencedColumnName = null); + public function joinKeyColumnName($entityName, $referencedColumnName = null); } diff --git a/lib/Doctrine/ORM/Mapping/Factory/RuntimeClassMetadataFactory.php b/lib/Doctrine/ORM/Mapping/Factory/RuntimeClassMetadataFactory.php new file mode 100644 index 00000000000..4abd635c753 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Factory/RuntimeClassMetadataFactory.php @@ -0,0 +1,35 @@ + + */ +class RuntimeClassMetadataFactory extends AbstractClassMetadataFactory +{ + /** @var RuntimeReflectionService */ + private $reflectionService; + + /** + * @return RuntimeReflectionService + */ + protected function getReflectionService() : RuntimeReflectionService + { + if (! $this->reflectionService) { + $this->reflectionService = new RuntimeReflectionService(); + } + + return $this->reflectionService; + } +} diff --git a/lib/Doctrine/ORM/Mapping/Factory/SecondPass.php b/lib/Doctrine/ORM/Mapping/Factory/SecondPass.php new file mode 100644 index 00000000000..bf5f0cb3d12 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Factory/SecondPass.php @@ -0,0 +1,16 @@ + + */ +class StaticClassMetadataFactory extends AbstractClassMetadataFactory +{ + /** @var StaticReflectionService */ + private $reflectionService; + + /** + * @return StaticReflectionService + */ + protected function getReflectionService() : StaticReflectionService + { + if (! $this->reflectionService) { + $this->reflectionService = new StaticReflectionService(); + } + + return $this->reflectionService; + } +} diff --git a/lib/Doctrine/ORM/Mapping/Factory/Strategy/ClassMetadataGeneratorStrategy.php b/lib/Doctrine/ORM/Mapping/Factory/Strategy/ClassMetadataGeneratorStrategy.php new file mode 100644 index 00000000000..e289d9cf332 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Factory/Strategy/ClassMetadataGeneratorStrategy.php @@ -0,0 +1,19 @@ +generator = $generator; + } + + /** + * {@inheritdoc} + */ + public function generate(string $filePath, ClassMetadataDefinition $definition): void + { + $sourceCode = $this->generator->generate($definition); + + eval($sourceCode); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Factory/Strategy/FileReaderClassMetadataGeneratorStrategy.php b/lib/Doctrine/ORM/Mapping/Factory/Strategy/FileReaderClassMetadataGeneratorStrategy.php new file mode 100644 index 00000000000..6e1808b5eb2 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Factory/Strategy/FileReaderClassMetadataGeneratorStrategy.php @@ -0,0 +1,19 @@ +generator = $generator; + } + + /** + * {@inheritdoc} + */ + public function generate(string $filePath, ClassMetadataDefinition $definition): void + { + $sourceCode = $this->generator->generate($definition); + + $this->ensureDirectoryIsReady(dirname($filePath)); + + $tmpFileName = $filePath . '.' . uniqid('', true); + + file_put_contents($tmpFileName, $sourceCode); + @chmod($tmpFileName, 0664); + rename($tmpFileName, $filePath); + + require $filePath; + } + + /** + * @param string $directory + * + * @throws \RuntimeException + */ + private function ensureDirectoryIsReady(string $directory) + { + if (! is_dir($directory) && (false === @mkdir($directory, 0775, true))) { + throw new \RuntimeException(sprintf('Your metadata directory "%s" must be writable', $directory)); + } + + if (! is_writable($directory)) { + throw new \RuntimeException(sprintf('Your proxy directory "%s" must be writable', $directory)); + } + } +} diff --git a/lib/Doctrine/ORM/Mapping/UnderscoreNamingStrategy.php b/lib/Doctrine/ORM/Mapping/Factory/UnderscoreNamingStrategy.php similarity index 74% rename from lib/Doctrine/ORM/Mapping/UnderscoreNamingStrategy.php rename to lib/Doctrine/ORM/Mapping/Factory/UnderscoreNamingStrategy.php index 543d92ba31c..7052d7a30a5 100644 --- a/lib/Doctrine/ORM/Mapping/UnderscoreNamingStrategy.php +++ b/lib/Doctrine/ORM/Mapping/Factory/UnderscoreNamingStrategy.php @@ -1,24 +1,9 @@ . - */ -namespace Doctrine\ORM\Mapping; +declare(strict_types=1); + +namespace Doctrine\ORM\Mapping\Factory; /** * Naming strategy implementing the underscore naming convention. diff --git a/lib/Doctrine/ORM/Mapping/FetchMode.php b/lib/Doctrine/ORM/Mapping/FetchMode.php new file mode 100644 index 00000000000..ccba60af42f --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/FetchMode.php @@ -0,0 +1,43 @@ + + */ +final class FetchMode +{ + /** + * Specifies that an association is to be fetched when it is first accessed. + */ + const LAZY = 'LAZY'; + + /** + * Specifies that an association is to be fetched when the owner of the + * association is fetched. + */ + const EAGER = 'EAGER'; + + /** + * Specifies that an association is to be fetched lazy (on first access) and that + * commands such as Collection#count, Collection#slice are issued directly against + * the database if the collection is not yet initialized. + */ + const EXTRA_LAZY = 'EXTRA_LAZY'; + + /** + * Will break upon instantiation. + * + */ + private function __construct() + { + } +} diff --git a/lib/Doctrine/ORM/Mapping/FieldMetadata.php b/lib/Doctrine/ORM/Mapping/FieldMetadata.php new file mode 100644 index 00000000000..208e5ae09f5 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/FieldMetadata.php @@ -0,0 +1,125 @@ + + */ +class FieldMetadata extends LocalColumnMetadata implements Property +{ + /** @var ComponentMetadata */ + protected $declaringClass; + + /** @var \ReflectionProperty */ + protected $reflection; + + /** @var string */ + protected $name; + + /** + * FieldMetadata constructor. + * + * @param string $name + * @param string $columnName + * @param Type $type + * + * @todo Leverage this implementation instead of default, simple constructor + */ + /*public function __construct(string $name, string $columnName, Type $type) + { + parent::__construct($columnName, $type); + + $this->name = $name; + }*/ + + public function __construct(string $name) + { + $this->name = $name; + } + + /** + * {@inheritdoc} + */ + public function getDeclaringClass() : ComponentMetadata + { + return $this->declaringClass; + } + + /** + * @param ComponentMetadata $declaringClass + */ + public function setDeclaringClass(ComponentMetadata $declaringClass) : void + { + $this->declaringClass = $declaringClass; + } + + /** + * {@inheritdoc} + */ + public function getName() : string + { + return $this->name; + } + + /** + * {@inheritdoc} + */ + public function setValue($object, $value) : void + { + $this->reflection->setValue($object, $value); + } + + /** + * {@inheritdoc} + */ + public function getValue($object) + { + return $this->reflection->getValue($object); + } + + /** + * {@inheritdoc} + */ + public function isAssociation() : bool + { + return false; + } + + /** + * {@inheritdoc} + */ + public function isField() : bool + { + return true; + } + + /** + * {@inheritdoc} + */ + public function setReflectionProperty(\ReflectionProperty $reflectionProperty) : void + { + $this->reflection = $reflectionProperty; + } + + /** + * {@inheritdoc} + */ + public function wakeupReflection(ReflectionService $reflectionService) : void + { + $this->setReflectionProperty( + $reflectionService->getAccessibleProperty($this->declaringClass->getClassName(), $this->name) + ); + } +} diff --git a/lib/Doctrine/ORM/Mapping/FieldResult.php b/lib/Doctrine/ORM/Mapping/FieldResult.php deleted file mode 100644 index 5e8aa0cd3e0..00000000000 --- a/lib/Doctrine/ORM/Mapping/FieldResult.php +++ /dev/null @@ -1,46 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * Is used to map the columns specified in the SELECT list of the query to the properties or fields of the entity class. - * - * @author Fabio B. Silva - * @since 2.3 - * - * @Annotation - * @Target("ANNOTATION") - */ -final class FieldResult implements Annotation -{ - /** - * Name of the column in the SELECT clause. - * - * @var string - */ - public $name; - - /** - * Name of the persistent field or property of the class. - * - * @var string - */ - public $column; -} diff --git a/lib/Doctrine/ORM/Mapping/GeneratedValue.php b/lib/Doctrine/ORM/Mapping/GeneratedValue.php deleted file mode 100644 index 27c03d4bee7..00000000000 --- a/lib/Doctrine/ORM/Mapping/GeneratedValue.php +++ /dev/null @@ -1,36 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("PROPERTY") - */ -final class GeneratedValue implements Annotation -{ - /** - * The type of Id generator. - * - * @var string - * - * @Enum({"AUTO", "SEQUENCE", "TABLE", "IDENTITY", "NONE", "UUID", "CUSTOM"}) - */ - public $strategy = 'AUTO'; -} diff --git a/lib/Doctrine/ORM/Mapping/GeneratorType.php b/lib/Doctrine/ORM/Mapping/GeneratorType.php new file mode 100644 index 00000000000..24ab6f7f6f4 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/GeneratorType.php @@ -0,0 +1,69 @@ + + */ +final class GeneratorType +{ + /** + * NONE means the class does not have a generated id. That means the class + * must have a natural, manually assigned id. + */ + const NONE = 'NONE'; + + /** + * AUTO means the generator type will depend on what the used platform prefers. + * Offers full portability. + */ + const AUTO = 'AUTO'; + + /** + * SEQUENCE means a separate sequence object will be used. Platforms that do + * not have native sequence support may emulate it. Full portability is currently + * not guaranteed. + */ + const SEQUENCE = 'SEQUENCE'; + + /** + * TABLE means a separate table is used for id generation. + * Offers full portability. + */ + const TABLE = 'TABLE'; + + /** + * IDENTITY means an identity column is used for id generation. The database + * will fill in the id column on insertion. Platforms that do not support + * native identity columns may emulate them. Full portability is currently + * not guaranteed. + */ + const IDENTITY = 'IDENTITY'; + + /** + * UUID means that a UUID/GUID expression is used for id generation. Full + * portability is currently not guaranteed. + */ + const UUID = 'UUID'; + + /** + * CUSTOM means that customer will use own ID generator that supposedly work + */ + const CUSTOM = 'CUSTOM'; + + /** + * Will break upon instantiation. + * + */ + private function __construct() + { + } +} diff --git a/lib/Doctrine/ORM/Mapping/HasLifecycleCallbacks.php b/lib/Doctrine/ORM/Mapping/HasLifecycleCallbacks.php deleted file mode 100644 index 313ece31f8c..00000000000 --- a/lib/Doctrine/ORM/Mapping/HasLifecycleCallbacks.php +++ /dev/null @@ -1,28 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("CLASS") - */ -final class HasLifecycleCallbacks implements Annotation -{ -} diff --git a/lib/Doctrine/ORM/Mapping/Id.php b/lib/Doctrine/ORM/Mapping/Id.php deleted file mode 100644 index 6c9bcef0d71..00000000000 --- a/lib/Doctrine/ORM/Mapping/Id.php +++ /dev/null @@ -1,28 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("PROPERTY") - */ -final class Id implements Annotation -{ -} diff --git a/lib/Doctrine/ORM/Mapping/Index.php b/lib/Doctrine/ORM/Mapping/Index.php deleted file mode 100644 index 45953a80478..00000000000 --- a/lib/Doctrine/ORM/Mapping/Index.php +++ /dev/null @@ -1,47 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("ANNOTATION") - */ -final class Index implements Annotation -{ - /** - * @var string - */ - public $name; - - /** - * @var array - */ - public $columns; - - /** - * @var array - */ - public $flags; - - /** - * @var array - */ - public $options; -} diff --git a/lib/Doctrine/ORM/Mapping/InheritanceType.php b/lib/Doctrine/ORM/Mapping/InheritanceType.php index de803369a30..dab853231e6 100644 --- a/lib/Doctrine/ORM/Mapping/InheritanceType.php +++ b/lib/Doctrine/ORM/Mapping/InheritanceType.php @@ -1,36 +1,49 @@ . - */ + + +declare(strict_types=1); namespace Doctrine\ORM\Mapping; /** - * @Annotation - * @Target("CLASS") + * Class InheritanceType + * + * @package Doctrine\ORM\Mapping + * @since 3.0 + * + * @author Guilherme Blanco */ -final class InheritanceType implements Annotation +final class InheritanceType { /** - * The inheritance type used by the class and its subclasses. - * - * @var string + * NONE means the class does not participate in an inheritance hierarchy + * and therefore does not need an inheritance mapping type. + */ + const NONE = 'NONE'; + + /** + * JOINED means the class will be persisted according to the rules of + * Class Table Inheritance. + */ + const JOINED = 'JOINED'; + + /** + * SINGLE_TABLE means the class will be persisted according to the rules of + * Single Table Inheritance. + */ + const SINGLE_TABLE = 'SINGLE_TABLE'; + + /** + * TABLE_PER_CLASS means the class will be persisted according to the rules + * of Concrete Table Inheritance. + */ + const TABLE_PER_CLASS = 'TABLE_PER_CLASS'; + + /** + * Will break upon instantiation. * - * @Enum({"NONE", "JOINED", "SINGLE_TABLE", "TABLE_PER_CLASS"}) */ - public $value; + private function __construct() + { + } } diff --git a/lib/Doctrine/ORM/Mapping/JoinColumn.php b/lib/Doctrine/ORM/Mapping/JoinColumn.php deleted file mode 100644 index febce917481..00000000000 --- a/lib/Doctrine/ORM/Mapping/JoinColumn.php +++ /dev/null @@ -1,64 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target({"PROPERTY","ANNOTATION"}) - */ -final class JoinColumn implements Annotation -{ - /** - * @var string - */ - public $name; - - /** - * @var string - */ - public $referencedColumnName = 'id'; - - /** - * @var boolean - */ - public $unique = false; - - /** - * @var boolean - */ - public $nullable = true; - - /** - * @var mixed - */ - public $onDelete; - - /** - * @var string - */ - public $columnDefinition; - - /** - * Field name used in non-object hydration (array/scalar). - * - * @var string - */ - public $fieldName; -} diff --git a/lib/Doctrine/ORM/Mapping/JoinColumnMetadata.php b/lib/Doctrine/ORM/Mapping/JoinColumnMetadata.php new file mode 100644 index 00000000000..cae19981785 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/JoinColumnMetadata.php @@ -0,0 +1,85 @@ + + */ +class JoinColumnMetadata extends ColumnMetadata +{ + /** @var string|null */ + protected $referencedColumnName; + + /** @var string|null */ + protected $aliasedName; + + /** @var boolean */ + protected $nullable = true; + + /** @var string */ + protected $onDelete = ''; + + /** + * @return string|null + */ + public function getReferencedColumnName() : ?string + { + return $this->referencedColumnName; + } + + /** + * @param string $referencedColumnName + */ + public function setReferencedColumnName(string $referencedColumnName) : void + { + $this->referencedColumnName = $referencedColumnName; + } + + /** + * @return string|null + */ + public function getAliasedName() : ?string + { + return $this->aliasedName; + } + + /** + * @param string $aliasedName + */ + public function setAliasedName(string $aliasedName) : void + { + $this->aliasedName = $aliasedName; + } + + /** + * @return string + */ + public function getOnDelete() : string + { + return $this->onDelete; + } + + /** + * @param string $onDelete + */ + public function setOnDelete(string $onDelete) : void + { + $this->onDelete = strtoupper($onDelete); + } + + /** + * @return bool + */ + public function isOnDeleteCascade() : bool + { + return $this->onDelete === 'CASCADE'; + } +} diff --git a/lib/Doctrine/ORM/Mapping/JoinColumns.php b/lib/Doctrine/ORM/Mapping/JoinColumns.php deleted file mode 100644 index ae096c27503..00000000000 --- a/lib/Doctrine/ORM/Mapping/JoinColumns.php +++ /dev/null @@ -1,32 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("PROPERTY") - */ -final class JoinColumns implements Annotation -{ - /** - * @var array<\Doctrine\ORM\Mapping\JoinColumn> - */ - public $value; -} diff --git a/lib/Doctrine/ORM/Mapping/JoinTable.php b/lib/Doctrine/ORM/Mapping/JoinTable.php deleted file mode 100644 index 879316a2874..00000000000 --- a/lib/Doctrine/ORM/Mapping/JoinTable.php +++ /dev/null @@ -1,47 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target({"PROPERTY","ANNOTATION"}) - */ -final class JoinTable implements Annotation -{ - /** - * @var string - */ - public $name; - - /** - * @var string - */ - public $schema; - - /** - * @var array<\Doctrine\ORM\Mapping\JoinColumn> - */ - public $joinColumns = []; - - /** - * @var array<\Doctrine\ORM\Mapping\JoinColumn> - */ - public $inverseJoinColumns = []; -} diff --git a/lib/Doctrine/ORM/Mapping/JoinTableMetadata.php b/lib/Doctrine/ORM/Mapping/JoinTableMetadata.php new file mode 100644 index 00000000000..da6955a9fed --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/JoinTableMetadata.php @@ -0,0 +1,74 @@ + + */ +final class JoinTableMetadata extends TableMetadata +{ + /** @var array */ + protected $joinColumns = []; + + /** @var array */ + protected $inverseJoinColumns = []; + + /** + * @return bool + */ + public function hasColumns() : bool + { + return $this->joinColumns || $this->inverseJoinColumns; + } + + /** + * @return array + */ + public function getJoinColumns() : array + { + return $this->joinColumns; + } + + /** + * @param JoinColumnMetadata $joinColumn + */ + public function addJoinColumn(JoinColumnMetadata $joinColumn) : void + { + $this->joinColumns[] = $joinColumn; + } + + /** + * @return array + */ + public function getInverseJoinColumns() : array + { + return $this->inverseJoinColumns; + } + + /** + * @param JoinColumnMetadata $joinColumn + */ + public function addInverseJoinColumn(JoinColumnMetadata $joinColumn) : void + { + $this->inverseJoinColumns[] = $joinColumn; + } + + public function __clone() + { + foreach ($this->joinColumns as $index => $joinColumn) { + $this->joinColumns[$index] = clone $joinColumn; + } + + foreach ($this->inverseJoinColumns as $index => $inverseJoinColumn) { + $this->inverseJoinColumns[$index] = clone $inverseJoinColumn; + } + } +} diff --git a/lib/Doctrine/ORM/Mapping/LocalColumnMetadata.php b/lib/Doctrine/ORM/Mapping/LocalColumnMetadata.php new file mode 100644 index 00000000000..acebbe87334 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/LocalColumnMetadata.php @@ -0,0 +1,109 @@ + + */ +abstract class LocalColumnMetadata extends ColumnMetadata +{ + /** + * @var int|null + */ + protected $length; + + /** + * @var int|null + */ + protected $scale; + + /** + * @var int|null + */ + protected $precision; + + /** + * @var ValueGeneratorMetadata|null + */ + protected $valueGenerator; + + /** + * @return int|null + */ + public function getLength() : ?int + { + return $this->length; + } + + /** + * @param int $length + */ + public function setLength(int $length) : void + { + $this->length = $length; + } + + /** + * @return int|null + */ + public function getScale() : ?int + { + return $this->scale; + } + + /** + * @param int $scale + */ + public function setScale(int $scale) : void + { + $this->scale = $scale; + } + + /** + * @return int|null + */ + public function getPrecision() : ?int + { + return $this->precision; + } + + /** + * @param int $precision + */ + public function setPrecision(int $precision) : void + { + $this->precision = $precision; + } + + /** + * @return bool + */ + public function hasValueGenerator() : bool + { + return $this->valueGenerator !== null; + } + + /** + * @return ValueGeneratorMetadata|null + */ + public function getValueGenerator() : ?ValueGeneratorMetadata + { + return $this->valueGenerator; + } + + /** + * @param ValueGeneratorMetadata|null $valueGenerator + */ + public function setValueGenerator(?ValueGeneratorMetadata $valueGenerator) : void + { + $this->valueGenerator = $valueGenerator; + } +} diff --git a/lib/Doctrine/ORM/Mapping/ManyToMany.php b/lib/Doctrine/ORM/Mapping/ManyToMany.php deleted file mode 100644 index ca2f53c9eea..00000000000 --- a/lib/Doctrine/ORM/Mapping/ManyToMany.php +++ /dev/null @@ -1,66 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("PROPERTY") - */ -final class ManyToMany implements Annotation -{ - /** - * @var string - */ - public $targetEntity; - - /** - * @var string - */ - public $mappedBy; - - /** - * @var string - */ - public $inversedBy; - - /** - * @var array - */ - public $cascade; - - /** - * The fetching strategy to use for the association. - * - * @var string - * - * @Enum({"LAZY", "EAGER", "EXTRA_LAZY"}) - */ - public $fetch = 'LAZY'; - - /** - * @var boolean - */ - public $orphanRemoval = false; - - /** - * @var string - */ - public $indexBy; -} diff --git a/lib/Doctrine/ORM/Mapping/ManyToManyAssociationMetadata.php b/lib/Doctrine/ORM/Mapping/ManyToManyAssociationMetadata.php new file mode 100644 index 00000000000..00ec1ec1dd2 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/ManyToManyAssociationMetadata.php @@ -0,0 +1,44 @@ + + */ +class ManyToManyAssociationMetadata extends ToManyAssociationMetadata +{ + /** @var null|JoinTableMetadata */ + private $joinTable; + + /** + * @param null|JoinTableMetadata $joinTable + */ + public function setJoinTable(JoinTableMetadata $joinTable = null) : void + { + $this->joinTable = $joinTable; + } + + /** + * @return JoinTableMetadata|null + */ + public function getJoinTable() : ?JoinTableMetadata + { + return $this->joinTable; + } + + public function __clone() + { + parent::__clone(); + + if ($this->joinTable) { + $this->joinTable = clone $this->joinTable; + } + } +} diff --git a/lib/Doctrine/ORM/Mapping/ManyToOne.php b/lib/Doctrine/ORM/Mapping/ManyToOne.php deleted file mode 100644 index d3414e6a956..00000000000 --- a/lib/Doctrine/ORM/Mapping/ManyToOne.php +++ /dev/null @@ -1,51 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("PROPERTY") - */ -final class ManyToOne implements Annotation -{ - /** - * @var string - */ - public $targetEntity; - - /** - * @var array - */ - public $cascade; - - /** - * The fetching strategy to use for the association. - * - * @var string - * - * @Enum({"LAZY", "EAGER", "EXTRA_LAZY"}) - */ - public $fetch = 'LAZY'; - - /** - * @var string - */ - public $inversedBy; -} diff --git a/lib/Doctrine/ORM/Mapping/ManyToOneAssociationMetadata.php b/lib/Doctrine/ORM/Mapping/ManyToOneAssociationMetadata.php new file mode 100644 index 00000000000..77bbcbd15fe --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/ManyToOneAssociationMetadata.php @@ -0,0 +1,17 @@ + + */ +class ManyToOneAssociationMetadata extends ToOneAssociationMetadata +{ +} diff --git a/lib/Doctrine/ORM/Mapping/MappedSuperClassMetadata.php b/lib/Doctrine/ORM/Mapping/MappedSuperClassMetadata.php new file mode 100644 index 00000000000..e8bfef07809 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/MappedSuperClassMetadata.php @@ -0,0 +1,95 @@ + + */ +class MappedSuperClassMetadata extends ComponentMetadata +{ + /** + * @var null|string + */ + protected $customRepositoryClassName; + + /** + * @var null|Property + */ + protected $declaredVersion; + + /** + * @return null|string + */ + public function getCustomRepositoryClassName() : ?string + { + return $this->customRepositoryClassName; + } + + /** + * @param null|string customRepositoryClassName + */ + public function setCustomRepositoryClassName(?string $customRepositoryClassName) : void + { + $this->customRepositoryClassName = $customRepositoryClassName; + } + + /** + * @return Property|null + */ + public function getDeclaredVersion() : ?Property + { + return $this->declaredVersion; + } + + /** + * @param Property $property + */ + public function setDeclaredVersion(Property $property) : void + { + $this->declaredVersion = $property; + } + + /** + * @return Property|null + */ + public function getVersion() : ?Property + { + /** @var MappedSuperClassMetadata|null $parent */ + $parent = $this->parent; + $version = $this->declaredVersion; + + if ($parent && ! $version) { + $version = $parent->getVersion(); + } + + return $version; + } + + /** + * @return bool + */ + public function isVersioned() : bool + { + return $this->getVersion() !== null; + } + + /** + * {@inheritdoc} + */ + public function addDeclaredProperty(Property $property) : void + { + parent::addDeclaredProperty($property); + + if ($property instanceof VersionFieldMetadata) { + $this->setDeclaredVersion($property); + } + } +} diff --git a/lib/Doctrine/ORM/Mapping/MappedSuperclass.php b/lib/Doctrine/ORM/Mapping/MappedSuperclass.php deleted file mode 100644 index 74588107d89..00000000000 --- a/lib/Doctrine/ORM/Mapping/MappedSuperclass.php +++ /dev/null @@ -1,32 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("CLASS") - */ -final class MappedSuperclass implements Annotation -{ - /** - * @var string - */ - public $repositoryClass; -} diff --git a/lib/Doctrine/ORM/Mapping/MappingException.php b/lib/Doctrine/ORM/Mapping/MappingException.php index 7dc4405159a..111a2382344 100644 --- a/lib/Doctrine/ORM/Mapping/MappingException.php +++ b/lib/Doctrine/ORM/Mapping/MappingException.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Mapping; @@ -147,63 +132,68 @@ public static function invalidOverrideFieldName($className, $fieldName) * * @return MappingException */ - public static function invalidOverrideFieldType($className, $fieldName) + public static function invalidOverridePropertyType($className, $fieldName) { - return new self("The column type of attribute '$fieldName' on class '$className' could not be changed."); + return new self("Invalid property override named '$fieldName' for class '$className'."); } /** - * @param string $className + * Exception for invalid version property override. + * + * @param string $className The entity's name. * @param string $fieldName * * @return MappingException */ - public static function mappingNotFound($className, $fieldName) + public static function invalidOverrideVersionField($className, $fieldName) { - return new self("No mapping found for field '$fieldName' on class '$className'."); + return new self("Invalid version field override named '$fieldName' for class '$className'."); } /** - * @param string $className - * @param string $queryName + * Exception for invalid property type override. + * + * @param string $className The entity's name. + * @param string $fieldName * * @return MappingException */ - public static function queryNotFound($className, $queryName) + public static function invalidOverrideFieldType($className, $fieldName) { - return new self("No query found named '$queryName' on class '$className'."); + return new self("The column type of attribute '$fieldName' on class '$className' could not be changed."); } /** * @param string $className - * @param string $resultName + * @param string $fieldName * * @return MappingException */ - public static function resultMappingNotFound($className, $resultName) + public static function mappingNotFound($className, $fieldName) { - return new self("No result set mapping found named '$resultName' on class '$className'."); + return new self("No mapping found for field '$fieldName' on class '$className'."); } /** - * @param string $entity + * @param string $className * @param string $queryName * * @return MappingException */ - public static function emptyQueryMapping($entity, $queryName) + public static function queryNotFound($className, $queryName) { - return new self('Query named "'.$queryName.'" in "'.$entity.'" could not be empty.'); + return new self("No query found named '$queryName' on class '$className'."); } /** * @param string $className + * @param string $resultName * * @return MappingException */ - public static function nameIsMandatoryForQueryMapping($className) + public static function resultMappingNotFound($className, $resultName) { - return new self("Query name on entity class '$className' is not defined."); + return new self("No result set mapping found named '$resultName' on class '$className'."); } /** @@ -279,7 +269,7 @@ public static function joinTableRequired($fieldName) * * @return MappingException */ - static function missingRequiredOption($field, $expectedOption, $hint = '') + public static function missingRequiredOption($field, $expectedOption, $hint = '') { $message = "The mapping of field '{$field}' is invalid: The option '{$expectedOption}' is required."; @@ -371,25 +361,19 @@ public static function tableIdGeneratorNotImplemented($className) } /** - * @param string $entity The entity's name. - * @param string $fieldName The name of the field that was already declared. + * @param string $className + * @param Property $property * * @return MappingException */ - public static function duplicateFieldMapping($entity, $fieldName) + public static function duplicateProperty($className, Property $property) { - return new self('Property "'.$fieldName.'" in "'.$entity.'" was already declared, but it must be declared only once'); - } - - /** - * @param string $entity - * @param string $fieldName - * - * @return MappingException - */ - public static function duplicateAssociationMapping($entity, $fieldName) - { - return new self('Property "'.$fieldName.'" in "'.$entity.'" was already declared, but it must be declared only once'); + return new self(sprintf( + 'Property "%s" in "%s" was already declared in "%s", but it must be declared only once', + $property->getName(), + $className, + $property->getDeclaringClass()->getClassName() + )); } /** @@ -435,17 +419,13 @@ public static function noIdDefined($entity) } /** - * @param string $entity - * @param string $fieldName * @param string $unsupportedType * * @return MappingException */ - public static function unsupportedOptimisticLockingType($entity, $fieldName, $unsupportedType) + public static function unsupportedOptimisticLockingType($unsupportedType) { - return new self('Locking type "'.$unsupportedType.'" (specified in "'.$entity.'", field "'.$fieldName.'") ' - .'is not supported by Doctrine.' - ); + return new self('Locking type "'.$unsupportedType.'" is not supported by Doctrine.'); } /** @@ -521,14 +501,13 @@ public static function missingDiscriminatorColumn($className) } /** - * @param string $className * @param string $type * * @return MappingException */ - public static function invalidDiscriminatorColumnType($className, $type) + public static function invalidDiscriminatorColumnType($type) { - return new self("Discriminator column type on entity class '$className' is not allowed to be '$type'. 'string' or 'integer' type variables are suggested!"); + return new self("Discriminator column type is not allowed to be '$type'. 'string' or 'integer' type variables are suggested!"); } /** @@ -552,6 +531,24 @@ public static function cannotVersionIdField($className, $fieldName) return new self("Setting Id field '$fieldName' as versionable in entity class '$className' is not supported."); } + /** + * @param string $className + * @param Property $property + * + * @return MappingException + */ + public static function sqlConversionNotAllowedForPrimaryKeyProperties($className, Property $property) + { + return new self(sprintf( + 'It is not possible to set id field "%s" to type "%s" in entity class "%s". ' . + 'The type "%s" requires conversion SQL which is not allowed for identifiers.', + $property->getName(), + $property->getTypeName(), + $className, + $property->getTypeName() + )); + } + /** * @param string $className * @param string $fieldName @@ -755,9 +752,19 @@ public static function invalidFetchMode($className, $annotation) * * @return MappingException */ - public static function compositeKeyAssignedIdGeneratorRequired($className) + public static function nonPrimaryidentityGeneratorNotSupported($className) + { + return new self("Entity '". $className . "' has a an Identity strategy defined on a non-primary field. This is not supported."); + } + + /** + * @param string $className + * + * @return MappingException + */ + public static function compositeIdentityGeneratorNotSupported($className) { - return new self("Entity '". $className . "' has a composite identifier but uses an ID generator other than manually assigning (Identity, Sequence). This is not supported."); + return new self("Entity '". $className . "' has a composite identifier with with an Identity strategy. This is not supported."); } /** @@ -769,7 +776,7 @@ public static function compositeKeyAssignedIdGeneratorRequired($className) */ public static function invalidTargetEntityClass($targetEntity, $sourceEntity, $associationName) { - return new self("The target-entity " . $targetEntity . " cannot be found in '" . $sourceEntity."#".$associationName."'."); + return new self("The target-entity '" . $targetEntity . "' cannot be found in '" . $sourceEntity."#".$associationName."'."); } /** @@ -784,7 +791,7 @@ public static function invalidCascadeOption(array $cascades, $className, $proper $cascades = implode(", ", array_map(function ($e) { return "'" . $e . "'"; }, $cascades)); return new self(sprintf( - "You have specified invalid cascade options for %s::$%s: %s; available options: 'remove', 'persist', 'refresh', 'merge', and 'detach'", + "You have specified invalid cascade options for %s::$%s: %s; available options: 'remove', 'persist', and 'refresh'", $className, $propertyName, $cascades diff --git a/lib/Doctrine/ORM/Mapping/NamedNativeQueries.php b/lib/Doctrine/ORM/Mapping/NamedNativeQueries.php deleted file mode 100644 index 2539107afcf..00000000000 --- a/lib/Doctrine/ORM/Mapping/NamedNativeQueries.php +++ /dev/null @@ -1,40 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * Is used to specify an array of native SQL named queries. - * The NamedNativeQueries annotation can be applied to an entity or mapped superclass. - * - * @author Fabio B. Silva - * @since 2.3 - * - * @Annotation - * @Target("CLASS") - */ -final class NamedNativeQueries implements Annotation -{ - /** - * One or more NamedNativeQuery annotations. - * - * @var array<\Doctrine\ORM\Mapping\NamedNativeQuery> - */ - public $value = []; -} diff --git a/lib/Doctrine/ORM/Mapping/NamedNativeQuery.php b/lib/Doctrine/ORM/Mapping/NamedNativeQuery.php deleted file mode 100644 index f336c99171d..00000000000 --- a/lib/Doctrine/ORM/Mapping/NamedNativeQuery.php +++ /dev/null @@ -1,61 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * Is used to specify a native SQL named query. - * The NamedNativeQuery annotation can be applied to an entity or mapped superclass. - * - * @author Fabio B. Silva - * @since 2.3 - * - * @Annotation - * @Target("ANNOTATION") - */ -final class NamedNativeQuery implements Annotation -{ - /** - * The name used to refer to the query with the EntityManager methods that create query objects. - * - * @var string - */ - public $name; - - /** - * The SQL query string. - * - * @var string - */ - public $query; - - /** - * The class of the result. - * - * @var string - */ - public $resultClass; - - /** - * The name of a SqlResultSetMapping, as defined in metadata. - * - * @var string - */ - public $resultSetMapping; -} diff --git a/lib/Doctrine/ORM/Mapping/NamedQueries.php b/lib/Doctrine/ORM/Mapping/NamedQueries.php deleted file mode 100644 index 5fce0727b28..00000000000 --- a/lib/Doctrine/ORM/Mapping/NamedQueries.php +++ /dev/null @@ -1,32 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("CLASS") - */ -final class NamedQueries implements Annotation -{ - /** - * @var array<\Doctrine\ORM\Mapping\NamedQuery> - */ - public $value; -} diff --git a/lib/Doctrine/ORM/Mapping/OneToMany.php b/lib/Doctrine/ORM/Mapping/OneToMany.php deleted file mode 100644 index 4b2465718e1..00000000000 --- a/lib/Doctrine/ORM/Mapping/OneToMany.php +++ /dev/null @@ -1,61 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("PROPERTY") - */ -final class OneToMany implements Annotation -{ - /** - * @var string - */ - public $mappedBy; - - /** - * @var string - */ - public $targetEntity; - - /** - * @var array - */ - public $cascade; - - /** - * The fetching strategy to use for the association. - * - * @var string - * - * @Enum({"LAZY", "EAGER", "EXTRA_LAZY"}) - */ - public $fetch = 'LAZY'; - - /** - * @var boolean - */ - public $orphanRemoval = false; - - /** - * @var string - */ - public $indexBy; -} diff --git a/lib/Doctrine/ORM/Mapping/OneToManyAssociationMetadata.php b/lib/Doctrine/ORM/Mapping/OneToManyAssociationMetadata.php new file mode 100644 index 00000000000..f62af06ab69 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/OneToManyAssociationMetadata.php @@ -0,0 +1,17 @@ + + */ +class OneToManyAssociationMetadata extends ToManyAssociationMetadata +{ +} diff --git a/lib/Doctrine/ORM/Mapping/OneToOne.php b/lib/Doctrine/ORM/Mapping/OneToOne.php deleted file mode 100644 index b2ab81f88d9..00000000000 --- a/lib/Doctrine/ORM/Mapping/OneToOne.php +++ /dev/null @@ -1,61 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("PROPERTY") - */ -final class OneToOne implements Annotation -{ - /** - * @var string - */ - public $targetEntity; - - /** - * @var string - */ - public $mappedBy; - - /** - * @var string - */ - public $inversedBy; - - /** - * @var array - */ - public $cascade; - - /** - * The fetching strategy to use for the association. - * - * @var string - * - * @Enum({"LAZY", "EAGER", "EXTRA_LAZY"}) - */ - public $fetch = 'LAZY'; - - /** - * @var boolean - */ - public $orphanRemoval = false; -} diff --git a/lib/Doctrine/ORM/Mapping/OneToOneAssociationMetadata.php b/lib/Doctrine/ORM/Mapping/OneToOneAssociationMetadata.php new file mode 100644 index 00000000000..8561e69a124 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/OneToOneAssociationMetadata.php @@ -0,0 +1,17 @@ + + */ +class OneToOneAssociationMetadata extends ToOneAssociationMetadata +{ +} diff --git a/lib/Doctrine/ORM/Mapping/OrderBy.php b/lib/Doctrine/ORM/Mapping/OrderBy.php deleted file mode 100644 index ad1b7a8f714..00000000000 --- a/lib/Doctrine/ORM/Mapping/OrderBy.php +++ /dev/null @@ -1,32 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("PROPERTY") - */ -final class OrderBy implements Annotation -{ - /** - * @var array - */ - public $value; -} diff --git a/lib/Doctrine/ORM/Mapping/PostLoad.php b/lib/Doctrine/ORM/Mapping/PostLoad.php deleted file mode 100644 index 2f8e9932e35..00000000000 --- a/lib/Doctrine/ORM/Mapping/PostLoad.php +++ /dev/null @@ -1,28 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("METHOD") - */ -final class PostLoad implements Annotation -{ -} diff --git a/lib/Doctrine/ORM/Mapping/PostPersist.php b/lib/Doctrine/ORM/Mapping/PostPersist.php deleted file mode 100644 index 2aea7194911..00000000000 --- a/lib/Doctrine/ORM/Mapping/PostPersist.php +++ /dev/null @@ -1,28 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("METHOD") - */ -final class PostPersist implements Annotation -{ -} diff --git a/lib/Doctrine/ORM/Mapping/PostRemove.php b/lib/Doctrine/ORM/Mapping/PostRemove.php deleted file mode 100644 index 321c4bd547b..00000000000 --- a/lib/Doctrine/ORM/Mapping/PostRemove.php +++ /dev/null @@ -1,28 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("METHOD") - */ -final class PostRemove implements Annotation -{ -} diff --git a/lib/Doctrine/ORM/Mapping/PostUpdate.php b/lib/Doctrine/ORM/Mapping/PostUpdate.php deleted file mode 100644 index a55f7072a69..00000000000 --- a/lib/Doctrine/ORM/Mapping/PostUpdate.php +++ /dev/null @@ -1,28 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("METHOD") - */ -final class PostUpdate implements Annotation -{ -} diff --git a/lib/Doctrine/ORM/Mapping/PreFlush.php b/lib/Doctrine/ORM/Mapping/PreFlush.php deleted file mode 100644 index 6697d372c37..00000000000 --- a/lib/Doctrine/ORM/Mapping/PreFlush.php +++ /dev/null @@ -1,28 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("METHOD") - */ -final class PreFlush implements Annotation -{ -} diff --git a/lib/Doctrine/ORM/Mapping/PrePersist.php b/lib/Doctrine/ORM/Mapping/PrePersist.php deleted file mode 100644 index fea05be6d3d..00000000000 --- a/lib/Doctrine/ORM/Mapping/PrePersist.php +++ /dev/null @@ -1,28 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("METHOD") - */ -final class PrePersist implements Annotation -{ -} diff --git a/lib/Doctrine/ORM/Mapping/PreRemove.php b/lib/Doctrine/ORM/Mapping/PreRemove.php deleted file mode 100644 index 29822edacc9..00000000000 --- a/lib/Doctrine/ORM/Mapping/PreRemove.php +++ /dev/null @@ -1,28 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("METHOD") - */ -final class PreRemove implements Annotation -{ -} diff --git a/lib/Doctrine/ORM/Mapping/PreUpdate.php b/lib/Doctrine/ORM/Mapping/PreUpdate.php deleted file mode 100644 index 290df72e04a..00000000000 --- a/lib/Doctrine/ORM/Mapping/PreUpdate.php +++ /dev/null @@ -1,28 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("METHOD") - */ -final class PreUpdate implements Annotation -{ -} diff --git a/lib/Doctrine/ORM/Mapping/Property.php b/lib/Doctrine/ORM/Mapping/Property.php new file mode 100644 index 00000000000..6bc8d3effa2 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/Property.php @@ -0,0 +1,53 @@ +. - */ - -namespace Doctrine\ORM\Mapping; - -use Doctrine\DBAL\Platforms\AbstractPlatform; - -/** - * A set of rules for determining the column, alias and table quotes. - * - * @since 2.3 - * @author Fabio B. Silva - */ -interface QuoteStrategy -{ - /** - * Gets the (possibly quoted) column name for safe use in an SQL statement. - * - * @param string $fieldName - * @param ClassMetadata $class - * @param AbstractPlatform $platform - * - * @return string - */ - function getColumnName($fieldName, ClassMetadata $class, AbstractPlatform $platform); - - /** - * Gets the (possibly quoted) primary table name for safe use in an SQL statement. - * - * @param ClassMetadata $class - * @param AbstractPlatform $platform - * - * @return string - */ - function getTableName(ClassMetadata $class, AbstractPlatform $platform); - - /** - * Gets the (possibly quoted) sequence name for safe use in an SQL statement. - * - * @param array $definition - * @param ClassMetadata $class - * @param AbstractPlatform $platform - * - * @return string - */ - function getSequenceName(array $definition, ClassMetadata $class, AbstractPlatform $platform); - - /** - * Gets the (possibly quoted) name of the join table. - * - * @param array $association - * @param ClassMetadata $class - * @param AbstractPlatform $platform - * - * @return string - */ - function getJoinTableName(array $association, ClassMetadata $class, AbstractPlatform $platform); - - /** - * Gets the (possibly quoted) join column name. - * - * @param array $joinColumn - * @param ClassMetadata $class - * @param AbstractPlatform $platform - * - * @return string - */ - function getJoinColumnName(array $joinColumn, ClassMetadata $class, AbstractPlatform $platform); - - /** - * Gets the (possibly quoted) join column name. - * - * @param array $joinColumn - * @param ClassMetadata $class - * @param AbstractPlatform $platform - * - * @return string - */ - function getReferencedJoinColumnName(array $joinColumn, ClassMetadata $class, AbstractPlatform $platform); - - /** - * Gets the (possibly quoted) identifier column names for safe use in an SQL statement. - * - * @param ClassMetadata $class - * @param AbstractPlatform $platform - * - * @return array - */ - function getIdentifierColumnNames(ClassMetadata $class, AbstractPlatform $platform); - - /** - * Gets the column alias. - * - * @param string $columnName - * @param integer $counter - * @param AbstractPlatform $platform - * @param ClassMetadata|null $class - * - * @return string - */ - function getColumnAlias($columnName, $counter, AbstractPlatform $platform, ClassMetadata $class = null); - -} diff --git a/lib/Doctrine/ORM/Mapping/Reflection/ReflectionPropertiesGetter.php b/lib/Doctrine/ORM/Mapping/Reflection/ReflectionPropertiesGetter.php deleted file mode 100644 index 6ac7f11c3fd..00000000000 --- a/lib/Doctrine/ORM/Mapping/Reflection/ReflectionPropertiesGetter.php +++ /dev/null @@ -1,163 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping\Reflection; - -use Doctrine\Common\Persistence\Mapping\ReflectionService; -use ReflectionClass; -use ReflectionProperty; - -/** - * Utility class to retrieve all reflection instance properties of a given class, including - * private inherited properties and transient properties. - * - * @private This API is for internal use only - * - * @author Marco Pivetta - */ -final class ReflectionPropertiesGetter -{ - /** - * @var ReflectionProperty[][] indexed by class name and property internal name - */ - private $properties = []; - - /** - * @var ReflectionService - */ - private $reflectionService; - - /** - * @param ReflectionService $reflectionService - */ - public function __construct(ReflectionService $reflectionService) - { - $this->reflectionService = $reflectionService; - } - - /** - * @param $className - * - * @return ReflectionProperty[] indexed by property internal name - */ - public function getProperties($className) - { - if (isset($this->properties[$className])) { - return $this->properties[$className]; - } - - return $this->properties[$className] = call_user_func_array( - 'array_merge', - // first merge because `array_merge` expects >= 1 params - array_merge( - [[]], - array_map( - [$this, 'getClassProperties'], - $this->getHierarchyClasses($className) - ) - ) - ); - } - - /** - * @param string $className - * - * @return ReflectionClass[] - */ - private function getHierarchyClasses($className) - { - $classes = []; - $parentClassName = $className; - - while ($parentClassName && $currentClass = $this->reflectionService->getClass($parentClassName)) { - $classes[] = $currentClass; - $parentClassName = null; - - if ($parentClass = $currentClass->getParentClass()) { - $parentClassName = $parentClass->getName(); - } - } - - return $classes; - } - - /** - * @param ReflectionClass $reflectionClass - * - * @return ReflectionProperty[] - */ - private function getClassProperties(ReflectionClass $reflectionClass) - { - $properties = $reflectionClass->getProperties(); - - return array_filter( - array_filter(array_map( - [$this, 'getAccessibleProperty'], - array_combine( - array_map([$this, 'getLogicalName'], $properties), - $properties - ) - )), - [$this, 'isInstanceProperty'] - ); - } - - /** - * @param ReflectionProperty $reflectionProperty - * - * @return bool - */ - private function isInstanceProperty(ReflectionProperty $reflectionProperty) - { - return ! $reflectionProperty->isStatic(); - } - - /** - * @param ReflectionProperty $property - * - * @return null|ReflectionProperty - */ - private function getAccessibleProperty(ReflectionProperty $property) - { - return $this->reflectionService->getAccessibleProperty( - $property->getDeclaringClass()->getName(), - $property->getName() - ); - } - - /** - * @param ReflectionProperty $property - * - * @return string - */ - private function getLogicalName(ReflectionProperty $property) - { - $propertyName = $property->getName(); - - if ($property->isPublic()) { - return $propertyName; - } - - if ($property->isProtected()) { - return "\0*\0" . $propertyName; - } - - return "\0" . $property->getDeclaringClass()->getName() . "\0" . $propertyName; - } -} diff --git a/lib/Doctrine/ORM/Mapping/ReflectionEmbeddedProperty.php b/lib/Doctrine/ORM/Mapping/ReflectionEmbeddedProperty.php index b224fff4eb5..2eb7c9e2ee9 100644 --- a/lib/Doctrine/ORM/Mapping/ReflectionEmbeddedProperty.php +++ b/lib/Doctrine/ORM/Mapping/ReflectionEmbeddedProperty.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Mapping; @@ -84,7 +69,7 @@ public function getValue($object = null) /** * {@inheritDoc} */ - public function setValue($object, $value = null) + public function setValue($object, $value = null) : void { $embeddedObject = $this->parentProperty->getValue($object); diff --git a/lib/Doctrine/ORM/Mapping/RootClassMetadata.php b/lib/Doctrine/ORM/Mapping/RootClassMetadata.php new file mode 100644 index 00000000000..ba9d5f02747 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/RootClassMetadata.php @@ -0,0 +1,27 @@ + + * + * @property MappedSuperClassMetadata $parent + */ +class RootClassMetadata extends EntityClassMetadata +{ + /** + * @return RootClassMetadata + */ + public function getRootClass() : RootClassMetadata + { + return $this; + } +} diff --git a/lib/Doctrine/ORM/Mapping/NamedQuery.php b/lib/Doctrine/ORM/Mapping/SecondPass.php similarity index 81% rename from lib/Doctrine/ORM/Mapping/NamedQuery.php rename to lib/Doctrine/ORM/Mapping/SecondPass.php index c4e6cd528fb..299d4883275 100644 --- a/lib/Doctrine/ORM/Mapping/NamedQuery.php +++ b/lib/Doctrine/ORM/Mapping/SecondPass.php @@ -1,4 +1,5 @@ . */ +declare(strict_types=1); + namespace Doctrine\ORM\Mapping; -/** - * @Annotation - * @Target("ANNOTATION") - */ -final class NamedQuery implements Annotation +interface SecondPass { /** - * @var string - */ - public $name; - - /** - * @var string + * @param ClassMetadataBuildingContext $metadataBuildingContext + * + * @return void */ - public $query; + public function process(ClassMetadataBuildingContext $metadataBuildingContext) : void; } diff --git a/lib/Doctrine/ORM/Mapping/SequenceGenerator.php b/lib/Doctrine/ORM/Mapping/SequenceGenerator.php deleted file mode 100644 index ba1c45b6425..00000000000 --- a/lib/Doctrine/ORM/Mapping/SequenceGenerator.php +++ /dev/null @@ -1,42 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("PROPERTY") - */ -final class SequenceGenerator implements Annotation -{ - /** - * @var string - */ - public $sequenceName; - - /** - * @var integer - */ - public $allocationSize = 1; - - /** - * @var integer - */ - public $initialValue = 1; -} diff --git a/lib/Doctrine/ORM/Mapping/SqlResultSetMapping.php b/lib/Doctrine/ORM/Mapping/SqlResultSetMapping.php deleted file mode 100644 index cb78c9a40a5..00000000000 --- a/lib/Doctrine/ORM/Mapping/SqlResultSetMapping.php +++ /dev/null @@ -1,54 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * The SqlResultSetMapping annotation is used to specify the mapping of the result of a native SQL query. - * The SqlResultSetMapping annotation can be applied to an entity or mapped superclass. - * - * @author Fabio B. Silva - * @since 2.3 - * - * @Annotation - * @Target("ANNOTATION") - */ -final class SqlResultSetMapping implements Annotation -{ - /** - * The name given to the result set mapping, and used to refer to it in the methods of the Query API. - * - * @var string - */ - public $name; - - /** - * Specifies the result set mapping to entities. - * - * @var array<\Doctrine\ORM\Mapping\EntityResult> - */ - public $entities = []; - - /** - * Specifies the result set mapping to scalar values. - * - * @var array<\Doctrine\ORM\Mapping\ColumnResult> - */ - public $columns = []; -} diff --git a/lib/Doctrine/ORM/Mapping/SqlResultSetMappings.php b/lib/Doctrine/ORM/Mapping/SqlResultSetMappings.php deleted file mode 100644 index 0b74f2d9598..00000000000 --- a/lib/Doctrine/ORM/Mapping/SqlResultSetMappings.php +++ /dev/null @@ -1,40 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * Is used to specify an array of mappings. - * The SqlResultSetMappings annotation can be applied to an entity or mapped superclass. - * - * @author Fabio B. Silva - * @since 2.3 - * - * @Annotation - * @Target("CLASS") - */ -final class SqlResultSetMappings implements Annotation -{ - /** - * One or more SqlResultSetMapping annotations. - * - * @var array<\Doctrine\ORM\Mapping\SqlResultSetMapping> - */ - public $value = []; -} diff --git a/lib/Doctrine/ORM/Mapping/SubClassMetadata.php b/lib/Doctrine/ORM/Mapping/SubClassMetadata.php new file mode 100644 index 00000000000..5f10f0f04bc --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/SubClassMetadata.php @@ -0,0 +1,27 @@ + + * + * @property EntityClassMetadata $parent + */ +class SubClassMetadata extends EntityClassMetadata +{ + /** + * @return RootClassMetadata + */ + public function getRootClass() : RootClassMetadata + { + return $this->parent->getRootClass(); + } +} diff --git a/lib/Doctrine/ORM/Mapping/Table.php b/lib/Doctrine/ORM/Mapping/Table.php deleted file mode 100644 index 6ed703750be..00000000000 --- a/lib/Doctrine/ORM/Mapping/Table.php +++ /dev/null @@ -1,52 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("CLASS") - */ -final class Table implements Annotation -{ - /** - * @var string - */ - public $name; - - /** - * @var string - */ - public $schema; - - /** - * @var array<\Doctrine\ORM\Mapping\Index> - */ - public $indexes; - - /** - * @var array<\Doctrine\ORM\Mapping\UniqueConstraint> - */ - public $uniqueConstraints; - - /** - * @var array - */ - public $options = []; -} diff --git a/lib/Doctrine/ORM/Mapping/TableMetadata.php b/lib/Doctrine/ORM/Mapping/TableMetadata.php new file mode 100644 index 00000000000..4a69aa4b963 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/TableMetadata.php @@ -0,0 +1,225 @@ + + */ +class TableMetadata +{ + /** @var string|null */ + protected $schema; + + /** @var string|null */ + protected $name; + + /** @var array */ + protected $options = []; + + /** @var array */ + protected $indexes = []; + + /** @var array */ + protected $uniqueConstraints = []; + + /** + * TableMetadata constructor. + * + * @param null|string $name + * @param null|string $schema + */ + public function __construct(?string $name = null, ?string $schema = null) + { + $this->name = $name; + $this->schema = $schema; + } + + /** + * @return string|null + */ + public function getSchema() : ?string + { + return $this->schema; + } + + /** + * @param string $schema + */ + public function setSchema(string $schema) : void + { + $this->schema = $schema; + } + + /** + * @param string $name + */ + public function setName(string $name) : void + { + $this->name = $name; + } + + /** + * @return string|null + */ + public function getName() : ?string + { + return $this->name; + } + + /** + * @param AbstractPlatform $platform + * + * @return string + */ + public function getQuotedQualifiedName(AbstractPlatform $platform) : string + { + if (!$this->schema) { + return $platform->quoteIdentifier($this->name); + } + + $separator = ( ! $platform->supportsSchemas() && $platform->canEmulateSchemas()) ? '__' : '.'; + + return $platform->quoteIdentifier(sprintf('%s%s%s', $this->schema, $separator, $this->name)); + } + + /** + * @return array + */ + public function getOptions() : array + { + return $this->options; + } + + /** + * @param array $options + */ + public function setOptions(array $options) : void + { + $this->options = $options; + } + + /** + * @param string $name + * + * @return mixed + */ + public function getOption(string $name) + { + return $this->options[$name]; + } + + /** + * @param string $name + * + * @return bool + */ + public function hasOption(string $name) : bool + { + return isset($this->options[$name]); + } + + /** + * @param string $name + * @param mixed $value + */ + public function addOption(string $name, $value) : void + { + $this->options[$name] = $value; + } + + /** + * @return array + */ + public function getIndexes() : array + { + return $this->indexes; + } + + /** + * @param string $name + * + * @return array + */ + public function getIndex(string $name) : array + { + return $this->indexes[$name]; + } + + /** + * @param string $name + * + * @return bool + */ + public function hasIndex(string $name) : bool + { + return isset($this->indexes[$name]); + } + + /** + * @param array $index + */ + public function addIndex(array $index) : void + { + if (! isset($index['name'])) { + $this->indexes[] = $index; + + return; + } + + $this->indexes[$index['name']] = $index; + } + + /** + * @return array + */ + public function getUniqueConstraints() : array + { + return $this->uniqueConstraints; + } + + /** + * @param string $name + * + * @return array + */ + public function getUniqueConstraint(string $name) : array + { + return $this->uniqueConstraints[$name]; + } + + /** + * @param string $name + * + * @return bool + */ + public function hasUniqueConstraint(string $name) : bool + { + return isset($this->uniqueConstraints[$name]); + } + + /** + * @param array $constraint + */ + public function addUniqueConstraint(array $constraint) : void + { + if (! isset($constraint['name'])) { + $this->uniqueConstraints[] = $constraint; + + return; + } + + $this->uniqueConstraints[$constraint['name']] = $constraint; + } +} diff --git a/lib/Doctrine/ORM/Mapping/TableOwner.php b/lib/Doctrine/ORM/Mapping/TableOwner.php new file mode 100644 index 00000000000..d7677e028c9 --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/TableOwner.php @@ -0,0 +1,26 @@ + + */ +interface TableOwner +{ + /** + * Sets the owner table metadata. + * + * @param TableMetadata $table + * + * @return void + */ + public function setTable(TableMetadata $table) : void; +} diff --git a/lib/Doctrine/ORM/Mapping/ToManyAssociationMetadata.php b/lib/Doctrine/ORM/Mapping/ToManyAssociationMetadata.php new file mode 100644 index 00000000000..6f969dac77d --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/ToManyAssociationMetadata.php @@ -0,0 +1,93 @@ + + */ +class ToManyAssociationMetadata extends AssociationMetadata +{ + /** @var array */ + private $orderBy = []; + + /** @var null|string */ + private $indexedBy; + + /** + * @param array $orderBy + */ + public function setOrderBy(array $orderBy) : void + { + $this->orderBy = $orderBy; + } + + /** + * @return array + */ + public function getOrderBy() : array + { + return $this->orderBy; + } + + /** + * @param null|string $indexedBy + */ + public function setIndexedBy(string $indexedBy = null) : void + { + $this->indexedBy = $indexedBy; + } + + /** + * @return null|string + */ + public function getIndexedBy() : ?string + { + return $this->indexedBy; + } + + /** + * @param object $owner + * @param null|array|Collection $collection + * @param EntityManagerInterface $entityManager + * + * @return PersistentCollection + */ + public function wrap($owner, $collection, EntityManagerInterface $entityManager) : PersistentCollection + { + if ($collection instanceof PersistentCollection) { + if ($collection->getOwner() === $owner) { + return $collection; + } + + $collection = $collection->getValues(); + } + + // If $value is not a Collection then use an ArrayCollection. + if (! $collection instanceof Collection) { + // @todo guilhermeblanco Conceptually, support to custom collections by replacing ArrayCollection creation. + $collection = new ArrayCollection((array) $collection); + } + + // Inject PersistentCollection + $targetClass = $entityManager->getClassMetadata($this->getTargetEntity()); + $collection = new PersistentCollection($entityManager, $targetClass, $collection); + + $collection->setOwner($owner, $this); + $collection->setDirty( ! $collection->isEmpty()); + $collection->setInitialized(true); + + return $collection; + } +} diff --git a/lib/Doctrine/ORM/Mapping/ToOneAssociationMetadata.php b/lib/Doctrine/ORM/Mapping/ToOneAssociationMetadata.php new file mode 100644 index 00000000000..b0f8297865d --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/ToOneAssociationMetadata.php @@ -0,0 +1,54 @@ + + */ +class ToOneAssociationMetadata extends AssociationMetadata +{ + /** + * @var array + */ + private $joinColumns = []; + + /** + * @param array $joinColumns + */ + public function setJoinColumns(array $joinColumns) : void + { + $this->joinColumns = $joinColumns; + } + + /** + * @return array + */ + public function getJoinColumns() : array + { + return $this->joinColumns; + } + + /** + * @param JoinColumnMetadata $joinColumn + */ + public function addJoinColumn(JoinColumnMetadata $joinColumn) : void + { + $this->joinColumns[] = $joinColumn; + } + + public function __clone() + { + parent::__clone(); + + foreach ($this->joinColumns as $index => $joinColumn) { + $this->joinColumns[$index] = clone $joinColumn; + } + } +} diff --git a/lib/Doctrine/ORM/Mapping/TransientMetadata.php b/lib/Doctrine/ORM/Mapping/TransientMetadata.php new file mode 100644 index 00000000000..2c31e38627c --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/TransientMetadata.php @@ -0,0 +1,104 @@ + + */ +class TransientMetadata implements Property +{ + /** @var ClassMetadata */ + protected $declaringClass; + + /** @var \ReflectionProperty */ + protected $reflection; + + /** @var string */ + protected $name; + + /** + * TransientMetadata constructor. + * + * @param string $name + */ + public function __construct(string $name) + { + $this->name = $name; + } + + /** + * {@inheritdoc} + */ + public function getDeclaringClass() : ComponentMetadata + { + return $this->declaringClass; + } + + /** + * @param ComponentMetadata $declaringClass + */ + public function setDeclaringClass(ComponentMetadata $declaringClass) : void + { + $this->declaringClass = $declaringClass; + } + + /** + * {@inheritdoc} + */ + public function getName() : string + { + return $this->name; + } + + /** + * {@inheritdoc} + */ + public function isPrimaryKey() : bool + { + return false; + } + + /** + * {@inheritdoc} + */ + public function setValue($object, $value) : void + { + $this->reflection->setValue($object, $value); + } + + /** + * {@inheritdoc} + */ + public function getValue($object) + { + return $this->reflection->getValue($object); + } + + /** + * {@inheritdoc} + */ + public function setReflectionProperty(\ReflectionProperty $reflectionProperty) : void + { + $this->reflection = $reflectionProperty; + } + + /** + * {@inheritdoc} + */ + public function wakeupReflection(ReflectionService $reflectionService) : void + { + $this->setReflectionProperty( + $reflectionService->getAccessibleProperty($this->declaringClass->getClassName(), $this->name) + ); + } +} diff --git a/lib/Doctrine/ORM/Mapping/UniqueConstraint.php b/lib/Doctrine/ORM/Mapping/UniqueConstraint.php deleted file mode 100644 index f117d1873e8..00000000000 --- a/lib/Doctrine/ORM/Mapping/UniqueConstraint.php +++ /dev/null @@ -1,42 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("ANNOTATION") - */ -final class UniqueConstraint implements Annotation -{ - /** - * @var string - */ - public $name; - - /** - * @var array - */ - public $columns; - - /** - * @var array - */ - public $options; -} diff --git a/lib/Doctrine/ORM/Mapping/ValueGeneratorMetadata.php b/lib/Doctrine/ORM/Mapping/ValueGeneratorMetadata.php new file mode 100644 index 00000000000..7fb84af36ce --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/ValueGeneratorMetadata.php @@ -0,0 +1,45 @@ + + */ +class ValueGeneratorMetadata +{ + /** @var string */ + protected $type; + + /** @var array */ + protected $definition; + + /** + * ValueGeneratorMetadata constructor. + * + * @param string $type + * @param array $definition + */ + public function __construct(string $type, array $definition = []) + { + $this->type = $type; + $this->definition = $definition; + } + + public function getType(): string + { + return $this->type; + } + + public function getDefinition(): array + { + return $this->definition; + } +} diff --git a/lib/Doctrine/ORM/Mapping/Version.php b/lib/Doctrine/ORM/Mapping/Version.php deleted file mode 100644 index a2377027950..00000000000 --- a/lib/Doctrine/ORM/Mapping/Version.php +++ /dev/null @@ -1,28 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Mapping; - -/** - * @Annotation - * @Target("PROPERTY") - */ -final class Version implements Annotation -{ -} diff --git a/lib/Doctrine/ORM/Mapping/VersionFieldMetadata.php b/lib/Doctrine/ORM/Mapping/VersionFieldMetadata.php new file mode 100644 index 00000000000..e17fc3de8cd --- /dev/null +++ b/lib/Doctrine/ORM/Mapping/VersionFieldMetadata.php @@ -0,0 +1,18 @@ + + */ +final class VersionFieldMetadata extends FieldMetadata +{ +} diff --git a/lib/Doctrine/ORM/NativeQuery.php b/lib/Doctrine/ORM/NativeQuery.php index ddc5418d672..e508b35ae1e 100644 --- a/lib/Doctrine/ORM/NativeQuery.php +++ b/lib/Doctrine/ORM/NativeQuery.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; @@ -30,7 +15,7 @@ final class NativeQuery extends AbstractQuery /** * @var string */ - private $_sql; + private $sql; /** * Sets the SQL of the query. @@ -41,7 +26,7 @@ final class NativeQuery extends AbstractQuery */ public function setSQL($sql) { - $this->_sql = $sql; + $this->sql = $sql; return $this; } @@ -55,13 +40,13 @@ public function setSQL($sql) */ public function getSQL() { - return $this->_sql; + return $this->sql; } /** * {@inheritdoc} */ - protected function _doExecute() + protected function doExecute() { $parameters = []; $types = []; @@ -85,8 +70,8 @@ protected function _doExecute() $types = array_values($types); } - return $this->_em->getConnection()->executeQuery( - $this->_sql, $parameters, $types, $this->_queryCacheProfile + return $this->em->getConnection()->executeQuery( + $this->sql, $parameters, $types, $this->queryCacheProfile ); } } diff --git a/lib/Doctrine/ORM/NoResultException.php b/lib/Doctrine/ORM/NoResultException.php index 2cbac8e9d95..38ab6e76769 100644 --- a/lib/Doctrine/ORM/NoResultException.php +++ b/lib/Doctrine/ORM/NoResultException.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; diff --git a/lib/Doctrine/ORM/NonUniqueResultException.php b/lib/Doctrine/ORM/NonUniqueResultException.php index 55b71300058..c512e8c1657 100644 --- a/lib/Doctrine/ORM/NonUniqueResultException.php +++ b/lib/Doctrine/ORM/NonUniqueResultException.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; diff --git a/lib/Doctrine/ORM/ORMException.php b/lib/Doctrine/ORM/ORMException.php index 3ce9ce9dc91..9c60851e954 100644 --- a/lib/Doctrine/ORM/ORMException.php +++ b/lib/Doctrine/ORM/ORMException.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; diff --git a/lib/Doctrine/ORM/ORMInvalidArgumentException.php b/lib/Doctrine/ORM/ORMInvalidArgumentException.php index accf1cc1517..64d49b0bcc9 100644 --- a/lib/Doctrine/ORM/ORMInvalidArgumentException.php +++ b/lib/Doctrine/ORM/ORMInvalidArgumentException.php @@ -1,24 +1,11 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; +use Doctrine\ORM\Mapping\AssociationMetadata; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; /** * Contains exception messages for all invalid lifecycle state exceptions inside UnitOfWork @@ -82,34 +69,49 @@ static public function readOnlyRequiresManagedEntity($entity) } /** - * @param array $assoc - * @param object $entry + * @param AssociationMetadata $association + * @param object $entry * * @return ORMInvalidArgumentException */ - static public function newEntityFoundThroughRelationship(array $assoc, $entry) + static public function newEntityFoundThroughRelationship(AssociationMetadata $association, $entry) { - return new self("A new entity was found through the relationship '" - . $assoc['sourceEntity'] . "#" . $assoc['fieldName'] . "' that was not" - . " configured to cascade persist operations for entity: " . self::objToStr($entry) . "." - . " To solve this issue: Either explicitly call EntityManager#persist()" - . " on this unknown entity or configure cascade persist " - . " this association in the mapping for example @ManyToOne(..,cascade={\"persist\"})." - . (method_exists($entry, '__toString') ? "": " If you cannot find out which entity causes the problem" - . " implement '" . $assoc['targetEntity'] . "#__toString()' to get a clue.")); + $message = "A new entity was found through the relationship '%s#%s' that was not configured to cascade " + . "persist operations for entity: %s. To solve this issue: Either explicitly call EntityManager#persist() " + . "on this unknown entity or configure cascade persist this association in the mapping for example " + . "@ManyToOne(..,cascade={\"persist\"}).%s"; + + $messageAppend = method_exists($entry, '__toString') + ? "" + : " If you cannot find out which entity causes the problem implement '%s#__toString()' to get a clue." + ; + + return new self(sprintf( + $message, + $association->getSourceEntity(), + $association->getName(), + self::objToStr($entry), + sprintf($messageAppend, $association->getTargetEntity()) + )); } /** - * @param array $assoc - * @param object $entry + * @param AssociationMetadata $association + * @param object $entry * * @return ORMInvalidArgumentException */ - static public function detachedEntityFoundThroughRelationship(array $assoc, $entry) + static public function detachedEntityFoundThroughRelationship(AssociationMetadata $association, $entry) { - return new self("A detached entity of type " . $assoc['targetEntity'] . " (" . self::objToStr($entry) . ") " - . " was found through the relationship '" . $assoc['sourceEntity'] . "#" . $assoc['fieldName'] . "' " - . "during cascading a persist operation."); + $messsage = "A detached entity of type %s (%s) was found through the relationship '%s#%s' during cascading a persist operation."; + + return new self(sprintf( + $messsage, + $association->getTargetEntity(), + self::objToStr($entry), + $association->getSourceEntity(), + $association->getName() + )); } /** @@ -193,35 +195,23 @@ public static function invalidIdentifierBindingEntity() * * @return self */ - public static function invalidAssociation(ClassMetadata $targetClass, $assoc, $actualValue) + public static function invalidAssociation(ClassMetadata $targetClass, AssociationMetadata $association, $actualValue) { $expectedType = 'Doctrine\Common\Collections\Collection|array'; - if (($assoc['type'] & ClassMetadata::TO_ONE) > 0) { - $expectedType = $targetClass->getName(); + if ($association instanceof ToOneAssociationMetadata) { + $expectedType = $targetClass->getClassName(); } return new self(sprintf( 'Expected value of type "%s" for association field "%s#$%s", got "%s" instead.', $expectedType, - $assoc['sourceEntity'], - $assoc['fieldName'], + $association->getSourceEntity(), + $association->getName(), is_object($actualValue) ? get_class($actualValue) : gettype($actualValue) )); } - /** - * Used when a given entityName hasn't the good type - * - * @param mixed $entityName The given entity (which shouldn't be a string) - * - * @return self - */ - public static function invalidEntityName($entityName) - { - return new self(sprintf('Entity name must be a string, %s given', gettype($entityName))); - } - /** * Helper method to show an object as string. * diff --git a/lib/Doctrine/ORM/OptimisticLockException.php b/lib/Doctrine/ORM/OptimisticLockException.php index 2fbd9ce5ec9..698e2f89878 100644 --- a/lib/Doctrine/ORM/OptimisticLockException.php +++ b/lib/Doctrine/ORM/OptimisticLockException.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; diff --git a/lib/Doctrine/ORM/PersistentCollection.php b/lib/Doctrine/ORM/PersistentCollection.php index 2210c3c310c..4a69f2bfff4 100644 --- a/lib/Doctrine/ORM/PersistentCollection.php +++ b/lib/Doctrine/ORM/PersistentCollection.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; @@ -24,7 +9,13 @@ use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Selectable; use Doctrine\Common\Collections\Criteria; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\ChangeTrackingPolicy; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\FetchMode; +use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata; +use Doctrine\ORM\Mapping\OneToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToManyAssociationMetadata; /** * A PersistentCollection represents a collection of elements that have persistent state. @@ -62,7 +53,7 @@ final class PersistentCollection extends AbstractLazyCollection implements Selec * The association mapping the collection belongs to. * This is currently either a OneToManyMapping or a ManyToManyMapping. * - * @var array + * @var ToManyAssociationMetadata */ private $association; @@ -116,16 +107,16 @@ public function __construct(EntityManagerInterface $em, $class, Collection $coll * Sets the collection's owning entity together with the AssociationMapping that * describes the association between the owner and the elements of the collection. * - * @param object $entity - * @param array $assoc + * @param object $entity + * @param ToManyAssociationMetadata $association * * @return void */ - public function setOwner($entity, array $assoc) + public function setOwner($entity, ToManyAssociationMetadata $association) { $this->owner = $entity; - $this->association = $assoc; - $this->backRefFieldName = $assoc['inversedBy'] ?: $assoc['mappedBy']; + $this->association = $association; + $this->backRefFieldName = $association->getInversedBy() ?: $association->getMappedBy(); } /** @@ -162,11 +153,11 @@ public function hydrateAdd($element) // If _backRefFieldName is set and its a one-to-many association, // we need to set the back reference. - if ($this->backRefFieldName && $this->association['type'] === ClassMetadata::ONE_TO_MANY) { + if ($this->backRefFieldName && $this->association instanceof OneToManyAssociationMetadata) { + $inversedAssociation = $this->typeClass->getProperty($this->backRefFieldName); + // Set back reference to owner - $this->typeClass->reflFields[$this->backRefFieldName]->setValue( - $element, $this->owner - ); + $inversedAssociation->setValue($element, $this->owner); $this->em->getUnitOfWork()->setOriginalEntityProperty( spl_object_hash($element), $this->backRefFieldName, $this->owner @@ -189,10 +180,14 @@ public function hydrateSet($key, $element) // If _backRefFieldName is set, then the association is bidirectional // and we need to set the back reference. - if ($this->backRefFieldName && $this->association['type'] === ClassMetadata::ONE_TO_MANY) { + if ($this->backRefFieldName && $this->association instanceof OneToManyAssociationMetadata) { + $inversedAssociation = $this->typeClass->getProperty($this->backRefFieldName); + // Set back reference to owner - $this->typeClass->reflFields[$this->backRefFieldName]->setValue( - $element, $this->owner + $inversedAssociation->setValue($element, $this->owner); + + $this->em->getUnitOfWork()->setOriginalEntityProperty( + spl_object_hash($element), $this->backRefFieldName, $this->owner ); } } @@ -245,11 +240,12 @@ public function getSnapshot() */ public function getDeleteDiff() { - return array_udiff_assoc( - $this->snapshot, - $this->collection->toArray(), - function($a, $b) { return $a === $b ? 0 : 1; } - ); + $collectionItems = $this->collection->toArray(); + + return \array_values(\array_diff_key( + \array_combine(\array_map('spl_object_hash', $this->snapshot), $this->snapshot), + \array_combine(\array_map('spl_object_hash', $collectionItems), $collectionItems) + )); } /** @@ -260,17 +256,18 @@ function($a, $b) { return $a === $b ? 0 : 1; } */ public function getInsertDiff() { - return array_udiff_assoc( - $this->collection->toArray(), - $this->snapshot, - function($a, $b) { return $a === $b ? 0 : 1; } - ); + $collectionItems = $this->collection->toArray(); + + return \array_values(\array_diff_key( + \array_combine(\array_map('spl_object_hash', $collectionItems), $collectionItems), + \array_combine(\array_map('spl_object_hash', $this->snapshot), $this->snapshot) + )); } /** * INTERNAL: Gets the association mapping of the collection. * - * @return array + * @return AssociationMetadata */ public function getMapping() { @@ -291,11 +288,11 @@ private function changed() $this->isDirty = true; if ($this->association !== null && - $this->association['isOwningSide'] && - $this->association['type'] === ClassMetadata::MANY_TO_MANY && + $this->association->isOwningSide() && + $this->association instanceof ManyToManyAssociationMetadata && $this->owner && - $this->em->getClassMetadata(get_class($this->owner))->isChangeTrackingNotify()) { - $this->em->getUnitOfWork()->scheduleForDirtyCheck($this->owner); + $this->em->getClassMetadata(get_class($this->owner))->changeTrackingPolicy === ChangeTrackingPolicy::NOTIFY) { + $this->em->getUnitOfWork()->scheduleForSynchronization($this->owner); } } @@ -352,9 +349,9 @@ public function remove($key) $this->changed(); if ($this->association !== null && - $this->association['type'] & ClassMetadata::TO_MANY && + $this->association instanceof ToManyAssociationMetadata && $this->owner && - $this->association['orphanRemoval']) { + $this->association->isOrphanRemoval()) { $this->em->getUnitOfWork()->scheduleOrphanRemoval($removed); } @@ -366,7 +363,9 @@ public function remove($key) */ public function removeElement($element) { - if ( ! $this->initialized && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY) { + if ( ! $this->initialized && + $this->association !== null && + $this->association->getFetchMode() === FetchMode::EXTRA_LAZY) { if ($this->collection->contains($element)) { return $this->collection->removeElement($element); } @@ -385,9 +384,9 @@ public function removeElement($element) $this->changed(); if ($this->association !== null && - $this->association['type'] & ClassMetadata::TO_MANY && + $this->association instanceof ToManyAssociationMetadata && $this->owner && - $this->association['orphanRemoval']) { + $this->association->isOrphanRemoval()) { $this->em->getUnitOfWork()->scheduleOrphanRemoval($element); } @@ -399,8 +398,10 @@ public function removeElement($element) */ public function containsKey($key) { - if (! $this->initialized && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY - && isset($this->association['indexBy'])) { + if (! $this->initialized && + $this->association !== null && + $this->association->getFetchMode() === FetchMode::EXTRA_LAZY && + $this->association->getIndexedBy()) { $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association); return $this->collection->containsKey($key) || $persister->containsKey($this, $key); @@ -414,7 +415,9 @@ public function containsKey($key) */ public function contains($element) { - if ( ! $this->initialized && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY) { + if (! $this->initialized && + $this->association !== null && + $this->association->getFetchMode() === FetchMode::EXTRA_LAZY) { $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association); return $this->collection->contains($element) || $persister->contains($this, $element); @@ -428,12 +431,12 @@ public function contains($element) */ public function get($key) { - if ( ! $this->initialized - && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY - && isset($this->association['indexBy']) - ) { - if (!$this->typeClass->isIdentifierComposite && $this->typeClass->isIdentifier($this->association['indexBy'])) { - return $this->em->find($this->typeClass->name, $key); + if (! $this->initialized && + $this->association !== null && + $this->association->getFetchMode() === FetchMode::EXTRA_LAZY && + $this->association->getIndexedBy()) { + if (!$this->typeClass->isIdentifierComposite() && $this->typeClass->isIdentifier($this->association->getIndexedBy())) { + return $this->em->find($this->typeClass->getClassName(), $key); } return $this->em->getUnitOfWork()->getCollectionPersister($this->association)->get($this, $key); @@ -447,7 +450,9 @@ public function get($key) */ public function count() { - if ( ! $this->initialized && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY) { + if (! $this->initialized && + $this->association !== null && + $this->association->getFetchMode() === FetchMode::EXTRA_LAZY) { $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association); return $persister->count($this) + ($this->isDirty ? $this->collection->count() : 0); @@ -530,7 +535,11 @@ public function offsetUnset($offset) */ public function isEmpty() { - return $this->collection->isEmpty() && $this->count() === 0; + if ($this->initialized) { + return $this->collection->isEmpty(); + } + + return $this->collection->isEmpty() && ! $this->count(); } /** @@ -546,9 +555,9 @@ public function clear() $uow = $this->em->getUnitOfWork(); - if ($this->association['type'] & ClassMetadata::TO_MANY && - $this->association['orphanRemoval'] && - $this->owner) { + if ($this->owner !== null && + $this->association !== null && + $this->association->isOrphanRemoval()) { // we need to initialize here, as orphan removal acts like implicit cascadeRemove, // hence for event listeners we need the objects in memory. $this->initialize(); @@ -562,7 +571,7 @@ public function clear() $this->initialized = true; // direct call, {@link initialize()} is too expensive - if ($this->association['isOwningSide'] && $this->owner) { + if ($this->association->isOwningSide() && $this->owner) { $this->changed(); $uow->scheduleCollectionDeletion($this); @@ -599,7 +608,10 @@ public function __sleep() */ public function slice($offset, $length = null) { - if ( ! $this->initialized && ! $this->isDirty && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY) { + if (! $this->initialized && + ! $this->isDirty && + $this->association !== null && + $this->association->getFetchMode() === FetchMode::EXTRA_LAZY) { $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association); return $persister->slice($this, $offset, $length); @@ -655,7 +667,7 @@ public function matching(Criteria $criteria) return $this->collection->matching($criteria); } - if ($this->association['type'] === ClassMetadata::MANY_TO_MANY) { + if ($this->association instanceof ManyToManyAssociationMetadata) { $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association); return new ArrayCollection($persister->loadCriteria($this, $criteria)); @@ -669,9 +681,9 @@ public function matching(Criteria $criteria) $criteria = clone $criteria; $criteria->where($expression); - $persister = $this->em->getUnitOfWork()->getEntityPersister($this->association['targetEntity']); + $persister = $this->em->getUnitOfWork()->getEntityPersister($this->association->getTargetEntity()); - return ($this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY) + return ($this->association->getFetchMode() === FetchMode::EXTRA_LAZY) ? new LazyCriteriaCollection($persister, $criteria) : new ArrayCollection($persister->loadCriteria($criteria)); } diff --git a/lib/Doctrine/ORM/PersistentObject.php b/lib/Doctrine/ORM/PersistentObject.php new file mode 100644 index 00000000000..5c837100c3e --- /dev/null +++ b/lib/Doctrine/ORM/PersistentObject.php @@ -0,0 +1,278 @@ +getId(); // method exists through __call + * + * @author Benjamin Eberlei + */ +abstract class PersistentObject implements EntityManagerAware +{ + /** + * @var EntityManagerInterface|null + */ + private static $entityManager = null; + + /** + * @var ClassMetadata|null + */ + private $cm = null; + + /** + * Sets the entity manager responsible for all persistent object base classes. + * + * @param EntityManagerInterface|null $entityManager + * + * @return void + */ + static public function setEntityManager(EntityManagerInterface $entityManager = null) + { + self::$entityManager = $entityManager; + } + + /** + * @return EntityManagerInterface|null + */ + static public function getEntityManager() + { + return self::$entityManager; + } + + /** + * Injects the Doctrine Object Manager. + * + * @param EntityManagerInterface $entityManager + * @param ClassMetadata $classMetadata + * + * @return void + * + * @throws \RuntimeException + */ + public function injectEntityManager(EntityManagerInterface $entityManager, ClassMetadata $classMetadata) : void + { + if ($entityManager !== self::$entityManager) { + throw new \RuntimeException( + "Trying to use PersistentObject with different EntityManager instances. " . + "Was PersistentObject::setEntityManager() called?" + ); + } + + $this->cm = $classMetadata; + } + + /** + * Sets a persistent fields value. + * + * @param string $field + * @param array $args + * + * @return object + * + * @throws \BadMethodCallException When no persistent field exists by that name. + * @throws \InvalidArgumentException When the wrong target object type is passed to an association. + */ + private function set($field, $args) + { + $this->initializeDoctrine(); + + $property = $this->cm->getProperty($field); + + if (! $property) { + throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getClassName()."'"); + } + + switch (true) { + case ($property instanceof FieldMetadata && ! $property->isPrimaryKey()): + $this->$field = $args[0]; + break; + + case ($property instanceof ToOneAssociationMetadata): + $targetClassName = $property->getTargetEntity(); + + if ($args[0] !== null && ! ($args[0] instanceof $targetClassName)) { + throw new \InvalidArgumentException("Expected persistent object of type '".$targetClassName."'"); + } + + $this->$field = $args[0]; + $this->completeOwningSide($property, $args[0]); + break; + } + + return $this; + } + + /** + * Gets a persistent field value. + * + * @param string $field + * + * @return mixed + * + * @throws \BadMethodCallException When no persistent field exists by that name. + */ + private function get($field) + { + $this->initializeDoctrine(); + + $property = $this->cm->getProperty($field); + + if (! $property) { + throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getClassName()."'"); + } + + return $this->$field; + } + + /** + * If this is an inverse side association, completes the owning side. + * + * @param AssociationMetadata $property + * @param object $targetObject + * + * @return void + */ + private function completeOwningSide(AssociationMetadata $property, $targetObject) + { + // add this object on the owning side as well, for obvious infinite recursion + // reasons this is only done when called on the inverse side. + if ($property->isOwningSide()) { + return; + } + + $mappedByField = $property->getMappedBy(); + $targetMetadata = self::$entityManager->getClassMetadata($property->getTargetEntity()); + $targetProperty = $targetMetadata->getProperty($mappedByField); + $setterMethodName = ($targetProperty instanceof ToManyAssociationMetadata ? 'add' : 'set') . $mappedByField; + + $targetObject->$setterMethodName($this); + } + + /** + * Adds an object to a collection. + * + * @param string $field + * @param array $args + * + * @return object + * + * @throws \BadMethodCallException + * @throws \InvalidArgumentException + */ + private function add($field, $args) + { + $this->initializeDoctrine(); + + $property = $this->cm->getProperty($field); + + if (! $property) { + throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getClassName()."'"); + } + + if (! ($property instanceof ToManyAssociationMetadata)) { + throw new \BadMethodCallException("There is no method add".$field."() on ".$this->cm->getClassName()); + } + + $targetClassName = $property->getTargetEntity(); + + if (! ($args[0] instanceof $targetClassName)) { + throw new \InvalidArgumentException("Expected persistent object of type '".$targetClassName."'"); + } + + if (! ($this->$field instanceof Collection)) { + $this->$field = new ArrayCollection($this->$field ?: []); + } + + $this->$field->add($args[0]); + + $this->completeOwningSide($property, $args[0]); + + return $this; + } + + /** + * Initializes Doctrine Metadata for this class. + * + * @return void + * + * @throws \RuntimeException + */ + private function initializeDoctrine() + { + if ($this->cm !== null) { + return; + } + + if (!self::$entityManager) { + throw new \RuntimeException("No runtime entity manager set. Call PersistentObject#setEntityManager()."); + } + + $this->cm = self::$entityManager->getClassMetadata(get_class($this)); + } + + /** + * Magic methods. + * + * @param string $method + * @param array $args + * + * @return mixed + * + * @throws \BadMethodCallException + */ + public function __call($method, $args) + { + $command = substr($method, 0, 3); + $field = lcfirst(substr($method, 3)); + + switch ($command) { + case 'set': + return $this->set($field, $args); + + case 'get': + return $this->get($field); + + case 'add': + return $this->add($field, $args); + + default: + throw new \BadMethodCallException("There is no method ".$method." on ".$this->cm->getClassName()); + } + } +} diff --git a/lib/Doctrine/ORM/Persisters/Collection/AbstractCollectionPersister.php b/lib/Doctrine/ORM/Persisters/Collection/AbstractCollectionPersister.php index 2e85b67f3b2..d2967a2036d 100644 --- a/lib/Doctrine/ORM/Persisters/Collection/AbstractCollectionPersister.php +++ b/lib/Doctrine/ORM/Persisters/Collection/AbstractCollectionPersister.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Persisters\Collection; @@ -52,13 +37,6 @@ abstract class AbstractCollectionPersister implements CollectionPersister */ protected $platform; - /** - * The quote strategy. - * - * @var \Doctrine\ORM\Mapping\QuoteStrategy - */ - protected $quoteStrategy; - /** * Initializes a new instance of a class derived from AbstractCollectionPersister. * @@ -66,11 +44,10 @@ abstract class AbstractCollectionPersister implements CollectionPersister */ public function __construct(EntityManagerInterface $em) { - $this->em = $em; - $this->uow = $em->getUnitOfWork(); - $this->conn = $em->getConnection(); - $this->platform = $this->conn->getDatabasePlatform(); - $this->quoteStrategy = $em->getConfiguration()->getQuoteStrategy(); + $this->em = $em; + $this->uow = $em->getUnitOfWork(); + $this->conn = $em->getConnection(); + $this->platform = $this->conn->getDatabasePlatform(); } /** diff --git a/lib/Doctrine/ORM/Persisters/Collection/CollectionPersister.php b/lib/Doctrine/ORM/Persisters/Collection/CollectionPersister.php index 36b5706a078..fe23901c0db 100644 --- a/lib/Doctrine/ORM/Persisters/Collection/CollectionPersister.php +++ b/lib/Doctrine/ORM/Persisters/Collection/CollectionPersister.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Persisters\Collection; diff --git a/lib/Doctrine/ORM/Persisters/Collection/ManyToManyPersister.php b/lib/Doctrine/ORM/Persisters/Collection/ManyToManyPersister.php index 176ef37ee07..32fdaaf2903 100644 --- a/lib/Doctrine/ORM/Persisters/Collection/ManyToManyPersister.php +++ b/lib/Doctrine/ORM/Persisters/Collection/ManyToManyPersister.php @@ -1,26 +1,17 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Persisters\Collection; use Doctrine\Common\Collections\Criteria; +use Doctrine\ORM\Mapping\AssociationMetadata; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\FieldMetadata; +use Doctrine\ORM\Mapping\JoinColumnMetadata; +use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; use Doctrine\ORM\Persisters\SqlValueVisitor; use Doctrine\ORM\PersistentCollection; use Doctrine\ORM\Query; @@ -41,20 +32,31 @@ class ManyToManyPersister extends AbstractCollectionPersister */ public function delete(PersistentCollection $collection) { - $mapping = $collection->getMapping(); + $association = $collection->getMapping(); - if ( ! $mapping['isOwningSide']) { + if (! $association->isOwningSide()) { return; // ignore inverse side } - $types = []; - $class = $this->em->getClassMetadata($mapping['sourceEntity']); + $class = $this->em->getClassMetadata($association->getSourceEntity()); + $joinTable = $association->getJoinTable(); + $types = []; + + foreach ($joinTable->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $referencedColumnName = $joinColumn->getReferencedColumnName(); - foreach ($mapping['joinTable']['joinColumns'] as $joinColumn) { - $types[] = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $class, $this->em); + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $class, $this->em)); + } + + $types[] = $joinColumn->getType(); } - $this->conn->executeUpdate($this->getDeleteSQL($collection), $this->getDeleteSQLParameters($collection), $types); + $sql = $this->getDeleteSQL($collection); + $params = $this->getDeleteSQLParameters($collection); + + $this->conn->executeUpdate($sql, $params, $types); } /** @@ -62,9 +64,9 @@ public function delete(PersistentCollection $collection) */ public function update(PersistentCollection $collection) { - $mapping = $collection->getMapping(); + $association = $collection->getMapping(); - if ( ! $mapping['isOwningSide']) { + if (! $association->isOwningSide()) { return; // ignore inverse side } @@ -93,18 +95,24 @@ public function update(PersistentCollection $collection) */ public function get(PersistentCollection $collection, $index) { - $mapping = $collection->getMapping(); + $association = $collection->getMapping(); - if ( ! isset($mapping['indexBy'])) { + if (! ($association instanceof ToManyAssociationMetadata && $association->getIndexedBy())) { throw new \BadMethodCallException("Selecting a collection by index is only supported on indexed collections."); } - $persister = $this->uow->getEntityPersister($mapping['targetEntity']); - $mappedKey = $mapping['isOwningSide'] - ? $mapping['inversedBy'] - : $mapping['mappedBy']; + $persister = $this->uow->getEntityPersister($association->getTargetEntity()); + $mappedKey = $association->isOwningSide() + ? $association->getInversedBy() + : $association->getMappedBy() + ; + + $criteria = [ + $mappedKey => $collection->getOwner(), + $association->getIndexedBy() => $index, + ]; - return $persister->load([$mappedKey => $collection->getOwner(), $mapping['indexBy'] => $index], null, $mapping, [], 0, 1); + return $persister->load($criteria, null, $association, [], 0, 1); } /** @@ -112,31 +120,40 @@ public function get(PersistentCollection $collection, $index) */ public function count(PersistentCollection $collection) { - $conditions = []; - $params = []; - $types = []; - $mapping = $collection->getMapping(); - $id = $this->uow->getEntityIdentifier($collection->getOwner()); - $sourceClass = $this->em->getClassMetadata($mapping['sourceEntity']); - $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); - $association = ( ! $mapping['isOwningSide']) - ? $targetClass->associationMappings[$mapping['mappedBy']] - : $mapping; - - $joinTableName = $this->quoteStrategy->getJoinTableName($association, $sourceClass, $this->platform); - $joinColumns = ( ! $mapping['isOwningSide']) - ? $association['joinTable']['inverseJoinColumns'] - : $association['joinTable']['joinColumns']; + $conditions = []; + $params = []; + $types = []; + $association = $collection->getMapping(); + $identifier = $this->uow->getEntityIdentifier($collection->getOwner()); + $sourceClass = $this->em->getClassMetadata($association->getSourceEntity()); + $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); + $owningAssociation = ! $association->isOwningSide() + ? $targetClass->getProperty($association->getMappedBy()) + : $association + ; + + $joinTable = $owningAssociation->getJoinTable(); + $joinTableName = $joinTable->getQuotedQualifiedName($this->platform); + $joinColumns = $association->isOwningSide() + ? $joinTable->getJoinColumns() + : $joinTable->getInverseJoinColumns() + ; foreach ($joinColumns as $joinColumn) { - $columnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $sourceClass, $this->platform); - $referencedName = $joinColumn['referencedColumnName']; - $conditions[] = 't.' . $columnName . ' = ?'; - $params[] = $id[$sourceClass->getFieldForColumn($referencedName)]; - $types[] = PersisterHelper::getTypeOfColumn($referencedName, $sourceClass, $this->em); + /** @var JoinColumnMetadata $joinColumn */ + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $sourceClass, $this->em)); + } + + $conditions[] = sprintf('t.%s = ?', $quotedColumnName); + $params[] = $identifier[$sourceClass->fieldNames[$referencedColumnName]]; + $types[] = $joinColumn->getType(); } - list($joinTargetEntitySQL, $filterSql) = $this->getFilterSql($mapping); + list($joinTargetEntitySQL, $filterSql) = $this->getFilterSql($association); if ($filterSql) { $conditions[] = $filterSql; @@ -147,12 +164,12 @@ public function count(PersistentCollection $collection) // /*if ($criteria && ($expression = $criteria->getWhereExpression()) !== null) { // A join is needed on the target entity - $targetTableName = $this->quoteStrategy->getTableName($targetClass, $this->platform); + $targetTableName = $targetClass->table->getQuotedQualifiedName($this->platform); $targetJoinSql = ' JOIN ' . $targetTableName . ' te' . ' ON' . implode(' AND ', $this->getOnConditionSQL($association)); // And criteria conditions needs to be added - $persister = $this->uow->getEntityPersister($targetClass->name); + $persister = $this->uow->getEntityPersister($targetClass->getClassName()); $visitor = new SqlExpressionVisitor($persister, $targetClass); $conditions[] = $visitor->dispatch($expression); @@ -172,19 +189,19 @@ public function count(PersistentCollection $collection) */ public function slice(PersistentCollection $collection, $offset, $length = null) { - $mapping = $collection->getMapping(); - $persister = $this->uow->getEntityPersister($mapping['targetEntity']); + $association = $collection->getMapping(); + $persister = $this->uow->getEntityPersister($association->getTargetEntity()); - return $persister->getManyToManyCollection($mapping, $collection->getOwner(), $offset, $length); + return $persister->getManyToManyCollection($association, $collection->getOwner(), $offset, $length); } /** * {@inheritdoc} */ public function containsKey(PersistentCollection $collection, $key) { - $mapping = $collection->getMapping(); + $association = $collection->getMapping(); - if ( ! isset($mapping['indexBy'])) { + if (! ($association instanceof ToManyAssociationMetadata && $association->getIndexedBy())) { throw new \BadMethodCallException("Selecting a collection by index is only supported on indexed collections."); } @@ -232,61 +249,66 @@ public function removeElement(PersistentCollection $collection, $element) */ public function loadCriteria(PersistentCollection $collection, Criteria $criteria) { - $mapping = $collection->getMapping(); + $association = $collection->getMapping(); $owner = $collection->getOwner(); $ownerMetadata = $this->em->getClassMetadata(get_class($owner)); - $id = $this->uow->getEntityIdentifier($owner); - $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); - $onConditions = $this->getOnConditionSQL($mapping); - $whereClauses = $params = []; - - if ( ! $mapping['isOwningSide']) { - $associationSourceClass = $targetClass; - $mapping = $targetClass->associationMappings[$mapping['mappedBy']]; - $sourceRelationMode = 'relationToTargetKeyColumns'; + $identifier = $this->uow->getEntityIdentifier($owner); + $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); + $onConditions = $this->getOnConditionSQL($association); + $whereClauses = $params = $types = []; + + if (! $association->isOwningSide()) { + $association = $targetClass->getProperty($association->getMappedBy()); + $joinColumns = $association->getJoinTable()->getInverseJoinColumns(); } else { - $associationSourceClass = $ownerMetadata; - $sourceRelationMode = 'relationToSourceKeyColumns'; + $joinColumns = $association->getJoinTable()->getJoinColumns(); } - foreach ($mapping[$sourceRelationMode] as $key => $value) { - $whereClauses[] = sprintf('t.%s = ?', $key); - $params[] = $ownerMetadata->containsForeignIdentifier - ? $id[$ownerMetadata->getFieldForColumn($value)] - : $id[$ownerMetadata->fieldNames[$value]]; + foreach ($joinColumns as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $ownerMetadata, $this->em)); + } + + $whereClauses[] = sprintf('t.%s = ?', $quotedColumnName); + $params[] = $identifier[$ownerMetadata->fieldNames[$referencedColumnName]]; + $types[] = $joinColumn->getType(); } $parameters = $this->expandCriteriaParameters($criteria); foreach ($parameters as $parameter) { list($name, $value) = $parameter; - $field = $this->quoteStrategy->getColumnName($name, $targetClass, $this->platform); - $whereClauses[] = sprintf('te.%s = ?', $field); - $params[] = $value; + + $property = $targetClass->getProperty($name); + $columnName = $this->platform->quoteIdentifier($property->getColumnName()); + + $whereClauses[] = sprintf('te.%s = ?', $columnName); + $params[] = $value; + $types[] = $property->getType(); } - $tableName = $this->quoteStrategy->getTableName($targetClass, $this->platform); - $joinTable = $this->quoteStrategy->getJoinTableName($mapping, $associationSourceClass, $this->platform); + $tableName = $targetClass->table->getQuotedQualifiedName($this->platform); + $joinTableName = $association->getJoinTable()->getQuotedQualifiedName($this->platform); + $resultSetMapping = new Query\ResultSetMappingBuilder($this->em); - $rsm = new Query\ResultSetMappingBuilder($this->em); - $rsm->addRootEntityFromClassMetadata($targetClass->name, 'te'); + $resultSetMapping->addRootEntityFromClassMetadata($targetClass->getClassName(), 'te'); - $sql = 'SELECT ' . $rsm->generateSelectClause() + $sql = 'SELECT ' . $resultSetMapping->generateSelectClause() . ' FROM ' . $tableName . ' te' - . ' JOIN ' . $joinTable . ' t ON' + . ' JOIN ' . $joinTableName . ' t ON' . implode(' AND ', $onConditions) . ' WHERE ' . implode(' AND ', $whereClauses); $sql .= $this->getOrderingSql($criteria, $targetClass); - $sql .= $this->getLimitSql($criteria); - $stmt = $this->conn->executeQuery($sql, $params); + $stmt = $this->conn->executeQuery($sql, $params, $types); - return $this - ->em - ->newHydrator(Query::HYDRATE_OBJECT) - ->hydrateAll($stmt, $rsm); + return $this->em->newHydrator(Query::HYDRATE_OBJECT)->hydrateAll($stmt, $resultSetMapping); } /** @@ -298,16 +320,16 @@ public function loadCriteria(PersistentCollection $collection, Criteria $criteri * have to join in the actual entities table leading to additional * JOIN. * - * @param array $mapping Array containing mapping information. + * @param ManyToManyAssociationMetadata $association * * @return string[] ordered tuple: * - JOIN condition to add to the SQL * - WHERE condition to add to the SQL */ - public function getFilterSql($mapping) + public function getFilterSql(ManyToManyAssociationMetadata $association) { - $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); - $rootClass = $this->em->getClassMetadata($targetClass->rootEntityName); + $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); + $rootClass = $this->em->getClassMetadata($targetClass->getRootClassName()); $filterSql = $this->generateFilterConditionSQL($rootClass, 'te'); if ('' === $filterSql) { @@ -315,9 +337,9 @@ public function getFilterSql($mapping) } // A join is needed if there is filtering on the target entity - $tableName = $this->quoteStrategy->getTableName($rootClass, $this->platform); + $tableName = $rootClass->table->getQuotedQualifiedName($this->platform); $joinSql = ' JOIN ' . $tableName . ' te' - . ' ON' . implode(' AND ', $this->getOnConditionSQL($mapping)); + . ' ON' . implode(' AND ', $this->getOnConditionSQL($association)); return [$joinSql, $filterSql]; } @@ -340,36 +362,45 @@ protected function generateFilterConditionSQL(ClassMetadata $targetEntity, $targ } } - return $filterClauses - ? '(' . implode(' AND ', $filterClauses) . ')' - : ''; + if (! $filterClauses) { + return ''; + } + + $filterSql = implode(' AND ', $filterClauses); + + return isset($filterClauses[1]) + ? '(' . $filterSql . ')' + : $filterSql + ; } /** * Generate ON condition * - * @param array $mapping + * @param ManyToManyAssociationMetadata $association * * @return array */ - protected function getOnConditionSQL($mapping) + protected function getOnConditionSQL(ManyToManyAssociationMetadata $association) { - $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); - $association = ( ! $mapping['isOwningSide']) - ? $targetClass->associationMappings[$mapping['mappedBy']] - : $mapping; + $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); + $owningAssociation = ! $association->isOwningSide() + ? $targetClass->getProperty($association->getMappedBy()) + : $association; - $joinColumns = $mapping['isOwningSide'] - ? $association['joinTable']['inverseJoinColumns'] - : $association['joinTable']['joinColumns']; + $joinTable = $owningAssociation->getJoinTable(); + $joinColumns = $association->isOwningSide() + ? $joinTable->getInverseJoinColumns() + : $joinTable->getJoinColumns() + ; $conditions = []; foreach ($joinColumns as $joinColumn) { - $joinColumnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform); - $refColumnName = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $targetClass, $this->platform); + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName()); - $conditions[] = ' t.' . $joinColumnName . ' = ' . 'te.' . $refColumnName; + $conditions[] = ' t.' . $quotedColumnName . ' = ' . 'te.' . $quotedReferencedColumnName; } return $conditions; @@ -382,17 +413,16 @@ protected function getOnConditionSQL($mapping) */ protected function getDeleteSQL(PersistentCollection $collection) { - $columns = []; - $mapping = $collection->getMapping(); - $class = $this->em->getClassMetadata(get_class($collection->getOwner())); - $joinTable = $this->quoteStrategy->getJoinTableName($mapping, $class, $this->platform); + $association = $collection->getMapping(); + $joinTable = $association->getJoinTable(); + $joinTableName = $joinTable->getQuotedQualifiedName($this->platform); + $columns = []; - foreach ($mapping['joinTable']['joinColumns'] as $joinColumn) { - $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); + foreach ($joinTable->getJoinColumns() as $joinColumn) { + $columns[] = $this->platform->quoteIdentifier($joinColumn->getColumnName()); } - return 'DELETE FROM ' . $joinTable - . ' WHERE ' . implode(' = ? AND ', $columns) . ' = ?'; + return 'DELETE FROM ' . $joinTableName . ' WHERE ' . implode(' = ? AND ', $columns) . ' = ?'; } /** @@ -403,22 +433,22 @@ protected function getDeleteSQL(PersistentCollection $collection) */ protected function getDeleteSQLParameters(PersistentCollection $collection) { - $mapping = $collection->getMapping(); - $identifier = $this->uow->getEntityIdentifier($collection->getOwner()); + $association = $collection->getMapping(); + $identifier = $this->uow->getEntityIdentifier($collection->getOwner()); + $joinTable = $association->getJoinTable(); + $joinColumns = $joinTable->getJoinColumns(); // Optimization for single column identifier - if (count($mapping['relationToSourceKeyColumns']) === 1) { + if (count($joinColumns) === 1) { return [reset($identifier)]; } // Composite identifier - $sourceClass = $this->em->getClassMetadata($mapping['sourceEntity']); + $sourceClass = $this->em->getClassMetadata($association->getSourceEntity()); $params = []; - foreach ($mapping['relationToSourceKeyColumns'] as $columnName => $refColumnName) { - $params[] = isset($sourceClass->fieldNames[$refColumnName]) - ? $identifier[$sourceClass->fieldNames[$refColumnName]] - : $identifier[$sourceClass->getFieldForColumn($columnName)]; + foreach ($joinColumns as $joinColumn) { + $params[] = $identifier[$sourceClass->fieldNames[$joinColumn->getReferencedColumnName()]]; } return $params; @@ -434,25 +464,43 @@ protected function getDeleteSQLParameters(PersistentCollection $collection) */ protected function getDeleteRowSQL(PersistentCollection $collection) { - $mapping = $collection->getMapping(); - $class = $this->em->getClassMetadata($mapping['sourceEntity']); - $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); + $association = $collection->getMapping(); + $class = $this->em->getClassMetadata($association->getSourceEntity()); + $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); $columns = []; $types = []; - foreach ($mapping['joinTable']['joinColumns'] as $joinColumn) { - $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); - $types[] = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $class, $this->em); + $joinTable = $association->getJoinTable(); + $joinTableName = $joinTable->getQuotedQualifiedName($this->platform); + + foreach ($joinTable->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $class, $this->em)); + } + + $columns[] = $quotedColumnName; + $types[] = $joinColumn->getType(); } - foreach ($mapping['joinTable']['inverseJoinColumns'] as $joinColumn) { - $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform); - $types[] = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); + foreach ($joinTable->getInverseJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); + } + + $columns[] = $quotedColumnName; + $types[] = $joinColumn->getType(); } return [ - 'DELETE FROM ' . $this->quoteStrategy->getJoinTableName($mapping, $class, $this->platform) - . ' WHERE ' . implode(' = ? AND ', $columns) . ' = ?', + sprintf('DELETE FROM %s WHERE %s = ?', $joinTableName, implode(' = ? AND ', $columns)), $types, ]; } @@ -483,27 +531,46 @@ protected function getDeleteRowSQLParameters(PersistentCollection $collection, $ */ protected function getInsertRowSQL(PersistentCollection $collection) { + $association = $collection->getMapping(); + $class = $this->em->getClassMetadata($association->getSourceEntity()); + $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); $columns = []; $types = []; - $mapping = $collection->getMapping(); - $class = $this->em->getClassMetadata($mapping['sourceEntity']); - $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); - foreach ($mapping['joinTable']['joinColumns'] as $joinColumn) { - $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform); - $types[] = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $class, $this->em); + $joinTable = $association->getJoinTable(); + $joinTableName = $joinTable->getQuotedQualifiedName($this->platform); + + foreach ($joinTable->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $class, $this->em)); + } + + $columns[] = $quotedColumnName; + $types[] = $joinColumn->getType(); } - foreach ($mapping['joinTable']['inverseJoinColumns'] as $joinColumn) { - $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform); - $types[] = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); + foreach ($joinTable->getInverseJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); + } + + $columns[] = $quotedColumnName; + $types[] = $joinColumn->getType(); } + $columnNamesAsString = implode(', ', $columns); + $columnValuesAsString = implode(', ', array_fill(0, count($columns), '?')); + return [ - 'INSERT INTO ' . $this->quoteStrategy->getJoinTableName($mapping, $class, $this->platform) - . ' (' . implode(', ', $columns) . ')' - . ' VALUES' - . ' (' . implode(', ', array_fill(0, count($columns), '?')) . ')', + sprintf('INSERT INTO %s (%s) VALUES (%s)', $joinTableName, $columnNamesAsString, $columnValuesAsString), $types, ]; } @@ -526,7 +593,7 @@ protected function getInsertRowSQLParameters(PersistentCollection $collection, $ /** * Collects the parameters for inserting/deleting on the join table in the order - * of the join table columns as specified in ManyToManyMapping#joinTableColumns. + * of the join table columns. * * @param \Doctrine\ORM\PersistentCollection $collection * @param object $element @@ -535,35 +602,24 @@ protected function getInsertRowSQLParameters(PersistentCollection $collection, $ */ private function collectJoinTableColumnParameters(PersistentCollection $collection, $element) { - $params = []; - $mapping = $collection->getMapping(); - $isComposite = count($mapping['joinTableColumns']) > 2; + $params = []; + $association = $collection->getMapping(); + $owningClass = $this->em->getClassMetadata(get_class($collection->getOwner())); + $targetClass = $collection->getTypeClass(); + $owningIdentifier = $this->uow->getEntityIdentifier($collection->getOwner()); + $targetIdentifier = $this->uow->getEntityIdentifier($element); + $joinTable = $association->getJoinTable(); - $identifier1 = $this->uow->getEntityIdentifier($collection->getOwner()); - $identifier2 = $this->uow->getEntityIdentifier($element); + foreach ($joinTable->getJoinColumns() as $joinColumn) { + $fieldName = $owningClass->fieldNames[$joinColumn->getReferencedColumnName()]; - $class1 = $class2 = null; - if ($isComposite) { - $class1 = $this->em->getClassMetadata(get_class($collection->getOwner())); - $class2 = $collection->getTypeClass(); + $params[] = $owningIdentifier[$fieldName]; } - foreach ($mapping['joinTableColumns'] as $joinTableColumn) { - $isRelationToSource = isset($mapping['relationToSourceKeyColumns'][$joinTableColumn]); - - if ( ! $isComposite) { - $params[] = $isRelationToSource ? array_pop($identifier1) : array_pop($identifier2); + foreach ($joinTable->getInverseJoinColumns() as $joinColumn) { + $fieldName = $targetClass->fieldNames[$joinColumn->getReferencedColumnName()]; - continue; - } - - if ($isRelationToSource) { - $params[] = $identifier1[$class1->getFieldForColumn($mapping['relationToSourceKeyColumns'][$joinTableColumn])]; - - continue; - } - - $params[] = $identifier2[$class2->getFieldForColumn($mapping['relationToTargetKeyColumns'][$joinTableColumn])]; + $params[] = $targetIdentifier[$fieldName]; } return $params; @@ -582,68 +638,93 @@ private function collectJoinTableColumnParameters(PersistentCollection $collecti */ private function getJoinTableRestrictionsWithKey(PersistentCollection $collection, $key, $addFilters) { - $filterMapping = $collection->getMapping(); - $mapping = $filterMapping; - $indexBy = $mapping['indexBy']; - $id = $this->uow->getEntityIdentifier($collection->getOwner()); - $sourceClass = $this->em->getClassMetadata($mapping['sourceEntity']); - $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); - - if (! $mapping['isOwningSide']) { - $associationSourceClass = $this->em->getClassMetadata($mapping['targetEntity']); - $mapping = $associationSourceClass->associationMappings[$mapping['mappedBy']]; - $joinColumns = $mapping['joinTable']['joinColumns']; - $sourceRelationMode = 'relationToTargetKeyColumns'; - $targetRelationMode = 'relationToSourceKeyColumns'; + $association = $collection->getMapping(); + $owningAssociation = $association; + $indexBy = $owningAssociation->getIndexedBy(); + $identifier = $this->uow->getEntityIdentifier($collection->getOwner()); + $sourceClass = $this->em->getClassMetadata($owningAssociation->getSourceEntity()); + $targetClass = $this->em->getClassMetadata($owningAssociation->getTargetEntity()); + + if (! $owningAssociation->isOwningSide()) { + $owningAssociation = $targetClass->getProperty($owningAssociation->getMappedBy()); + $joinTable = $owningAssociation->getJoinTable(); + $joinColumns = $joinTable->getJoinColumns(); + $inverseJoinColumns = $joinTable->getInverseJoinColumns(); } else { - $associationSourceClass = $this->em->getClassMetadata($mapping['sourceEntity']); - $joinColumns = $mapping['joinTable']['inverseJoinColumns']; - $sourceRelationMode = 'relationToSourceKeyColumns'; - $targetRelationMode = 'relationToTargetKeyColumns'; + $joinTable = $owningAssociation->getJoinTable(); + $joinColumns = $joinTable->getInverseJoinColumns(); + $inverseJoinColumns = $joinTable->getJoinColumns(); } - $quotedJoinTable = $this->quoteStrategy->getJoinTableName($mapping, $associationSourceClass, $this->platform). ' t'; + $joinTableName = $joinTable->getQuotedQualifiedName($this->platform); + $quotedJoinTable = $joinTableName . ' t'; $whereClauses = []; $params = []; $types = []; - - $joinNeeded = ! in_array($indexBy, $targetClass->identifier); + $joinNeeded = ! in_array($indexBy, $targetClass->identifier); if ($joinNeeded) { // extra join needed if indexBy is not a @id $joinConditions = []; - foreach ($joinColumns as $joinTableColumn) { - $joinConditions[] = 't.' . $joinTableColumn['name'] . ' = tr.' . $joinTableColumn['referencedColumnName']; + foreach ($joinColumns as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName()); + + $joinConditions[] = ' t.' . $quotedColumnName . ' = ' . 'tr.' . $quotedReferencedColumnName; } - $tableName = $this->quoteStrategy->getTableName($targetClass, $this->platform); + $tableName = $targetClass->table->getQuotedQualifiedName($this->platform); $quotedJoinTable .= ' JOIN ' . $tableName . ' tr ON ' . implode(' AND ', $joinConditions); - $columnName = $targetClass->getColumnName($indexBy); + $indexByProperty = $targetClass->getProperty($indexBy); + + switch (true) { + case ($indexByProperty instanceof FieldMetadata): + $quotedColumnName = $this->platform->quoteIdentifier($indexByProperty->getColumnName()); - $whereClauses[] = 'tr.' . $columnName . ' = ?'; - $params[] = $key; - $types[] = PersisterHelper::getTypeOfColumn($columnName, $targetClass, $this->em); + $whereClauses[] = sprintf('tr.%s = ?', $quotedColumnName); + $params[] = $key; + $types[] = $indexByProperty->getType(); + break; + + case ($indexByProperty instanceof ToOneAssociationMetadata && $indexByProperty->isOwningSide()): + // Cannot be supported because PHP does not accept objects as keys. =( + break; + } + } + + foreach ($inverseJoinColumns as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $sourceClass, $this->em)); + } + + $whereClauses[] = sprintf('t.%s = ?', $quotedColumnName); + $params[] = $identifier[$sourceClass->fieldNames[$joinColumn->getReferencedColumnName()]]; + $types[] = $joinColumn->getType(); } - foreach ($mapping['joinTableColumns'] as $joinTableColumn) { - if (isset($mapping[$sourceRelationMode][$joinTableColumn])) { - $column = $mapping[$sourceRelationMode][$joinTableColumn]; - $whereClauses[] = 't.' . $joinTableColumn . ' = ?'; - $params[] = $sourceClass->containsForeignIdentifier - ? $id[$sourceClass->getFieldForColumn($column)] - : $id[$sourceClass->fieldNames[$column]]; - $types[] = PersisterHelper::getTypeOfColumn($column, $sourceClass, $this->em); - } elseif ( ! $joinNeeded) { - $column = $mapping[$targetRelationMode][$joinTableColumn]; + if (! $joinNeeded) { + foreach ($joinColumns as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); + } - $whereClauses[] = 't.' . $joinTableColumn . ' = ?'; + $whereClauses[] = sprintf('t.%s = ?', $quotedColumnName); $params[] = $key; - $types[] = PersisterHelper::getTypeOfColumn($column, $targetClass, $this->em); + $types[] = $joinColumn->getType(); } } if ($addFilters) { - list($joinTargetEntitySQL, $filterSql) = $this->getFilterSql($filterMapping); + list($joinTargetEntitySQL, $filterSql) = $this->getFilterSql($association); if ($filterSql) { $quotedJoinTable .= ' ' . $joinTargetEntitySQL; @@ -667,49 +748,62 @@ private function getJoinTableRestrictionsWithKey(PersistentCollection $collectio */ private function getJoinTableRestrictions(PersistentCollection $collection, $element, $addFilters) { - $filterMapping = $collection->getMapping(); - $mapping = $filterMapping; + $association = $collection->getMapping(); + $owningAssociation = $association; - if ( ! $mapping['isOwningSide']) { - $sourceClass = $this->em->getClassMetadata($mapping['targetEntity']); - $targetClass = $this->em->getClassMetadata($mapping['sourceEntity']); - $sourceId = $this->uow->getEntityIdentifier($element); - $targetId = $this->uow->getEntityIdentifier($collection->getOwner()); + if (! $association->isOwningSide()) { + $sourceClass = $this->em->getClassMetadata($association->getTargetEntity()); + $targetClass = $this->em->getClassMetadata($association->getSourceEntity()); + $sourceIdentifier = $this->uow->getEntityIdentifier($element); + $targetIdentifier = $this->uow->getEntityIdentifier($collection->getOwner()); - $mapping = $sourceClass->associationMappings[$mapping['mappedBy']]; + $owningAssociation = $sourceClass->getProperty($association->getMappedBy()); } else { - $sourceClass = $this->em->getClassMetadata($mapping['sourceEntity']); - $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); - $sourceId = $this->uow->getEntityIdentifier($collection->getOwner()); - $targetId = $this->uow->getEntityIdentifier($element); + $sourceClass = $this->em->getClassMetadata($association->getSourceEntity()); + $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); + $sourceIdentifier = $this->uow->getEntityIdentifier($collection->getOwner()); + $targetIdentifier = $this->uow->getEntityIdentifier($element); } - $quotedJoinTable = $this->quoteStrategy->getJoinTableName($mapping, $sourceClass, $this->platform); + $joinTable = $owningAssociation->getJoinTable(); + $joinTableName = $joinTable->getQuotedQualifiedName($this->platform); + $quotedJoinTable = $joinTableName; $whereClauses = []; $params = []; $types = []; - foreach ($mapping['joinTableColumns'] as $joinTableColumn) { - $whereClauses[] = ($addFilters ? 't.' : '') . $joinTableColumn . ' = ?'; + foreach ($joinTable->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $referencedColumnName = $joinColumn->getReferencedColumnName(); - if (isset($mapping['relationToTargetKeyColumns'][$joinTableColumn])) { - $targetColumn = $mapping['relationToTargetKeyColumns'][$joinTableColumn]; - $params[] = $targetId[$targetClass->getFieldForColumn($targetColumn)]; - $types[] = PersisterHelper::getTypeOfColumn($targetColumn, $targetClass, $this->em); + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $sourceClass, $this->em)); + } + + $whereClauses[] = ($addFilters ? 't.' : '') . $quotedColumnName . ' = ?'; + $params[] = $sourceIdentifier[$sourceClass->fieldNames[$referencedColumnName]]; + $types[] = $joinColumn->getType(); + } + + foreach ($joinTable->getInverseJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $referencedColumnName = $joinColumn->getReferencedColumnName(); - continue; + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); } - // relationToSourceKeyColumns - $targetColumn = $mapping['relationToSourceKeyColumns'][$joinTableColumn]; - $params[] = $sourceId[$sourceClass->getFieldForColumn($targetColumn)]; - $types[] = PersisterHelper::getTypeOfColumn($targetColumn, $sourceClass, $this->em); + $whereClauses[] = ($addFilters ? 't.' : '') . $quotedColumnName . ' = ?'; + $params[] = $targetIdentifier[$targetClass->fieldNames[$referencedColumnName]]; + $types[] = $joinColumn->getType(); } if ($addFilters) { $quotedJoinTable .= ' t'; - list($joinTargetEntitySQL, $filterSql) = $this->getFilterSql($filterMapping); + list($joinTargetEntitySQL, $filterSql) = $this->getFilterSql($association); if ($filterSql) { $quotedJoinTable .= ' ' . $joinTargetEntitySQL; @@ -753,15 +847,15 @@ private function expandCriteriaParameters(Criteria $criteria) private function getOrderingSql(Criteria $criteria, ClassMetadata $targetClass) { $orderings = $criteria->getOrderings(); + if ($orderings) { $orderBy = []; + foreach ($orderings as $name => $direction) { - $field = $this->quoteStrategy->getColumnName( - $name, - $targetClass, - $this->platform - ); - $orderBy[] = $field . ' ' . $direction; + $property = $targetClass->getProperty($name); + $columnName = $this->platform->quoteIdentifier($property->getColumnName()); + + $orderBy[] = $columnName . ' ' . $direction; } return ' ORDER BY ' . implode(', ', $orderBy); diff --git a/lib/Doctrine/ORM/Persisters/Collection/OneToManyPersister.php b/lib/Doctrine/ORM/Persisters/Collection/OneToManyPersister.php index 82115071f35..14b275f1df8 100644 --- a/lib/Doctrine/ORM/Persisters/Collection/OneToManyPersister.php +++ b/lib/Doctrine/ORM/Persisters/Collection/OneToManyPersister.php @@ -1,28 +1,14 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Persisters\Collection; use Doctrine\Common\Collections\Criteria; -use Doctrine\DBAL\Types\Type; +use Doctrine\ORM\Mapping\ColumnMetadata; +use Doctrine\ORM\Mapping\InheritanceType; +use Doctrine\ORM\Mapping\ToManyAssociationMetadata; use Doctrine\ORM\PersistentCollection; -use Doctrine\ORM\Utility\PersisterHelper; /** * Persister for one-to-many collections. @@ -42,18 +28,18 @@ public function delete(PersistentCollection $collection) // The only valid case here is when you have weak entities. In this // scenario, you have @OneToMany with orphanRemoval=true, and replacing // the entire collection with a new would trigger this operation. - $mapping = $collection->getMapping(); + $association = $collection->getMapping(); - if ( ! $mapping['orphanRemoval']) { + if (! $association->isOrphanRemoval()) { // Handling non-orphan removal should never happen, as @OneToMany // can only be inverse side. For owning side one to many, it is // required to have a join table, which would classify as a ManyToManyPersister. return; } - $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); + $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); - return $targetClass->isInheritanceTypeJoined() + return $targetClass->inheritanceType === InheritanceType::JOINED ? $this->deleteJoinedEntityCollection($collection) : $this->deleteEntityCollection($collection); } @@ -74,25 +60,19 @@ public function update(PersistentCollection $collection) */ public function get(PersistentCollection $collection, $index) { - $mapping = $collection->getMapping(); + $association = $collection->getMapping(); - if ( ! isset($mapping['indexBy'])) { + if (! ($association instanceof ToManyAssociationMetadata && $association->getIndexedBy())) { throw new \BadMethodCallException("Selecting a collection by index is only supported on indexed collections."); } - $persister = $this->uow->getEntityPersister($mapping['targetEntity']); - - return $persister->load( - [ - $mapping['mappedBy'] => $collection->getOwner(), - $mapping['indexBy'] => $index - ], - null, - $mapping, - [], - null, - 1 - ); + $persister = $this->uow->getEntityPersister($association->getTargetEntity()); + $criteria = [ + $association->getMappedBy() => $collection->getOwner(), + $association->getIndexedBy() => $index, + ]; + + return $persister->load($criteria, null, $association, [], null, 1); } /** @@ -100,13 +80,15 @@ public function get(PersistentCollection $collection, $index) */ public function count(PersistentCollection $collection) { - $mapping = $collection->getMapping(); - $persister = $this->uow->getEntityPersister($mapping['targetEntity']); + $association = $collection->getMapping(); + $persister = $this->uow->getEntityPersister($association->getTargetEntity()); // only works with single id identifier entities. Will throw an // exception in Entity Persisters if that is not the case for the // 'mappedBy' field. - $criteria = new Criteria(Criteria::expr()->eq($mapping['mappedBy'], $collection->getOwner())); + $criteria = [ + $association->getMappedBy() => $collection->getOwner(), + ]; return $persister->count($criteria); } @@ -116,10 +98,10 @@ public function count(PersistentCollection $collection) */ public function slice(PersistentCollection $collection, $offset, $length = null) { - $mapping = $collection->getMapping(); - $persister = $this->uow->getEntityPersister($mapping['targetEntity']); + $association = $collection->getMapping(); + $persister = $this->uow->getEntityPersister($association->getTargetEntity()); - return $persister->getOneToManyCollection($mapping, $collection->getOwner(), $offset, $length); + return $persister->getOneToManyCollection($association, $collection->getOwner(), $offset, $length); } /** @@ -127,21 +109,21 @@ public function slice(PersistentCollection $collection, $offset, $length = null) */ public function containsKey(PersistentCollection $collection, $key) { - $mapping = $collection->getMapping(); + $association = $collection->getMapping(); - if ( ! isset($mapping['indexBy'])) { + if (! ($association instanceof ToManyAssociationMetadata && $association->getIndexedBy())) { throw new \BadMethodCallException("Selecting a collection by index is only supported on indexed collections."); } - $persister = $this->uow->getEntityPersister($mapping['targetEntity']); + $persister = $this->uow->getEntityPersister($association->getTargetEntity()); // only works with single id identifier entities. Will throw an // exception in Entity Persisters if that is not the case for the // 'mappedBy' field. - $criteria = new Criteria(); - - $criteria->andWhere(Criteria::expr()->eq($mapping['mappedBy'], $collection->getOwner())); - $criteria->andWhere(Criteria::expr()->eq($mapping['indexBy'], $key)); + $criteria = [ + $association->getMappedBy() => $collection->getOwner(), + $association->getIndexedBy() => $key, + ]; return (bool) $persister->count($criteria); } @@ -155,13 +137,15 @@ public function contains(PersistentCollection $collection, $element) return false; } - $mapping = $collection->getMapping(); - $persister = $this->uow->getEntityPersister($mapping['targetEntity']); + $association = $collection->getMapping(); + $persister = $this->uow->getEntityPersister($association->getTargetEntity()); // only works with single id identifier entities. Will throw an // exception in Entity Persisters if that is not the case for the // 'mappedBy' field. - $criteria = new Criteria(Criteria::expr()->eq($mapping['mappedBy'], $collection->getOwner())); + $criteria = new Criteria( + Criteria::expr()->eq($association->getMappedBy(), $collection->getOwner()) + ); return $persister->exists($element, $criteria); } @@ -171,21 +155,20 @@ public function contains(PersistentCollection $collection, $element) */ public function removeElement(PersistentCollection $collection, $element) { - $mapping = $collection->getMapping(); + $association = $collection->getMapping(); - if ( ! $mapping['orphanRemoval']) { + if (! $association->isOrphanRemoval()) { // no-op: this is not the owning side, therefore no operations should be applied return false; } - if ( ! $this->isValidEntityState($element)) { + if (! $this->isValidEntityState($element)) { return false; } - return $this - ->uow - ->getEntityPersister($mapping['targetEntity']) - ->delete($element); + $persister = $this->uow->getEntityPersister($association->getTargetEntity()); + + return $persister->delete($element); } /** @@ -205,20 +188,21 @@ public function loadCriteria(PersistentCollection $collection, Criteria $criteri */ private function deleteEntityCollection(PersistentCollection $collection) { - $mapping = $collection->getMapping(); - $identifier = $this->uow->getEntityIdentifier($collection->getOwner()); - $sourceClass = $this->em->getClassMetadata($mapping['sourceEntity']); - $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); - $columns = []; - $parameters = []; - - foreach ($targetClass->associationMappings[$mapping['mappedBy']]['joinColumns'] as $joinColumn) { - $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform); - $parameters[] = $identifier[$sourceClass->getFieldForColumn($joinColumn['referencedColumnName'])]; + $association = $collection->getMapping(); + $identifier = $this->uow->getEntityIdentifier($collection->getOwner()); + $sourceClass = $this->em->getClassMetadata($association->getSourceEntity()); + $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); + $inverseAssoc = $targetClass->getProperty($association->getMappedBy()); + $columns = []; + $parameters = []; + + foreach ($inverseAssoc->getJoinColumns() as $joinColumn) { + $columns[] = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $parameters[] = $identifier[$sourceClass->fieldNames[$joinColumn->getReferencedColumnName()]]; } - $statement = 'DELETE FROM ' . $this->quoteStrategy->getTableName($targetClass, $this->platform) - . ' WHERE ' . implode(' = ? AND ', $columns) . ' = ?'; + $tableName = $targetClass->table->getQuotedQualifiedName($this->platform); + $statement = 'DELETE FROM ' . $tableName . ' WHERE ' . implode(' = ? AND ', $columns) . ' = ?'; return $this->conn->executeUpdate($statement, $parameters); } @@ -237,21 +221,23 @@ private function deleteEntityCollection(PersistentCollection $collection) */ private function deleteJoinedEntityCollection(PersistentCollection $collection) { - $mapping = $collection->getMapping(); - $sourceClass = $this->em->getClassMetadata($mapping['sourceEntity']); - $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); - $rootClass = $this->em->getClassMetadata($targetClass->rootEntityName); + $association = $collection->getMapping(); + $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); + $rootClass = $this->em->getClassMetadata($targetClass->getRootClassName()); + $sourcePersister = $this->uow->getEntityPersister($association->getSourceEntity()); // 1) Build temporary table DDL $tempTable = $this->platform->getTemporaryTableName($rootClass->getTemporaryIdTableName()); - $idColumnNames = $rootClass->getIdentifierColumnNames(); - $idColumnList = implode(', ', $idColumnNames); + $idColumns = $rootClass->getIdentifierColumns($this->em); + $idColumnNameList = implode(', ', array_keys($idColumns)); $columnDefinitions = []; - foreach ($idColumnNames as $idColumnName) { - $columnDefinitions[$idColumnName] = [ + foreach ($idColumns as $columnName => $column) { + $type = $column->getType(); + + $columnDefinitions[$columnName] = [ 'notnull' => true, - 'type' => Type::getType(PersisterHelper::getTypeOfColumn($idColumnName, $rootClass, $this->em)), + 'type' => $type, ]; } @@ -261,27 +247,39 @@ private function deleteJoinedEntityCollection(PersistentCollection $collection) $this->conn->executeUpdate($statement); // 2) Build insert table records into temporary table - $query = $this->em->createQuery( - ' SELECT t0.' . implode(', t0.', $rootClass->getIdentifierFieldNames()) - . ' FROM ' . $targetClass->name . ' t0 WHERE t0.' . $mapping['mappedBy'] . ' = :owner' - )->setParameter('owner', $collection->getOwner()); + $dql = ' SELECT t0.' . implode(', t0.', $rootClass->getIdentifierFieldNames()) + . ' FROM ' . $targetClass->getClassName() . ' t0 WHERE t0.' . $association->getMappedBy() . ' = :owner'; + $query = $this->em->createQuery($dql)->setParameter('owner', $collection->getOwner()); - $statement = 'INSERT INTO ' . $tempTable . ' (' . $idColumnList . ') ' . $query->getSQL(); - $parameters = array_values($sourceClass->getIdentifierValues($collection->getOwner())); + $statement = 'INSERT INTO ' . $tempTable . ' (' . $idColumnNameList . ') ' . $query->getSQL(); + $parameters = array_values($sourcePersister->getIdentifier($collection->getOwner())); $numDeleted = $this->conn->executeUpdate($statement, $parameters); - // 3) Delete records on each table in the hierarchy - $classNames = array_merge($targetClass->parentClasses, [$targetClass->name], $targetClass->subClasses); + // 3) Create statement used in DELETE ... WHERE ... IN (subselect) + $deleteSQLTemplate = sprintf( + 'DELETE FROM %%s WHERE (%s) IN (SELECT %s FROM %s)', + $idColumnNameList, + $idColumnNameList, + $tempTable + ); + + // 4) Delete records on each table in the hierarchy + $hierarchyClasses = array_merge( + array_map( + function ($className) { return $this->em->getClassMetadata($className); }, + array_reverse($targetClass->getSubClasses()) + ), + [$targetClass], + $targetClass->getAncestorsIterator()->getArrayCopy() + ); - foreach (array_reverse($classNames) as $className) { - $tableName = $this->quoteStrategy->getTableName($this->em->getClassMetadata($className), $this->platform); - $statement = 'DELETE FROM ' . $tableName . ' WHERE (' . $idColumnList . ')' - . ' IN (SELECT ' . $idColumnList . ' FROM ' . $tempTable . ')'; + foreach ($hierarchyClasses as $class) { + $statement = sprintf($deleteSQLTemplate, $class->table->getQuotedQualifiedName($this->platform)); $this->conn->executeUpdate($statement); } - // 4) Drop temporary table + // 5) Drop temporary table $statement = $this->platform->getDropTemporaryTableSQL($tempTable); $this->conn->executeUpdate($statement); diff --git a/lib/Doctrine/ORM/Persisters/Entity/AbstractEntityInheritancePersister.php b/lib/Doctrine/ORM/Persisters/Entity/AbstractEntityInheritancePersister.php index 79472b50c0e..0b16a6003c9 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/AbstractEntityInheritancePersister.php +++ b/lib/Doctrine/ORM/Persisters/Entity/AbstractEntityInheritancePersister.php @@ -1,26 +1,12 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Persisters\Entity; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\DBAL\Types\Type; +use Doctrine\ORM\Mapping\JoinColumnMetadata; /** * Base class for entity persisters that implement a certain inheritance mapping strategy. @@ -36,64 +22,43 @@ abstract class AbstractEntityInheritancePersister extends BasicEntityPersister /** * {@inheritdoc} */ - protected function prepareInsertData($entity) + protected function prepareInsertData($entity) : array { $data = parent::prepareInsertData($entity); // Populate the discriminator column $discColumn = $this->class->discriminatorColumn; - $this->columnTypes[$discColumn['name']] = $discColumn['type']; - $data[$this->getDiscriminatorColumnTableName()][$discColumn['name']] = $this->class->discriminatorValue; + $tableName = $discColumn->getTableName(); + $columnName = $discColumn->getColumnName(); - return $data; - } + $this->columns[$columnName] = $discColumn; - /** - * Gets the name of the table that contains the discriminator column. - * - * @return string The table name. - */ - abstract protected function getDiscriminatorColumnTableName(); + $data[$tableName][$columnName] = $this->class->discriminatorValue; - /** - * {@inheritdoc} - */ - protected function getSelectColumnSQL($field, ClassMetadata $class, $alias = 'r') - { - $tableAlias = $alias == 'r' ? '' : $alias; - $fieldMapping = $class->fieldMappings[$field]; - $columnAlias = $this->getSQLColumnAlias($fieldMapping['columnName']); - $sql = sprintf( - '%s.%s', - $this->getSQLTableAlias($class->name, $tableAlias), - $this->quoteStrategy->getColumnName($field, $class, $this->platform) - ); - - $this->currentPersisterContext->rsm->addFieldResult($alias, $columnAlias, $field, $class->name); - - if (isset($fieldMapping['requireSQLConversion'])) { - $type = Type::getType($fieldMapping['type']); - $sql = $type->convertToPHPValueSQL($sql, $this->platform); - } - - return $sql . ' AS ' . $columnAlias; + return $data; } /** - * @param string $tableAlias - * @param string $joinColumnName - * @param string $quotedColumnName - * - * @param string $type + * @param JoinColumnMetadata $joinColumnMetadata * * @return string */ - protected function getSelectJoinColumnSQL($tableAlias, $joinColumnName, $quotedColumnName, $type) + protected function getSelectJoinColumnSQL(JoinColumnMetadata $joinColumnMetadata) { - $columnAlias = $this->getSQLColumnAlias($joinColumnName); + $tableAlias = $this->getSQLTableAlias($joinColumnMetadata->getTableName()); + $columnAlias = $this->getSQLColumnAlias(); + $columnType = $joinColumnMetadata->getType(); + $quotedColumnName = $this->platform->quoteIdentifier($joinColumnMetadata->getColumnName()); + $sql = sprintf('%s.%s', $tableAlias, $quotedColumnName); - $this->currentPersisterContext->rsm->addMetaResult('r', $columnAlias, $joinColumnName, false, $type); + $this->currentPersisterContext->rsm->addMetaResult( + 'r', + $columnAlias, + $joinColumnMetadata->getColumnName(), + $joinColumnMetadata->isPrimaryKey(), + $columnType + ); - return $tableAlias . '.' . $quotedColumnName . ' AS ' . $columnAlias; + return $columnType->convertToPHPValueSQL($sql, $this->platform) . ' AS ' . $columnAlias; } } diff --git a/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php b/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php index 972199c5ea2..5ac34ed96d6 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php +++ b/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Persisters\Entity; @@ -26,8 +11,20 @@ use Doctrine\DBAL\LockMode; use Doctrine\DBAL\Types\Type; use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\AssociationMetadata; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\FetchMode; +use Doctrine\ORM\Mapping\FieldMetadata; +use Doctrine\ORM\Mapping\GeneratorType; +use Doctrine\ORM\Mapping\InheritanceType; +use Doctrine\ORM\Mapping\JoinColumnMetadata; +use Doctrine\ORM\Mapping\LocalColumnMetadata; +use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata; use Doctrine\ORM\Mapping\MappingException; +use Doctrine\ORM\Mapping\OneToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; +use Doctrine\ORM\Mapping\VersionFieldMetadata; use Doctrine\ORM\OptimisticLockException; use Doctrine\ORM\ORMException; use Doctrine\ORM\PersistentCollection; @@ -35,7 +32,6 @@ use Doctrine\ORM\Persisters\SqlValueVisitor; use Doctrine\ORM\Query; use Doctrine\ORM\UnitOfWork; -use Doctrine\ORM\Utility\IdentifierFlattener; use Doctrine\ORM\Utility\PersisterHelper; /** @@ -50,8 +46,7 @@ * The persisting operations that are invoked during a commit of a UnitOfWork to * persist the persistent entity state are: * - * - {@link addInsert} : To schedule an entity for insertion. - * - {@link executeInserts} : To execute all scheduled insertions. + * - {@link insert} : To insert the persistent state of an entity. * - {@link update} : To update the persistent state of an entity. * - {@link delete} : To delete the persistent state of an entity. * @@ -63,7 +58,7 @@ * * - {@link load} : Loads (the state of) a single, managed entity. * - {@link loadAll} : Loads multiple, managed entities. - * - {@link loadOneToOneEntity} : Loads a one/many-to-one entity association (lazy-loading). + * - {@link loadToOneEntity} : Loads a one/many-to-one entity association (lazy-loading). * - {@link loadOneToManyCollection} : Loads a one-to-many entity association (lazy-loading). * - {@link loadManyToManyCollection} : Loads a many-to-many entity association (lazy-loading). * @@ -73,6 +68,7 @@ * Subclasses can be created to provide custom persisting and querying strategies, * i.e. spanning multiple tables. * + * @author Guilherme Blanco * @author Roman Borschel * @author Giorgio Sironi * @author Benjamin Eberlei @@ -130,32 +126,14 @@ class BasicEntityPersister implements EntityPersister protected $em; /** - * Queued inserts. + * The map of column names to DBAL columns used when INSERTing or UPDATEing an entity. * - * @var array - */ - protected $queuedInserts = []; - - /** - * The map of column names to DBAL mapping types of all prepared columns used - * when INSERTing or UPDATEing an entity. - * - * @var array + * @var array * * @see prepareInsertData($entity) * @see prepareUpdateData($entity) */ - protected $columnTypes = []; - - /** - * The map of quoted column names. - * - * @var array - * - * @see prepareInsertData($entity) - * @see prepareUpdateData($entity) - */ - protected $quotedColumns = []; + protected $columns = []; /** * The INSERT SQL statement used for entities handled by this persister. @@ -165,20 +143,6 @@ class BasicEntityPersister implements EntityPersister */ private $insertSql; - /** - * The quote strategy. - * - * @var \Doctrine\ORM\Mapping\QuoteStrategy - */ - protected $quoteStrategy; - - /** - * The IdentifierFlattener used for manipulating identifiers - * - * @var \Doctrine\ORM\Utility\IdentifierFlattener - */ - private $identifierFlattener; - /** * @var CachedPersisterContext */ @@ -203,13 +167,11 @@ class BasicEntityPersister implements EntityPersister */ public function __construct(EntityManagerInterface $em, ClassMetadata $class) { - $this->em = $em; - $this->class = $class; - $this->conn = $em->getConnection(); - $this->platform = $this->conn->getDatabasePlatform(); - $this->quoteStrategy = $em->getConfiguration()->getQuoteStrategy(); - $this->identifierFlattener = new IdentifierFlattener($em->getUnitOfWork(), $em->getMetadataFactory()); - $this->noLimitsContext = $this->currentPersisterContext = new CachedPersisterContext( + $this->em = $em; + $this->class = $class; + $this->conn = $em->getConnection(); + $this->platform = $this->conn->getDatabasePlatform(); + $this->noLimitsContext = $this->currentPersisterContext = new CachedPersisterContext( $class, new Query\ResultSetMapping(), false @@ -240,70 +202,70 @@ public function getResultSetMapping() /** * {@inheritdoc} */ - public function addInsert($entity) + public function getIdentifier($entity): array { - $this->queuedInserts[spl_object_hash($entity)] = $entity; + $id = []; + + foreach ($this->class->getIdentifier() as $fieldName) { + $property = $this->class->getProperty($fieldName); + $value = $property->getValue($entity); + + if (null !== $value) { + $id[$fieldName] = $value; + } + } + + return $id; } /** - * {@inheritdoc} + * Populates the entity identifier of an entity. + * + * @param object $entity + * @param array $id + * + * @return void */ - public function getInserts() + public function setIdentifier($entity, array $id) : void { - return $this->queuedInserts; + foreach ($id as $idField => $idValue) { + $property = $this->class->getProperty($idField); + + $property->setValue($entity, $idValue); + } } /** * {@inheritdoc} */ - public function executeInserts() + public function insert($entity) { - if ( ! $this->queuedInserts) { - return []; - } + $stmt = $this->conn->prepare($this->getInsertSQL()); + $tableName = $this->class->getTableName(); + $insertData = $this->prepareInsertData($entity); + $generationPlan = $this->class->getValueGenerationPlan(); - $postInsertIds = []; - $idGenerator = $this->class->idGenerator; - $isPostInsertId = $idGenerator->isPostInsertGenerator(); - - $stmt = $this->conn->prepare($this->getInsertSQL()); - $tableName = $this->class->getTableName(); + if (isset($insertData[$tableName])) { + $paramIndex = 1; - foreach ($this->queuedInserts as $entity) { - $insertData = $this->prepareInsertData($entity); + foreach ($insertData[$tableName] as $columnName => $value) { + $type = $this->columns[$columnName]->getType(); - if (isset($insertData[$tableName])) { - $paramIndex = 1; - - foreach ($insertData[$tableName] as $column => $value) { - $stmt->bindValue($paramIndex++, $value, $this->columnTypes[$column]); - } + $stmt->bindValue($paramIndex++, $value, $type); } + } - $stmt->execute(); - - if ($isPostInsertId) { - $generatedId = $idGenerator->generate($this->em, $entity); - $id = [ - $this->class->identifier[0] => $generatedId - ]; - $postInsertIds[] = [ - 'generatedId' => $generatedId, - 'entity' => $entity, - ]; - } else { - $id = $this->class->getIdentifierValues($entity); - } + $stmt->execute(); - if ($this->class->isVersioned) { - $this->assignDefaultVersionValue($entity, $id); - } + if ($generationPlan->containsDeferred()) { + $generationPlan->executeDeferred($this->em, $entity); } - $stmt->closeCursor(); - $this->queuedInserts = []; + if ($this->class->isVersioned()) { + $this->assignDefaultVersionValue($entity, $this->getIdentifier($entity)); + } - return $postInsertIds; + $stmt->closeCursor(); } /** @@ -318,43 +280,46 @@ public function executeInserts() */ protected function assignDefaultVersionValue($entity, array $id) { - $value = $this->fetchVersionValue($this->class, $id); + $versionProperty = $this->class->versionProperty; + $versionValue = $this->fetchVersionValue($versionProperty, $id); - $this->class->setFieldValue($entity, $this->class->versionField, $value); + $versionProperty->setValue($entity, $versionValue); } /** * Fetches the current version value of a versioned entity. * - * @param \Doctrine\ORM\Mapping\ClassMetadata $versionedClass - * @param array $id + * @param \Doctrine\ORM\Mapping\VersionFieldMetadata $versionProperty + * @param array $id * * @return mixed */ - protected function fetchVersionValue($versionedClass, array $id) + protected function fetchVersionValue(FieldMetadata $versionProperty, array $id) { - $versionField = $versionedClass->versionField; - $fieldMapping = $versionedClass->fieldMappings[$versionField]; - $tableName = $this->quoteStrategy->getTableName($versionedClass, $this->platform); - $identifier = $this->quoteStrategy->getIdentifierColumnNames($versionedClass, $this->platform); - $columnName = $this->quoteStrategy->getColumnName($versionField, $versionedClass, $this->platform); + $versionedClass = $versionProperty->getDeclaringClass(); + $tableName = $versionedClass->table->getQuotedQualifiedName($this->platform); + $columnName = $this->platform->quoteIdentifier($versionProperty->getColumnName()); + $identifier = array_map( + function ($columnName) { return $this->platform->quoteIdentifier($columnName); }, + array_keys($versionedClass->getIdentifierColumns($this->em)) + ); // FIXME: Order with composite keys might not be correct $sql = 'SELECT ' . $columnName . ' FROM ' . $tableName . ' WHERE ' . implode(' = ? AND ', $identifier) . ' = ?'; - - $flatId = $this->identifierFlattener->flattenIdentifier($versionedClass, $id); + $flattenedId = $this->em->getIdentifierFlattener()->flattenIdentifier($versionedClass, $id); + $versionType = $versionProperty->getType(); $value = $this->conn->fetchColumn( $sql, - array_values($flatId), + array_values($flattenedId), 0, $this->extractIdentifierTypes($id, $versionedClass) ); - return Type::getType($fieldMapping['type'])->convertToPHPValue($value, $this->platform); + return $versionType->convertToPHPValue($value, $this->platform); } private function extractIdentifierTypes(array $id, ClassMetadata $versionedClass) : array @@ -380,8 +345,8 @@ public function update($entity) return; } - $isVersioned = $this->class->isVersioned; - $quotedTableName = $this->quoteStrategy->getTableName($this->class, $this->platform); + $isVersioned = $this->class->isVersioned(); + $quotedTableName = $this->class->table->getQuotedQualifiedName($this->platform); $this->updateTable($entity, $quotedTableName, $data, $isVersioned); @@ -392,6 +357,69 @@ public function update($entity) } } + /** + * {@inheritdoc} + */ + public function delete($entity) + { + $class = $this->class; + $unitOfWork = $this->em->getUnitOfWork(); + $identifier = $unitOfWork->getEntityIdentifier($entity); + $tableName = $class->table->getQuotedQualifiedName($this->platform); + + $types = []; + $id = []; + + foreach ($class->identifier as $field) { + $property = $class->getProperty($field); + + if ($property instanceof FieldMetadata) { + $columnName = $property->getColumnName(); + $quotedColumnName = $this->platform->quoteIdentifier($columnName); + + $id[$quotedColumnName] = $identifier[$field]; + $types[] = $property->getType(); + + continue; + } + + $targetClass = $this->em->getClassMetadata($property->getTargetEntity()); + $joinColumns = $property instanceof ManyToManyAssociationMetadata + ? $property->getTable()->getJoinColumns() + : $property->getJoinColumns() + ; + + $associationValue = null; + + if (($value = $identifier[$field]) !== null) { + // @todo guilhermeblanco Make sure we do not have flat association values. + if (! is_array($value)) { + $value = [$targetClass->identifier[0] => $value]; + } + + $associationValue = $value; + } + + foreach ($joinColumns as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + $targetField = $targetClass->fieldNames[$referencedColumnName]; + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); + } + + $id[$quotedColumnName] = $associationValue ? $associationValue[$targetField] : null; + $types[] = $joinColumn->getType(); + } + } + + $this->deleteJoinTableRecords($identifier); + + return (bool) $this->conn->delete($tableName, $id, $types); + } + /** * Performs an UPDATE statement for an entity on a specific table. * The UPDATE can optionally be versioned, which requires the entity to have a version field. @@ -413,81 +441,71 @@ protected final function updateTable($entity, $quotedTableName, array $updateDat $params = []; foreach ($updateData as $columnName => $value) { - $placeholder = '?'; - $column = $columnName; - - switch (true) { - case isset($this->class->fieldNames[$columnName]): - $fieldName = $this->class->fieldNames[$columnName]; - $column = $this->quoteStrategy->getColumnName($fieldName, $this->class, $this->platform); - - if (isset($this->class->fieldMappings[$fieldName]['requireSQLConversion'])) { - $type = Type::getType($this->columnTypes[$columnName]); - $placeholder = $type->convertToDatabaseValueSQL('?', $this->platform); - } - - break; + $column = $this->columns[$columnName]; + $quotedColumnName = $this->platform->quoteIdentifier($column->getColumnName()); + $type = $column->getType(); + $placeholder = $type->convertToDatabaseValueSQL('?', $this->platform); - case isset($this->quotedColumns[$columnName]): - $column = $this->quotedColumns[$columnName]; - - break; - } - - $params[] = $value; - $set[] = $column . ' = ' . $placeholder; - $types[] = $this->columnTypes[$columnName]; + $set[] = sprintf('%s = %s', $quotedColumnName, $placeholder); + $params[] = $value; + $types[] = $column->getType(); } + // @todo guilhermeblanco Bring this back: $this->em->getUnitOfWork()->getEntityIdentifier($entity); + $identifier = $this->getIdentifier($entity); $where = []; - $identifier = $this->em->getUnitOfWork()->getEntityIdentifier($entity); foreach ($this->class->identifier as $idField) { - if ( ! isset($this->class->associationMappings[$idField])) { - $params[] = $identifier[$idField]; - $types[] = $this->class->fieldMappings[$idField]['type']; - $where[] = $this->quoteStrategy->getColumnName($idField, $this->class, $this->platform); - - continue; - } - - $params[] = $identifier[$idField]; - $where[] = $this->class->associationMappings[$idField]['joinColumns'][0]['name']; - $targetMapping = $this->em->getClassMetadata($this->class->associationMappings[$idField]['targetEntity']); + $property = $this->class->getProperty($idField); switch (true) { - case (isset($targetMapping->fieldMappings[$targetMapping->identifier[0]])): - $types[] = $targetMapping->fieldMappings[$targetMapping->identifier[0]]['type']; + case ($property instanceof FieldMetadata): + $where[] = $this->platform->quoteIdentifier($property->getColumnName()); + $params[] = $identifier[$idField]; + $types[] = $property->getType(); break; - case (isset($targetMapping->associationMappings[$targetMapping->identifier[0]])): - $types[] = $targetMapping->associationMappings[$targetMapping->identifier[0]]['type']; - break; + case ($property instanceof ToOneAssociationMetadata): + $targetClass = $this->em->getClassMetadata($property->getTargetEntity()); + $targetPersister = $this->em->getUnitOfWork()->getEntityPersister($property->getTargetEntity()); - default: - throw ORMException::unrecognizedField($targetMapping->identifier[0]); - } + foreach ($property->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); + } + + $value = $targetPersister->getColumnValue($identifier[$idField], $referencedColumnName); + + $where[] = $quotedColumnName; + $params[] = $value; + $types[] = $joinColumn->getType(); + } + break; + } } if ($versioned) { - $versionField = $this->class->versionField; - $versionFieldType = $this->class->fieldMappings[$versionField]['type']; - $versionColumn = $this->quoteStrategy->getColumnName($versionField, $this->class, $this->platform); + $versionProperty = $this->class->versionProperty; + $versionColumnType = $versionProperty->getType(); + $versionColumnName = $this->platform->quoteIdentifier($versionProperty->getColumnName()); - $where[] = $versionColumn; - $types[] = $this->class->fieldMappings[$versionField]['type']; - $params[] = $this->class->reflFields[$versionField]->getValue($entity); + $where[] = $versionColumnName; + $types[] = $versionColumnType; + $params[] = $versionProperty->getValue($entity); - switch ($versionFieldType) { + switch ($versionColumnType->getName()) { case Type::SMALLINT: case Type::INTEGER: case Type::BIGINT: - $set[] = $versionColumn . ' = ' . $versionColumn . ' + 1'; + $set[] = $versionColumnName . ' = ' . $versionColumnName . ' + 1'; break; case Type::DATETIME: - $set[] = $versionColumn . ' = CURRENT_TIMESTAMP'; + $set[] = $versionColumnName . ' = CURRENT_TIMESTAMP'; break; } } @@ -512,50 +530,60 @@ protected final function updateTable($entity, $quotedTableName, array $updateDat */ protected function deleteJoinTableRecords($identifier) { - foreach ($this->class->associationMappings as $mapping) { - if ($mapping['type'] !== ClassMetadata::MANY_TO_MANY) { + foreach ($this->class->getDeclaredPropertiesIterator() as $association) { + if (! ($association instanceof ManyToManyAssociationMetadata)) { continue; } // @Todo this only covers scenarios with no inheritance or of the same level. Is there something // like self-referential relationship between different levels of an inheritance hierarchy? I hope not! - $selfReferential = ($mapping['targetEntity'] == $mapping['sourceEntity']); - $class = $this->class; - $association = $mapping; - $otherColumns = []; - $otherKeys = []; - $keys = []; - - if ( ! $mapping['isOwningSide']) { - $class = $this->em->getClassMetadata($mapping['targetEntity']); - $association = $class->associationMappings[$mapping['mappedBy']]; + $selfReferential = $association->getTargetEntity() === $association->getSourceEntity(); + $owningAssociation = $association; + $otherColumns = []; + $otherKeys = []; + $keys = []; + + if ( ! $owningAssociation->isOwningSide()) { + $class = $this->em->getClassMetadata($association->getTargetEntity()); + $owningAssociation = $class->getProperty($association->getMappedBy()); } - $joinColumns = $mapping['isOwningSide'] - ? $association['joinTable']['joinColumns'] - : $association['joinTable']['inverseJoinColumns']; - + $joinTable = $owningAssociation->getJoinTable(); + $joinTableName = $joinTable->getQuotedQualifiedName($this->platform); + $joinColumns = $association->isOwningSide() + ? $joinTable->getJoinColumns() + : $joinTable->getInverseJoinColumns() + ; if ($selfReferential) { - $otherColumns = (! $mapping['isOwningSide']) - ? $association['joinTable']['joinColumns'] - : $association['joinTable']['inverseJoinColumns']; + $otherColumns = ! $association->isOwningSide() + ? $joinTable->getJoinColumns() + : $joinTable->getInverseJoinColumns() + ; } + $isOnDeleteCascade = false; + foreach ($joinColumns as $joinColumn) { - $keys[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); + $keys[] = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + + if ($joinColumn->isOnDeleteCascade()) { + $isOnDeleteCascade = true; + } } foreach ($otherColumns as $joinColumn) { - $otherKeys[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); + $otherKeys[] = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + + if ($joinColumn->isOnDeleteCascade()) { + $isOnDeleteCascade = true; + } } - if (isset($mapping['isOnDeleteCascade'])) { + if ($isOnDeleteCascade) { continue; } - $joinTableName = $this->quoteStrategy->getJoinTableName($association, $this->class, $this->platform); - $this->conn->delete($joinTableName, array_combine($keys, $identifier)); if ($selfReferential) { @@ -565,37 +593,18 @@ protected function deleteJoinTableRecords($identifier) } /** - * {@inheritdoc} + * Prepares the data changeset of a managed entity for database insertion (initial INSERT). + * The changeset of the entity is obtained from the currently running UnitOfWork. + * + * The default insert data preparation is the same as for updates. + * + * @param object $entity The entity for which to prepare the data. + * + * @return array The prepared data for the tables to update. */ - public function delete($entity) + protected function prepareInsertData($entity) : array { - $self = $this; - $class = $this->class; - $identifier = $this->em->getUnitOfWork()->getEntityIdentifier($entity); - $tableName = $this->quoteStrategy->getTableName($class, $this->platform); - $idColumns = $this->quoteStrategy->getIdentifierColumnNames($class, $this->platform); - $id = array_combine($idColumns, $identifier); - $types = array_map(function ($identifier) use ($class, $self) { - if (isset($class->fieldMappings[$identifier])) { - return $class->fieldMappings[$identifier]['type']; - } - - $targetMapping = $self->em->getClassMetadata($class->associationMappings[$identifier]['targetEntity']); - - if (isset($targetMapping->fieldMappings[$targetMapping->identifier[0]])) { - return $targetMapping->fieldMappings[$targetMapping->identifier[0]]['type']; - } - - if (isset($targetMapping->associationMappings[$targetMapping->identifier[0]])) { - return $targetMapping->associationMappings[$targetMapping->identifier[0]]['type']; - } - - throw ORMException::unrecognizedField($targetMapping->identifier[0]); - }, $class->identifier); - - $this->deleteJoinTableRecords($identifier); - - return (bool) $this->conn->delete($tableName, $id, $types); + return $this->prepareUpdateData($entity); } /** @@ -621,75 +630,63 @@ public function delete($entity) */ protected function prepareUpdateData($entity) { - $versionField = null; - $result = []; - $uow = $this->em->getUnitOfWork(); - - if (($versioned = $this->class->isVersioned) != false) { - $versionField = $this->class->versionField; - } - - foreach ($uow->getEntityChangeSet($entity) as $field => $change) { - if (isset($versionField) && $versionField == $field) { - continue; - } - - if (isset($this->class->embeddedClasses[$field])) { + $uow = $this->em->getUnitOfWork(); + $result = []; + $versionPropertyName = $this->class->isVersioned() + ? $this->class->versionProperty->getName() + : null + ; + + // @todo guilhermeblanco This should check column insertability/updateability instead of field changeset + foreach ($uow->getEntityChangeSet($entity) as $propertyName => $propertyChangeSet) { + if ($versionPropertyName === $propertyName) { continue; } - $newVal = $change[1]; - - if ( ! isset($this->class->associationMappings[$field])) { - $fieldMapping = $this->class->fieldMappings[$field]; - $columnName = $fieldMapping['columnName']; + $property = $this->class->getProperty($propertyName); + $newValue = $propertyChangeSet[1]; - $this->columnTypes[$columnName] = $fieldMapping['type']; + if ($property instanceof FieldMetadata) { + // @todo guilhermeblanco Please remove this in the future for good... + $this->columns[$property->getColumnName()] = $property; - $result[$this->getOwningTable($field)][$columnName] = $newVal; + $result[$property->getTableName()][$property->getColumnName()] = $newValue; continue; } - $assoc = $this->class->associationMappings[$field]; - // Only owning side of x-1 associations can have a FK column. - if ( ! $assoc['isOwningSide'] || ! ($assoc['type'] & ClassMetadata::TO_ONE)) { + if (! $property instanceof ToOneAssociationMetadata || ! $property->isOwningSide()) { continue; } - if ($newVal !== null) { - $oid = spl_object_hash($newVal); + // The associated entity $newVal is not yet persisted, so we must + // set $newVal = null, in order to insert a null value and schedule an + // extra update on the UnitOfWork. + if ($newValue !== null && $uow->isScheduledForInsert($newValue)) { + $uow->scheduleExtraUpdate($entity, [$propertyName => [null, $newValue]]); - if (isset($this->queuedInserts[$oid]) || $uow->isScheduledForInsert($newVal)) { - // The associated entity $newVal is not yet persisted, so we must - // set $newVal = null, in order to insert a null value and schedule an - // extra update on the UnitOfWork. - $uow->scheduleExtraUpdate($entity, [$field => [null, $newVal]]); - - $newVal = null; - } + $newValue = null; } - $newValId = null; + $targetClass = $this->em->getClassMetadata($property->getTargetEntity()); + $targetPersister = $uow->getEntityPersister($targetClass->getClassName()); - if ($newVal !== null) { - $newValId = $uow->getEntityIdentifier($newVal); - } + foreach ($property->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $referencedColumnName = $joinColumn->getReferencedColumnName(); - $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); - $owningTable = $this->getOwningTable($field); + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); + } - foreach ($assoc['joinColumns'] as $joinColumn) { - $sourceColumn = $joinColumn['name']; - $targetColumn = $joinColumn['referencedColumnName']; - $quotedColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform); + // @todo guilhermeblanco Please remove this in the future for good... + $this->columns[$joinColumn->getColumnName()] = $joinColumn; - $this->quotedColumns[$sourceColumn] = $quotedColumn; - $this->columnTypes[$sourceColumn] = PersisterHelper::getTypeOfColumn($targetColumn, $targetClass, $this->em); - $result[$owningTable][$sourceColumn] = $newValId - ? $newValId[$targetClass->getFieldForColumn($targetColumn)] - : null; + $result[$joinColumn->getTableName()][$joinColumn->getColumnName()] = $newValue !== null + ? $targetPersister->getColumnValue($newValue, $referencedColumnName) + : null + ; } } @@ -697,39 +694,69 @@ protected function prepareUpdateData($entity) } /** - * Prepares the data changeset of a managed entity for database insertion (initial INSERT). - * The changeset of the entity is obtained from the currently running UnitOfWork. - * - * The default insert data preparation is the same as for updates. - * - * @param object $entity The entity for which to prepare the data. - * - * @return array The prepared data for the tables to update. + * @param object $entity + * @param string $columnName * - * @see prepareUpdateData + * @return mixed|null */ - protected function prepareInsertData($entity) + public function getColumnValue($entity, string $columnName) { - return $this->prepareUpdateData($entity); - } + // Looking for fields by column is the easiest way to look at local columns or x-1 owning side associations + $propertyName = $this->class->fieldNames[$columnName]; + $property = $this->class->getProperty($propertyName); - /** - * {@inheritdoc} - */ - public function getOwningTable($fieldName) - { - return $this->class->getTableName(); + if (! $property) { + return null; + } + + $propertyValue = $property->getValue($entity); + + if ($property instanceof LocalColumnMetadata) { + return $propertyValue; + } + + /* @var ToOneAssociationMetadata $property */ + $unitOfWork = $this->em->getUnitOfWork(); + $targetClass = $this->em->getClassMetadata($property->getTargetEntity()); + $targetPersister = $unitOfWork->getEntityPersister($property->getTargetEntity()); + + foreach ($property->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $referencedColumnName = $joinColumn->getReferencedColumnName(); + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); + } + + if ($joinColumn->getColumnName() !== $columnName) { + continue; + } + + return $targetPersister->getColumnValue($propertyValue, $referencedColumnName); + } + + return null; } /** * {@inheritdoc} */ - public function load(array $criteria, $entity = null, $assoc = null, array $hints = [], $lockMode = null, $limit = null, array $orderBy = null) + public function load( + array $criteria, + $entity = null, + AssociationMetadata $association = null, + array $hints = [], + $lockMode = null, + $limit = null, + array $orderBy = [] + ) { $this->switchPersisterContext(null, $limit); - $sql = $this->getSelectSQL($criteria, $assoc, $lockMode, $limit, null, $orderBy); + $sql = $this->getSelectSQL($criteria, $association, $lockMode, $limit, null, $orderBy); + list($params, $types) = $this->expandParameters($criteria); + $stmt = $this->conn->executeQuery($sql, $params, $types); if ($entity !== null) { @@ -754,23 +781,28 @@ public function loadById(array $identifier, $entity = null) /** * {@inheritdoc} */ - public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifier = []) + public function loadToOneEntity(ToOneAssociationMetadata $association, $sourceEntity, array $identifier = []) { - if (($foundEntity = $this->em->getUnitOfWork()->tryGetById($identifier, $assoc['targetEntity'])) != false) { + $unitOfWork = $this->em->getUnitOfWork(); + $targetEntity = $association->getTargetEntity(); + + if (($foundEntity = $unitOfWork->tryGetById($identifier, $targetEntity)) != false) { return $foundEntity; } - $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); + $targetClass = $this->em->getClassMetadata($targetEntity); - if ($assoc['isOwningSide']) { - $isInverseSingleValued = $assoc['inversedBy'] && ! $targetClass->isCollectionValuedAssociation($assoc['inversedBy']); + if ($association->isOwningSide()) { + $inversedBy = $association->getInversedBy(); + $targetProperty = $inversedBy ? $targetClass->getProperty($inversedBy) : null; + $isInverseSingleValued = $targetProperty && $targetProperty instanceof ToOneAssociationMetadata; // Mark inverse side as fetched in the hints, otherwise the UoW would // try to load it in a separate query (remember: to-one inverse sides can not be lazy). $hints = []; if ($isInverseSingleValued) { - $hints['fetched']["r"][$assoc['inversedBy']] = true; + $hints['fetched']["r"][$inversedBy] = true; } /* cascade read-only status @@ -779,42 +811,48 @@ public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifie } */ - $targetEntity = $this->load($identifier, null, $assoc, $hints); + $entity = $this->load($identifier, null, $association, $hints); // Complete bidirectional association, if necessary - if ($targetEntity !== null && $isInverseSingleValued) { - $targetClass->reflFields[$assoc['inversedBy']]->setValue($targetEntity, $sourceEntity); + if ($entity !== null && $isInverseSingleValued) { + $targetProperty->setValue($entity, $sourceEntity); } - return $targetEntity; + return $entity; } - $sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']); - $owningAssoc = $targetClass->getAssociationMapping($assoc['mappedBy']); + $sourceClass = $association->getDeclaringClass(); + $owningAssociation = $targetClass->getProperty($association->getMappedBy()); + $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName()); + + foreach ($owningAssociation->getJoinColumns() as $joinColumn) { + $sourceKeyColumn = $joinColumn->getReferencedColumnName(); + $targetKeyColumn = $joinColumn->getColumnName(); - // TRICKY: since the association is specular source and target are flipped - foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) { if ( ! isset($sourceClass->fieldNames[$sourceKeyColumn])) { throw MappingException::joinColumnMustPointToMappedField( - $sourceClass->name, $sourceKeyColumn + $sourceClass->getClassName(), $sourceKeyColumn ); } + $property = $sourceClass->getProperty($sourceClass->fieldNames[$sourceKeyColumn]); + $value = $property->getValue($sourceEntity); + // unset the old value and set the new sql aliased value here. By definition // unset($identifier[$targetKeyColumn] works here with how UnitOfWork::createEntity() calls this method. - $identifier[$targetClass->getFieldForColumn($targetKeyColumn)] = - $sourceClass->reflFields[$sourceClass->fieldNames[$sourceKeyColumn]]->getValue($sourceEntity); + // @todo guilhermeblanco In master we have: $identifier[$targetClass->getFieldForColumn($targetKeyColumn)] = + $identifier[$targetTableAlias . "." . $targetKeyColumn] = $value; unset($identifier[$targetKeyColumn]); } - $targetEntity = $this->load($identifier, null, $assoc); + $entity = $this->load($identifier, null, $association); - if ($targetEntity !== null) { - $targetClass->setFieldValue($targetEntity, $assoc['mappedBy'], $sourceEntity); + if ($entity !== null) { + $owningAssociation->setValue($entity, $sourceEntity); } - return $targetEntity; + return $entity; } /** @@ -856,11 +894,13 @@ public function loadCriteria(Criteria $criteria) list($params, $types) = $this->expandCriteriaParameters($criteria); - $stmt = $this->conn->executeQuery($query, $params, $types); - $hydrator = $this->em->newHydrator(($this->currentPersisterContext->selectJoinSql) ? Query::HYDRATE_OBJECT : Query::HYDRATE_SIMPLEOBJECT); + $stmt = $this->conn->executeQuery($query, $params, $types); + $rsm = $this->currentPersisterContext->rsm; + $hints = [UnitOfWork::HINT_DEFEREAGERLOAD => true]; + $hydratorType = $this->currentPersisterContext->selectJoinSql ? Query::HYDRATE_OBJECT : Query::HYDRATE_SIMPLEOBJECT; + $hydrator = $this->em->newHydrator($hydratorType); - return $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true] - ); + return $hydrator->hydrateAll($stmt, $rsm, $hints); } /** @@ -897,156 +937,168 @@ public function expandCriteriaParameters(Criteria $criteria) /** * {@inheritdoc} */ - public function loadAll(array $criteria = [], array $orderBy = null, $limit = null, $offset = null) + public function loadAll(array $criteria = [], array $orderBy = [], $limit = null, $offset = null) { $this->switchPersisterContext($offset, $limit); $sql = $this->getSelectSQL($criteria, null, null, $limit, $offset, $orderBy); + list($params, $types) = $this->expandParameters($criteria); - $stmt = $this->conn->executeQuery($sql, $params, $types); - $hydrator = $this->em->newHydrator(($this->currentPersisterContext->selectJoinSql) ? Query::HYDRATE_OBJECT : Query::HYDRATE_SIMPLEOBJECT); + $stmt = $this->conn->executeQuery($sql, $params, $types); + $rsm = $this->currentPersisterContext->rsm; + $hints = [UnitOfWork::HINT_DEFEREAGERLOAD => true]; + $hydratorType = $this->currentPersisterContext->selectJoinSql ? Query::HYDRATE_OBJECT : Query::HYDRATE_SIMPLEOBJECT; + $hydrator = $this->em->newHydrator($hydratorType); - return $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true] - ); + return $hydrator->hydrateAll($stmt, $rsm, $hints); } /** * {@inheritdoc} */ - public function getManyToManyCollection(array $assoc, $sourceEntity, $offset = null, $limit = null) + public function getManyToManyCollection( + ManyToManyAssociationMetadata $association, + $sourceEntity, + $offset = null, + $limit = null + ) { $this->switchPersisterContext($offset, $limit); - $stmt = $this->getManyToManyStatement($assoc, $sourceEntity, $offset, $limit); + $stmt = $this->getManyToManyStatement($association, $sourceEntity, $offset, $limit); + + return $this->loadArrayFromStatement($association, $stmt); + } + + /** + * {@inheritdoc} + */ + public function loadManyToManyCollection( + ManyToManyAssociationMetadata $association, + $sourceEntity, + PersistentCollection $collection + ) + { + $stmt = $this->getManyToManyStatement($association, $sourceEntity); - return $this->loadArrayFromStatement($assoc, $stmt); + return $this->loadCollectionFromStatement($association, $stmt, $collection); } /** * Loads an array of entities from a given DBAL statement. * - * @param array $assoc - * @param \Doctrine\DBAL\Statement $stmt + * @param ToManyAssociationMetadata $association + * @param \Doctrine\DBAL\Statement $stmt * * @return array */ - private function loadArrayFromStatement($assoc, $stmt) + private function loadArrayFromStatement(ToManyAssociationMetadata $association, $stmt) { - $rsm = $this->currentPersisterContext->rsm; - $hints = [UnitOfWork::HINT_DEFEREAGERLOAD => true]; + $rsm = $this->currentPersisterContext->rsm; - if (isset($assoc['indexBy'])) { + if ($association->getIndexedBy()) { $rsm = clone ($this->currentPersisterContext->rsm); // this is necessary because the "default rsm" should be changed. - $rsm->addIndexBy('r', $assoc['indexBy']); + $rsm->addIndexBy('r', $association->getIndexedBy()); } - return $this->em->newHydrator(Query::HYDRATE_OBJECT)->hydrateAll($stmt, $rsm, $hints); + $hydrator = $this->em->newHydrator(Query::HYDRATE_OBJECT); + $hints = [UnitOfWork::HINT_DEFEREAGERLOAD => true]; + + return $hydrator->hydrateAll($stmt, $rsm, $hints); } /** * Hydrates a collection from a given DBAL statement. * - * @param array $assoc - * @param \Doctrine\DBAL\Statement $stmt - * @param PersistentCollection $coll + * @param ToManyAssociationMetadata $association + * @param \Doctrine\DBAL\Statement $stmt + * @param PersistentCollection $collection * * @return array */ - private function loadCollectionFromStatement($assoc, $stmt, $coll) + private function loadCollectionFromStatement(ToManyAssociationMetadata $association, $stmt, $collection) { - $rsm = $this->currentPersisterContext->rsm; - $hints = [ - UnitOfWork::HINT_DEFEREAGERLOAD => true, - 'collection' => $coll - ]; + $rsm = $this->currentPersisterContext->rsm; - if (isset($assoc['indexBy'])) { + if ($association->getIndexedBy()) { $rsm = clone ($this->currentPersisterContext->rsm); // this is necessary because the "default rsm" should be changed. - $rsm->addIndexBy('r', $assoc['indexBy']); + $rsm->addIndexBy('r', $association->getIndexedBy()); } - return $this->em->newHydrator(Query::HYDRATE_OBJECT)->hydrateAll($stmt, $rsm, $hints); - } - - /** - * {@inheritdoc} - */ - public function loadManyToManyCollection(array $assoc, $sourceEntity, PersistentCollection $coll) - { - $stmt = $this->getManyToManyStatement($assoc, $sourceEntity); + $hydrator = $this->em->newHydrator(Query::HYDRATE_OBJECT); + $hints = [ + UnitOfWork::HINT_DEFEREAGERLOAD => true, + 'collection' => $collection + ]; - return $this->loadCollectionFromStatement($assoc, $stmt, $coll); + return $hydrator->hydrateAll($stmt, $rsm, $hints); } /** - * @param array $assoc - * @param object $sourceEntity - * @param int|null $offset - * @param int|null $limit + * @param ManyToManyAssociationMetadata $association + * @param object $sourceEntity + * @param int|null $offset + * @param int|null $limit * * @return \Doctrine\DBAL\Driver\Statement * * @throws \Doctrine\ORM\Mapping\MappingException */ - private function getManyToManyStatement(array $assoc, $sourceEntity, $offset = null, $limit = null) + private function getManyToManyStatement( + ManyToManyAssociationMetadata $association, + $sourceEntity, + $offset = null, + $limit = null + ) { $this->switchPersisterContext($offset, $limit); - $sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']); + /** @var ClassMetadata $sourceClass */ + $sourceClass = $this->em->getClassMetadata($association->getSourceEntity()); $class = $sourceClass; - $association = $assoc; + $owningAssoc = $association; $criteria = []; $parameters = []; - if ( ! $assoc['isOwningSide']) { - $class = $this->em->getClassMetadata($assoc['targetEntity']); - $association = $class->associationMappings[$assoc['mappedBy']]; + if (! $association->isOwningSide()) { + $class = $this->em->getClassMetadata($association->getTargetEntity()); + $owningAssoc = $class->getProperty($association->getMappedBy()); } - $joinColumns = $assoc['isOwningSide'] - ? $association['joinTable']['joinColumns'] - : $association['joinTable']['inverseJoinColumns']; - - $quotedJoinTable = $this->quoteStrategy->getJoinTableName($association, $class, $this->platform); + $joinTable = $owningAssoc->getJoinTable(); + $joinTableName = $joinTable->getQuotedQualifiedName($this->platform); + $joinColumns = $association->isOwningSide() + ? $joinTable->getJoinColumns() + : $joinTable->getInverseJoinColumns() + ; foreach ($joinColumns as $joinColumn) { - $sourceKeyColumn = $joinColumn['referencedColumnName']; - $quotedKeyColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); - - switch (true) { - case $sourceClass->containsForeignIdentifier: - $field = $sourceClass->getFieldForColumn($sourceKeyColumn); - $value = $sourceClass->reflFields[$field]->getValue($sourceEntity); - - if (isset($sourceClass->associationMappings[$field])) { - $value = $this->em->getUnitOfWork()->getEntityIdentifier($value); - $value = $value[$this->em->getClassMetadata($sourceClass->associationMappings[$field]['targetEntity'])->identifier[0]]; - } - - break; - - case isset($sourceClass->fieldNames[$sourceKeyColumn]): - $field = $sourceClass->fieldNames[$sourceKeyColumn]; - $value = $sourceClass->reflFields[$field]->getValue($sourceEntity); - - break; - - default: - throw MappingException::joinColumnMustPointToMappedField( - $sourceClass->name, $sourceKeyColumn - ); + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $fieldName = $sourceClass->fieldNames[$joinColumn->getReferencedColumnName()]; + $property = $sourceClass->getProperty($fieldName); + + if ($property instanceof FieldMetadata) { + $value = $property->getValue($sourceEntity); + } else if ($property instanceof AssociationMetadata) { + $property = $sourceClass->getProperty($fieldName); + $targetClass = $this->em->getClassMetadata($property->getTargetEntity()); + $value = $property->getValue($sourceEntity); + + $value = $this->em->getUnitOfWork()->getEntityIdentifier($value); + $value = $value[$targetClass->identifier[0]]; } - $criteria[$quotedJoinTable . '.' . $quotedKeyColumn] = $value; + $criteria[$joinTableName . '.' . $quotedColumnName] = $value; $parameters[] = [ 'value' => $value, - 'field' => $field, + 'field' => $fieldName, 'class' => $sourceClass, ]; } - $sql = $this->getSelectSQL($criteria, $assoc, null, $limit, $offset); + $sql = $this->getSelectSQL($criteria, $association, null, $limit, $offset); + list($params, $types) = $this->expandToManyParameters($parameters); return $this->conn->executeQuery($sql, $params, $types); @@ -1055,7 +1107,14 @@ private function getManyToManyStatement(array $assoc, $sourceEntity, $offset = n /** * {@inheritdoc} */ - public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit = null, $offset = null, array $orderBy = null) + public function getSelectSQL( + $criteria, + AssociationMetadata $association = null, + $lockMode = null, + $limit = null, + $offset = null, + array $orderBy = [] + ) { $this->switchPersisterContext($offset, $limit); @@ -1063,21 +1122,21 @@ public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit $joinSql = ''; $orderBySql = ''; - if ($assoc != null && $assoc['type'] == ClassMetadata::MANY_TO_MANY) { - $joinSql = $this->getSelectManyToManyJoinSQL($assoc); + if ($association instanceof ManyToManyAssociationMetadata) { + $joinSql = $this->getSelectManyToManyJoinSQL($association); } - if (isset($assoc['orderBy'])) { - $orderBy = $assoc['orderBy']; + if ($association instanceof ToManyAssociationMetadata && $association->getOrderBy()) { + $orderBy = $association->getOrderBy(); } if ($orderBy) { - $orderBySql = $this->getOrderBySQL($orderBy, $this->getSQLTableAlias($this->class->name)); + $orderBySql = $this->getOrderBySQL($orderBy, $this->getSQLTableAlias($this->class->getTableName())); } $conditionSql = ($criteria instanceof Criteria) ? $this->getSelectConditionCriteriaSQL($criteria) - : $this->getSelectConditionSQL($criteria, $assoc); + : $this->getSelectConditionSQL($criteria, $association); switch ($lockMode) { case LockMode::PESSIMISTIC_READ: @@ -1090,9 +1149,9 @@ public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit } $columnList = $this->getSelectColumnsSQL(); - $tableAlias = $this->getSQLTableAlias($this->class->name); + $tableAlias = $this->getSQLTableAlias($this->class->getTableName()); $filterSql = $this->generateFilterConditionSQL($this->class, $tableAlias); - $tableName = $this->quoteStrategy->getTableName($this->class, $this->platform); + $tableName = $this->class->table->getQuotedQualifiedName($this->platform); if ('' !== $filterSql) { $conditionSql = $conditionSql @@ -1119,8 +1178,8 @@ public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit */ public function getCountSQL($criteria = []) { - $tableName = $this->quoteStrategy->getTableName($this->class, $this->platform); - $tableAlias = $this->getSQLTableAlias($this->class->name); + $tableName = $this->class->table->getQuotedQualifiedName($this->platform); + $tableAlias = $this->getSQLTableAlias($this->class->getTableName()); $conditionSql = ($criteria instanceof Criteria) ? $this->getSelectConditionCriteriaSQL($criteria) @@ -1153,40 +1212,43 @@ public function getCountSQL($criteria = []) */ protected final function getOrderBySQL(array $orderBy, $baseTableAlias) { + if (! $orderBy) { + return ''; + } + $orderByList = []; foreach ($orderBy as $fieldName => $orientation) { - $orientation = strtoupper(trim($orientation)); - if ($orientation != 'ASC' && $orientation != 'DESC') { - throw ORMException::invalidOrientation($this->class->name, $fieldName); + if (! in_array($orientation, ['ASC', 'DESC'])) { + throw ORMException::invalidOrientation($this->class->getClassName(), $fieldName); } - if (isset($this->class->fieldMappings[$fieldName])) { - $tableAlias = isset($this->class->fieldMappings[$fieldName]['inherited']) - ? $this->getSQLTableAlias($this->class->fieldMappings[$fieldName]['inherited']) - : $baseTableAlias; + $property = $this->class->getProperty($fieldName); + + if ($property instanceof FieldMetadata) { + $tableAlias = $this->getSQLTableAlias($property->getTableName()); + $columnName = $this->platform->quoteIdentifier($property->getColumnName()); - $columnName = $this->quoteStrategy->getColumnName($fieldName, $this->class, $this->platform); $orderByList[] = $tableAlias . '.' . $columnName . ' ' . $orientation; continue; - } - - if (isset($this->class->associationMappings[$fieldName])) { - - if ( ! $this->class->associationMappings[$fieldName]['isOwningSide']) { - throw ORMException::invalidFindByInverseAssociation($this->class->name, $fieldName); + } else if ($property instanceof AssociationMetadata) { + if (! $property->isOwningSide()) { + throw ORMException::invalidFindByInverseAssociation($this->class->getClassName(), $fieldName); } - $tableAlias = isset($this->class->associationMappings[$fieldName]['inherited']) - ? $this->getSQLTableAlias($this->class->associationMappings[$fieldName]['inherited']) - : $baseTableAlias; + $class = $this->class->isInheritedProperty($fieldName) + ? $property->getDeclaringClass() + : $this->class; + $tableAlias = $this->getSQLTableAlias($class->getTableName()); - foreach ($this->class->associationMappings[$fieldName]['joinColumns'] as $joinColumn) { - $columnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform); - $orderByList[] = $tableAlias . '.' . $columnName . ' ' . $orientation; + foreach ($property->getJoinColumns() as $joinColumn) { + /* @var JoinColumnMetadata $joinColumn */ + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + + $orderByList[] = $tableAlias . '.' . $quotedColumnName . ' ' . $orientation; } continue; @@ -1215,104 +1277,103 @@ protected function getSelectColumnsSQL() return $this->currentPersisterContext->selectColumnListSql; } - $columnList = []; - $this->currentPersisterContext->rsm->addEntityResult($this->class->name, 'r'); // r for root - - // Add regular columns to select list - foreach ($this->class->fieldNames as $field) { - $columnList[] = $this->getSelectColumnSQL($field, $this->class); - } + $this->currentPersisterContext->rsm->addEntityResult($this->class->getClassName(), 'r'); // r for root $this->currentPersisterContext->selectJoinSql = ''; - $eagerAliasCounter = 0; - foreach ($this->class->associationMappings as $assocField => $assoc) { - $assocColumnSQL = $this->getSelectColumnAssociationSQL($assocField, $assoc, $this->class); + $eagerAliasCounter = 0; + $columnList = []; - if ($assocColumnSQL) { - $columnList[] = $assocColumnSQL; - } + foreach ($this->class->getDeclaredPropertiesIterator() as $fieldName => $property) { + switch (true) { + case ($property instanceof FieldMetadata): + $columnList[] = $this->getSelectColumnSQL($fieldName, $this->class); + break; - $isAssocToOneInverseSide = $assoc['type'] & ClassMetadata::TO_ONE && ! $assoc['isOwningSide']; - $isAssocFromOneEager = $assoc['type'] !== ClassMetadata::MANY_TO_MANY && $assoc['fetch'] === ClassMetadata::FETCH_EAGER; + case ($property instanceof AssociationMetadata): + $assocColumnSQL = $this->getSelectColumnAssociationSQL($fieldName, $property, $this->class); - if ( ! ($isAssocFromOneEager || $isAssocToOneInverseSide)) { - continue; - } + if ($assocColumnSQL) { + $columnList[] = $assocColumnSQL; + } - if ((($assoc['type'] & ClassMetadata::TO_MANY) > 0) && $this->currentPersisterContext->handlesLimits) { - continue; - } + $isAssocToOneInverseSide = $property instanceof ToOneAssociationMetadata && ! $property->isOwningSide(); + $isAssocFromOneEager = ! $property instanceof ManyToManyAssociationMetadata && $property->getFetchMode() === FetchMode::EAGER; - $eagerEntity = $this->em->getClassMetadata($assoc['targetEntity']); + if ( ! ($isAssocFromOneEager || $isAssocToOneInverseSide)) { + break; + } - if ($eagerEntity->inheritanceType != ClassMetadata::INHERITANCE_TYPE_NONE) { - continue; // now this is why you shouldn't use inheritance - } + if ($property instanceof ToManyAssociationMetadata && $this->currentPersisterContext->handlesLimits) { + break; + } - $assocAlias = 'e' . ($eagerAliasCounter++); - $this->currentPersisterContext->rsm->addJoinedEntityResult($assoc['targetEntity'], $assocAlias, 'r', $assocField); + $targetEntity = $property->getTargetEntity(); + $eagerEntity = $this->em->getClassMetadata($targetEntity); - foreach ($eagerEntity->fieldNames as $field) { - $columnList[] = $this->getSelectColumnSQL($field, $eagerEntity, $assocAlias); - } + if ($eagerEntity->inheritanceType !== InheritanceType::NONE) { + break; // now this is why you shouldn't use inheritance + } - foreach ($eagerEntity->associationMappings as $eagerAssocField => $eagerAssoc) { - $eagerAssocColumnSQL = $this->getSelectColumnAssociationSQL( - $eagerAssocField, $eagerAssoc, $eagerEntity, $assocAlias - ); + $assocAlias = 'e' . ($eagerAliasCounter++); - if ($eagerAssocColumnSQL) { - $columnList[] = $eagerAssocColumnSQL; - } - } + $this->currentPersisterContext->rsm->addJoinedEntityResult($targetEntity, $assocAlias, 'r', $fieldName); - $association = $assoc; - $joinCondition = []; + foreach ($eagerEntity->getDeclaredPropertiesIterator() as $eagerProperty) { + switch (true) { + case ($eagerProperty instanceof FieldMetadata): + $columnList[] = $this->getSelectColumnSQL($eagerProperty->getName(), $eagerEntity, $assocAlias); + break; - if (isset($assoc['indexBy'])) { - $this->currentPersisterContext->rsm->addIndexBy($assocAlias, $assoc['indexBy']); - } + case ($eagerProperty instanceof ToOneAssociationMetadata && $eagerProperty->isOwningSide()): + $columnList[] = $this->getSelectColumnAssociationSQL( + $eagerProperty->getName(), $eagerProperty, $eagerEntity, $assocAlias + ); + break; + } + } - if ( ! $assoc['isOwningSide']) { - $eagerEntity = $this->em->getClassMetadata($assoc['targetEntity']); - $association = $eagerEntity->getAssociationMapping($assoc['mappedBy']); - } + $owningAssociation = $property; + $joinCondition = []; - $joinTableAlias = $this->getSQLTableAlias($eagerEntity->name, $assocAlias); - $joinTableName = $this->quoteStrategy->getTableName($eagerEntity, $this->platform); + if ($property instanceof ToManyAssociationMetadata && $property->getIndexedBy()) { + $this->currentPersisterContext->rsm->addIndexBy($assocAlias, $property->getIndexedBy()); + } - if ($assoc['isOwningSide']) { - $tableAlias = $this->getSQLTableAlias($association['targetEntity'], $assocAlias); - $this->currentPersisterContext->selectJoinSql .= ' ' . $this->getJoinSQLForJoinColumns($association['joinColumns']); + if (! $property->isOwningSide()) { + $owningAssociation = $eagerEntity->getProperty($property->getMappedBy()); + } - foreach ($association['joinColumns'] as $joinColumn) { - $sourceCol = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform); - $targetCol = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $this->class, $this->platform); - $joinCondition[] = $this->getSQLTableAlias($association['sourceEntity']) - . '.' . $sourceCol . ' = ' . $tableAlias . '.' . $targetCol; - } + $joinTableAlias = $this->getSQLTableAlias($eagerEntity->getTableName(), $assocAlias); + $joinTableName = $eagerEntity->table->getQuotedQualifiedName($this->platform); - // Add filter SQL - if ($filterSql = $this->generateFilterConditionSQL($eagerEntity, $tableAlias)) { - $joinCondition[] = $filterSql; - } + $this->currentPersisterContext->selectJoinSql .= ' ' . $this->getJoinSQLForAssociation($property); - } else { + $sourceClass = $this->em->getClassMetadata($owningAssociation->getSourceEntity()); + $targetClass = $this->em->getClassMetadata($owningAssociation->getTargetEntity()); + $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName(), $property->isOwningSide() ? $assocAlias : ''); + $sourceTableAlias = $this->getSQLTableAlias($sourceClass->getTableName(), $property->isOwningSide() ? '' : $assocAlias); - $this->currentPersisterContext->selectJoinSql .= ' LEFT JOIN'; + foreach ($owningAssociation->getJoinColumns() as $joinColumn) { + $joinCondition[] = sprintf( + '%s.%s = %s.%s', + $sourceTableAlias, + $this->platform->quoteIdentifier($joinColumn->getColumnName()), + $targetTableAlias, + $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName()) + ); + } - foreach ($association['joinColumns'] as $joinColumn) { - $sourceCol = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform); - $targetCol = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $this->class, $this->platform); + // Add filter SQL + if ($filterSql = $this->generateFilterConditionSQL($eagerEntity, $targetTableAlias)) { + $joinCondition[] = $filterSql; + } - $joinCondition[] = $this->getSQLTableAlias($association['sourceEntity'], $assocAlias) . '.' . $sourceCol . ' = ' - . $this->getSQLTableAlias($association['targetEntity']) . '.' . $targetCol; - } - } + $this->currentPersisterContext->selectJoinSql .= ' ' . $joinTableName . ' ' . $joinTableAlias . ' ON '; + $this->currentPersisterContext->selectJoinSql .= implode(' AND ', $joinCondition); - $this->currentPersisterContext->selectJoinSql .= ' ' . $joinTableName . ' ' . $joinTableAlias . ' ON '; - $this->currentPersisterContext->selectJoinSql .= implode(' AND ', $joinCondition); + break; + } } $this->currentPersisterContext->selectColumnListSql = implode(', ', $columnList); @@ -1323,32 +1384,43 @@ protected function getSelectColumnsSQL() /** * Gets the SQL join fragment used when selecting entities from an association. * - * @param string $field - * @param array $assoc - * @param ClassMetadata $class - * @param string $alias + * @param string $field + * @param AssociationMetadata $association + * @param ClassMetadata $class + * @param string $alias * * @return string */ - protected function getSelectColumnAssociationSQL($field, $assoc, ClassMetadata $class, $alias = 'r') + protected function getSelectColumnAssociationSQL($field, AssociationMetadata $association, ClassMetadata $class, $alias = 'r') { - if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) ) { + if (! ($association->isOwningSide() && $association instanceof ToOneAssociationMetadata)) { return ''; } $columnList = []; - $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); - $isIdentifier = isset($assoc['id']) && $assoc['id'] === true; - $sqlTableAlias = $this->getSQLTableAlias($class->name, ($alias == 'r' ? '' : $alias)); - - foreach ($assoc['joinColumns'] as $joinColumn) { - $quotedColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform); - $resultColumnName = $this->getSQLColumnAlias($joinColumn['name']); - $type = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); + $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); + $sqlTableAlias = $this->getSQLTableAlias($class->getTableName(), ($alias == 'r' ? '' : $alias)); + + foreach ($association->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $columnName = $joinColumn->getColumnName(); + $quotedColumnName = $this->platform->quoteIdentifier($columnName); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + $resultColumnName = $this->getSQLColumnAlias(); + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); + } - $this->currentPersisterContext->rsm->addMetaResult($alias, $resultColumnName, $joinColumn['name'], $isIdentifier, $type); + $this->currentPersisterContext->rsm->addMetaResult( + $alias, + $resultColumnName, + $columnName, + $association->isPrimaryKey(), + $joinColumn->getType() + ); - $columnList[] = sprintf('%s.%s AS %s', $sqlTableAlias, $quotedColumn, $resultColumnName); + $columnList[] = sprintf('%s.%s AS %s', $sqlTableAlias, $quotedColumnName, $resultColumnName); } return implode(', ', $columnList); @@ -1358,30 +1430,36 @@ protected function getSelectColumnAssociationSQL($field, $assoc, ClassMetadata $ * Gets the SQL join fragment used when selecting entities from a * many-to-many association. * - * @param array $manyToMany + * @param ManyToManyAssociationMetadata $manyToMany * * @return string */ - protected function getSelectManyToManyJoinSQL(array $manyToMany) + protected function getSelectManyToManyJoinSQL(ManyToManyAssociationMetadata $association) { - $conditions = []; - $association = $manyToMany; - $sourceTableAlias = $this->getSQLTableAlias($this->class->name); + $conditions = []; + $owningAssociation = $association; + $sourceTableAlias = $this->getSQLTableAlias($this->class->getTableName()); - if ( ! $manyToMany['isOwningSide']) { - $targetEntity = $this->em->getClassMetadata($manyToMany['targetEntity']); - $association = $targetEntity->associationMappings[$manyToMany['mappedBy']]; + if (! $association->isOwningSide()) { + $targetEntity = $this->em->getClassMetadata($association->getTargetEntity()); + $owningAssociation = $targetEntity->getProperty($association->getMappedBy()); } - $joinTableName = $this->quoteStrategy->getJoinTableName($association, $this->class, $this->platform); - $joinColumns = ($manyToMany['isOwningSide']) - ? $association['joinTable']['inverseJoinColumns'] - : $association['joinTable']['joinColumns']; + $joinTable = $owningAssociation->getJoinTable(); + $joinTableName = $joinTable->getQuotedQualifiedName($this->platform); + $joinColumns = $association->isOwningSide() + ? $joinTable->getInverseJoinColumns() + : $joinTable->getJoinColumns() + ; foreach ($joinColumns as $joinColumn) { - $quotedSourceColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform); - $quotedTargetColumn = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $this->class, $this->platform); - $conditions[] = $sourceTableAlias . '.' . $quotedTargetColumn . ' = ' . $joinTableName . '.' . $quotedSourceColumn; + $conditions[] = sprintf( + '%s.%s = %s.%s', + $sourceTableAlias, + $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName()), + $joinTableName, + $this->platform->quoteIdentifier($joinColumn->getColumnName()) + ); } return ' INNER JOIN ' . $joinTableName . ' ON ' . implode(' AND ', $conditions); @@ -1397,35 +1475,31 @@ public function getInsertSQL() } $columns = $this->getInsertColumnList(); - $tableName = $this->quoteStrategy->getTableName($this->class, $this->platform); + $tableName = $this->class->table->getQuotedQualifiedName($this->platform); if (empty($columns)) { - $identityColumn = $this->quoteStrategy->getColumnName($this->class->identifier[0], $this->class, $this->platform); + $property = $this->class->getProperty($this->class->identifier[0]); + $identityColumn = $this->platform->quoteIdentifier($property->getColumnName()); + $this->insertSql = $this->platform->getEmptyIdentityInsertSQL($tableName, $identityColumn); return $this->insertSql; } - $values = []; - $columns = array_unique($columns); - - foreach ($columns as $column) { - $placeholder = '?'; + $quotedColumns = []; + $values = []; - if (isset($this->class->fieldNames[$column]) - && isset($this->columnTypes[$this->class->fieldNames[$column]]) - && isset($this->class->fieldMappings[$this->class->fieldNames[$column]]['requireSQLConversion'])) { - $type = Type::getType($this->columnTypes[$this->class->fieldNames[$column]]); - $placeholder = $type->convertToDatabaseValueSQL('?', $this->platform); - } + foreach ($columns as $columnName) { + $column = $this->columns[$columnName]; - $values[] = $placeholder; + $quotedColumns[] = $this->platform->quoteIdentifier($column->getColumnName()); + $values[] = $column->getType()->convertToDatabaseValueSQL('?', $this->platform); } - $columns = implode(', ', $columns); - $values = implode(', ', $values); + $quotedColumns = implode(', ', $quotedColumns); + $values = implode(', ', $values); - $this->insertSql = sprintf('INSERT INTO %s (%s) VALUES (%s)', $tableName, $columns, $values); + $this->insertSql = sprintf('INSERT INTO %s (%s) VALUES (%s)', $tableName, $quotedColumns, $values); return $this->insertSql; } @@ -1440,32 +1514,60 @@ public function getInsertSQL() */ protected function getInsertColumnList() { - $columns = []; - - foreach ($this->class->reflFields as $name => $field) { - if ($this->class->isVersioned && $this->class->versionField == $name) { + $columns = []; + $versionPropertyName = $this->class->isVersioned() + ? $this->class->versionProperty->getName() + : null + ; + + foreach ($this->class->getDeclaredPropertiesIterator() as $name => $property) { + /*if (isset($this->class->embeddedClasses[$name])) { continue; - } + }*/ - if (isset($this->class->embeddedClasses[$name])) { - continue; - } + switch (true) { + case ($property instanceof VersionFieldMetadata): + // Do nothing + break; + + case ($property instanceof LocalColumnMetadata): + if (($property instanceof FieldMetadata + && ( + ! $property->hasValueGenerator() + || $property->getValueGenerator()->getType() !== GeneratorType::IDENTITY + ) + ) + || $this->class->identifier[0] !== $name + ) { + $columnName = $property->getColumnName(); - if (isset($this->class->associationMappings[$name])) { - $assoc = $this->class->associationMappings[$name]; + $columns[] = $columnName; - if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) { - foreach ($assoc['joinColumns'] as $joinColumn) { - $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform); + $this->columns[$columnName] = $property; } - } - continue; - } + break; + + case ($property instanceof AssociationMetadata): + if ($property->isOwningSide() && $property instanceof ToOneAssociationMetadata) { + $targetClass = $this->em->getClassMetadata($property->getTargetEntity()); - if (! $this->class->isIdGeneratorIdentity() || $this->class->identifier[0] != $name) { - $columns[] = $this->quoteStrategy->getColumnName($name, $this->class, $this->platform); - $this->columnTypes[$name] = $this->class->fieldMappings[$name]['type']; + foreach ($property->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $columnName = $joinColumn->getColumnName(); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); + } + + $columns[] = $columnName; + + $this->columns[$columnName] = $joinColumn; + } + } + + break; } } @@ -1484,45 +1586,40 @@ protected function getInsertColumnList() */ protected function getSelectColumnSQL($field, ClassMetadata $class, $alias = 'r') { - $root = $alias == 'r' ? '' : $alias ; - $tableAlias = $this->getSQLTableAlias($class->name, $root); - $fieldMapping = $class->fieldMappings[$field]; - $sql = sprintf('%s.%s', $tableAlias, $this->quoteStrategy->getColumnName($field, $class, $this->platform)); - $columnAlias = $this->getSQLColumnAlias($fieldMapping['columnName']); + $property = $class->getProperty($field); + $columnAlias = $this->getSQLColumnAlias(); + $sql = sprintf( + '%s.%s', + $this->getSQLTableAlias($property->getTableName(), ($alias == 'r' ? '' : $alias)), + $this->platform->quoteIdentifier($property->getColumnName()) + ); - $this->currentPersisterContext->rsm->addFieldResult($alias, $columnAlias, $field); + $this->currentPersisterContext->rsm->addFieldResult($alias, $columnAlias, $field, $class->getClassName()); - if (isset($fieldMapping['requireSQLConversion'])) { - $type = Type::getType($fieldMapping['type']); - $sql = $type->convertToPHPValueSQL($sql, $this->platform); - } - - return $sql . ' AS ' . $columnAlias; + return $property->getType()->convertToPHPValueSQL($sql, $this->platform) . ' AS ' . $columnAlias; } /** * Gets the SQL table alias for the given class name. * - * @param string $className + * @param string $tableName * @param string $assocName * * @return string The SQL table alias. - * - * @todo Reconsider. Binding table aliases to class names is not such a good idea. */ - protected function getSQLTableAlias($className, $assocName = '') + protected function getSQLTableAlias($tableName, $assocName = '') { - if ($assocName) { - $className .= '#' . $assocName; + if ($tableName) { + $tableName .= '#' . $assocName; } - if (isset($this->currentPersisterContext->sqlTableAliases[$className])) { - return $this->currentPersisterContext->sqlTableAliases[$className]; + if (isset($this->currentPersisterContext->sqlTableAliases[$tableName])) { + return $this->currentPersisterContext->sqlTableAliases[$tableName]; } $tableAlias = 't' . $this->currentPersisterContext->sqlAliasCounter++; - $this->currentPersisterContext->sqlTableAliases[$className] = $tableAlias; + $this->currentPersisterContext->sqlTableAliases[$tableName] = $tableAlias; return $tableAlias; } @@ -1567,10 +1664,10 @@ public function lock(array $criteria, $lockMode) */ protected function getLockTablesSql($lockMode) { + $tableName = $this->class->table->getQuotedQualifiedName($this->platform); + return $this->platform->appendLockHint( - 'FROM ' - . $this->quoteStrategy->getTableName($this->class, $this->platform) . ' ' - . $this->getSQLTableAlias($this->class->name), + 'FROM ' . $tableName . ' ' . $this->getSQLTableAlias($this->class->getTableName()), $lockMode ); } @@ -1598,25 +1695,27 @@ protected function getSelectConditionCriteriaSQL(Criteria $criteria) /** * {@inheritdoc} */ - public function getSelectConditionStatementSQL($field, $value, $assoc = null, $comparison = null) + public function getSelectConditionStatementSQL( + $field, + $value, + AssociationMetadata $association = null, + $comparison = null + ) { $selectedColumns = []; - $columns = $this->getSelectConditionStatementColumnSQL($field, $assoc); + $columns = $this->getSelectConditionStatementColumnSQL($field, $association); - if (count($columns) > 1 && $comparison === Comparison::IN) { - /* - * @todo try to support multi-column IN expressions. - * Example: (col1, col2) IN (('val1A', 'val2A'), ('val1B', 'val2B')) - */ + if (in_array($comparison, [Comparison::IN, Comparison::NIN]) && isset($columns[1])) { + // @todo try to support multi-column IN expressions. Example: (col1, col2) IN (('val1A', 'val2A'), ...) throw ORMException::cantUseInOperatorOnCompositeKeys(); } foreach ($columns as $column) { + $property = $this->class->getProperty($field); $placeholder = '?'; - if (isset($this->class->fieldMappings[$field]['requireSQLConversion'])) { - $type = Type::getType($this->class->fieldMappings[$field]['type']); - $placeholder = $type->convertToDatabaseValueSQL($placeholder, $this->platform); + if ($property instanceof FieldMetadata) { + $placeholder = $property->getType()->convertToDatabaseValueSQL($placeholder, $this->platform); } if (null !== $comparison) { @@ -1667,61 +1766,69 @@ public function getSelectConditionStatementSQL($field, $value, $assoc = null, $c /** * Builds the left-hand-side of a where condition statement. * - * @param string $field - * @param array|null $assoc + * @param string $field + * @param AssociationMetadata|null $association * * @return string[] * * @throws \Doctrine\ORM\ORMException */ - private function getSelectConditionStatementColumnSQL($field, $assoc = null) + private function getSelectConditionStatementColumnSQL($field, AssociationMetadata $association = null) { - if (isset($this->class->fieldMappings[$field])) { - $className = (isset($this->class->fieldMappings[$field]['inherited'])) - ? $this->class->fieldMappings[$field]['inherited'] - : $this->class->name; + $property = $this->class->getProperty($field); + + if ($property instanceof FieldMetadata) { + $tableAlias = $this->getSQLTableAlias($property->getTableName()); + $columnName = $this->platform->quoteIdentifier($property->getColumnName()); - return [$this->getSQLTableAlias($className) . '.' . $this->quoteStrategy->getColumnName($field, $this->class, $this->platform)]; + return [$tableAlias . '.' . $columnName]; } - if (isset($this->class->associationMappings[$field])) { - $association = $this->class->associationMappings[$field]; - // Many-To-Many requires join table check for joinColumn + if ($property instanceof AssociationMetadata) { + $owningAssociation = $property; $columns = []; - $class = $this->class; - if ($association['type'] === ClassMetadata::MANY_TO_MANY) { - if ( ! $association['isOwningSide']) { - $association = $assoc; + // Many-To-Many requires join table check for joinColumn + if ($owningAssociation instanceof ManyToManyAssociationMetadata) { + if (! $owningAssociation->isOwningSide()) { + $owningAssociation = $association; } - $joinTableName = $this->quoteStrategy->getJoinTableName($association, $class, $this->platform); - $joinColumns = $assoc['isOwningSide'] - ? $association['joinTable']['joinColumns'] - : $association['joinTable']['inverseJoinColumns']; - + $joinTable = $owningAssociation->getJoinTable(); + $joinTableName = $joinTable->getQuotedQualifiedName($this->platform); + $joinColumns = $association->isOwningSide() + ? $joinTable->getJoinColumns() + : $joinTable->getInverseJoinColumns() + ; foreach ($joinColumns as $joinColumn) { - $columns[] = $joinTableName . '.' . $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + + $columns[] = $joinTableName . '.' . $quotedColumnName; } } else { - if ( ! $association['isOwningSide']) { - throw ORMException::invalidFindByInverseAssociation($this->class->name, $field); + if (! $owningAssociation->isOwningSide()) { + throw ORMException::invalidFindByInverseAssociation($this->class->getClassName(), $field); } - $className = (isset($association['inherited'])) - ? $association['inherited'] - : $this->class->name; + $class = $this->class->isInheritedProperty($field) + ? $owningAssociation->getDeclaringClass() + : $this->class + ; + $tableAlias = $this->getSQLTableAlias($class->getTableName()); + + foreach ($owningAssociation->getJoinColumns() as $joinColumn) { + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); - foreach ($association['joinColumns'] as $joinColumn) { - $columns[] = $this->getSQLTableAlias($className) . '.' . $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform); + $columns[] = $tableAlias . '.' . $quotedColumnName; } } + return $columns; } - if ($assoc !== null && strpos($field, " ") === false && strpos($field, "(") === false) { + if ($association !== null && strpos($field, ' ') === false && strpos($field, '(') === false) { // very careless developers could potentially open up this normally hidden api for userland attacks, // therefore checking for spaces and function calls which are not allowed. @@ -1739,17 +1846,17 @@ private function getSelectConditionStatementColumnSQL($field, $assoc = null) * Subclasses are supposed to override this method if they intend to change * or alter the criteria by which entities are selected. * - * @param array $criteria - * @param array|null $assoc + * @param array $criteria + * @param AssociationMetadata|null $association * * @return string */ - protected function getSelectConditionSQL(array $criteria, $assoc = null) + protected function getSelectConditionSQL(array $criteria, AssociationMetadata $association = null) { $conditions = []; foreach ($criteria as $field => $value) { - $conditions[] = $this->getSelectConditionStatementSQL($field, $value, $assoc); + $conditions[] = $this->getSelectConditionStatementSQL($field, $value, $association); } return implode(' AND ', $conditions); @@ -1758,78 +1865,84 @@ protected function getSelectConditionSQL(array $criteria, $assoc = null) /** * {@inheritdoc} */ - public function getOneToManyCollection(array $assoc, $sourceEntity, $offset = null, $limit = null) + public function getOneToManyCollection( + OneToManyAssociationMetadata $association, + $sourceEntity, + $offset = null, + $limit = null + ) { $this->switchPersisterContext($offset, $limit); - $stmt = $this->getOneToManyStatement($assoc, $sourceEntity, $offset, $limit); + $stmt = $this->getOneToManyStatement($association, $sourceEntity, $offset, $limit); - return $this->loadArrayFromStatement($assoc, $stmt); + return $this->loadArrayFromStatement($association, $stmt); } /** * {@inheritdoc} */ - public function loadOneToManyCollection(array $assoc, $sourceEntity, PersistentCollection $coll) + public function loadOneToManyCollection( + OneToManyAssociationMetadata $association, + $sourceEntity, + PersistentCollection $collection + ) { - $stmt = $this->getOneToManyStatement($assoc, $sourceEntity); + $stmt = $this->getOneToManyStatement($association, $sourceEntity); - return $this->loadCollectionFromStatement($assoc, $stmt, $coll); + return $this->loadCollectionFromStatement($association, $stmt, $collection); } /** * Builds criteria and execute SQL statement to fetch the one to many entities from. * - * @param array $assoc - * @param object $sourceEntity - * @param int|null $offset - * @param int|null $limit + * @param OneToManyAssociationMetadata $association + * @param object $sourceEntity + * @param int|null $offset + * @param int|null $limit * * @return \Doctrine\DBAL\Statement */ - private function getOneToManyStatement(array $assoc, $sourceEntity, $offset = null, $limit = null) + private function getOneToManyStatement( + OneToManyAssociationMetadata $association, + $sourceEntity, + $offset = null, + $limit = null + ) { $this->switchPersisterContext($offset, $limit); $criteria = []; $parameters = []; - $owningAssoc = $this->class->associationMappings[$assoc['mappedBy']]; - $sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']); - $tableAlias = $this->getSQLTableAlias(isset($owningAssoc['inherited']) ? $owningAssoc['inherited'] : $this->class->name); - - foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) { - if ($sourceClass->containsForeignIdentifier) { - $field = $sourceClass->getFieldForColumn($sourceKeyColumn); - $value = $sourceClass->reflFields[$field]->getValue($sourceEntity); - - if (isset($sourceClass->associationMappings[$field])) { - $value = $this->em->getUnitOfWork()->getEntityIdentifier($value); - $value = $value[$this->em->getClassMetadata($sourceClass->associationMappings[$field]['targetEntity'])->identifier[0]]; - } - - $criteria[$tableAlias . "." . $targetKeyColumn] = $value; - $parameters[] = [ - 'value' => $value, - 'field' => $field, - 'class' => $sourceClass, - ]; - - continue; + $owningAssoc = $this->class->getProperty($association->getMappedBy()); + $sourceClass = $this->em->getClassMetadata($association->getSourceEntity()); + $class = $owningAssoc->getDeclaringClass(); + $tableAlias = $this->getSQLTableAlias($class->getTableName()); + + foreach ($owningAssoc->getJoinColumns() as $joinColumn) { + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $fieldName = $sourceClass->fieldNames[$joinColumn->getReferencedColumnName()]; + $property = $sourceClass->getProperty($fieldName); + + if ($property instanceof FieldMetadata) { + $value = $property->getValue($sourceEntity); + } else if ($property instanceof AssociationMetadata) { + $targetClass = $this->em->getClassMetadata($property->getTargetEntity()); + $value = $property->getValue($sourceEntity); + + $value = $this->em->getUnitOfWork()->getEntityIdentifier($value); + $value = $value[$targetClass->identifier[0]]; } - $field = $sourceClass->fieldNames[$sourceKeyColumn]; - $value = $sourceClass->reflFields[$field]->getValue($sourceEntity); - - $criteria[$tableAlias . "." . $targetKeyColumn] = $value; + $criteria[$tableAlias . "." . $quotedColumnName] = $value; $parameters[] = [ 'value' => $value, - 'field' => $field, + 'field' => $fieldName, 'class' => $sourceClass, ]; - } - $sql = $this->getSelectSQL($criteria, $assoc, null, $limit, $offset); + $sql = $this->getSelectSQL($criteria, $association, null, $limit, $offset); list($params, $types) = $this->expandToManyParameters($parameters); return $this->conn->executeQuery($sql, $params, $types); @@ -1897,29 +2010,38 @@ private function expandToManyParameters($criteria) */ private function getTypes($field, $value, ClassMetadata $class) { - $types = []; + $property = $class->getProperty($field); + $types = []; switch (true) { - case (isset($class->fieldMappings[$field])): - $types = array_merge($types, [$class->fieldMappings[$field]['type']]); + case ($property instanceof FieldMetadata): + $types = array_merge($types, [$property->getType()]); break; - case (isset($class->associationMappings[$field])): - $assoc = $class->associationMappings[$field]; - $class = $this->em->getClassMetadata($assoc['targetEntity']); + case ($property instanceof AssociationMetadata): + $class = $this->em->getClassMetadata($property->getTargetEntity()); - if (! $assoc['isOwningSide']) { - $assoc = $class->associationMappings[$assoc['mappedBy']]; - $class = $this->em->getClassMetadata($assoc['targetEntity']); + if (! $property->isOwningSide()) { + $property = $class->getProperty($property->getMappedBy()); + $class = $this->em->getClassMetadata($property->getTargetEntity()); } - $columns = $assoc['type'] === ClassMetadata::MANY_TO_MANY - ? $assoc['relationToTargetKeyColumns'] - : $assoc['sourceToTargetKeyColumns']; + $joinColumns = $property instanceof ManyToManyAssociationMetadata + ? $property->getJoinTable()->getInverseJoinColumns() + : $property->getJoinColumns() + ; - foreach ($columns as $column){ - $types[] = PersisterHelper::getTypeOfColumn($column, $class, $this->em); + foreach ($joinColumns as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $referencedColumnName = $joinColumn->getReferencedColumnName(); + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $class, $this->em)); + } + + $types[] = $joinColumn->getType(); } + break; default: @@ -1929,8 +2051,6 @@ private function getTypes($field, $value, ClassMetadata $class) if (is_array($value)) { return array_map(function ($type) { - $type = Type::getType($type); - return $type->getBindingType() + Connection::ARRAY_PARAM_OFFSET; }, $types); } @@ -1957,12 +2077,17 @@ private function getValues($value) return [$newValue]; } - if (is_object($value) && $this->em->getMetadataFactory()->hasMetadataFor(ClassUtils::getClass($value))) { - $class = $this->em->getClassMetadata(get_class($value)); - if ($class->isIdentifierComposite) { + $metadataFactory = $this->em->getMetadataFactory(); + $unitOfWork = $this->em->getUnitOfWork(); + + if (is_object($value) && $metadataFactory->hasMetadataFor(ClassUtils::getClass($value))) { + $class = $metadataFactory->getMetadataFor(get_class($value)); + $persister = $unitOfWork->getEntityPersister($class->getClassName()); + + if ($class->isIdentifierComposite()) { $newValue = []; - foreach ($class->getIdentifierValues($value) as $innerValue) { + foreach ($persister->getIdentifier($value) as $innerValue) { $newValue = array_merge($newValue, $this->getValues($innerValue)); } @@ -1994,13 +2119,13 @@ private function getIndividualValue($value) */ public function exists($entity, Criteria $extraConditions = null) { - $criteria = $this->class->getIdentifierValues($entity); + $criteria = $this->getIdentifier($entity); if ( ! $criteria) { return false; } - $alias = $this->getSQLTableAlias($this->class->name); + $alias = $this->getSQLTableAlias($this->class->getTableName()); $sql = 'SELECT 1 ' . $this->getLockTablesSql(null) @@ -2024,30 +2149,38 @@ public function exists($entity, Criteria $extraConditions = null) } /** - * Generates the appropriate join SQL for the given join column. + * Generates the appropriate join SQL for the given association. * - * @param array $joinColumns The join columns definition of an association. + * @param AssociationMetadata $association * * @return string LEFT JOIN if one of the columns is nullable, INNER JOIN otherwise. */ - protected function getJoinSQLForJoinColumns($joinColumns) + protected function getJoinSQLForAssociation(AssociationMetadata $association) { + if (! $association->isOwningSide()) { + return 'LEFT JOIN'; + } + // if one of the join columns is nullable, return left join - foreach ($joinColumns as $joinColumn) { - if ( ! isset($joinColumn['nullable']) || $joinColumn['nullable']) { - return 'LEFT JOIN'; + foreach ($association->getJoinColumns() as $joinColumn) { + if (! $joinColumn->isNullable()) { + continue; } + + return 'LEFT JOIN'; } return 'INNER JOIN'; } /** - * {@inheritdoc} + * Gets an SQL column alias for a column name. + * + * @return string */ - public function getSQLColumnAlias($columnName) + public function getSQLColumnAlias() { - return $this->quoteStrategy->getColumnAlias($columnName, $this->currentPersisterContext->sqlAliasCounter++, $this->platform); + return $this->platform->getSQLResultCasing('c' . $this->currentPersisterContext->sqlAliasCounter++); } /** diff --git a/lib/Doctrine/ORM/Persisters/Entity/CachedPersisterContext.php b/lib/Doctrine/ORM/Persisters/Entity/CachedPersisterContext.php index 132dac7e4de..aa24a44a419 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/CachedPersisterContext.php +++ b/lib/Doctrine/ORM/Persisters/Entity/CachedPersisterContext.php @@ -1,24 +1,10 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Persisters\Entity; -use Doctrine\Common\Persistence\Mapping\ClassMetadata; + +use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Query\ResultSetMapping; /** @@ -58,7 +44,7 @@ class CachedPersisterContext /** * The JOIN SQL fragment used to eagerly load all many-to-one and one-to-one - * associations configured as FETCH_EAGER, as well as all inverse one-to-one associations. + * associations configured as FetchMode::EAGER, as well as all inverse one-to-one associations. * * @var string */ diff --git a/lib/Doctrine/ORM/Persisters/Entity/EntityPersister.php b/lib/Doctrine/ORM/Persisters/Entity/EntityPersister.php index 9ac63166832..3f2844814bb 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/EntityPersister.php +++ b/lib/Doctrine/ORM/Persisters/Entity/EntityPersister.php @@ -1,24 +1,14 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Persisters\Entity; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata; +use Doctrine\ORM\Mapping\OneToManyAssociationMetadata; +use Doctrine\ORM\Mapping\OneToOneAssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; use Doctrine\ORM\PersistentCollection; use Doctrine\Common\Collections\Criteria; @@ -44,35 +34,55 @@ public function getClassMetadata(); public function getResultSetMapping(); /** - * Get all queued inserts. + * Extracts the identifier values of an entity that relies on this persister. + * + * For composite identifiers, the identifier values are returned as an array + * with the same order as the field order in {@link ClassMetadata#identifier}. + * + * @param object $entity * * @return array - */ - public function getInserts(); + */ + public function getIdentifier($entity) : array; - /** - * @TODO - It should not be here. - * But its necessary since JoinedSubclassPersister#executeInserts invoke the root persister. + /** + * Populates the entity identifier of an entity. * - * Gets the INSERT SQL used by the persister to persist a new entity. + * @param object $entity + * @param array $id * - * @return string + * @return void + */ + public function setIdentifier($entity, array $id) : void; + + /** + * @param object $entity + * @param string $columnName + * + * @return mixed|null */ - public function getInsertSQL(); + public function getColumnValue($entity, string $columnName); /** * Gets the SELECT SQL to select one or more entities by a set of field criteria. * * @param array|\Doctrine\Common\Collections\Criteria $criteria - * @param array|null $assoc + * @param AssociationMetadata|null $association * @param int|null $lockMode * @param int|null $limit * @param int|null $offset - * @param array|null $orderBy + * @param array $orderBy * * @return string */ - public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit = null, $offset = null, array $orderBy = null); + public function getSelectSQL( + $criteria, + AssociationMetadata $association = null, + $lockMode = null, + $limit = null, + $offset = null, + array $orderBy = [] + ); /** * Get the COUNT SQL to count entities (optionally based on a criteria) @@ -104,39 +114,35 @@ public function expandCriteriaParameters(Criteria $criteria); /** * Gets the SQL WHERE condition for matching a field with a given value. * - * @param string $field - * @param mixed $value - * @param array|null $assoc - * @param string|null $comparison + * @param string $field + * @param mixed $value + * @param AssociationMetadata|null $association + * @param string|null $comparison * * @return string */ - public function getSelectConditionStatementSQL($field, $value, $assoc = null, $comparison = null); + public function getSelectConditionStatementSQL( + $field, + $value, + AssociationMetadata $association = null, + $comparison = null + ); /** - * Adds an entity to the queued insertions. - * The entity remains queued until {@link executeInserts} is invoked. + * Inserts an entity. Returns any generated post-insert identifiers that were created as a result of the insertion. + * The insertion happens instantaneously. * - * @param object $entity The entity to queue for insertion. + * Subclasses may override this method to customize the semantics of entity deletion. * * @return void */ - public function addInsert($entity); + public function insert($entity); /** - * Executes all queued entity insertions and returns any generated post-insert - * identifiers that were created as a result of the insertions. + * Updates a managed entity. The entity is updated according to its current changeset in the running UnitOfWork. + * If there is no changeset, nothing is updated. * - * If no inserts are queued, invoking this method is a NOOP. - * - * @return array An array of any generated post-insert IDs. This will be an empty array - * if the entity class does not use the IDENTITY generation strategy. - */ - public function executeInserts(); - - /** - * Updates a managed entity. The entity is updated according to its current changeset - * in the running UnitOfWork. If there is no changeset, nothing is updated. + * Subclasses may override this method to customize the semantics of entity update. * * @param object $entity The entity to update. * @@ -147,8 +153,7 @@ public function update($entity); /** * Deletes a managed entity. * - * The entity to delete must be managed and have a persistent identifier. - * The deletion happens instantaneously. + * The entity to delete must be managed and have a persistent identifier. The deletion happens instantaneously. * * Subclasses may override this method to customize the semantics of entity deletion. * @@ -168,36 +173,64 @@ public function delete($entity); public function count($criteria = []); /** - * Gets the name of the table that owns the column the given field is mapped to. + * Locks all rows of this entity matching the given criteria with the specified pessimistic lock mode. * - * The default implementation in BasicEntityPersister always returns the name - * of the table the entity type of this persister is mapped to, since an entity - * is always persisted to a single table with a BasicEntityPersister. + * @param array $criteria + * @param int $lockMode One of the Doctrine\DBAL\LockMode::* constants. * - * @param string $fieldName The field name. + * @return void + */ + public function lock(array $criteria, $lockMode); + + /** + * Checks whether the given managed entity exists in the database. + * + * @param object $entity + * @param Criteria|null $extraConditions * - * @return string The table name. + * @return boolean TRUE if the entity exists in the database, FALSE otherwise. */ - public function getOwningTable($fieldName); + public function exists($entity, Criteria $extraConditions = null); + + /** + * Refreshes a managed entity. + * + * @param array $id The identifier of the entity as an associative array from + * column or field names to values. + * @param object $entity The entity to refresh. + * @param int|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants + * or NULL if no specific lock mode should be used + * for refreshing the managed entity. + * + * @return void + */ + public function refresh(array $id, $entity, $lockMode = null); /** * Loads an entity by a list of field criteria. * - * @param array $criteria The criteria by which to load the entity. - * @param object|null $entity The entity to load the data into. If not specified, a new entity is created. - * @param array|null $assoc The association that connects the entity to load to another entity, if any. - * @param array $hints Hints for entity creation. - * @param int|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants - * or NULL if no specific lock mode should be used - * for loading the entity. - * @param int|null $limit Limit number of results. - * @param array|null $orderBy Criteria to order by. + * @param array $criteria The criteria by which to load the entity. + * @param object|null $entity The entity to load the data into. If not specified, a new entity is created. + * @param AssociationMetadata|null $association The association that connects the entity to load to another entity, if any. + * @param array $hints Hints for entity creation. + * @param int|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants or NULL if no specific lock mode + * should be used for loading the entity. + * @param int|null $limit Limit number of results. + * @param array $orderBy Criteria to order by. * * @return object|null The loaded and managed entity instance or NULL if the entity can not be found. * * @todo Check identity map? loadById method? Try to guess whether $criteria is the id? */ - public function load(array $criteria, $entity = null, $assoc = null, array $hints = [], $lockMode = null, $limit = null, array $orderBy = null); + public function load( + array $criteria, + $entity = null, + AssociationMetadata $association = null, + array $hints = [], + $lockMode = null, + $limit = null, + array $orderBy = [] + ); /** * Loads an entity by identifier. @@ -211,36 +244,6 @@ public function load(array $criteria, $entity = null, $assoc = null, array $hint */ public function loadById(array $identifier, $entity = null); - /** - * Loads an entity of this persister's mapped class as part of a single-valued - * association from another entity. - * - * @param array $assoc The association to load. - * @param object $sourceEntity The entity that owns the association (not necessarily the "owning side"). - * @param array $identifier The identifier of the entity to load. Must be provided if - * the association to load represents the owning side, otherwise - * the identifier is derived from the $sourceEntity. - * - * @return object The loaded and managed entity instance or NULL if the entity can not be found. - * - * @throws \Doctrine\ORM\Mapping\MappingException - */ - public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifier = []); - - /** - * Refreshes a managed entity. - * - * @param array $id The identifier of the entity as an associative array from - * column or field names to values. - * @param object $entity The entity to refresh. - * @param int|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants - * or NULL if no specific lock mode should be used - * for refreshing the managed entity. - * - * @return void - */ - public function refresh(array $id, $entity, $lockMode = null); - /** * Loads Entities matching the given Criteria object. * @@ -253,78 +256,96 @@ public function loadCriteria(Criteria $criteria); /** * Loads a list of entities by a list of field criteria. * - * @param array $criteria - * @param array|null $orderBy - * @param int|null $limit - * @param int|null $offset + * @param array $criteria + * @param array $orderBy + * @param int|null $limit Limit number of results. + * @param int|null $offset * * @return array */ - public function loadAll(array $criteria = [], array $orderBy = null, $limit = null, $offset = null); + public function loadAll(array $criteria = [], array $orderBy = [], $limit = null, $offset = null); /** - * Gets (sliced or full) elements of the given collection. + * Loads an entity of this persister's mapped class as part of a single-valued + * association from another entity. * - * @param array $assoc - * @param object $sourceEntity - * @param int|null $offset - * @param int|null $limit + * @param ToOneAssociationMetadata $association The association to load. + * @param object $sourceEntity The entity that owns the association (not necessarily the "owning side"). + * @param array $identifier The identifier of the entity to load. Must be provided if + * the association to load represents the owning side, otherwise + * the identifier is derived from the $sourceEntity. * - * @return array + * @return object The loaded and managed entity instance or NULL if the entity can not be found. + * + * @throws \Doctrine\ORM\Mapping\MappingException */ - public function getManyToManyCollection(array $assoc, $sourceEntity, $offset = null, $limit = null); + public function loadToOneEntity( + ToOneAssociationMetadata $association, + $sourceEntity, + array $identifier = [] + ); /** - * Loads a collection of entities of a many-to-many association. + * Returns an array with (sliced or full list) of elements in the specified collection. * - * @param array $assoc The association mapping of the association being loaded. - * @param object $sourceEntity The entity that owns the collection. - * @param PersistentCollection $collection The collection to fill. + * @param OneToManyAssociationMetadata $association The association mapping of the association being loaded. + * @param object $sourceEntity The entity that owns the collection. + * @param int|null $offset + * @param int|null $limit Limit number of results. * * @return array */ - public function loadManyToManyCollection(array $assoc, $sourceEntity, PersistentCollection $collection); + public function getOneToManyCollection( + OneToManyAssociationMetadata $association, + $sourceEntity, + $offset = null, + $limit = null + ); /** * Loads a collection of entities in a one-to-many association. * - * @param array $assoc - * @param object $sourceEntity - * @param PersistentCollection $collection The collection to load/fill. + * @param OneToManyAssociationMetadata $association The association mapping of the association being loaded. + * @param object $sourceEntity The entity that owns the collection. + * @param PersistentCollection $collection The collection to load/fill. * * @return array */ - public function loadOneToManyCollection(array $assoc, $sourceEntity, PersistentCollection $collection); + public function loadOneToManyCollection( + OneToManyAssociationMetadata $association, + $sourceEntity, + PersistentCollection $collection + ); /** - * Locks all rows of this entity matching the given criteria with the specified pessimistic lock mode. - * - * @param array $criteria - * @param int $lockMode One of the Doctrine\DBAL\LockMode::* constants. - * - * @return void - */ - public function lock(array $criteria, $lockMode); - - /** - * Returns an array with (sliced or full list) of elements in the specified collection. + * Gets (sliced or full) elements of the given collection. * - * @param array $assoc - * @param object $sourceEntity - * @param int|null $offset - * @param int|null $limit + * @param ManyToManyAssociationMetadata $association The association mapping of the association being loaded. + * @param object $sourceEntity The entity that owns the collection. + * @param int|null $offset + * @param int|null $limit Limit number of results. * * @return array */ - public function getOneToManyCollection(array $assoc, $sourceEntity, $offset = null, $limit = null); + public function getManyToManyCollection( + ManyToManyAssociationMetadata $association, + $sourceEntity, + $offset = null, + $limit = null + ); /** - * Checks whether the given managed entity exists in the database. + * Loads a collection of entities of a many-to-many association. * - * @param object $entity - * @param Criteria|null $extraConditions + * @param ManyToManyAssociationMetadata $association The association mapping of the association being loaded. + * @param object $sourceEntity The entity that owns the collection. + * @param PersistentCollection $collection The collection to load/fill. * - * @return boolean TRUE if the entity exists in the database, FALSE otherwise. + * @return array */ - public function exists($entity, Criteria $extraConditions = null); + public function loadManyToManyCollection( + ManyToManyAssociationMetadata $association, + $sourceEntity, + PersistentCollection $collection + ); } diff --git a/lib/Doctrine/ORM/Persisters/Entity/JoinedSubclassPersister.php b/lib/Doctrine/ORM/Persisters/Entity/JoinedSubclassPersister.php index 0be15068977..2a414b669ee 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/JoinedSubclassPersister.php +++ b/lib/Doctrine/ORM/Persisters/Entity/JoinedSubclassPersister.php @@ -1,30 +1,22 @@ . - */ -namespace Doctrine\ORM\Persisters\Entity; +declare(strict_types=1); -use Doctrine\ORM\Mapping\ClassMetadata; +namespace Doctrine\ORM\Persisters\Entity; +use Doctrine\Common\Collections\Criteria; use Doctrine\DBAL\LockMode; use Doctrine\DBAL\Types\Type; - -use Doctrine\Common\Collections\Criteria; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\ColumnMetadata; +use Doctrine\ORM\Mapping\FieldMetadata; +use Doctrine\ORM\Mapping\GeneratorType; +use Doctrine\ORM\Mapping\JoinColumnMetadata; +use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; +use Doctrine\ORM\Mapping\VersionFieldMetadata; use Doctrine\ORM\Utility\PersisterHelper; /** @@ -39,106 +31,18 @@ */ class JoinedSubclassPersister extends AbstractEntityInheritancePersister { - /** - * Map that maps column names to the table names that own them. - * This is mainly a temporary cache, used during a single request. - * - * @var array - */ - private $owningTableMap = []; - - /** - * Map of table to quoted table names. - * - * @var array - */ - private $quotedTableMap = []; - - /** - * {@inheritdoc} - */ - protected function getDiscriminatorColumnTableName() - { - $class = ($this->class->name !== $this->class->rootEntityName) - ? $this->em->getClassMetadata($this->class->rootEntityName) - : $this->class; - - return $class->getTableName(); - } - - /** - * This function finds the ClassMetadata instance in an inheritance hierarchy - * that is responsible for enabling versioning. - * - * @return \Doctrine\ORM\Mapping\ClassMetadata - */ - private function getVersionedClassMetadata() - { - if (isset($this->class->fieldMappings[$this->class->versionField]['inherited'])) { - $definingClassName = $this->class->fieldMappings[$this->class->versionField]['inherited']; - - return $this->em->getClassMetadata($definingClassName); - } - - return $this->class; - } - - /** - * Gets the name of the table that owns the column the given field is mapped to. - * - * @param string $fieldName - * - * @return string - * - * @override - */ - public function getOwningTable($fieldName) - { - if (isset($this->owningTableMap[$fieldName])) { - return $this->owningTableMap[$fieldName]; - } - - switch (true) { - case isset($this->class->associationMappings[$fieldName]['inherited']): - $cm = $this->em->getClassMetadata($this->class->associationMappings[$fieldName]['inherited']); - break; - - case isset($this->class->fieldMappings[$fieldName]['inherited']): - $cm = $this->em->getClassMetadata($this->class->fieldMappings[$fieldName]['inherited']); - break; - - default: - $cm = $this->class; - break; - } - - $tableName = $cm->getTableName(); - $quotedTableName = $this->quoteStrategy->getTableName($cm, $this->platform); - - $this->owningTableMap[$fieldName] = $tableName; - $this->quotedTableMap[$tableName] = $quotedTableName; - - return $tableName; - } - /** * {@inheritdoc} */ - public function executeInserts() + public function insert($entity) { - if ( ! $this->queuedInserts) { - return []; - } - - $postInsertIds = []; - $idGenerator = $this->class->idGenerator; - $isPostInsertId = $idGenerator->isPostInsertGenerator(); - $rootClass = ($this->class->name !== $this->class->rootEntityName) - ? $this->em->getClassMetadata($this->class->rootEntityName) + $rootClass = ! $this->class->isRootEntity() + ? $this->em->getClassMetadata($this->class->getRootClassName()) : $this->class; + $generationPlan = $this->class->getValueGenerationPlan(); // Prepare statement for the root table - $rootPersister = $this->em->getUnitOfWork()->getEntityPersister($rootClass->name); + $rootPersister = $this->em->getUnitOfWork()->getEntityPersister($rootClass->getClassName()); $rootTableName = $rootClass->getTableName(); $rootTableStmt = $this->conn->prepare($rootPersister->getInsertSQL()); @@ -149,12 +53,14 @@ public function executeInserts() $subTableStmts[$this->class->getTableName()] = $this->conn->prepare($this->getInsertSQL()); } - foreach ($this->class->parentClasses as $parentClassName) { - $parentClass = $this->em->getClassMetadata($parentClassName); + $parentClass = $this->class; + + while (($parentClass = $parentClass->getParent()) !== null) { $parentTableName = $parentClass->getTableName(); if ($parentClass !== $rootClass) { - $parentPersister = $this->em->getUnitOfWork()->getEntityPersister($parentClassName); + $parentPersister = $this->em->getUnitOfWork()->getEntityPersister($parentClass->getClassName()); + $subTableStmts[$parentTableName] = $this->conn->prepare($parentPersister->getInsertSQL()); } } @@ -162,58 +68,59 @@ public function executeInserts() // Execute all inserts. For each entity: // 1) Insert on root table // 2) Insert on sub tables - foreach ($this->queuedInserts as $entity) { - $insertData = $this->prepareInsertData($entity); + $insertData = $this->prepareInsertData($entity); - // Execute insert on root table - $paramIndex = 1; + // Execute insert on root table + $paramIndex = 1; - foreach ($insertData[$rootTableName] as $columnName => $value) { - $rootTableStmt->bindValue($paramIndex++, $value, $this->columnTypes[$columnName]); - } + foreach ($insertData[$rootTableName] as $columnName => $value) { + $type = $this->columns[$columnName]->getType(); - $rootTableStmt->execute(); - - if ($isPostInsertId) { - $generatedId = $idGenerator->generate($this->em, $entity); - $id = [ - $this->class->identifier[0] => $generatedId - ]; - $postInsertIds[] = [ - 'generatedId' => $generatedId, - 'entity' => $entity, - ]; - } else { - $id = $this->em->getUnitOfWork()->getEntityIdentifier($entity); - } + $rootTableStmt->bindValue($paramIndex++, $value, $type); + } - if ($this->class->isVersioned) { - $this->assignDefaultVersionValue($entity, $id); - } + $rootTableStmt->execute(); - // Execute inserts on subtables. - // The order doesn't matter because all child tables link to the root table via FK. - foreach ($subTableStmts as $tableName => $stmt) { - /** @var \Doctrine\DBAL\Statement $stmt */ - $paramIndex = 1; - $data = isset($insertData[$tableName]) - ? $insertData[$tableName] - : []; + if ($generationPlan->containsDeferred()) { + $generationPlan->executeDeferred($this->em, $entity); + $id = $this->getIdentifier($entity); + } else { + $id = $this->em->getUnitOfWork()->getEntityIdentifier($entity); + } - foreach ((array) $id as $idName => $idVal) { - $type = isset($this->columnTypes[$idName]) ? $this->columnTypes[$idName] : Type::STRING; - $stmt->bindValue($paramIndex++, $idVal, $type); - } + if ($this->class->isVersioned()) { + $this->assignDefaultVersionValue($entity, $id); + } - foreach ($data as $columnName => $value) { - if (!is_array($id) || !isset($id[$columnName])) { - $stmt->bindValue($paramIndex++, $value, $this->columnTypes[$columnName]); - } + // Execute inserts on subtables. + // The order doesn't matter because all child tables link to the root table via FK. + foreach ($subTableStmts as $tableName => $stmt) { + /** @var \Doctrine\DBAL\Statement $stmt */ + $paramIndex = 1; + $data = isset($insertData[$tableName]) + ? $insertData[$tableName] + : []; + + foreach ((array) $id as $idName => $idVal) { + $type = Type::getType('string'); + + if (isset($this->columns[$idName])) { + $type = $this->columns[$idName]->getType(); } - $stmt->execute(); + $stmt->bindValue($paramIndex++, $idVal, $type); } + + foreach ($data as $columnName => $value) { + if (!is_array($id) || !isset($id[$columnName])) { + $type = $this->columns[$columnName]->getType(); + + $stmt->bindValue($paramIndex++, $value, $type); + } + } + + $stmt->execute(); } $rootTableStmt->closeCursor(); @@ -221,10 +128,6 @@ public function executeInserts() foreach ($subTableStmts as $stmt) { $stmt->closeCursor(); } - - $this->queuedInserts = []; - - return $postInsertIds; } /** @@ -238,25 +141,22 @@ public function update($entity) return; } - if (($isVersioned = $this->class->isVersioned) === false) { - return; - } - - $versionedClass = $this->getVersionedClassMetadata(); - $versionedTable = $versionedClass->getTableName(); + $isVersioned = $this->class->isVersioned(); foreach ($updateData as $tableName => $data) { - $tableName = $this->quotedTableMap[$tableName]; - $versioned = $isVersioned && $versionedTable === $tableName; + $versioned = $isVersioned && $this->class->versionProperty->getTableName() === $tableName; - $this->updateTable($entity, $tableName, $data, $versioned); + $this->updateTable($entity, $this->platform->quoteIdentifier($tableName), $data, $versioned); } // Make sure the table with the version column is updated even if no columns on that // table were affected. if ($isVersioned) { + $versionedClass = $this->class->versionProperty->getDeclaringClass(); + $versionedTable = $versionedClass->getTableName(); + if ( ! isset($updateData[$versionedTable])) { - $tableName = $this->quoteStrategy->getTableName($versionedClass, $this->platform); + $tableName = $versionedClass->table->getQuotedQualifiedName($this->platform); $this->updateTable($entity, $tableName, [], true); } @@ -273,27 +173,26 @@ public function update($entity) public function delete($entity) { $identifier = $this->em->getUnitOfWork()->getEntityIdentifier($entity); - $id = array_combine($this->class->getIdentifierColumnNames(), $identifier); + $id = array_combine(array_keys($this->class->getIdentifierColumns($this->em)), $identifier); $this->deleteJoinTableRecords($identifier); // If the database platform supports FKs, just // delete the row from the root table. Cascades do the rest. if ($this->platform->supportsForeignKeyConstraints()) { - $rootClass = $this->em->getClassMetadata($this->class->rootEntityName); - $rootTable = $this->quoteStrategy->getTableName($rootClass, $this->platform); + $rootClass = $this->em->getClassMetadata($this->class->getRootClassName()); + $rootTable = $rootClass->table->getQuotedQualifiedName($this->platform); return (bool) $this->conn->delete($rootTable, $id); } // Delete from all tables individually, starting from this class' table up to the root table. - $rootTable = $this->quoteStrategy->getTableName($this->class, $this->platform); - + $rootTable = $this->class->table->getQuotedQualifiedName($this->platform); $affectedRows = $this->conn->delete($rootTable, $id); + $parentClass = $this->class; - foreach ($this->class->parentClasses as $parentClass) { - $parentMetadata = $this->em->getClassMetadata($parentClass); - $parentTable = $this->quoteStrategy->getTableName($parentMetadata, $this->platform); + while (($parentClass = $parentClass->getParent()) !== null) { + $parentTable = $parentClass->table->getQuotedQualifiedName($this->platform); $this->conn->delete($parentTable, $id); } @@ -304,57 +203,58 @@ public function delete($entity) /** * {@inheritdoc} */ - public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit = null, $offset = null, array $orderBy = null) + public function getSelectSQL( + $criteria, + AssociationMetadata $association = null, + $lockMode = null, + $limit = null, + $offset = null, + array $orderBy = [] + ) { $this->switchPersisterContext($offset, $limit); - $baseTableAlias = $this->getSQLTableAlias($this->class->name); + $baseTableAlias = $this->getSQLTableAlias($this->class->getTableName()); $joinSql = $this->getJoinSql($baseTableAlias); - if ($assoc != null && $assoc['type'] == ClassMetadata::MANY_TO_MANY) { - $joinSql .= $this->getSelectManyToManyJoinSQL($assoc); + if ($association instanceof ManyToManyAssociationMetadata) { + $joinSql .= $this->getSelectManyToManyJoinSQL($association); + } + + if ($association instanceof ToManyAssociationMetadata && $association->getOrderBy()) { + $orderBy = $association->getOrderBy(); } + $orderBySql = $this->getOrderBySQL($orderBy, $baseTableAlias); $conditionSql = ($criteria instanceof Criteria) ? $this->getSelectConditionCriteriaSQL($criteria) - : $this->getSelectConditionSQL($criteria, $assoc); + : $this->getSelectConditionSQL($criteria, $association); // If the current class in the root entity, add the filters - if ($filterSql = $this->generateFilterConditionSQL($this->em->getClassMetadata($this->class->rootEntityName), $this->getSQLTableAlias($this->class->rootEntityName))) { + $rootClass = $this->em->getClassMetadata($this->class->getRootClassName()); + $tableAlias = $this->getSQLTableAlias($rootClass->getTableName()); + + if ($filterSql = $this->generateFilterConditionSQL($rootClass, $tableAlias)) { $conditionSql .= $conditionSql ? ' AND ' . $filterSql : $filterSql; } - $orderBySql = ''; - - if ($assoc !== null && isset($assoc['orderBy'])) { - $orderBy = $assoc['orderBy']; - } - - if ($orderBy) { - $orderBySql = $this->getOrderBySQL($orderBy, $baseTableAlias); - } - $lockSql = ''; switch ($lockMode) { case LockMode::PESSIMISTIC_READ: - $lockSql = ' ' . $this->platform->getReadLockSQL(); - break; case LockMode::PESSIMISTIC_WRITE: - $lockSql = ' ' . $this->platform->getWriteLockSQL(); - break; } - $tableName = $this->quoteStrategy->getTableName($this->class, $this->platform); + $tableName = $this->class->table->getQuotedQualifiedName($this->platform); $from = ' FROM ' . $tableName . ' ' . $baseTableAlias; - $where = $conditionSql != '' ? ' WHERE ' . $conditionSql : ''; + $where = $conditionSql !== '' ? ' WHERE ' . $conditionSql : ''; $lock = $this->platform->appendLockHint($from, $lockMode); $columnList = $this->getSelectColumnsSQL(); $query = 'SELECT ' . $columnList @@ -371,15 +271,17 @@ public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit */ public function getCountSQL($criteria = []) { - $tableName = $this->quoteStrategy->getTableName($this->class, $this->platform); - $baseTableAlias = $this->getSQLTableAlias($this->class->name); + $tableName = $this->class->table->getQuotedQualifiedName($this->platform); + $baseTableAlias = $this->getSQLTableAlias($this->class->getTableName()); $joinSql = $this->getJoinSql($baseTableAlias); $conditionSql = ($criteria instanceof Criteria) ? $this->getSelectConditionCriteriaSQL($criteria) : $this->getSelectConditionSQL($criteria); - $filterSql = $this->generateFilterConditionSQL($this->em->getClassMetadata($this->class->rootEntityName), $this->getSQLTableAlias($this->class->rootEntityName)); + $rootClass = $this->em->getClassMetadata($this->class->getRootClassName()); + $tableAlias = $this->getSQLTableAlias($rootClass->getTableName()); + $filterSql = $this->generateFilterConditionSQL($rootClass, $tableAlias); if ('' !== $filterSql) { $conditionSql = $conditionSql @@ -401,18 +303,22 @@ public function getCountSQL($criteria = []) protected function getLockTablesSql($lockMode) { $joinSql = ''; - $identifierColumns = $this->class->getIdentifierColumnNames(); - $baseTableAlias = $this->getSQLTableAlias($this->class->name); + $identifierColumns = $this->class->getIdentifierColumns($this->em); + $baseTableAlias = $this->getSQLTableAlias($this->class->getTableName()); // INNER JOIN parent tables - foreach ($this->class->parentClasses as $parentClassName) { - $conditions = []; - $tableAlias = $this->getSQLTableAlias($parentClassName); - $parentClass = $this->em->getClassMetadata($parentClassName); - $joinSql .= ' INNER JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->platform) . ' ' . $tableAlias . ' ON '; + $parentClass = $this->class; + + while (($parentClass = $parentClass->getParent()) !== null) { + $conditions = []; + $tableName = $parentClass->table->getQuotedQualifiedName($this->platform); + $tableAlias = $this->getSQLTableAlias($parentClass->getTableName()); + $joinSql .= ' INNER JOIN ' . $tableName . ' ' . $tableAlias . ' ON '; foreach ($identifierColumns as $idColumn) { - $conditions[] = $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn; + $quotedColumnName = $this->platform->quoteIdentifier($idColumn->getColumnName()); + + $conditions[] = $baseTableAlias . '.' . $quotedColumnName . ' = ' . $tableAlias . '.' . $quotedColumnName; } $joinSql .= implode(' AND ', $conditions); @@ -433,85 +339,79 @@ protected function getSelectColumnsSQL() return $this->currentPersisterContext->selectColumnListSql; } - $columnList = []; - $discrColumn = $this->class->discriminatorColumn['name']; - $discrColumnType = $this->class->discriminatorColumn['type']; - $baseTableAlias = $this->getSQLTableAlias($this->class->name); - $resultColumnName = $this->platform->getSQLResultCasing($discrColumn); + $this->currentPersisterContext->rsm->addEntityResult($this->class->getClassName(), 'r'); - $this->currentPersisterContext->rsm->addEntityResult($this->class->name, 'r'); - $this->currentPersisterContext->rsm->setDiscriminatorColumn('r', $resultColumnName); - $this->currentPersisterContext->rsm->addMetaResult('r', $resultColumnName, $discrColumn, false, $discrColumnType); + $columnList = []; - // Add regular columns - foreach ($this->class->fieldMappings as $fieldName => $mapping) { - $class = isset($mapping['inherited']) - ? $this->em->getClassMetadata($mapping['inherited']) - : $this->class; + // Add columns + foreach ($this->class->getDeclaredPropertiesIterator() as $fieldName => $property) { + if ($property instanceof FieldMetadata) { + $columnList[] = $this->getSelectColumnSQL($fieldName, $property->getDeclaringClass()); - $columnList[] = $this->getSelectColumnSQL($fieldName, $class); - } + continue; + } - // Add foreign key columns - foreach ($this->class->associationMappings as $mapping) { - if ( ! $mapping['isOwningSide'] || ! ($mapping['type'] & ClassMetadata::TO_ONE)) { + if (! ($property instanceof ToOneAssociationMetadata) || ! $property->isOwningSide()) { continue; } - $tableAlias = isset($mapping['inherited']) - ? $this->getSQLTableAlias($mapping['inherited']) - : $baseTableAlias; + $targetClass = $this->em->getClassMetadata($property->getTargetEntity()); - $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); + foreach ($property->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $referencedColumnName = $joinColumn->getReferencedColumnName(); - foreach ($mapping['joinColumns'] as $joinColumn) { - $columnList[] = $this->getSelectJoinColumnSQL( - $tableAlias, - $joinColumn['name'], - $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform), - PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em) - ); + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); + } + + $columnList[] = $this->getSelectJoinColumnSQL($joinColumn); } } // Add discriminator column (DO NOT ALIAS, see AbstractEntityInheritancePersister#processSQLResult). - $tableAlias = ($this->class->rootEntityName == $this->class->name) - ? $baseTableAlias - : $this->getSQLTableAlias($this->class->rootEntityName); + $discrColumn = $this->class->discriminatorColumn; + $discrTableAlias = $this->getSQLTableAlias($discrColumn->getTableName()); + $discrColumnName = $discrColumn->getColumnName(); + $discrColumnType = $discrColumn->getType(); + $resultColumnName = $this->platform->getSQLResultCasing($discrColumnName); + $quotedColumnName = $this->platform->quoteIdentifier($discrColumn->getColumnName()); + + $this->currentPersisterContext->rsm->setDiscriminatorColumn('r', $resultColumnName); + $this->currentPersisterContext->rsm->addMetaResult('r', $resultColumnName, $discrColumnName, false, $discrColumnType); - $columnList[] = $tableAlias . '.' . $discrColumn; + $columnList[] = $discrColumnType->convertToDatabaseValueSQL($discrTableAlias . '.' . $quotedColumnName, $this->platform); // sub tables - foreach ($this->class->subClasses as $subClassName) { - $subClass = $this->em->getClassMetadata($subClassName); - $tableAlias = $this->getSQLTableAlias($subClassName); + foreach ($this->class->getSubClasses() as $subClassName) { + $subClass = $this->em->getClassMetadata($subClassName); - // Add subclass columns - foreach ($subClass->fieldMappings as $fieldName => $mapping) { - if (isset($mapping['inherited'])) { + // Add columns + foreach ($subClass->getDeclaredPropertiesIterator() as $fieldName => $property) { + if ($subClass->isInheritedProperty($fieldName)) { continue; } - $columnList[] = $this->getSelectColumnSQL($fieldName, $subClass); - } + switch (true) { + case ($property instanceof FieldMetadata): + $columnList[] = $this->getSelectColumnSQL($fieldName, $subClass); + break; - // Add join columns (foreign keys) - foreach ($subClass->associationMappings as $mapping) { - if ( ! $mapping['isOwningSide'] - || ! ($mapping['type'] & ClassMetadata::TO_ONE) - || isset($mapping['inherited'])) { - continue; - } + case ($property instanceof ToOneAssociationMetadata && $property->isOwningSide()): + $targetClass = $this->em->getClassMetadata($property->getTargetEntity()); + + foreach ($property->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $referencedColumnName = $joinColumn->getReferencedColumnName(); - $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); + } - foreach ($mapping['joinColumns'] as $joinColumn) { - $columnList[] = $this->getSelectJoinColumnSQL( - $tableAlias, - $joinColumn['name'], - $this->quoteStrategy->getJoinColumnName($joinColumn, $subClass, $this->platform), - PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em) - ); + $columnList[] = $this->getSelectJoinColumnSQL($joinColumn); + } + + break; } } } @@ -527,50 +427,73 @@ protected function getSelectColumnsSQL() protected function getInsertColumnList() { // Identifier columns must always come first in the column list of subclasses. - $columns = $this->class->parentClasses - ? $this->class->getIdentifierColumnNames() + $columns = []; + $parentColumns = $this->class->getParent() + ? $this->class->getIdentifierColumns($this->em) : []; - foreach ($this->class->reflFields as $name => $field) { - if (isset($this->class->fieldMappings[$name]['inherited']) - && ! isset($this->class->fieldMappings[$name]['id']) - || isset($this->class->associationMappings[$name]['inherited']) - || ($this->class->isVersioned && $this->class->versionField == $name) - || isset($this->class->embeddedClasses[$name])) { + foreach ($parentColumns as $columnName => $column) { + $columns[] = $columnName; + + $this->columns[$columnName] = $column; + } + + foreach ($this->class->getDeclaredPropertiesIterator() as $name => $property) { + if (($property instanceof FieldMetadata && ($property instanceof VersionFieldMetadata || $this->class->isInheritedProperty($name))) + || ($property instanceof AssociationMetadata && $this->class->isInheritedProperty($name)) + /*|| isset($this->class->embeddedClasses[$name])*/) { continue; } - if (isset($this->class->associationMappings[$name])) { - $assoc = $this->class->associationMappings[$name]; - if ($assoc['type'] & ClassMetadata::TO_ONE && $assoc['isOwningSide']) { - foreach ($assoc['targetToSourceKeyColumns'] as $sourceCol) { - $columns[] = $sourceCol; + if ($property instanceof AssociationMetadata) { + if ($property->isOwningSide() && $property instanceof ToOneAssociationMetadata) { + $targetClass = $this->em->getClassMetadata($property->getTargetEntity()); + + foreach ($property->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $columnName = $joinColumn->getColumnName(); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); + } + + $columns[] = $columnName; + + $this->columns[$columnName] = $joinColumn; } } - } else if ($this->class->name != $this->class->rootEntityName || - ! $this->class->isIdGeneratorIdentity() || $this->class->identifier[0] != $name) { - $columns[] = $this->quoteStrategy->getColumnName($name, $this->class, $this->platform); - $this->columnTypes[$name] = $this->class->fieldMappings[$name]['type']; + + continue; + } + + if ( + $this->class->getClassName() !== $this->class->getRootClassName() + || ! $this->class->getProperty($name)->hasValueGenerator() + || $this->class->getProperty($name)->getValueGenerator()->getType() !== GeneratorType::IDENTITY + || $this->class->identifier[0] !== $name + ) { + $columnName = $property->getColumnName(); + + $columns[] = $columnName; + + $this->columns[$columnName] = $property; } } // Add discriminator column if it is the topmost class. - if ($this->class->name == $this->class->rootEntityName) { - $columns[] = $this->class->discriminatorColumn['name']; + if ($this->class->isRootEntity()) { + $discrColumn = $this->class->discriminatorColumn; + $discrColumnName = $discrColumn->getColumnName(); + + $columns[] = $discrColumnName; + + $this->columns[$discrColumnName] = $discrColumn; } return $columns; } - /** - * {@inheritdoc} - */ - protected function assignDefaultVersionValue($entity, array $id) - { - $value = $this->fetchVersionValue($this->getVersionedClassMetadata(), $id); - $this->class->setFieldValue($entity, $this->class->versionField, $value); - } - /** * @param string $baseTableAlias * @@ -578,33 +501,39 @@ protected function assignDefaultVersionValue($entity, array $id) */ private function getJoinSql($baseTableAlias) { - $joinSql = ''; - $identifierColumn = $this->class->getIdentifierColumnNames(); + $joinSql = ''; + $identifierColumns = $this->class->getIdentifierColumns($this->em); // INNER JOIN parent tables - foreach ($this->class->parentClasses as $parentClassName) { + $parentClass = $this->class; + + while (($parentClass = $parentClass->getParent()) !== null) { $conditions = []; - $parentClass = $this->em->getClassMetadata($parentClassName); - $tableAlias = $this->getSQLTableAlias($parentClassName); - $joinSql .= ' INNER JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->platform) . ' ' . $tableAlias . ' ON '; + $tableName = $parentClass->table->getQuotedQualifiedName($this->platform); + $tableAlias = $this->getSQLTableAlias($parentClass->getTableName()); + $joinSql .= ' INNER JOIN ' . $tableName . ' ' . $tableAlias . ' ON '; + foreach ($identifierColumns as $idColumn) { + $quotedColumnName = $this->platform->quoteIdentifier($idColumn->getColumnName()); - foreach ($identifierColumn as $idColumn) { - $conditions[] = $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn; + $conditions[] = $baseTableAlias . '.' . $quotedColumnName . ' = ' . $tableAlias . '.' . $quotedColumnName; } $joinSql .= implode(' AND ', $conditions); } // OUTER JOIN sub tables - foreach ($this->class->subClasses as $subClassName) { + foreach ($this->class->getSubClasses() as $subClassName) { $conditions = []; $subClass = $this->em->getClassMetadata($subClassName); - $tableAlias = $this->getSQLTableAlias($subClassName); - $joinSql .= ' LEFT JOIN ' . $this->quoteStrategy->getTableName($subClass, $this->platform) . ' ' . $tableAlias . ' ON '; + $tableName = $subClass->table->getQuotedQualifiedName($this->platform); + $tableAlias = $this->getSQLTableAlias($subClass->getTableName()); + $joinSql .= ' LEFT JOIN ' . $tableName . ' ' . $tableAlias . ' ON '; + + foreach ($identifierColumns as $idColumn) { + $quotedColumnName = $this->platform->quoteIdentifier($idColumn->getColumnName()); - foreach ($identifierColumn as $idColumn) { - $conditions[] = $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn; + $conditions[] = $baseTableAlias . '.' . $quotedColumnName . ' = ' . $tableAlias . '.' . $quotedColumnName; } $joinSql .= implode(' AND ', $conditions); diff --git a/lib/Doctrine/ORM/Persisters/Entity/SingleTablePersister.php b/lib/Doctrine/ORM/Persisters/Entity/SingleTablePersister.php index 4b8352b350c..d3d00d1cabb 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/SingleTablePersister.php +++ b/lib/Doctrine/ORM/Persisters/Entity/SingleTablePersister.php @@ -1,32 +1,23 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Persisters\Entity; +use Doctrine\ORM\Mapping\AssociationMetadata; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\Common\Collections\Criteria; +use Doctrine\ORM\Mapping\FieldMetadata; +use Doctrine\ORM\Mapping\JoinColumnMetadata; +use Doctrine\ORM\Mapping\ToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; use Doctrine\ORM\Utility\PersisterHelper; /** * Persister for entities that participate in a hierarchy mapped with the * SINGLE_TABLE strategy. * + * @author Guilherme Blanco * @author Roman Borschel * @author Benjamin Eberlei * @author Alexander @@ -35,14 +26,6 @@ */ class SingleTablePersister extends AbstractEntityInheritancePersister { - /** - * {@inheritdoc} - */ - protected function getDiscriminatorColumnTableName() - { - return $this->class->getTableName(); - } - /** * {@inheritdoc} */ @@ -54,48 +37,49 @@ protected function getSelectColumnsSQL() $columnList[] = parent::getSelectColumnsSQL(); - $rootClass = $this->em->getClassMetadata($this->class->rootEntityName); - $tableAlias = $this->getSQLTableAlias($rootClass->name); - // Append discriminator column - $discrColumn = $this->class->discriminatorColumn['name']; - $discrColumnType = $this->class->discriminatorColumn['type']; - - $columnList[] = $tableAlias . '.' . $discrColumn; - - $resultColumnName = $this->platform->getSQLResultCasing($discrColumn); + $discrColumn = $this->class->discriminatorColumn; + $discrTableAlias = $this->getSQLTableAlias($discrColumn->getTableName()); + $discrColumnName = $discrColumn->getColumnName(); + $discrColumnType = $discrColumn->getType(); + $resultColumnName = $this->platform->getSQLResultCasing($discrColumnName); + $quotedColumnName = $this->platform->quoteIdentifier($discrColumn->getColumnName()); $this->currentPersisterContext->rsm->setDiscriminatorColumn('r', $resultColumnName); - $this->currentPersisterContext->rsm->addMetaResult('r', $resultColumnName, $discrColumn, false, $discrColumnType); + $this->currentPersisterContext->rsm->addMetaResult('r', $resultColumnName, $discrColumnName, false, $discrColumnType); + + $columnList[] = $discrColumnType->convertToDatabaseValueSQL($discrTableAlias . '.' . $quotedColumnName, $this->platform); // Append subclass columns - foreach ($this->class->subClasses as $subClassName) { + foreach ($this->class->getSubClasses() as $subClassName) { $subClass = $this->em->getClassMetadata($subClassName); - // Regular columns - foreach ($subClass->fieldMappings as $fieldName => $mapping) { - if (isset($mapping['inherited'])) { + // Subclass columns + foreach ($subClass->getDeclaredPropertiesIterator() as $fieldName => $property) { + if ($subClass->isInheritedProperty($fieldName)) { continue; } - $columnList[] = $this->getSelectColumnSQL($fieldName, $subClass); - } + switch (true) { + case ($property instanceof FieldMetadata): + $columnList[] = $this->getSelectColumnSQL($fieldName, $subClass); + break; - // Foreign key columns - foreach ($subClass->associationMappings as $assoc) { - if ( ! $assoc['isOwningSide'] || ! ($assoc['type'] & ClassMetadata::TO_ONE) || isset($assoc['inherited'])) { - continue; - } + case ($property instanceof ToOneAssociationMetadata && $property->isOwningSide()): + $targetClass = $this->em->getClassMetadata($property->getTargetEntity()); + + foreach ($property->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $referencedColumnName = $joinColumn->getReferencedColumnName(); + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); + } - $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); + $columnList[] = $this->getSelectJoinColumnSQL($joinColumn); + } - foreach ($assoc['joinColumns'] as $joinColumn) { - $columnList[] = $this->getSelectJoinColumnSQL( - $tableAlias, - $joinColumn['name'], - $this->quoteStrategy->getJoinColumnName($joinColumn, $subClass, $this->platform), - PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em) - ); + break; } } } @@ -113,7 +97,12 @@ protected function getInsertColumnList() $columns = parent::getInsertColumnList(); // Add discriminator column to the INSERT SQL - $columns[] = $this->class->discriminatorColumn['name']; + $discrColumn = $this->class->discriminatorColumn; + $discrColumnName = $discrColumn->getColumnName(); + + $columns[] = $discrColumnName; + + $this->columns[$discrColumnName] = $discrColumn; return $columns; } @@ -121,17 +110,17 @@ protected function getInsertColumnList() /** * {@inheritdoc} */ - protected function getSQLTableAlias($className, $assocName = '') + protected function getSQLTableAlias($tableName, $assocName = '') { - return parent::getSQLTableAlias($this->class->rootEntityName, $assocName); + return parent::getSQLTableAlias($this->class->getTableName(), $assocName); } /** * {@inheritdoc} */ - protected function getSelectConditionSQL(array $criteria, $assoc = null) + protected function getSelectConditionSQL(array $criteria, AssociationMetadata $association = null) { - $conditionSql = parent::getSelectConditionSQL($criteria, $assoc); + $conditionSql = parent::getSelectConditionSQL($criteria, $association); if ($conditionSql) { $conditionSql .= ' AND '; @@ -167,15 +156,20 @@ protected function getSelectConditionDiscriminatorValueSQL() $discrValues = array_flip($this->class->discriminatorMap); - foreach ($this->class->subClasses as $subclassName) { + foreach ($this->class->getSubClasses() as $subclassName) { $values[] = $this->conn->quote($discrValues[$subclassName]); } - $values = implode(', ', $values); - $discColumn = $this->class->discriminatorColumn['name']; - $tableAlias = $this->getSQLTableAlias($this->class->name); + $discrColumn = $this->class->discriminatorColumn; + $discrColumnType = $discrColumn->getType(); + $tableAlias = $this->getSQLTableAlias($discrColumn->getTableName()); + $quotedColumnName = $this->platform->quoteIdentifier($discrColumn->getColumnName()); - return $tableAlias . '.' . $discColumn . ' IN (' . $values . ')'; + return sprintf( + '%s IN (%s)', + $discrColumnType->convertToDatabaseValueSQL($tableAlias . '.' . $quotedColumnName, $this->platform), + implode(', ', $values) + ); } /** @@ -184,7 +178,7 @@ protected function getSelectConditionDiscriminatorValueSQL() protected function generateFilterConditionSQL(ClassMetadata $targetEntity, $targetTableAlias) { // Ensure that the filters are applied to the root entity of the inheritance tree - $targetEntity = $this->em->getClassMetadata($targetEntity->rootEntityName); + $targetEntity = $this->em->getClassMetadata($targetEntity->getRootClassName()); // we don't care about the $targetTableAlias, in a STI there is only one table. return parent::generateFilterConditionSQL($targetEntity, $targetTableAlias); diff --git a/lib/Doctrine/ORM/Persisters/PersisterException.php b/lib/Doctrine/ORM/Persisters/PersisterException.php index 09f73b21b5d..387a8576f2a 100644 --- a/lib/Doctrine/ORM/Persisters/PersisterException.php +++ b/lib/Doctrine/ORM/Persisters/PersisterException.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Persisters; diff --git a/lib/Doctrine/ORM/Persisters/SqlExpressionVisitor.php b/lib/Doctrine/ORM/Persisters/SqlExpressionVisitor.php index 476ecaba81e..1a35b0127a5 100644 --- a/lib/Doctrine/ORM/Persisters/SqlExpressionVisitor.php +++ b/lib/Doctrine/ORM/Persisters/SqlExpressionVisitor.php @@ -1,24 +1,10 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Persisters; +use Doctrine\ORM\Mapping\AssociationMetadata; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\Common\Collections\Expr\ExpressionVisitor; @@ -64,15 +50,16 @@ public function __construct(BasicEntityPersister $persister, ClassMetadata $clas */ public function walkComparison(Comparison $comparison) { - $field = $comparison->getField(); - $value = $comparison->getValue()->getValue(); // shortcut for walkValue() + $field = $comparison->getField(); + $value = $comparison->getValue()->getValue(); // shortcut for walkValue() + $property = $this->classMetadata->getProperty($field); - if (isset($this->classMetadata->associationMappings[$field]) && + if ($property instanceof AssociationMetadata && $value !== null && ! is_object($value) && ! in_array($comparison->getOperator(), [Comparison::IN, Comparison::NIN])) { - throw PersisterException::matchingAssocationFieldRequiresObject($this->classMetadata->name, $field); + throw PersisterException::matchingAssocationFieldRequiresObject($this->classMetadata->getClassName(), $field); } return $this->persister->getSelectConditionStatementSQL($field, $value, null, $comparison->getOperator()); diff --git a/lib/Doctrine/ORM/Persisters/SqlValueVisitor.php b/lib/Doctrine/ORM/Persisters/SqlValueVisitor.php index 78fd0333bb0..2a80da78465 100644 --- a/lib/Doctrine/ORM/Persisters/SqlValueVisitor.php +++ b/lib/Doctrine/ORM/Persisters/SqlValueVisitor.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Persisters; diff --git a/lib/Doctrine/ORM/PessimisticLockException.php b/lib/Doctrine/ORM/PessimisticLockException.php index d60f7a82177..aea82a6ca14 100644 --- a/lib/Doctrine/ORM/PessimisticLockException.php +++ b/lib/Doctrine/ORM/PessimisticLockException.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; diff --git a/lib/Doctrine/ORM/Proxy/Autoloader.php b/lib/Doctrine/ORM/Proxy/Autoloader.php deleted file mode 100644 index 9b2e2cdfa1a..00000000000 --- a/lib/Doctrine/ORM/Proxy/Autoloader.php +++ /dev/null @@ -1,29 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Proxy; - -use Doctrine\Common\Proxy\Autoloader as BaseAutoloader; - -/** - * @deprecated use \Doctrine\Common\Proxy\Autoloader instead - */ -class Autoloader extends BaseAutoloader -{ -} diff --git a/lib/Doctrine/ORM/Proxy/Factory/Autoloader.php b/lib/Doctrine/ORM/Proxy/Factory/Autoloader.php new file mode 100644 index 00000000000..ac8923896ef --- /dev/null +++ b/lib/Doctrine/ORM/Proxy/Factory/Autoloader.php @@ -0,0 +1,92 @@ + + */ +class Autoloader +{ + /** + * Resolves proxy class name to a filename based on the following pattern. + * + * 1. Remove Proxy namespace from class name. + * 2. Remove namespace separators from remaining class name. + * 3. Return PHP filename from proxy-dir with the result from 2. + * + * @param string $proxyDir + * @param string $proxyNamespace + * @param string $className + * + * @return string + * + * @throws InvalidArgumentException + */ + public static function resolveFile(string $proxyDir, string $proxyNamespace, string $className) : string + { + if (0 !== strpos($className, $proxyNamespace)) { + throw new InvalidArgumentException( + sprintf('The class "%s" is not part of the proxy namespace "%s"', $className, $proxyNamespace) + ); + } + + // remove proxy namespace from class name + $classNameRelativeToProxyNamespace = substr($className, strlen($proxyNamespace)); + + // remove namespace separators from remaining class name + $fileName = str_replace('\\', '', $classNameRelativeToProxyNamespace); + + return $proxyDir . DIRECTORY_SEPARATOR . $fileName . '.php'; + } + + /** + * Registers and returns autoloader callback for the given proxy dir and namespace. + * + * @param string $proxyDir + * @param string $proxyNamespace + * @param callable|null $notFoundCallback Invoked when the proxy file is not found. + * + * @return \Closure + * + * @throws InvalidArgumentException + */ + public static function register( + string $proxyDir, + string $proxyNamespace, + callable $notFoundCallback = null + ) : \Closure + { + $proxyNamespace = ltrim($proxyNamespace, '\\'); + + if (! (null === $notFoundCallback || is_callable($notFoundCallback))) { + $type = is_object($notFoundCallback) ? get_class($notFoundCallback) : gettype($notFoundCallback); + + throw new InvalidArgumentException( + sprintf('Invalid \$notFoundCallback given: must be a callable, "%s" given', $type) + ); + } + + $autoloader = function ($className) use ($proxyDir, $proxyNamespace, $notFoundCallback) { + if (0 === strpos($className, $proxyNamespace)) { + $file = Autoloader::resolveFile($proxyDir, $proxyNamespace, $className); + + if ($notFoundCallback && ! file_exists($file)) { + call_user_func($notFoundCallback, $proxyDir, $proxyNamespace, $className); + } + + require $file; + } + }; + + spl_autoload_register($autoloader); + + return $autoloader; + } +} diff --git a/lib/Doctrine/ORM/Proxy/Factory/DefaultProxyResolver.php b/lib/Doctrine/ORM/Proxy/Factory/DefaultProxyResolver.php new file mode 100644 index 00000000000..84e29fddabf --- /dev/null +++ b/lib/Doctrine/ORM/Proxy/Factory/DefaultProxyResolver.php @@ -0,0 +1,57 @@ +namespace = ltrim($namespace, '\\'); + $this->directory = rtrim($directory, DIRECTORY_SEPARATOR); + } + + /** + * {@inheritdoc} + */ + public function resolveProxyClassName(string $className) : string + { + return sprintf('%s\%s\%s', $this->namespace, self::MARKER, ltrim($className, '\\')); + } + + /** + * {@inheritdoc} + */ + public function resolveProxyClassPath(string $className) : string + { + return sprintf('%s/%s/%s.php', $this->directory, self::MARKER, str_replace('\\', '.', $className)); + } +} diff --git a/lib/Doctrine/ORM/Proxy/Factory/ProxyDefinition.php b/lib/Doctrine/ORM/Proxy/Factory/ProxyDefinition.php new file mode 100644 index 00000000000..710e1547e39 --- /dev/null +++ b/lib/Doctrine/ORM/Proxy/Factory/ProxyDefinition.php @@ -0,0 +1,190 @@ + + * @author Benjamin Eberlei + */ +class ProxyDefinition +{ + /** + * @var ClassMetadata + */ + public $entityClassMetadata; + + /** + * @var EntityPersister + */ + public $entityPersister; + + /** + * @var string + */ + public $proxyClassName; + + /** + * @var array|null + */ + private $lazyPropertyList; + + /** + * @param ClassMetadata $entityClassMetadata + * @param EntityPersister $entityPersister + * @param string $proxyClassName + */ + public function __construct( + ClassMetadata $entityClassMetadata, + EntityPersister $entityPersister, + string $proxyClassName + ) + { + $this->entityClassMetadata = $entityClassMetadata; + $this->entityPersister = $entityPersister; + $this->proxyClassName = $proxyClassName; + } + + /** + * Method responsible for loading properties in the proxy object. + * This should accept 3 parameters: + * - $proxy: the proxy object to be initialized + * - $method: the method that triggered the initialization process + * - $parameters: an array of ordered parameters that were passed to that method + * + * @param Proxy $proxy + * + * @throws EntityNotFoundException + */ + public function initializer(Proxy $proxy) : void + { + if ($proxy->__isInitialized()) { + return; + } + + $proxy->__setInitialized(true); + + $lazyPropertyList = $this->getLazyPublicPropertyList(); + $existingProperties = get_object_vars($proxy); // Do not override properties manually set. + + foreach ($lazyPropertyList as $propertyName => $defaultValue) { + if (! array_key_exists($propertyName, $existingProperties)) { + $proxy->$propertyName = $defaultValue; + } + } + + if (method_exists($proxy, '__wakeup')) { + $proxy->__wakeup(); + } + + $classMetadata = $this->entityClassMetadata; + $identifier = $this->entityPersister->getIdentifier($proxy); + $original = $this->entityPersister->loadById($identifier, $proxy); + + if (null === $original) { + $proxy->__setInitialized(false); + + throw EntityNotFoundException::fromClassNameAndIdentifier( + $classMetadata->getClassName(), $identifier + ); + + // @todo guilhermeblanco Move the flattening identifier to Persisters + /*$identifierFlattener = new IdentifierFlattener( + $this->entityManager->getUnitOfWork(), + $this->entityManager->getMetadataFactory() + ); + + throw EntityNotFoundException::fromClassNameAndIdentifier( + $classMetadata->getClassName(), + $identifierFlattener->flattenIdentifier($classMetadata, $identifier) + );*/ + } + } + + /** + * Method responsible of loading properties that need to be copied in the cloned object. + * This should accept a single parameter, which is the cloned proxy instance itself. + * + * @param Proxy $proxy + * + * @throws EntityNotFoundException + */ + public function cloner(Proxy $proxy) : void + { + if ($proxy->__isInitialized()) { + return; + } + + $proxy->__setInitialized(true); + + $classMetadata = $this->entityClassMetadata; + $identifier = $this->entityPersister->getIdentifier($proxy); + $original = $this->entityPersister->loadById($identifier); + + if (null === $original) { + throw EntityNotFoundException::fromClassNameAndIdentifier( + $classMetadata->getClassName(), $identifier + ); + + // @todo guilhermeblanco Move the flattening identifier to Persisters + /*$identifierFlattener = new IdentifierFlattener( + $this->entityManager->getUnitOfWork(), + $this->entityManager->getMetadataFactory() + ); + + throw EntityNotFoundException::fromClassNameAndIdentifier( + $classMetadata->getClassName(), + $identifierFlattener->flattenIdentifier($classMetadata, $identifier) + );*/ + } + + foreach ($classMetadata->getDeclaredPropertiesIterator() as $property) { + /** @var Property $property */ + $property->setValue($proxy, $property->getValue($original)); + } + } + + /** + * Generates the list of public properties to be lazy loaded, with their default values. + * + * @return array + */ + public function getLazyPublicPropertyList() : array + { + if (null !== $this->lazyPropertyList) { + return $this->lazyPropertyList; + } + + $reflectionClass = $this->entityClassMetadata->getReflectionClass(); + $defaultPropertyList = $reflectionClass->getDefaultProperties(); + $lazyPropertyList = []; + + foreach ($reflectionClass->getProperties(\ReflectionProperty::IS_PUBLIC) as $reflectionProperty) { + if ($reflectionProperty->isStatic()) { + continue; + } + + $propertyName = $reflectionProperty->getName(); + $property = $this->entityClassMetadata->getProperty($propertyName); + + if (! $property || $property instanceof TransientMetadata || $property->isPrimaryKey()) { + continue; + } + + $lazyPropertyList[$propertyName] = $defaultPropertyList[$propertyName]; + } + + return $this->lazyPropertyList = $lazyPropertyList; + } +} diff --git a/lib/Doctrine/ORM/Proxy/Factory/ProxyDefinitionFactory.php b/lib/Doctrine/ORM/Proxy/Factory/ProxyDefinitionFactory.php new file mode 100644 index 00000000000..30a08708561 --- /dev/null +++ b/lib/Doctrine/ORM/Proxy/Factory/ProxyDefinitionFactory.php @@ -0,0 +1,83 @@ +entityManager = $entityManager; + $this->resolver = $resolver; + $this->generatorStrategy = $generatorStrategy; + } + + /** + * @param ClassMetadata $classMetadata + * + * @return ProxyDefinition + */ + public function build(ClassMetadata $classMetadata) : ProxyDefinition + { + $definition = $this->createDefinition($classMetadata); + + if (! class_exists($definition->proxyClassName, false)) { + $proxyClassPath = $this->resolver->resolveProxyClassPath($classMetadata->getClassName()); + + $this->generatorStrategy->generate($proxyClassPath, $definition); + } + + return $definition; + } + + /** + * @param ClassMetadata $classMetadata + * + * @return ProxyDefinition + */ + private function createDefinition(ClassMetadata $classMetadata) : ProxyDefinition + { + $unitOfWork = $this->entityManager->getUnitOfWork(); + $entityPersister = $unitOfWork->getEntityPersister($classMetadata->getClassName()); + $proxyClassName = $this->resolver->resolveProxyClassName($classMetadata->getClassName()); + + return new ProxyDefinition($classMetadata, $entityPersister, $proxyClassName); + } +} diff --git a/lib/Doctrine/ORM/Proxy/Factory/ProxyException.php b/lib/Doctrine/ORM/Proxy/Factory/ProxyException.php new file mode 100644 index 00000000000..34ddb55c88d --- /dev/null +++ b/lib/Doctrine/ORM/Proxy/Factory/ProxyException.php @@ -0,0 +1,17 @@ + + */ +interface ProxyException +{ +} diff --git a/lib/Doctrine/ORM/Proxy/Factory/ProxyFactory.php b/lib/Doctrine/ORM/Proxy/Factory/ProxyFactory.php new file mode 100644 index 00000000000..f16c2dfbb27 --- /dev/null +++ b/lib/Doctrine/ORM/Proxy/Factory/ProxyFactory.php @@ -0,0 +1,66 @@ + $classMetadataList + * + * @return int + */ + public function generateProxyClasses(array $classMetadataList) : int; + + /** + * Gets a reference proxy instance for the entity of the given type and identified by + * the given identifier. + * + * @param string $className + * @param array $identifier + * + * @return \Doctrine\ORM\Proxy\Proxy + */ + public function getProxy(string $className, array $identifier) : Proxy; +} diff --git a/lib/Doctrine/ORM/Proxy/Factory/ProxyGenerator.php b/lib/Doctrine/ORM/Proxy/Factory/ProxyGenerator.php new file mode 100644 index 00000000000..de2ca5af3bd --- /dev/null +++ b/lib/Doctrine/ORM/Proxy/Factory/ProxyGenerator.php @@ -0,0 +1,814 @@ + + * @author Marco Pivetta + * @since 2.4 + */ +class ProxyGenerator +{ + /** + * Used to match very simple id methods that don't need + * to be decorated since the identifier is known. + */ + const PATTERN_MATCH_ID_METHOD = '((public\s+)?(function\s+%s\s*\(\)\s*)\s*(?::\s*\??\s*\\\\?[a-z_\x7f-\xff][\w\x7f-\xff]*(?:\\\\[a-z_\x7f-\xff][\w\x7f-\xff]*)*\s*)?{\s*return\s*\$this->%s;\s*})i'; + + /** + * Map of callables used to fill in placeholders set in the template. + * + * @var string[]|callable[] + */ + protected $placeholders = [ + 'baseProxyInterface' => Proxy::class, + 'additionalProperties' => '', + ]; + + /** + * Template used as a blueprint to generate proxies. + * + * @var string + */ + protected $proxyClassTemplate = '; + +use Doctrine\ORM\Proxy\Factory\ProxyDefinition; + +/** + * DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE\'S PROXY GENERATOR + */ +class extends \ implements \ +{ + /** + * @static + * @var array Cache for an array of proxy managed public properties + */ + static private $__lazyPublicPropertyList__ = ; + + /** + * @var ProxyDefinition + + * @see \Doctrine\ORM\Proxy::__setProxyDefinition + */ + private $__proxyDefinition__; + + /** + * @var boolean flag indicating if this object was already initialized + * + * @see \Doctrine\ORM\Proxy::__isInitialized + */ + private $__isInitialized__ = false; + + + + /** + * @param ProxyDefinition $definition + */ + public function __construct(ProxyDefinition $definition) + { + $this->__proxyDefinition__ = $definition; + + foreach (static::$__lazyPublicPropertyList__ as $propertyName => $defaultValue) { + unset($this->$propertyName); + } + } + + /** + * {@inheritDoc} + * @internal generated method: use only when explicitly handling proxy specific loading logic + */ + public function __isInitialized() + { + return $this->__isInitialized__; + } + + /** + * {@inheritDoc} + * @internal generated method: use only when explicitly handling proxy specific loading logic + */ + public function __setInitialized($initialized) + { + $this->__isInitialized__ = $initialized; + } + + /** + * Clones the proxy + */ + public function __clone() + { + ! $this->__isInitialized__ && $this->__proxyDefinition__->cloner($this); + + if (is_callable("parent::__clone")) { + parent::__clone(); + } + } + + /** + * Forces initialization of the proxy + */ + public function __load() + { + ! $this->__isInitialized__ && $this->__proxyDefinition__->initializer($this, "__load", []); + + if (is_callable("parent::__load")) { + parent::__load(); + } + } + + + + + + + + + + + + +} +'; + + /** + * Sets a placeholder to be replaced in the template. + * + * @param string $name + * @param string|callable $placeholder + * + * @throws \InvalidArgumentException + */ + public function setPlaceholder($name, $placeholder) + { + if (! is_string($placeholder) && ! is_callable($placeholder)) { + throw new \InvalidArgumentException( + sprintf('Provided placeholder for "%s" must be either a string or a valid callable', $name) + ); + } + + $this->placeholders[$name] = $placeholder; + } + + /** + * Sets the base template used to create proxy classes. + * + * @param string $proxyClassTemplate + */ + public function setProxyClassTemplate($proxyClassTemplate) + { + $this->proxyClassTemplate = (string) $proxyClassTemplate; + } + + /** + * Generates proxy class code. + * + * @param ProxyDefinition $definition + * + * @return string + */ + public function generate(ProxyDefinition $definition) : string + { + $this->verifyClassCanBeProxied($definition->entityClassMetadata); + + return $this->renderTemplate($this->proxyClassTemplate, $definition, $this->placeholders); + } + + /** + * @param ClassMetadata $class + * + * @throws \InvalidArgumentException + */ + private function verifyClassCanBeProxied(ClassMetadata $class) + { + $reflectionClass = $class->getReflectionClass(); + + if ($reflectionClass->isFinal()) { + throw new \InvalidArgumentException( + sprintf('Unable to create a proxy for a final class "%s".', $reflectionClass->getName()) + ); + } + + if ($reflectionClass->isAbstract()) { + throw new \InvalidArgumentException( + sprintf('Unable to create a proxy for an abstract class "%s".', $reflectionClass->getName()) + ); + } + } + + /** + * Generates the proxy short class name to be used in the template. + * + * @param ProxyDefinition $definition + * + * @return string + */ + private function generateProxyShortClassName(ProxyDefinition $definition) : string + { + $parts = explode('\\', strrev($definition->proxyClassName), 2); + + return strrev($parts[0]); + } + + /** + * Generates the proxy namespace. + * + * @param ProxyDefinition $definition + * + * @return string + */ + private function generateNamespace(ProxyDefinition $definition) : string + { + $parts = explode('\\', strrev($definition->proxyClassName), 2); + + return strrev($parts[1]); + } + + /** + * Generates the original class name. + * + * @param ProxyDefinition $definition + * + * @return string + */ + private function generateClassName(ProxyDefinition $definition) : string + { + return $definition->entityClassMetadata->getClassName(); + } + + private function generateLazyPublicPropertyList(ProxyDefinition $definition) : string + { + $lazyPublicProperties = $definition->getLazyPublicPropertyList(); + + return var_export($lazyPublicProperties, true); + } + + /** + * Generates the magic wakeup invoked when unserialize is called. + * + * @param ProxyDefinition $definition + * + * @return string + */ + private function generateMagicWakeup(ProxyDefinition $definition) : string + { + $lazyPublicProperties = $definition->getLazyPublicPropertyList(); + $reflectionClass = $definition->entityClassMetadata->getReflectionClass(); + $hasParentWakeup = $reflectionClass->hasMethod('__wakeup'); + + if (empty($lazyPublicProperties) && ! $hasParentWakeup) { + return ''; + } + + if ($hasParentWakeup) { + return <<<'EOT' + /** + * {@inheritDoc} + */ + public function __wakeup() + { + if (! $this->__isInitialized__) { + foreach (static::$__lazyPublicPropertyList__ as $propertyName => $defaultValue) { + unset($this->$propertyName); + } + } + + parent::__wakeup(); + } +EOT; + } + + return <<<'EOT' + /** + * Provides deserialization support for the proxy + */ + public function __wakeup() + { + if (! $this->__isInitialized__) { + foreach (static::$__lazyPublicPropertyList__ as $propertyName => $defaultValue) { + unset($this->$propertyName); + } + } + } +EOT; + } + + private function generateMagicSleep(ProxyDefinition $definition) : string + { + $reflectionClass = $definition->entityClassMetadata->getReflectionClass(); + $hasParentSleep = $reflectionClass->hasMethod('__sleep'); + + if ($hasParentSleep) { + return <<<'EOT' + /** + * {@inheritDoc} + */ + public function __sleep() + { + $allProperties = array_merge(["__isInitialized__"], parent::__sleep()); + + return ! $this->__isInitialized__ + ? array_diff($allProperties, array_keys(static::$__lazyPublicPropertyList__)) + : $allProperties + ; + } +EOT; + } + + return <<<'EOT' + /** + * Provides serialization support for the proxy + */ + public function __sleep() + { + $classMetadata = $this->__proxyDefinition__->entityClassMetadata; + $reflectionClass = $classMetadata->getReflectionClass(); + $allProperties = ["__isInitialized__"]; + + foreach ($reflectionClass->getProperties() as $reflectionProperty) { + if ($reflectionProperty->isStatic()) { + continue; + } + + $propertyPrefix = $reflectionProperty->isPrivate() + ? "\0" . $reflectionProperty->getDeclaringClass()->getName() . "\0" + : "" + ; + + $allProperties[] = $propertyPrefix . $reflectionProperty->getName(); + } + + return ! $this->__isInitialized__ + ? array_diff($allProperties, array_keys(static::$__lazyPublicPropertyList__)) + : $allProperties + ; + } +EOT; + } + + /** + * Generates the magic getter invoked when lazy loaded public properties are requested. + * + * @param ProxyDefinition $definition + * + * @return string + */ + private function generateMagicGet(ProxyDefinition $definition) : string + { + $lazyPublicProperties = $definition->getLazyPublicPropertyList(); + $reflectionClass = $definition->entityClassMetadata->getReflectionClass(); + $hasParentGet = $reflectionClass->hasMethod('__get'); + + if (empty($lazyPublicProperties) && ! $hasParentGet) { + return ''; + } + + if ($hasParentGet) { + $returnReference = $reflectionClass->getMethod('__get')->returnsReference() ? '& ' : ''; + + $magicGet = <<<'EOT' + /** + * {@inheritDoc} + */ + public function __get($name) + { + ! $this->__isInitialized__ && $this->__proxyDefinition__->initializer($this, '__get', [$name]); + + return parent::__get($name); + } +EOT; + + return $this->renderTemplate($magicGet, $definition, [ + 'returnReference' => $returnReference, + ]); + } + + return <<<'EOT' + /** + * Provides property retrieval support for the proxy + */ + public function __get($name) + { + if (static::$__lazyPublicPropertyList__ && array_key_exists($name, static::$__lazyPublicPropertyList__)) { + ! $this->__isInitialized__ && $this->__proxyDefinition__->initializer($this, '__get', [$name]); + + return $this->$name; + } + + trigger_error(sprintf('Undefined property: %s::$%s', __CLASS__, $name), E_USER_NOTICE); + } +EOT; + } + + /** + * Generates the magic setter (currently unused). + * + * @param ProxyDefinition $definition + * + * @return string + */ + private function generateMagicSet(ProxyDefinition $definition) : string + { + $lazyPublicProperties = $definition->getLazyPublicPropertyList(); + $reflectionClass = $definition->entityClassMetadata->getReflectionClass(); + $hasParentSet = $reflectionClass->hasMethod('__set'); + + if (empty($lazyPublicProperties) && ! $hasParentSet) { + return ''; + } + + if ($hasParentSet) { + return <<<'EOT' + /** + * {@inheritDoc} + */ + public function __set($name, $value) + { + ! $this->__isInitialized__ && $this->__proxyDefinition__->initializer($this, '__set', [$name, $value]); + + return parent::__set($name, $value); + } +EOT; + } + + return <<<'EOT' + /** + * Provides property accessor support for the proxy + */ + public function __set($name, $value) + { + if (static::$__lazyPublicPropertyList__ && array_key_exists($name, static::$__lazyPublicPropertyList__)) { + ! $this->__isInitialized__ && $this->__proxyDefinition__->initializer($this, '__set', [$name, $value]); + } + + $this->$name = $value; + } +EOT; + } + + /** + * Generates the magic issetter invoked when lazy loaded public properties are checked against isset(). + * + * @param ProxyDefinition $definition + * + * @return string + */ + private function generateMagicIsset(ProxyDefinition $definition) : string + { + $lazyPublicProperties = $definition->getLazyPublicPropertyList(); + $reflectionClass = $definition->entityClassMetadata->getReflectionClass(); + $hasParentIsset = $reflectionClass->hasMethod('__isset'); + + if (empty($lazyPublicProperties) && ! $hasParentIsset) { + return ''; + } + + if ($hasParentIsset) { + return <<<'EOT' + /** + * {@inheritDoc} + */ + public function __isset($name) + { + ! $this->__isInitialized__ && $this->__proxyDefinition__->initializer($this, '__isset', [$name]); + + return parent::__isset($name); + } +EOT; + } + + return <<<'EOT' + /** + * Provide property checker for the proxy + */ + public function __isset($name) + { + if (static::$__lazyPublicPropertyList__ && array_key_exists($name, static::$__lazyPublicPropertyList__)) { + ! $this->__isInitialized__ &&$this->__proxyDefinition__->initializer($this, '__isset', [$name]); + + return isset($this->$name); + } + + return false; + } +EOT; + } + + /** + * Generates decorated methods by picking those available in the parent class. + * + * @param ProxyDefinition $definition + * + * @return string + */ + private function generateMethods(ProxyDefinition $definition) : string + { + $classMetadata = $definition->entityClassMetadata; + $reflectionClass = $classMetadata->getReflectionClass(); + $reflectionMethods = $reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC); + $filteredMethods = array_filter($reflectionMethods, function (\ReflectionMethod $reflectionMethod) use ($classMetadata) { + // Do not consider static or constructor + if ($reflectionMethod->isConstructor() || $reflectionMethod->isStatic()) { + return false; + } + + // Do not consider non-visible (or overloadable) methods + if ($reflectionMethod->isFinal() || ! $reflectionMethod->isPublic()) { + return false; + } + + // Do not consider identifier-getter methods + $fieldCandidate = lcfirst((string) substr($reflectionMethod->getName(), 3)); + $isIdentifier = $reflectionMethod->getNumberOfParameters() === 0 + && strpos($reflectionMethod->getName(), 'get') === 0 + && $classMetadata->hasField($fieldCandidate) + && in_array($fieldCandidate, $classMetadata->getIdentifier(), true) + ; + + if ($isIdentifier) { + return false; + } + + // Do not consider magic methods + $skippedMethods = [ + '__clone' => true, + '__get' => true, + '__isset' => true, + '__set' => true, + '__sleep' => true, + '__wakeup' => true, + ]; + + return ! isset($skippedMethods[strtolower($reflectionMethod->getName())]); + }); + + $methodList = []; + + /** @var \ReflectionMethod $reflectionMethod */ + foreach ($filteredMethods as $reflectionMethod) { + $methodName = $reflectionMethod->getName(); + $methodParameters = $reflectionMethod->getParameters(); + + $parameterList = $this->buildParametersString($reflectionMethod, $methodParameters); + $invocationParameterList = implode(', ', $this->getParameterNamesForInvocation($methodParameters)); + + $returnReference = $reflectionMethod->returnsReference() ? '& ' : ''; + $returnType = $this->getMethodReturnType($reflectionMethod); + $returnValue = $this->doesMethodReturnValue($reflectionMethod) ? 'return ' : ''; + + $methodTemplate = <<<'EOT' + /** + * {@inheritdoc} + */ + public function () + { + ! $this->__isInitialized__ && $this->__proxyDefinition__->initializer($this, __METHOD__, []); + + parent::(); + } +EOT; + + $methodList[] = $this->renderTemplate($methodTemplate, $definition, [ + 'methodName' => $methodName, + 'parameterList' => $parameterList, + 'invocationParameterList' => $invocationParameterList, + 'returnReference' => $returnReference, + 'returnType' => $returnType, + 'returnValue' => $returnValue, + ]); + } + + return implode("\n\n", $methodList); + } + + /** + * @param \ReflectionMethod $method + * @param \ReflectionParameter[] $parameters + * + * @return string + */ + private function buildParametersString(\ReflectionMethod $method, array $parameters) + { + $parameterDefinitions = []; + + /* @var $param \ReflectionParameter */ + foreach ($parameters as $param) { + $parameterDefinition = ''; + + if ($parameterType = $this->getParameterType($method, $param)) { + $parameterDefinition .= $parameterType . ' '; + } + + if ($param->isPassedByReference()) { + $parameterDefinition .= '&'; + } + + if ($param->isVariadic()) { + $parameterDefinition .= '...'; + } + + $parameterDefinition .= '$' . $param->getName(); + + if ($param->isDefaultValueAvailable()) { + $parameterDefinition .= ' = ' . var_export($param->getDefaultValue(), true); + } + + $parameterDefinitions[] = $parameterDefinition; + } + + return implode(', ', $parameterDefinitions); + } + + /** + * @param \ReflectionMethod $method + * @param \ReflectionParameter $parameter + * + * @return string|null + */ + private function getParameterType(\ReflectionMethod $method, \ReflectionParameter $parameter) + { + if (method_exists($parameter, 'hasType')) { + if (! $parameter->hasType()) { + return ''; + } + + return $this->formatType($parameter->getType(), $parameter->getDeclaringFunction(), $parameter); + } + + // For PHP 5.x, we need to pick the type hint in the old way (to be removed for PHP 7.0+) + if ($parameter->isArray()) { + return 'array'; + } + + if ($parameter->isCallable()) { + return 'callable'; + } + + try { + $parameterClass = $parameter->getClass(); + + if ($parameterClass) { + return '\\' . $parameterClass->getName(); + } + } catch (\ReflectionException $previous) { + throw new \UnexpectedValueException( + sprintf( + 'The type hint of parameter "%s" in method "%s" in class "%s" is invalid.', + $method->getDeclaringClass()->getName(), + $method->getName(), + $parameter->getName() + ), + 0, + $previous + ); + } + + return null; + } + + /** + * @param \ReflectionParameter[] $parameters + * + * @return string[] + */ + private function getParameterNamesForInvocation(array $parameters) + { + return array_map( + function (\ReflectionParameter $parameter) { + $name = ''; + + if ($parameter->isVariadic()) { + $name .= '...'; + } + + $name .= '$' . $parameter->getName(); + + return $name; + }, + $parameters + ); + } + + /** + * @param \ReflectionMethod $method + * + * @return string + */ + private function getMethodReturnType(\ReflectionMethod $method) + { + return $method->hasReturnType() + ? ': ' . $this->formatType($method->getReturnType(), $method) + : '' + ; + } + + /** + * @param \ReflectionMethod $method + * + * @return bool + */ + private function doesMethodReturnValue(\ReflectionMethod $method) + { + return $method->hasReturnType() + ? 'void' !== strtolower($this->formatType($method->getReturnType(), $method)) + : true + ; + } + + /** + * @param \ReflectionType $type + * @param \ReflectionMethod $method + * @param \ReflectionParameter|null $parameter + * + * @return string + * + * @throws \UnexpectedValueException + */ + private function formatType( + \ReflectionType $type, + \ReflectionMethod $method, + \ReflectionParameter $parameter = null + ) { + $name = method_exists($type, 'getName') ? $type->getName() : (string) $type; + $nameLower = strtolower($name); + + if ('self' === $nameLower) { + $name = $method->getDeclaringClass()->getName(); + } + + if ('parent' === $nameLower) { + $name = $method->getDeclaringClass()->getParentClass()->getName(); + } + + if ( ! $type->isBuiltin() && ! class_exists($name) && ! interface_exists($name)) { + if (null !== $parameter) { + throw new \UnexpectedValueException( + sprintf( + 'The type hint of parameter "%s" in method "%s" in class "%s" is invalid.', + $method->getDeclaringClass()->getName(), + $method->getName(), + $parameter->getName() + ) + ); + } + + throw new \UnexpectedValueException( + sprintf( + 'The return type of method "%s" in class "%s" is invalid.', + $method->getDeclaringClass()->getName(), + $method->getName() + ) + ); + } + + if (! $type->isBuiltin()) { + $name = '\\' . $name; + } + + if ($type->allowsNull() + && (null === $parameter || ! $parameter->isDefaultValueAvailable() || null !== $parameter->getDefaultValue()) + ) { + $name = '?' . $name; + } + + return $name; + } + + /** + * @param string $template + * @param ProxyDefinition $definition + * @param array $placeholders + * + * @return string + */ + private function renderTemplate(string $template, ProxyDefinition $definition, array $placeholders = []) : string + { + preg_match_all('(<([a-zA-Z]+)>)', $template, $placeholderMatches); + + $placeholderMatches = array_combine($placeholderMatches[0], $placeholderMatches[1]); + $replacements = []; + + foreach ($placeholderMatches as $tag => $tagName) { + if (isset($placeholders[$tagName]) && is_string($placeholders[$tagName])) { + $replacements[$tag] = $placeholders[$tagName]; + + continue; + } + + $callable = $placeholders[$tagName] ?? [$this, 'generate' . ucfirst($tagName)]; + + $replacements[$tag] = call_user_func($callable, $definition); + } + + return strtr($template, $replacements); + } +} diff --git a/lib/Doctrine/ORM/Proxy/Factory/ProxyResolver.php b/lib/Doctrine/ORM/Proxy/Factory/ProxyResolver.php new file mode 100644 index 00000000000..3541569bb32 --- /dev/null +++ b/lib/Doctrine/ORM/Proxy/Factory/ProxyResolver.php @@ -0,0 +1,31 @@ + + */ +interface ProxyResolver +{ + /** + * @param string $className + * + * @return string + */ + public function resolveProxyClassName(string $className) : string; + + /** + * @param string $className + * + * @return string + */ + public function resolveProxyClassPath(string $className) : string; +} diff --git a/lib/Doctrine/ORM/Proxy/Factory/StaticProxyFactory.php b/lib/Doctrine/ORM/Proxy/Factory/StaticProxyFactory.php new file mode 100644 index 00000000000..d0c80ebb76e --- /dev/null +++ b/lib/Doctrine/ORM/Proxy/Factory/StaticProxyFactory.php @@ -0,0 +1,127 @@ + + * @author Guilherme Blanco + */ +class StaticProxyFactory implements ProxyFactory +{ + /** + * @var EntityManagerInterface + */ + protected $entityManager; + + /** + * @var ProxyGenerator + */ + protected $generator; + + /** + * @var ProxyDefinitionFactory + */ + protected $definitionFactory; + + /** + * @var array + */ + private $definitions = []; + + /** + * ProxyFactory constructor. + * + * @param ProxyConfiguration $configuration + */ + public function __construct(EntityManagerInterface $entityManager, ProxyConfiguration $configuration) + { + $resolver = $configuration->getResolver(); + //$autoGenerate = $configuration->getAutoGenerate(); + $generator = new ProxyGenerator(); + $generatorStrategy = new Strategy\ConditionalFileWriterProxyGeneratorStrategy($generator); + $definitionFactory = new ProxyDefinitionFactory($entityManager, $resolver, $generatorStrategy); + + $generator->setPlaceholder('baseProxyInterface', Proxy::class); + + $this->entityManager = $entityManager; + $this->definitionFactory = $definitionFactory; + } + + /** + * {@inheritdoc} + */ + public function generateProxyClasses(array $classMetadataList) : int + { + $generated = 0; + + foreach ($classMetadataList as $classMetadata) { + if ($classMetadata->isMappedSuperclass || $classMetadata->getReflectionClass()->isAbstract()) { + continue; + } + + $this->definitionFactory->build($classMetadata); + + $generated++; + } + + return $generated; + } + + /** + * {@inheritdoc} + */ + public function getProxy(string $className, array $identifier) : Proxy + { + $proxyDefinition = $this->getOrCreateProxyDefinition($className); + $proxyInstance = $this->createProxyInstance($proxyDefinition); + $proxyPersister = $proxyDefinition->entityPersister; + + $proxyPersister->setIdentifier($proxyInstance, $identifier); + + return $proxyInstance; + } + + /** + * @param ProxyDefinition $definition + * + * @return Proxy + */ + protected function createProxyInstance(ProxyDefinition $definition) : Proxy + { + /** @var Proxy $classMetadata */ + $proxyClassName = $definition->proxyClassName; + + return new $proxyClassName($definition); + } + + /** + * Create a proxy definition for the given class name. + * + * @param string $className + * + * @return ProxyDefinition + */ + private function getOrCreateProxyDefinition(string $className) : ProxyDefinition + { + if (! isset($this->definitions[$className])) { + $classMetadata = $this->entityManager->getClassMetadata($className); + + $this->definitions[$className] = $this->definitionFactory->build($classMetadata); + } + + return $this->definitions[$className]; + } +} diff --git a/lib/Doctrine/ORM/Proxy/Factory/Strategy/ConditionalFileWriterProxyGeneratorStrategy.php b/lib/Doctrine/ORM/Proxy/Factory/Strategy/ConditionalFileWriterProxyGeneratorStrategy.php new file mode 100644 index 00000000000..093c449cc50 --- /dev/null +++ b/lib/Doctrine/ORM/Proxy/Factory/Strategy/ConditionalFileWriterProxyGeneratorStrategy.php @@ -0,0 +1,25 @@ +generator = $generator; + } + + /** + * {@inheritdoc} + */ + public function generate(string $filePath, ProxyDefinition $definition): void + { + $sourceCode = $this->generator->generate($definition); + + eval($sourceCode); + } +} diff --git a/lib/Doctrine/ORM/Proxy/Factory/Strategy/FileReaderProxyGeneratorStrategy.php b/lib/Doctrine/ORM/Proxy/Factory/Strategy/FileReaderProxyGeneratorStrategy.php new file mode 100644 index 00000000000..6ba9067b734 --- /dev/null +++ b/lib/Doctrine/ORM/Proxy/Factory/Strategy/FileReaderProxyGeneratorStrategy.php @@ -0,0 +1,19 @@ +generator = $generator; + } + + /** + * {@inheritdoc} + */ + public function generate(string $filePath, ProxyDefinition $definition): void + { + $sourceCode = $this->generator->generate($definition); + + $this->ensureDirectoryIsReady(dirname($filePath)); + + $tmpFileName = $filePath . '.' . uniqid('', true); + + file_put_contents($tmpFileName, $sourceCode); + @chmod($tmpFileName, 0664); + rename($tmpFileName, $filePath); + + require $filePath; + } + + /** + * @param string $directory + * + * @throws \RuntimeException + */ + private function ensureDirectoryIsReady(string $directory) + { + if (! is_dir($directory) && (false === @mkdir($directory, 0775, true))) { + throw new \RuntimeException(sprintf('Your proxy directory "%s" must be writable', $directory)); + } + + if (! is_writable($directory)) { + throw new \RuntimeException(sprintf('Your proxy directory "%s" must be writable', $directory)); + } + } +} diff --git a/lib/Doctrine/ORM/Proxy/Factory/Strategy/ProxyGeneratorStrategy.php b/lib/Doctrine/ORM/Proxy/Factory/Strategy/ProxyGeneratorStrategy.php new file mode 100644 index 00000000000..863aa3c902f --- /dev/null +++ b/lib/Doctrine/ORM/Proxy/Factory/Strategy/ProxyGeneratorStrategy.php @@ -0,0 +1,19 @@ +. - */ + + +declare(strict_types=1); namespace Doctrine\ORM\Proxy; -use Doctrine\Common\Proxy\Proxy as BaseProxy; +use Doctrine\ORM\Proxy\Factory\ProxyDefinition; /** * Interface for proxy classes. @@ -27,6 +13,30 @@ * @author Roman Borschel * @since 2.0 */ -interface Proxy extends BaseProxy +interface Proxy { + /** + * Initializes this proxy if its not yet initialized. + * + * Acts as a no-op if already initialized. + * + * @return void + */ + public function __load(); + + /** + * Returns whether this proxy is initialized or not. + * + * @return bool + */ + public function __isInitialized(); + + /** + * Marks the proxy as initialized or not. + * + * @param boolean $initialized + * + * @return void + */ + public function __setInitialized($initialized); } diff --git a/lib/Doctrine/ORM/Proxy/ProxyFactory.php b/lib/Doctrine/ORM/Proxy/ProxyFactory.php deleted file mode 100644 index 6bc7dc5272a..00000000000 --- a/lib/Doctrine/ORM/Proxy/ProxyFactory.php +++ /dev/null @@ -1,209 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Proxy; - -use Doctrine\Common\Persistence\Mapping\ClassMetadata; -use Doctrine\Common\Proxy\AbstractProxyFactory; -use Doctrine\Common\Proxy\Proxy as BaseProxy; -use Doctrine\Common\Proxy\ProxyDefinition; -use Doctrine\Common\Proxy\ProxyGenerator; -use Doctrine\Common\Util\ClassUtils; -use Doctrine\ORM\EntityManagerInterface; -use Doctrine\ORM\Persisters\Entity\EntityPersister; -use Doctrine\ORM\EntityNotFoundException; -use Doctrine\ORM\Utility\IdentifierFlattener; - -/** - * This factory is used to create proxy objects for entities at runtime. - * - * @author Roman Borschel - * @author Giorgio Sironi - * @author Marco Pivetta - * @since 2.0 - */ -class ProxyFactory extends AbstractProxyFactory -{ - /** - * @var EntityManagerInterface The EntityManager this factory is bound to. - */ - private $em; - - /** - * @var \Doctrine\ORM\UnitOfWork The UnitOfWork this factory uses to retrieve persisters - */ - private $uow; - - /** - * @var string - */ - private $proxyNs; - - /** - * The IdentifierFlattener used for manipulating identifiers - * - * @var \Doctrine\ORM\Utility\IdentifierFlattener - */ - private $identifierFlattener; - - /** - * Initializes a new instance of the ProxyFactory class that is - * connected to the given EntityManager. - * - * @param EntityManagerInterface $em The EntityManager the new factory works for. - * @param string $proxyDir The directory to use for the proxy classes. It must exist. - * @param string $proxyNs The namespace to use for the proxy classes. - * @param boolean|int $autoGenerate The strategy for automatically generating proxy classes. Possible - * values are constants of Doctrine\Common\Proxy\AbstractProxyFactory. - */ - public function __construct(EntityManagerInterface $em, $proxyDir, $proxyNs, $autoGenerate = AbstractProxyFactory::AUTOGENERATE_NEVER) - { - $proxyGenerator = new ProxyGenerator($proxyDir, $proxyNs); - - $proxyGenerator->setPlaceholder('baseProxyInterface', Proxy::class); - parent::__construct($proxyGenerator, $em->getMetadataFactory(), $autoGenerate); - - $this->em = $em; - $this->uow = $em->getUnitOfWork(); - $this->proxyNs = $proxyNs; - $this->identifierFlattener = new IdentifierFlattener($this->uow, $em->getMetadataFactory()); - } - - /** - * {@inheritDoc} - */ - protected function skipClass(ClassMetadata $metadata) - { - /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadataInfo */ - return $metadata->isMappedSuperclass || $metadata->getReflectionClass()->isAbstract(); - } - - /** - * {@inheritDoc} - */ - protected function createProxyDefinition($className) - { - $classMetadata = $this->em->getClassMetadata($className); - $entityPersister = $this->uow->getEntityPersister($className); - - return new ProxyDefinition( - ClassUtils::generateProxyClassName($className, $this->proxyNs), - $classMetadata->getIdentifierFieldNames(), - $classMetadata->getReflectionProperties(), - $this->createInitializer($classMetadata, $entityPersister), - $this->createCloner($classMetadata, $entityPersister) - ); - } - - /** - * Creates a closure capable of initializing a proxy - * - * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $classMetadata - * @param \Doctrine\ORM\Persisters\Entity\EntityPersister $entityPersister - * - * @return \Closure - * - * @throws \Doctrine\ORM\EntityNotFoundException - */ - private function createInitializer(ClassMetadata $classMetadata, EntityPersister $entityPersister) - { - $wakeupProxy = $classMetadata->getReflectionClass()->hasMethod('__wakeup'); - - return function (BaseProxy $proxy) use ($entityPersister, $classMetadata, $wakeupProxy) { - $initializer = $proxy->__getInitializer(); - $cloner = $proxy->__getCloner(); - - $proxy->__setInitializer(null); - $proxy->__setCloner(null); - - if ($proxy->__isInitialized()) { - return; - } - - $properties = $proxy->__getLazyProperties(); - - foreach ($properties as $propertyName => $property) { - if ( ! isset($proxy->$propertyName)) { - $proxy->$propertyName = $properties[$propertyName]; - } - } - - $proxy->__setInitialized(true); - - if ($wakeupProxy) { - $proxy->__wakeup(); - } - - $identifier = $classMetadata->getIdentifierValues($proxy); - - if (null === $entityPersister->loadById($identifier, $proxy)) { - $proxy->__setInitializer($initializer); - $proxy->__setCloner($cloner); - $proxy->__setInitialized(false); - - throw EntityNotFoundException::fromClassNameAndIdentifier( - $classMetadata->getName(), - $this->identifierFlattener->flattenIdentifier($classMetadata, $identifier) - ); - } - }; - } - - /** - * Creates a closure capable of finalizing state a cloned proxy - * - * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $classMetadata - * @param \Doctrine\ORM\Persisters\Entity\EntityPersister $entityPersister - * - * @return \Closure - * - * @throws \Doctrine\ORM\EntityNotFoundException - */ - private function createCloner(ClassMetadata $classMetadata, EntityPersister $entityPersister) - { - return function (BaseProxy $proxy) use ($entityPersister, $classMetadata) { - if ($proxy->__isInitialized()) { - return; - } - - $proxy->__setInitialized(true); - $proxy->__setInitializer(null); - - $class = $entityPersister->getClassMetadata(); - $identifier = $classMetadata->getIdentifierValues($proxy); - $original = $entityPersister->loadById($identifier); - - if (null === $original) { - throw EntityNotFoundException::fromClassNameAndIdentifier( - $classMetadata->getName(), - $this->identifierFlattener->flattenIdentifier($classMetadata, $identifier) - ); - } - - foreach ($class->getReflectionProperties() as $property) { - if ( ! $class->hasField($property->name) && ! $class->hasAssociation($property->name)) { - continue; - } - - $property->setAccessible(true); - $property->setValue($proxy, $property->getValue($original)); - } - }; - } -} diff --git a/lib/Doctrine/ORM/Query.php b/lib/Doctrine/ORM/Query.php index 385b8c8ea6b..beb7d85c762 100644 --- a/lib/Doctrine/ORM/Query.php +++ b/lib/Doctrine/ORM/Query.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; @@ -129,70 +114,70 @@ final class Query extends AbstractQuery * * @var integer */ - private $_state = self::STATE_CLEAN; + private $state = self::STATE_CLEAN; /** * A snapshot of the parameter types the query was parsed with. * * @var array */ - private $_parsedTypes = []; + private $parsedTypes = []; /** * Cached DQL query. * * @var string */ - private $_dql = null; + private $dql = null; /** * The parser result that holds DQL => SQL information. * * @var \Doctrine\ORM\Query\ParserResult */ - private $_parserResult; + private $parserResult; /** * The first result to return (the "offset"). * * @var integer */ - private $_firstResult = null; + private $firstResult = null; /** * The maximum number of results to return (the "limit"). * * @var integer */ - private $_maxResults = null; + private $maxResults = null; /** * The cache driver used for caching queries. * * @var \Doctrine\Common\Cache\Cache|null */ - private $_queryCache; + private $queryCache; /** * Whether or not expire the query cache. * * @var boolean */ - private $_expireQueryCache = false; + private $expireQueryCache = false; /** * The query cache lifetime. * * @var int */ - private $_queryCacheTTL; + private $queryCacheTTL; /** * Whether to use a query cache, if available. Defaults to TRUE. * * @var boolean */ - private $_useQueryCache = true; + private $useQueryCache = true; /** * Gets the SQL query/queries that correspond to this DQL query. @@ -203,7 +188,7 @@ final class Query extends AbstractQuery */ public function getSQL() { - return $this->_parse()->getSqlExecutor()->getSqlStatements(); + return $this->parse()->getSQLExecutor()->getSQLStatements(); } /** @@ -226,21 +211,21 @@ public function getAST() protected function getResultSetMapping() { // parse query or load from cache - if ($this->_resultSetMapping === null) { - $this->_resultSetMapping = $this->_parse()->getResultSetMapping(); + if ($this->resultSetMapping === null) { + $this->resultSetMapping = $this->parse()->getResultSetMapping(); } - return $this->_resultSetMapping; + return $this->resultSetMapping; } /** * Parses the DQL query, if necessary, and stores the parser result. * - * Note: Populates $this->_parserResult as a side-effect. + * Note: Populates $this->parserResult as a side-effect. * * @return \Doctrine\ORM\Query\ParserResult */ - private function _parse() + private function parse() { $types = []; @@ -250,61 +235,61 @@ private function _parse() } // Return previous parser result if the query and the filter collection are both clean - if ($this->_state === self::STATE_CLEAN && $this->_parsedTypes === $types && $this->_em->isFiltersStateClean()) { - return $this->_parserResult; + if ($this->state === self::STATE_CLEAN && $this->parsedTypes === $types && $this->em->isFiltersStateClean()) { + return $this->parserResult; } - $this->_state = self::STATE_CLEAN; - $this->_parsedTypes = $types; + $this->state = self::STATE_CLEAN; + $this->parsedTypes = $types; // Check query cache. - if ( ! ($this->_useQueryCache && ($queryCache = $this->getQueryCacheDriver()))) { + if ( ! ($this->useQueryCache && ($queryCache = $this->getQueryCacheDriver()))) { $parser = new Parser($this); - $this->_parserResult = $parser->parse(); + $this->parserResult = $parser->parse(); - return $this->_parserResult; + return $this->parserResult; } - $hash = $this->_getQueryCacheId(); - $cached = $this->_expireQueryCache ? false : $queryCache->fetch($hash); + $hash = $this->getQueryCacheId(); + $cached = $this->expireQueryCache ? false : $queryCache->fetch($hash); if ($cached instanceof ParserResult) { // Cache hit. - $this->_parserResult = $cached; + $this->parserResult = $cached; - return $this->_parserResult; + return $this->parserResult; } // Cache miss. $parser = new Parser($this); - $this->_parserResult = $parser->parse(); + $this->parserResult = $parser->parse(); - $queryCache->save($hash, $this->_parserResult, $this->_queryCacheTTL); + $queryCache->save($hash, $this->parserResult, $this->queryCacheTTL); - return $this->_parserResult; + return $this->parserResult; } /** * {@inheritdoc} */ - protected function _doExecute() + protected function doExecute() { - $executor = $this->_parse()->getSqlExecutor(); + $executor = $this->parse()->getSqlExecutor(); - if ($this->_queryCacheProfile) { - $executor->setQueryCacheProfile($this->_queryCacheProfile); + if ($this->queryCacheProfile) { + $executor->setQueryCacheProfile($this->queryCacheProfile); } else { $executor->removeQueryCacheProfile(); } - if ($this->_resultSetMapping === null) { - $this->_resultSetMapping = $this->_parserResult->getResultSetMapping(); + if ($this->resultSetMapping === null) { + $this->resultSetMapping = $this->parserResult->getResultSetMapping(); } // Prepare parameters - $paramMappings = $this->_parserResult->getParameterMappings(); + $paramMappings = $this->parserResult->getParameterMappings(); $paramCount = count($this->parameters); $mappingCount = count($paramMappings); @@ -317,7 +302,7 @@ protected function _doExecute() } // evict all cache for the entity region - if ($this->hasCache && isset($this->_hints[self::HINT_CACHE_EVICT]) && $this->_hints[self::HINT_CACHE_EVICT]) { + if ($this->hasCache && isset($this->hints[self::HINT_CACHE_EVICT]) && $this->hints[self::HINT_CACHE_EVICT]) { $this->evictEntityCacheRegion(); } @@ -327,10 +312,10 @@ protected function _doExecute() $executor, $sqlParams, $types, - $this->_em->getConnection()->getParams() + $this->em->getConnection()->getParams() ); - return $executor->execute($this->_em->getConnection(), $sqlParams, $types); + return $executor->execute($this->em->getConnection(), $sqlParams, $types); } private function evictResultSetCache( @@ -339,15 +324,15 @@ private function evictResultSetCache( array $types, array $connectionParams ) { - if (null === $this->_queryCacheProfile || ! $this->getExpireResultCache()) { + if (null === $this->queryCacheProfile || ! $this->getExpireResultCache()) { return; } - $cacheDriver = $this->_queryCacheProfile->getResultCacheDriver(); + $cacheDriver = $this->queryCacheProfile->getResultCacheDriver(); $statements = (array) $executor->getSqlStatements(); // Type casted since it can either be a string or an array foreach ($statements as $statement) { - $cacheKeys = $this->_queryCacheProfile->generateCacheKeys($statement, $sqlParams, $types, $connectionParams); + $cacheKeys = $this->queryCacheProfile->generateCacheKeys($statement, $sqlParams, $types, $connectionParams); $cacheDriver->delete(reset($cacheKeys)); } @@ -368,7 +353,7 @@ private function evictEntityCacheRegion() ? $AST->deleteClause->abstractSchemaName : $AST->updateClause->abstractSchemaName; - $this->_em->getCache()->evictEntityRegion($className); + $this->em->getCache()->evictEntityRegion($className); } /** @@ -386,18 +371,13 @@ private function processParameterMappings($paramMappings) $types = []; foreach ($this->parameters as $parameter) { - $key = $parameter->getName(); - $value = $parameter->getValue(); - $rsm = $this->getResultSetMapping(); + $key = $parameter->getName(); + $value = $parameter->getValue(); if ( ! isset($paramMappings[$key])) { throw QueryException::unknownParameter($key); } - if (isset($rsm->metadataParameterMapping[$key]) && $value instanceof ClassMetadata) { - $value = $value->getMetadataValue($rsm->metadataParameterMapping[$key]); - } - $value = $this->processParameterValue($value); $type = ($parameter->getValue() === $value) ? $parameter->getType() @@ -408,18 +388,19 @@ private function processParameterMappings($paramMappings) } $sqlPositions = $paramMappings[$key]; + $sqlPositionsCount = count($sqlPositions); // optimized multi value sql positions away for now, // they are not allowed in DQL anyways. $value = [$value]; $countValue = count($value); - for ($i = 0, $l = count($sqlPositions); $i < $l; $i++) { + for ($i = 0, $l = $sqlPositionsCount; $i < $l; $i++) { $sqlParams[$sqlPositions[$i]] = $value[($i % $countValue)]; } } - if (count($sqlParams) != count($types)) { + if (count($sqlParams) !== count($types)) { throw QueryException::parameterTypeMismatch(); } @@ -443,7 +424,7 @@ private function processParameterMappings($paramMappings) */ public function setQueryCacheDriver($queryCache) { - $this->_queryCache = $queryCache; + $this->queryCache = $queryCache; return $this; } @@ -457,7 +438,7 @@ public function setQueryCacheDriver($queryCache) */ public function useQueryCache($bool) { - $this->_useQueryCache = $bool; + $this->useQueryCache = $bool; return $this; } @@ -470,11 +451,11 @@ public function useQueryCache($bool) */ public function getQueryCacheDriver() { - if ($this->_queryCache) { - return $this->_queryCache; + if ($this->queryCache) { + return $this->queryCache; } - return $this->_em->getConfiguration()->getQueryCacheImpl(); + return $this->em->getConfiguration()->getQueryCacheImpl(); } /** @@ -490,7 +471,7 @@ public function setQueryCacheLifetime($timeToLive) $timeToLive = (int) $timeToLive; } - $this->_queryCacheTTL = $timeToLive; + $this->queryCacheTTL = $timeToLive; return $this; } @@ -502,7 +483,7 @@ public function setQueryCacheLifetime($timeToLive) */ public function getQueryCacheLifetime() { - return $this->_queryCacheTTL; + return $this->queryCacheTTL; } /** @@ -514,7 +495,7 @@ public function getQueryCacheLifetime() */ public function expireQueryCache($expire = true) { - $this->_expireQueryCache = $expire; + $this->expireQueryCache = $expire; return $this; } @@ -526,7 +507,7 @@ public function expireQueryCache($expire = true) */ public function getExpireQueryCache() { - return $this->_expireQueryCache; + return $this->expireQueryCache; } /** @@ -536,8 +517,8 @@ public function free() { parent::free(); - $this->_dql = null; - $this->_state = self::STATE_CLEAN; + $this->dql = null; + $this->state = self::STATE_CLEAN; } /** @@ -550,8 +531,8 @@ public function free() public function setDQL($dqlQuery) { if ($dqlQuery !== null) { - $this->_dql = $dqlQuery; - $this->_state = self::STATE_DIRTY; + $this->dql = $dqlQuery; + $this->state = self::STATE_DIRTY; } return $this; @@ -564,7 +545,7 @@ public function setDQL($dqlQuery) */ public function getDQL() { - return $this->_dql; + return $this->dql; } /** @@ -579,7 +560,7 @@ public function getDQL() */ public function getState() { - return $this->_state; + return $this->state; } /** @@ -603,8 +584,8 @@ public function contains($dql) */ public function setFirstResult($firstResult) { - $this->_firstResult = $firstResult; - $this->_state = self::STATE_DIRTY; + $this->firstResult = $firstResult; + $this->state = self::STATE_DIRTY; return $this; } @@ -617,7 +598,7 @@ public function setFirstResult($firstResult) */ public function getFirstResult() { - return $this->_firstResult; + return $this->firstResult; } /** @@ -629,8 +610,8 @@ public function getFirstResult() */ public function setMaxResults($maxResults) { - $this->_maxResults = $maxResults; - $this->_state = self::STATE_DIRTY; + $this->maxResults = $maxResults; + $this->state = self::STATE_DIRTY; return $this; } @@ -643,7 +624,7 @@ public function setMaxResults($maxResults) */ public function getMaxResults() { - return $this->_maxResults; + return $this->maxResults; } /** @@ -667,7 +648,7 @@ public function iterate($parameters = null, $hydrationMode = self::HYDRATE_OBJEC */ public function setHint($name, $value) { - $this->_state = self::STATE_DIRTY; + $this->state = self::STATE_DIRTY; return parent::setHint($name, $value); } @@ -677,7 +658,7 @@ public function setHint($name, $value) */ public function setHydrationMode($hydrationMode) { - $this->_state = self::STATE_DIRTY; + $this->state = self::STATE_DIRTY; return parent::setHydrationMode($hydrationMode); } @@ -696,7 +677,7 @@ public function setHydrationMode($hydrationMode) public function setLockMode($lockMode) { if (in_array($lockMode, [LockMode::NONE, LockMode::PESSIMISTIC_READ, LockMode::PESSIMISTIC_WRITE], true)) { - if ( ! $this->_em->getConnection()->isTransactionActive()) { + if ( ! $this->em->getConnection()->isTransactionActive()) { throw TransactionRequiredException::transactionRequired(); } } @@ -727,9 +708,9 @@ public function getLockMode() * * @return string */ - protected function _getQueryCacheId() + protected function getQueryCacheId() { - ksort($this->_hints); + ksort($this->hints); $platform = $this->getEntityManager() ->getConnection() @@ -737,11 +718,11 @@ protected function _getQueryCacheId() ->getName(); return md5( - $this->getDQL() . serialize($this->_hints) . + $this->getDQL() . serialize($this->hints) . '&platform=' . $platform . - ($this->_em->hasFilters() ? $this->_em->getFilters()->getHash() : '') . - '&firstResult=' . $this->_firstResult . '&maxResult=' . $this->_maxResults . - '&hydrationMode=' . $this->_hydrationMode . '&types=' . serialize($this->_parsedTypes) . 'DOCTRINE_QUERY_CACHE_SALT' + ($this->em->hasFilters() ? $this->em->getFilters()->getHash() : '') . + '&firstResult=' . $this->firstResult . '&maxResult=' . $this->maxResults . + '&hydrationMode=' . $this->hydrationMode . '&types=' . serialize($this->parsedTypes) . 'DOCTRINE_QUERY_CACHE_SALT' ); } @@ -750,7 +731,7 @@ protected function _getQueryCacheId() */ protected function getHash() { - return sha1(parent::getHash(). '-'. $this->_firstResult . '-' . $this->_maxResults); + return sha1(parent::getHash(). '-'. $this->firstResult . '-' . $this->maxResults); } /** @@ -762,6 +743,6 @@ public function __clone() { parent::__clone(); - $this->_state = self::STATE_DIRTY; + $this->state = self::STATE_DIRTY; } } diff --git a/lib/Doctrine/ORM/Query/AST/ASTException.php b/lib/Doctrine/ORM/Query/AST/ASTException.php index b8f931b45ee..4b0f95e71f6 100644 --- a/lib/Doctrine/ORM/Query/AST/ASTException.php +++ b/lib/Doctrine/ORM/Query/AST/ASTException.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/AggregateExpression.php b/lib/Doctrine/ORM/Query/AST/AggregateExpression.php index 0966d902b84..918ac762b2b 100644 --- a/lib/Doctrine/ORM/Query/AST/AggregateExpression.php +++ b/lib/Doctrine/ORM/Query/AST/AggregateExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/ArithmeticExpression.php b/lib/Doctrine/ORM/Query/AST/ArithmeticExpression.php index b586cba3084..6e849cb2910 100644 --- a/lib/Doctrine/ORM/Query/AST/ArithmeticExpression.php +++ b/lib/Doctrine/ORM/Query/AST/ArithmeticExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/ArithmeticFactor.php b/lib/Doctrine/ORM/Query/AST/ArithmeticFactor.php index 3120466fd86..8140710c72e 100644 --- a/lib/Doctrine/ORM/Query/AST/ArithmeticFactor.php +++ b/lib/Doctrine/ORM/Query/AST/ArithmeticFactor.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/ArithmeticTerm.php b/lib/Doctrine/ORM/Query/AST/ArithmeticTerm.php index e08ae7fbb83..f3247d873ed 100644 --- a/lib/Doctrine/ORM/Query/AST/ArithmeticTerm.php +++ b/lib/Doctrine/ORM/Query/AST/ArithmeticTerm.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/BetweenExpression.php b/lib/Doctrine/ORM/Query/AST/BetweenExpression.php index 1e31fd1a5a6..7ec5f04b009 100644 --- a/lib/Doctrine/ORM/Query/AST/BetweenExpression.php +++ b/lib/Doctrine/ORM/Query/AST/BetweenExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/CoalesceExpression.php b/lib/Doctrine/ORM/Query/AST/CoalesceExpression.php index 9e3b4c526fb..b913e3d5fbe 100644 --- a/lib/Doctrine/ORM/Query/AST/CoalesceExpression.php +++ b/lib/Doctrine/ORM/Query/AST/CoalesceExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/CollectionMemberExpression.php b/lib/Doctrine/ORM/Query/AST/CollectionMemberExpression.php index 70989a26784..91e62850f96 100644 --- a/lib/Doctrine/ORM/Query/AST/CollectionMemberExpression.php +++ b/lib/Doctrine/ORM/Query/AST/CollectionMemberExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/ComparisonExpression.php b/lib/Doctrine/ORM/Query/AST/ComparisonExpression.php index ad4d2225736..46ca746c1de 100644 --- a/lib/Doctrine/ORM/Query/AST/ComparisonExpression.php +++ b/lib/Doctrine/ORM/Query/AST/ComparisonExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/ConditionalExpression.php b/lib/Doctrine/ORM/Query/AST/ConditionalExpression.php index bf823629b69..26c201bb6be 100644 --- a/lib/Doctrine/ORM/Query/AST/ConditionalExpression.php +++ b/lib/Doctrine/ORM/Query/AST/ConditionalExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/ConditionalFactor.php b/lib/Doctrine/ORM/Query/AST/ConditionalFactor.php index 7c89faa420b..e7cffa010d9 100644 --- a/lib/Doctrine/ORM/Query/AST/ConditionalFactor.php +++ b/lib/Doctrine/ORM/Query/AST/ConditionalFactor.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/ConditionalPrimary.php b/lib/Doctrine/ORM/Query/AST/ConditionalPrimary.php index 1eed41dce67..3c46b806286 100644 --- a/lib/Doctrine/ORM/Query/AST/ConditionalPrimary.php +++ b/lib/Doctrine/ORM/Query/AST/ConditionalPrimary.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/ConditionalTerm.php b/lib/Doctrine/ORM/Query/AST/ConditionalTerm.php index 7122c9c6822..638123119de 100644 --- a/lib/Doctrine/ORM/Query/AST/ConditionalTerm.php +++ b/lib/Doctrine/ORM/Query/AST/ConditionalTerm.php @@ -1,21 +1,6 @@ . - */ +declare(strict_types=1); + namespace Doctrine\ORM\Query\AST; /** diff --git a/lib/Doctrine/ORM/Query/AST/DeleteClause.php b/lib/Doctrine/ORM/Query/AST/DeleteClause.php index 8ca35c6772f..5eeef3a2f1c 100644 --- a/lib/Doctrine/ORM/Query/AST/DeleteClause.php +++ b/lib/Doctrine/ORM/Query/AST/DeleteClause.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/DeleteStatement.php b/lib/Doctrine/ORM/Query/AST/DeleteStatement.php index da6859b8678..ee9c4b86aac 100644 --- a/lib/Doctrine/ORM/Query/AST/DeleteStatement.php +++ b/lib/Doctrine/ORM/Query/AST/DeleteStatement.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/EmptyCollectionComparisonExpression.php b/lib/Doctrine/ORM/Query/AST/EmptyCollectionComparisonExpression.php index bd978af04be..5311361da8b 100644 --- a/lib/Doctrine/ORM/Query/AST/EmptyCollectionComparisonExpression.php +++ b/lib/Doctrine/ORM/Query/AST/EmptyCollectionComparisonExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/ExistsExpression.php b/lib/Doctrine/ORM/Query/AST/ExistsExpression.php index c53a10775e1..01bdbb01de4 100644 --- a/lib/Doctrine/ORM/Query/AST/ExistsExpression.php +++ b/lib/Doctrine/ORM/Query/AST/ExistsExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/FromClause.php b/lib/Doctrine/ORM/Query/AST/FromClause.php index fdb61ca373a..5c704544d85 100644 --- a/lib/Doctrine/ORM/Query/AST/FromClause.php +++ b/lib/Doctrine/ORM/Query/AST/FromClause.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/AbsFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/AbsFunction.php index 4c614355844..f1b0bbbe92a 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/AbsFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/AbsFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/AvgFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/AvgFunction.php index 6cb8d92b6b2..2ee710a63b8 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/AvgFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/AvgFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/BitAndFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/BitAndFunction.php index 469a4b0a24e..f36c605c71d 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/BitAndFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/BitAndFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/BitOrFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/BitOrFunction.php index d3a3efc8324..36d8a92c8cc 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/BitOrFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/BitOrFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/ConcatFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/ConcatFunction.php index b7c5ae13f82..1a7df4902ac 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/ConcatFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/ConcatFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/CountFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/CountFunction.php index f232cf43f65..f537a2af953 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/CountFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/CountFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/CurrentDateFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/CurrentDateFunction.php index 565b87581b3..0792d9f7006 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/CurrentDateFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/CurrentDateFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimeFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimeFunction.php index ec9ceb757f5..5fc194413e1 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimeFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimeFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimestampFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimestampFunction.php index 4203072128d..209d1e99997 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimestampFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimestampFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/DateAddFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/DateAddFunction.php index 859426f0801..72db330b98e 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/DateAddFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/DateAddFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/DateDiffFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/DateDiffFunction.php index 53724825f4e..4897e6588c2 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/DateDiffFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/DateDiffFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/DateSubFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/DateSubFunction.php index a6415a2863e..d398661d224 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/DateSubFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/DateSubFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/FunctionNode.php b/lib/Doctrine/ORM/Query/AST/Functions/FunctionNode.php index 2f33c9da34b..a65c332ec07 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/FunctionNode.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/FunctionNode.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/IdentityFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/IdentityFunction.php index 6f69d5357ac..a2fa416012a 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/IdentityFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/IdentityFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; @@ -50,27 +35,26 @@ class IdentityFunction extends FunctionNode */ public function getSql(SqlWalker $sqlWalker) { - $platform = $sqlWalker->getEntityManager()->getConnection()->getDatabasePlatform(); - $quoteStrategy = $sqlWalker->getEntityManager()->getConfiguration()->getQuoteStrategy(); + $entityManager = $sqlWalker->getEntityManager(); + $platform = $entityManager->getConnection()->getDatabasePlatform(); $dqlAlias = $this->pathExpression->identificationVariable; $assocField = $this->pathExpression->field; $qComp = $sqlWalker->getQueryComponent($dqlAlias); $class = $qComp['metadata']; - $assoc = $class->associationMappings[$assocField]; - $targetEntity = $sqlWalker->getEntityManager()->getClassMetadata($assoc['targetEntity']); - $joinColumn = reset($assoc['joinColumns']); + $association = $class->getProperty($assocField); + $targetEntity = $sqlWalker->getEntityManager()->getClassMetadata($association->getTargetEntity()); + $joinColumns = $association->getJoinColumns(); + $joinColumn = reset($joinColumns); if ($this->fieldMapping !== null) { - if ( ! isset($targetEntity->fieldMappings[$this->fieldMapping])) { + if (($property = $targetEntity->getProperty($this->fieldMapping)) === null) { throw new QueryException(sprintf('Undefined reference field mapping "%s"', $this->fieldMapping)); } - $field = $targetEntity->fieldMappings[$this->fieldMapping]; $joinColumn = null; - foreach ($assoc['joinColumns'] as $mapping) { - - if ($mapping['referencedColumnName'] === $field['columnName']) { + foreach ($joinColumns as $mapping) { + if ($mapping->getReferencedColumnName() === $property->getColumnName()) { $joinColumn = $mapping; break; @@ -83,12 +67,13 @@ public function getSql(SqlWalker $sqlWalker) } // The table with the relation may be a subclass, so get the table name from the association definition - $tableName = $sqlWalker->getEntityManager()->getClassMetadata($assoc['sourceEntity'])->getTableName(); + $sourceClass = $sqlWalker->getEntityManager()->getClassMetadata($association->getSourceEntity()); + $tableName = $sourceClass->getTableName(); - $tableAlias = $sqlWalker->getSQLTableAlias($tableName, $dqlAlias); - $columnName = $quoteStrategy->getJoinColumnName($joinColumn, $targetEntity, $platform); + $tableAlias = $sqlWalker->getSQLTableAlias($tableName, $dqlAlias); + $quotedColumnName = $platform->quoteIdentifier($joinColumn->getColumnName()); - return $tableAlias . '.' . $columnName; + return $tableAlias . '.' . $quotedColumnName; } /** diff --git a/lib/Doctrine/ORM/Query/AST/Functions/LengthFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/LengthFunction.php index 3d2b1a6c92a..da0e07cf0a5 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/LengthFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/LengthFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/LocateFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/LocateFunction.php index 473aa34eec9..930994e530d 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/LocateFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/LocateFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/LowerFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/LowerFunction.php index 5f0fb950018..d1c4431f338 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/LowerFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/LowerFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/MaxFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/MaxFunction.php index eba9b86393a..a48c4bdd049 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/MaxFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/MaxFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/MinFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/MinFunction.php index e1c08691323..0b3c74c4f81 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/MinFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/MinFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/ModFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/ModFunction.php index 61bc9a79ed9..74c15b3198b 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/ModFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/ModFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/SizeFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/SizeFunction.php index bf0f7a4ec04..3500523d889 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/SizeFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/SizeFunction.php @@ -1,24 +1,10 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; +use Doctrine\ORM\Mapping\OneToManyAssociationMetadata; use Doctrine\ORM\Query\Lexer; /** @@ -46,63 +32,71 @@ class SizeFunction extends FunctionNode */ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { - $platform = $sqlWalker->getEntityManager()->getConnection()->getDatabasePlatform(); - $quoteStrategy = $sqlWalker->getEntityManager()->getConfiguration()->getQuoteStrategy(); - $dqlAlias = $this->collectionPathExpression->identificationVariable; - $assocField = $this->collectionPathExpression->field; - - $qComp = $sqlWalker->getQueryComponent($dqlAlias); - $class = $qComp['metadata']; - $assoc = $class->associationMappings[$assocField]; - $sql = 'SELECT COUNT(*) FROM '; - - if ($assoc['type'] == \Doctrine\ORM\Mapping\ClassMetadata::ONE_TO_MANY) { - $targetClass = $sqlWalker->getEntityManager()->getClassMetadata($assoc['targetEntity']); + $platform = $sqlWalker->getEntityManager()->getConnection()->getDatabasePlatform(); + $dqlAlias = $this->collectionPathExpression->identificationVariable; + $assocField = $this->collectionPathExpression->field; + $sql = 'SELECT COUNT(*) FROM '; + $qComp = $sqlWalker->getQueryComponent($dqlAlias); + $class = $qComp['metadata']; + $association = $class->getProperty($assocField); + $targetClass = $sqlWalker->getEntityManager()->getClassMetadata($association->getTargetEntity()); + $owningAssociation = $association->isOwningSide() + ? $association + : $targetClass->getProperty($association->getMappedBy()) + ; + + if ($association instanceof OneToManyAssociationMetadata) { + $targetTableName = $targetClass->table->getQuotedQualifiedName($platform); $targetTableAlias = $sqlWalker->getSQLTableAlias($targetClass->getTableName()); $sourceTableAlias = $sqlWalker->getSQLTableAlias($class->getTableName(), $dqlAlias); - $sql .= $quoteStrategy->getTableName($targetClass, $platform) . ' ' . $targetTableAlias . ' WHERE '; + $sql .= $targetTableName . ' ' . $targetTableAlias . ' WHERE '; - $owningAssoc = $targetClass->associationMappings[$assoc['mappedBy']]; - - $first = true; + $owningAssociation = $targetClass->getProperty($association->getMappedBy()); + $first = true; - foreach ($owningAssoc['targetToSourceKeyColumns'] as $targetColumn => $sourceColumn) { + foreach ($owningAssociation->getJoinColumns() as $joinColumn) { if ($first) $first = false; else $sql .= ' AND '; - $sql .= $targetTableAlias . '.' . $sourceColumn - . ' = ' - . $sourceTableAlias . '.' . $quoteStrategy->getColumnName($class->fieldNames[$targetColumn], $class, $platform); + $sql .= sprintf('%s.%s = %s.%s', + $targetTableAlias, + $platform->quoteIdentifier($joinColumn->getColumnName()), + $sourceTableAlias, + $platform->quoteIdentifier($joinColumn->getReferencedColumnName()) + ); } } else { // many-to-many - $targetClass = $sqlWalker->getEntityManager()->getClassMetadata($assoc['targetEntity']); - - $owningAssoc = $assoc['isOwningSide'] ? $assoc : $targetClass->associationMappings[$assoc['mappedBy']]; - $joinTable = $owningAssoc['joinTable']; + $joinTable = $owningAssociation->getJoinTable(); + $joinTableName = $joinTable->getQuotedQualifiedName($platform); // SQL table aliases - $joinTableAlias = $sqlWalker->getSQLTableAlias($joinTable['name']); + $joinTableAlias = $sqlWalker->getSQLTableAlias($joinTable->getName()); $sourceTableAlias = $sqlWalker->getSQLTableAlias($class->getTableName(), $dqlAlias); + // Quote in case source table alias matches class table name (happens in an UPDATE statement) + if ($sourceTableAlias === $class->getTableName()) { + $sourceTableAlias = $platform->quoteIdentifier($sourceTableAlias); + } + // join to target table - $sql .= $quoteStrategy->getJoinTableName($owningAssoc, $targetClass, $platform) . ' ' . $joinTableAlias . ' WHERE '; + $sql .= $joinTableName . ' ' . $joinTableAlias . ' WHERE '; - $joinColumns = $assoc['isOwningSide'] - ? $joinTable['joinColumns'] - : $joinTable['inverseJoinColumns']; + $joinColumns = $association->isOwningSide() + ? $joinTable->getJoinColumns() + : $joinTable->getInverseJoinColumns() + ; $first = true; foreach ($joinColumns as $joinColumn) { if ($first) $first = false; else $sql .= ' AND '; - $sourceColumnName = $quoteStrategy->getColumnName( - $class->fieldNames[$joinColumn['referencedColumnName']], $class, $platform + $sql .= sprintf('%s.%s = %s.%s', + $joinTableAlias, + $platform->quoteIdentifier($joinColumn->getColumnName()), + $sourceTableAlias, + $platform->quoteIdentifier($joinColumn->getReferencedColumnName()) ); - - $sql .= $joinTableAlias . '.' . $joinColumn['name'] - . ' = ' - . $sourceTableAlias . '.' . $sourceColumnName; } } diff --git a/lib/Doctrine/ORM/Query/AST/Functions/SqrtFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/SqrtFunction.php index 08155d25b56..d01fd11d29e 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/SqrtFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/SqrtFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/SubstringFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/SubstringFunction.php index a6a80f8112b..36ca898ee10 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/SubstringFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/SubstringFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/SumFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/SumFunction.php index c9fcf7b04e7..84f5991e752 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/SumFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/SumFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/TrimFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/TrimFunction.php index 9e748c308f8..4d0b51be1b0 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/TrimFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/TrimFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/Functions/UpperFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/UpperFunction.php index 28e0f162714..1ac1d8069f0 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/UpperFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/UpperFunction.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST\Functions; diff --git a/lib/Doctrine/ORM/Query/AST/GeneralCaseExpression.php b/lib/Doctrine/ORM/Query/AST/GeneralCaseExpression.php index e7937d60d2e..00065b7f424 100644 --- a/lib/Doctrine/ORM/Query/AST/GeneralCaseExpression.php +++ b/lib/Doctrine/ORM/Query/AST/GeneralCaseExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/GroupByClause.php b/lib/Doctrine/ORM/Query/AST/GroupByClause.php index 687512a4c73..984898c4aa3 100644 --- a/lib/Doctrine/ORM/Query/AST/GroupByClause.php +++ b/lib/Doctrine/ORM/Query/AST/GroupByClause.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/HavingClause.php b/lib/Doctrine/ORM/Query/AST/HavingClause.php index 1d369fff66a..c2edc01cff4 100644 --- a/lib/Doctrine/ORM/Query/AST/HavingClause.php +++ b/lib/Doctrine/ORM/Query/AST/HavingClause.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/IdentificationVariableDeclaration.php b/lib/Doctrine/ORM/Query/AST/IdentificationVariableDeclaration.php index 2e2032ca341..9296445610a 100644 --- a/lib/Doctrine/ORM/Query/AST/IdentificationVariableDeclaration.php +++ b/lib/Doctrine/ORM/Query/AST/IdentificationVariableDeclaration.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/InExpression.php b/lib/Doctrine/ORM/Query/AST/InExpression.php index 64ef1340573..64e37cb060f 100644 --- a/lib/Doctrine/ORM/Query/AST/InExpression.php +++ b/lib/Doctrine/ORM/Query/AST/InExpression.php @@ -1,21 +1,6 @@ . - */ +declare(strict_types=1); + namespace Doctrine\ORM\Query\AST; /** diff --git a/lib/Doctrine/ORM/Query/AST/IndexBy.php b/lib/Doctrine/ORM/Query/AST/IndexBy.php index c7874b70a35..691a00d199b 100644 --- a/lib/Doctrine/ORM/Query/AST/IndexBy.php +++ b/lib/Doctrine/ORM/Query/AST/IndexBy.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/InputParameter.php b/lib/Doctrine/ORM/Query/AST/InputParameter.php index 4da550f9b4f..f54e6b7dae4 100644 --- a/lib/Doctrine/ORM/Query/AST/InputParameter.php +++ b/lib/Doctrine/ORM/Query/AST/InputParameter.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/InstanceOfExpression.php b/lib/Doctrine/ORM/Query/AST/InstanceOfExpression.php index c1fd65b8e6b..4d44e1f446d 100644 --- a/lib/Doctrine/ORM/Query/AST/InstanceOfExpression.php +++ b/lib/Doctrine/ORM/Query/AST/InstanceOfExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/Join.php b/lib/Doctrine/ORM/Query/AST/Join.php index 5c203aa0b47..beb6acaac95 100644 --- a/lib/Doctrine/ORM/Query/AST/Join.php +++ b/lib/Doctrine/ORM/Query/AST/Join.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/JoinAssociationDeclaration.php b/lib/Doctrine/ORM/Query/AST/JoinAssociationDeclaration.php index a33900a6d65..1355a67b575 100644 --- a/lib/Doctrine/ORM/Query/AST/JoinAssociationDeclaration.php +++ b/lib/Doctrine/ORM/Query/AST/JoinAssociationDeclaration.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/JoinAssociationPathExpression.php b/lib/Doctrine/ORM/Query/AST/JoinAssociationPathExpression.php index 946bbb15b7d..a9d05a1add3 100644 --- a/lib/Doctrine/ORM/Query/AST/JoinAssociationPathExpression.php +++ b/lib/Doctrine/ORM/Query/AST/JoinAssociationPathExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/JoinClassPathExpression.php b/lib/Doctrine/ORM/Query/AST/JoinClassPathExpression.php index 7e374149f2d..534031f3e71 100644 --- a/lib/Doctrine/ORM/Query/AST/JoinClassPathExpression.php +++ b/lib/Doctrine/ORM/Query/AST/JoinClassPathExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/JoinVariableDeclaration.php b/lib/Doctrine/ORM/Query/AST/JoinVariableDeclaration.php index 89aa83ad8cc..dfc52fd570c 100644 --- a/lib/Doctrine/ORM/Query/AST/JoinVariableDeclaration.php +++ b/lib/Doctrine/ORM/Query/AST/JoinVariableDeclaration.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/LikeExpression.php b/lib/Doctrine/ORM/Query/AST/LikeExpression.php index e320c51c882..9c49aaf9042 100644 --- a/lib/Doctrine/ORM/Query/AST/LikeExpression.php +++ b/lib/Doctrine/ORM/Query/AST/LikeExpression.php @@ -1,21 +1,6 @@ . - */ +declare(strict_types=1); + namespace Doctrine\ORM\Query\AST; /** diff --git a/lib/Doctrine/ORM/Query/AST/Literal.php b/lib/Doctrine/ORM/Query/AST/Literal.php index 43d71add08f..47d37db5cbe 100644 --- a/lib/Doctrine/ORM/Query/AST/Literal.php +++ b/lib/Doctrine/ORM/Query/AST/Literal.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/NewObjectExpression.php b/lib/Doctrine/ORM/Query/AST/NewObjectExpression.php index ec011ce29f0..a091e8af433 100644 --- a/lib/Doctrine/ORM/Query/AST/NewObjectExpression.php +++ b/lib/Doctrine/ORM/Query/AST/NewObjectExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/Node.php b/lib/Doctrine/ORM/Query/AST/Node.php index a257dc2d79c..3144176b22a 100644 --- a/lib/Doctrine/ORM/Query/AST/Node.php +++ b/lib/Doctrine/ORM/Query/AST/Node.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/NullComparisonExpression.php b/lib/Doctrine/ORM/Query/AST/NullComparisonExpression.php index 84a199784cc..a50f1b92ee8 100644 --- a/lib/Doctrine/ORM/Query/AST/NullComparisonExpression.php +++ b/lib/Doctrine/ORM/Query/AST/NullComparisonExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/NullIfExpression.php b/lib/Doctrine/ORM/Query/AST/NullIfExpression.php index e33bc72b15e..3b83d89fde8 100644 --- a/lib/Doctrine/ORM/Query/AST/NullIfExpression.php +++ b/lib/Doctrine/ORM/Query/AST/NullIfExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/OrderByClause.php b/lib/Doctrine/ORM/Query/AST/OrderByClause.php index e0e30e9d997..cc269b4637f 100644 --- a/lib/Doctrine/ORM/Query/AST/OrderByClause.php +++ b/lib/Doctrine/ORM/Query/AST/OrderByClause.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/OrderByItem.php b/lib/Doctrine/ORM/Query/AST/OrderByItem.php index bf3288a7b9a..06ee75b098e 100644 --- a/lib/Doctrine/ORM/Query/AST/OrderByItem.php +++ b/lib/Doctrine/ORM/Query/AST/OrderByItem.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/ParenthesisExpression.php b/lib/Doctrine/ORM/Query/AST/ParenthesisExpression.php index f16db0eb74d..ff3ad7b7482 100644 --- a/lib/Doctrine/ORM/Query/AST/ParenthesisExpression.php +++ b/lib/Doctrine/ORM/Query/AST/ParenthesisExpression.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; @@ -48,4 +33,4 @@ public function dispatch($walker) { return $walker->walkParenthesisExpression($this); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/ORM/Query/AST/PartialObjectExpression.php b/lib/Doctrine/ORM/Query/AST/PartialObjectExpression.php index e4ffe79b2aa..c0fa381e778 100644 --- a/lib/Doctrine/ORM/Query/AST/PartialObjectExpression.php +++ b/lib/Doctrine/ORM/Query/AST/PartialObjectExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/PathExpression.php b/lib/Doctrine/ORM/Query/AST/PathExpression.php index 37674b6fd47..0eec8da22f5 100644 --- a/lib/Doctrine/ORM/Query/AST/PathExpression.php +++ b/lib/Doctrine/ORM/Query/AST/PathExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/QuantifiedExpression.php b/lib/Doctrine/ORM/Query/AST/QuantifiedExpression.php index 15be9523471..8af695efebc 100644 --- a/lib/Doctrine/ORM/Query/AST/QuantifiedExpression.php +++ b/lib/Doctrine/ORM/Query/AST/QuantifiedExpression.php @@ -1,21 +1,6 @@ . - */ +declare(strict_types=1); + namespace Doctrine\ORM\Query\AST; /** diff --git a/lib/Doctrine/ORM/Query/AST/RangeVariableDeclaration.php b/lib/Doctrine/ORM/Query/AST/RangeVariableDeclaration.php index 0ca5274d19e..1d756377263 100644 --- a/lib/Doctrine/ORM/Query/AST/RangeVariableDeclaration.php +++ b/lib/Doctrine/ORM/Query/AST/RangeVariableDeclaration.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/SelectClause.php b/lib/Doctrine/ORM/Query/AST/SelectClause.php index f8e6f472a1e..3b865ab4890 100644 --- a/lib/Doctrine/ORM/Query/AST/SelectClause.php +++ b/lib/Doctrine/ORM/Query/AST/SelectClause.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/SelectExpression.php b/lib/Doctrine/ORM/Query/AST/SelectExpression.php index 4187013994a..d8f8dfbc510 100644 --- a/lib/Doctrine/ORM/Query/AST/SelectExpression.php +++ b/lib/Doctrine/ORM/Query/AST/SelectExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/SelectStatement.php b/lib/Doctrine/ORM/Query/AST/SelectStatement.php index d84f7258a9f..afe27928e16 100644 --- a/lib/Doctrine/ORM/Query/AST/SelectStatement.php +++ b/lib/Doctrine/ORM/Query/AST/SelectStatement.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/SimpleArithmeticExpression.php b/lib/Doctrine/ORM/Query/AST/SimpleArithmeticExpression.php index 80ecd15ce57..2883ec908fb 100644 --- a/lib/Doctrine/ORM/Query/AST/SimpleArithmeticExpression.php +++ b/lib/Doctrine/ORM/Query/AST/SimpleArithmeticExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/SimpleCaseExpression.php b/lib/Doctrine/ORM/Query/AST/SimpleCaseExpression.php index 67e354e5569..92ec4f79a89 100644 --- a/lib/Doctrine/ORM/Query/AST/SimpleCaseExpression.php +++ b/lib/Doctrine/ORM/Query/AST/SimpleCaseExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/SimpleSelectClause.php b/lib/Doctrine/ORM/Query/AST/SimpleSelectClause.php index 92361da45b7..196e69369cb 100644 --- a/lib/Doctrine/ORM/Query/AST/SimpleSelectClause.php +++ b/lib/Doctrine/ORM/Query/AST/SimpleSelectClause.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/SimpleSelectExpression.php b/lib/Doctrine/ORM/Query/AST/SimpleSelectExpression.php index e556835ed61..f1dca885df0 100644 --- a/lib/Doctrine/ORM/Query/AST/SimpleSelectExpression.php +++ b/lib/Doctrine/ORM/Query/AST/SimpleSelectExpression.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/SimpleWhenClause.php b/lib/Doctrine/ORM/Query/AST/SimpleWhenClause.php index 4f60881d42a..bbdf3aec47e 100644 --- a/lib/Doctrine/ORM/Query/AST/SimpleWhenClause.php +++ b/lib/Doctrine/ORM/Query/AST/SimpleWhenClause.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/Subselect.php b/lib/Doctrine/ORM/Query/AST/Subselect.php index ce08266f083..78203e3515e 100644 --- a/lib/Doctrine/ORM/Query/AST/Subselect.php +++ b/lib/Doctrine/ORM/Query/AST/Subselect.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/SubselectFromClause.php b/lib/Doctrine/ORM/Query/AST/SubselectFromClause.php index 9704061e8cd..2e853bdc5c1 100644 --- a/lib/Doctrine/ORM/Query/AST/SubselectFromClause.php +++ b/lib/Doctrine/ORM/Query/AST/SubselectFromClause.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/SubselectIdentificationVariableDeclaration.php b/lib/Doctrine/ORM/Query/AST/SubselectIdentificationVariableDeclaration.php index 866f112226b..12fb52ca6d1 100644 --- a/lib/Doctrine/ORM/Query/AST/SubselectIdentificationVariableDeclaration.php +++ b/lib/Doctrine/ORM/Query/AST/SubselectIdentificationVariableDeclaration.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/UpdateClause.php b/lib/Doctrine/ORM/Query/AST/UpdateClause.php index 23c722a62b2..13206741750 100644 --- a/lib/Doctrine/ORM/Query/AST/UpdateClause.php +++ b/lib/Doctrine/ORM/Query/AST/UpdateClause.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/UpdateItem.php b/lib/Doctrine/ORM/Query/AST/UpdateItem.php index f1a288cae21..6da8485470d 100644 --- a/lib/Doctrine/ORM/Query/AST/UpdateItem.php +++ b/lib/Doctrine/ORM/Query/AST/UpdateItem.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/UpdateStatement.php b/lib/Doctrine/ORM/Query/AST/UpdateStatement.php index c578efef487..7c2fe06c6ac 100644 --- a/lib/Doctrine/ORM/Query/AST/UpdateStatement.php +++ b/lib/Doctrine/ORM/Query/AST/UpdateStatement.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/WhenClause.php b/lib/Doctrine/ORM/Query/AST/WhenClause.php index 01c0330f48c..b1ba6fbff1c 100644 --- a/lib/Doctrine/ORM/Query/AST/WhenClause.php +++ b/lib/Doctrine/ORM/Query/AST/WhenClause.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/AST/WhereClause.php b/lib/Doctrine/ORM/Query/AST/WhereClause.php index e6597752fff..dbf7c468ed7 100644 --- a/lib/Doctrine/ORM/Query/AST/WhereClause.php +++ b/lib/Doctrine/ORM/Query/AST/WhereClause.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\AST; diff --git a/lib/Doctrine/ORM/Query/Exec/AbstractSqlExecutor.php b/lib/Doctrine/ORM/Query/Exec/AbstractSqlExecutor.php index 8955b9215d5..bdc50a98934 100644 --- a/lib/Doctrine/ORM/Query/Exec/AbstractSqlExecutor.php +++ b/lib/Doctrine/ORM/Query/Exec/AbstractSqlExecutor.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Exec; @@ -36,7 +21,7 @@ abstract class AbstractSqlExecutor /** * @var array */ - protected $_sqlStatements; + protected $sqlStatements; /** * @var QueryCacheProfile @@ -50,7 +35,7 @@ abstract class AbstractSqlExecutor */ public function getSqlStatements() { - return $this->_sqlStatements; + return $this->sqlStatements; } /** diff --git a/lib/Doctrine/ORM/Query/Exec/MultiTableDeleteExecutor.php b/lib/Doctrine/ORM/Query/Exec/MultiTableDeleteExecutor.php index aaf94d7ff90..caacbf72cef 100644 --- a/lib/Doctrine/ORM/Query/Exec/MultiTableDeleteExecutor.php +++ b/lib/Doctrine/ORM/Query/Exec/MultiTableDeleteExecutor.php @@ -1,26 +1,11 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Exec; use Doctrine\DBAL\Connection; -use Doctrine\DBAL\Types\Type; +use Doctrine\ORM\Mapping\ColumnMetadata; use Doctrine\ORM\Query\AST; use Doctrine\ORM\Utility\PersisterHelper; @@ -38,17 +23,17 @@ class MultiTableDeleteExecutor extends AbstractSqlExecutor /** * @var string */ - private $_createTempTableSql; + private $createTempTableSql; /** * @var string */ - private $_dropTempTableSql; + private $dropTempTableSql; /** * @var string */ - private $_insertSql; + private $insertSql; /** * Initializes a new MultiTableDeleteExecutor. @@ -64,53 +49,66 @@ public function __construct(AST\Node $AST, $sqlWalker) $em = $sqlWalker->getEntityManager(); $conn = $em->getConnection(); $platform = $conn->getDatabasePlatform(); - $quoteStrategy = $em->getConfiguration()->getQuoteStrategy(); - $primaryClass = $em->getClassMetadata($AST->deleteClause->abstractSchemaName); - $primaryDqlAlias = $AST->deleteClause->aliasIdentificationVariable; - $rootClass = $em->getClassMetadata($primaryClass->rootEntityName); + $primaryClass = $em->getClassMetadata($AST->deleteClause->abstractSchemaName); + $primaryDqlAlias = $AST->deleteClause->aliasIdentificationVariable; + $rootClass = $em->getClassMetadata($primaryClass->getRootClassName()); - $tempTable = $platform->getTemporaryTableName($rootClass->getTemporaryIdTableName()); - $idColumnNames = $rootClass->getIdentifierColumnNames(); - $idColumnList = implode(', ', $idColumnNames); + $tempTable = $platform->getTemporaryTableName($rootClass->getTemporaryIdTableName()); + $idColumns = $rootClass->getIdentifierColumns($em); + $idColumnNameList = implode(', ', array_keys($idColumns)); // 1. Create an INSERT INTO temptable ... SELECT identifiers WHERE $AST->getWhereClause() - $sqlWalker->setSQLTableAlias($primaryClass->getTableName(), 't0', $primaryDqlAlias); + $sqlWalker->setSQLTableAlias($primaryClass->getTableName(), 'i0', $primaryDqlAlias); - $this->_insertSql = 'INSERT INTO ' . $tempTable . ' (' . $idColumnList . ')' - . ' SELECT t0.' . implode(', t0.', $idColumnNames); + $this->insertSql = 'INSERT INTO ' . $tempTable . ' (' . $idColumnNameList . ')' + . ' SELECT i0.' . implode(', i0.', array_keys($idColumns)); - $rangeDecl = new AST\RangeVariableDeclaration($primaryClass->name, $primaryDqlAlias); + $rangeDecl = new AST\RangeVariableDeclaration($primaryClass->getClassName(), $primaryDqlAlias); $fromClause = new AST\FromClause([new AST\IdentificationVariableDeclaration($rangeDecl, null, [])]); - $this->_insertSql .= $sqlWalker->walkFromClause($fromClause); + $this->insertSql .= $sqlWalker->walkFromClause($fromClause); // Append WHERE clause, if there is one. if ($AST->whereClause) { - $this->_insertSql .= $sqlWalker->walkWhereClause($AST->whereClause); + $this->insertSql .= $sqlWalker->walkWhereClause($AST->whereClause); } - // 2. Create ID subselect statement used in DELETE ... WHERE ... IN (subselect) - $idSubselect = 'SELECT ' . $idColumnList . ' FROM ' . $tempTable; + // 2. Create statement used in DELETE ... WHERE ... IN (subselect) + $deleteSQLTemplate = sprintf( + 'DELETE FROM %%s WHERE (%s) IN (SELECT %s FROM %s)', + $idColumnNameList, + $idColumnNameList, + $tempTable + ); // 3. Create and store DELETE statements - $classNames = array_merge($primaryClass->parentClasses, [$primaryClass->name], $primaryClass->subClasses); - foreach (array_reverse($classNames) as $className) { - $tableName = $quoteStrategy->getTableName($em->getClassMetadata($className), $platform); - $this->_sqlStatements[] = 'DELETE FROM ' . $tableName - . ' WHERE (' . $idColumnList . ') IN (' . $idSubselect . ')'; + $hierarchyClasses = array_merge( + array_map( + function ($className) use ($em) { return $em->getClassMetadata($className); }, + array_reverse($primaryClass->getSubClasses()) + ), + [$primaryClass], + $primaryClass->getAncestorsIterator()->getArrayCopy() + ); + + foreach ($hierarchyClasses as $class) { + $this->sqlStatements[] = sprintf($deleteSQLTemplate, $class->table->getQuotedQualifiedName($platform)); } // 4. Store DDL for temporary identifier table. $columnDefinitions = []; - foreach ($idColumnNames as $idColumnName) { - $columnDefinitions[$idColumnName] = [ + + foreach ($idColumns as $columnName => $column) { + $columnDefinitions[$columnName] = [ 'notnull' => true, - 'type' => Type::getType(PersisterHelper::getTypeOfColumn($idColumnName, $rootClass, $em)), + 'type' => $column->getType(), ]; } - $this->_createTempTableSql = $platform->getCreateTemporaryTableSnippetSQL() . ' ' . $tempTable . ' (' + + $this->createTempTableSql = $platform->getCreateTemporaryTableSnippetSQL() . ' ' . $tempTable . ' (' . $platform->getColumnDeclarationListSQL($columnDefinitions) . ')'; - $this->_dropTempTableSql = $platform->getDropTemporaryTableSQL($tempTable); + + $this->dropTempTableSql = $platform->getDropTemporaryTableSQL($tempTable); } /** @@ -119,26 +117,26 @@ public function __construct(AST\Node $AST, $sqlWalker) public function execute(Connection $conn, array $params, array $types) { // Create temporary id table - $conn->executeUpdate($this->_createTempTableSql); + $conn->executeUpdate($this->createTempTableSql); try { // Insert identifiers - $numDeleted = $conn->executeUpdate($this->_insertSql, $params, $types); + $numDeleted = $conn->executeUpdate($this->insertSql, $params, $types); // Execute DELETE statements - foreach ($this->_sqlStatements as $sql) { + foreach ($this->sqlStatements as $sql) { $conn->executeUpdate($sql); } } catch (\Exception $exception) { // FAILURE! Drop temporary table to avoid possible collisions - $conn->executeUpdate($this->_dropTempTableSql); + $conn->executeUpdate($this->dropTempTableSql); // Re-throw exception throw $exception; } // Drop temporary table - $conn->executeUpdate($this->_dropTempTableSql); + $conn->executeUpdate($this->dropTempTableSql); return $numDeleted; } diff --git a/lib/Doctrine/ORM/Query/Exec/MultiTableUpdateExecutor.php b/lib/Doctrine/ORM/Query/Exec/MultiTableUpdateExecutor.php index acad25a924b..20afc3d8485 100644 --- a/lib/Doctrine/ORM/Query/Exec/MultiTableUpdateExecutor.php +++ b/lib/Doctrine/ORM/Query/Exec/MultiTableUpdateExecutor.php @@ -1,28 +1,13 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Exec; use Doctrine\DBAL\Connection; -use Doctrine\DBAL\Types\Type; -use Doctrine\ORM\Query\ParameterTypeInferer; +use Doctrine\ORM\Mapping\ColumnMetadata; use Doctrine\ORM\Query\AST; +use Doctrine\ORM\Query\ParameterTypeInferer; use Doctrine\ORM\Utility\PersisterHelper; /** @@ -37,27 +22,27 @@ class MultiTableUpdateExecutor extends AbstractSqlExecutor /** * @var string */ - private $_createTempTableSql; + private $createTempTableSql; /** * @var string */ - private $_dropTempTableSql; + private $dropTempTableSql; /** * @var string */ - private $_insertSql; + private $insertSql; /** * @var array */ - private $_sqlParameters = []; + private $sqlParameters = []; /** * @var int */ - private $_numParametersInUpdateClause = 0; + private $numParametersInUpdateClause = 0; /** * Initializes a new MultiTableUpdateExecutor. @@ -73,89 +58,97 @@ public function __construct(AST\Node $AST, $sqlWalker) $em = $sqlWalker->getEntityManager(); $conn = $em->getConnection(); $platform = $conn->getDatabasePlatform(); - $quoteStrategy = $em->getConfiguration()->getQuoteStrategy(); $updateClause = $AST->updateClause; $primaryClass = $sqlWalker->getEntityManager()->getClassMetadata($updateClause->abstractSchemaName); - $rootClass = $em->getClassMetadata($primaryClass->rootEntityName); + $rootClass = $em->getClassMetadata($primaryClass->getRootClassName()); $updateItems = $updateClause->updateItems; - $tempTable = $platform->getTemporaryTableName($rootClass->getTemporaryIdTableName()); - $idColumnNames = $rootClass->getIdentifierColumnNames(); - $idColumnList = implode(', ', $idColumnNames); + $tempTable = $platform->getTemporaryTableName($rootClass->getTemporaryIdTableName()); + $idColumns = $rootClass->getIdentifierColumns($em); + $idColumnNameList = implode(', ', array_keys($idColumns)); // 1. Create an INSERT INTO temptable ... SELECT identifiers WHERE $AST->getWhereClause() - $sqlWalker->setSQLTableAlias($primaryClass->getTableName(), 't0', $updateClause->aliasIdentificationVariable); + $sqlWalker->setSQLTableAlias($primaryClass->getTableName(), 'i0', $updateClause->aliasIdentificationVariable); - $this->_insertSql = 'INSERT INTO ' . $tempTable . ' (' . $idColumnList . ')' - . ' SELECT t0.' . implode(', t0.', $idColumnNames); + $this->insertSql = 'INSERT INTO ' . $tempTable . ' (' . $idColumnNameList . ')' + . ' SELECT i0.' . implode(', i0.', array_keys($idColumns)); - $rangeDecl = new AST\RangeVariableDeclaration($primaryClass->name, $updateClause->aliasIdentificationVariable); + $rangeDecl = new AST\RangeVariableDeclaration($primaryClass->getClassName(), $updateClause->aliasIdentificationVariable); $fromClause = new AST\FromClause([new AST\IdentificationVariableDeclaration($rangeDecl, null, [])]); - $this->_insertSql .= $sqlWalker->walkFromClause($fromClause); + $this->insertSql .= $sqlWalker->walkFromClause($fromClause); - // 2. Create ID subselect statement used in UPDATE ... WHERE ... IN (subselect) - $idSubselect = 'SELECT ' . $idColumnList . ' FROM ' . $tempTable; + // 2. Create statement used in UPDATE ... WHERE ... IN (subselect) + $updateSQLTemplate = sprintf( + 'UPDATE %%s SET %%s WHERE (%s) IN (SELECT %s FROM %s)', + $idColumnNameList, + $idColumnNameList, + $tempTable + ); // 3. Create and store UPDATE statements - $classNames = array_merge($primaryClass->parentClasses, [$primaryClass->name], $primaryClass->subClasses); - $i = -1; + $hierarchyClasses = array_merge( + array_map( + function ($className) use ($em) { return $em->getClassMetadata($className); }, + array_reverse($primaryClass->getSubClasses()) + ), + [$primaryClass], + $primaryClass->getAncestorsIterator()->getArrayCopy() + ); - foreach (array_reverse($classNames) as $className) { - $affected = false; - $class = $em->getClassMetadata($className); - $updateSql = 'UPDATE ' . $quoteStrategy->getTableName($class, $platform) . ' SET '; + $i = 0; - foreach ($updateItems as $updateItem) { - $field = $updateItem->pathExpression->field; - - if ((isset($class->fieldMappings[$field]) && ! isset($class->fieldMappings[$field]['inherited'])) || - (isset($class->associationMappings[$field]) && ! isset($class->associationMappings[$field]['inherited']))) { - $newValue = $updateItem->newValue; + foreach ($hierarchyClasses as $class) { + $updateSQLParts = []; - if ( ! $affected) { - $affected = true; - ++$i; - } else { - $updateSql .= ', '; - } + foreach ($updateItems as $updateItem) { + $field = $updateItem->pathExpression->field; + $property = $class->getProperty($field); - $updateSql .= $sqlWalker->walkUpdateItem($updateItem); + if ($property && ! $class->isInheritedProperty($field)) { + $updateSQLParts[] = $sqlWalker->walkUpdateItem($updateItem); + $newValue = $updateItem->newValue; if ($newValue instanceof AST\InputParameter) { - $this->_sqlParameters[$i][] = $newValue->name; + $this->sqlParameters[$i][] = $newValue->name; - ++$this->_numParametersInUpdateClause; + ++$this->numParametersInUpdateClause; } } } - if ($affected) { - $this->_sqlStatements[$i] = $updateSql . ' WHERE (' . $idColumnList . ') IN (' . $idSubselect . ')'; + if ($updateSQLParts) { + $this->sqlStatements[$i] = sprintf( + $updateSQLTemplate, + $class->table->getQuotedQualifiedName($platform), + implode(', ', $updateSQLParts) + ); + + $i++; } } // Append WHERE clause to insertSql, if there is one. if ($AST->whereClause) { - $this->_insertSql .= $sqlWalker->walkWhereClause($AST->whereClause); + $this->insertSql .= $sqlWalker->walkWhereClause($AST->whereClause); } // 4. Store DDL for temporary identifier table. $columnDefinitions = []; - foreach ($idColumnNames as $idColumnName) { - $columnDefinitions[$idColumnName] = [ + foreach ($idColumns as $columnName => $column) { + $columnDefinitions[$columnName] = [ 'notnull' => true, - 'type' => Type::getType(PersisterHelper::getTypeOfColumn($idColumnName, $rootClass, $em)), + 'type' => $column->getType(), ]; } - $this->_createTempTableSql = $platform->getCreateTemporaryTableSnippetSQL() . ' ' . $tempTable . ' (' + $this->createTempTableSql = $platform->getCreateTemporaryTableSnippetSQL() . ' ' . $tempTable . ' (' . $platform->getColumnDeclarationListSQL($columnDefinitions) . ')'; - $this->_dropTempTableSql = $platform->getDropTemporaryTableSQL($tempTable); + $this->dropTempTableSql = $platform->getDropTemporaryTableSQL($tempTable); } /** @@ -164,25 +157,28 @@ public function __construct(AST\Node $AST, $sqlWalker) public function execute(Connection $conn, array $params, array $types) { // Create temporary id table - $conn->executeUpdate($this->_createTempTableSql); + $conn->executeUpdate($this->createTempTableSql); try { // Insert identifiers. Parameters from the update clause are cut off. $numUpdated = $conn->executeUpdate( - $this->_insertSql, - array_slice($params, $this->_numParametersInUpdateClause), - array_slice($types, $this->_numParametersInUpdateClause) + $this->insertSql, + array_slice($params, $this->numParametersInUpdateClause), + array_slice($types, $this->numParametersInUpdateClause) ); // Execute UPDATE statements - foreach ($this->_sqlStatements as $key => $statement) { + foreach ($this->sqlStatements as $key => $statement) { $paramValues = []; $paramTypes = []; - if (isset($this->_sqlParameters[$key])) { - foreach ($this->_sqlParameters[$key] as $parameterKey => $parameterName) { + if (isset($this->sqlParameters[$key])) { + foreach ($this->sqlParameters[$key] as $parameterKey => $parameterName) { $paramValues[] = $params[$parameterKey]; - $paramTypes[] = isset($types[$parameterKey]) ? $types[$parameterKey] : ParameterTypeInferer::inferType($params[$parameterKey]); + $paramTypes[] = isset($types[$parameterKey]) + ? $types[$parameterKey] + : ParameterTypeInferer::inferType($params[$parameterKey]) + ; } } @@ -190,14 +186,14 @@ public function execute(Connection $conn, array $params, array $types) } } catch (\Exception $exception) { // FAILURE! Drop temporary table to avoid possible collisions - $conn->executeUpdate($this->_dropTempTableSql); + $conn->executeUpdate($this->dropTempTableSql); // Re-throw exception throw $exception; } // Drop temporary table - $conn->executeUpdate($this->_dropTempTableSql); + $conn->executeUpdate($this->dropTempTableSql); return $numUpdated; } diff --git a/lib/Doctrine/ORM/Query/Exec/SingleSelectExecutor.php b/lib/Doctrine/ORM/Query/Exec/SingleSelectExecutor.php index 91827ab1adc..46f262783fb 100644 --- a/lib/Doctrine/ORM/Query/Exec/SingleSelectExecutor.php +++ b/lib/Doctrine/ORM/Query/Exec/SingleSelectExecutor.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Exec; @@ -39,7 +24,7 @@ class SingleSelectExecutor extends AbstractSqlExecutor */ public function __construct(SelectStatement $AST, SqlWalker $sqlWalker) { - $this->_sqlStatements = $sqlWalker->walkSelectStatement($AST); + $this->sqlStatements = $sqlWalker->walkSelectStatement($AST); } /** @@ -47,6 +32,6 @@ public function __construct(SelectStatement $AST, SqlWalker $sqlWalker) */ public function execute(Connection $conn, array $params, array $types) { - return $conn->executeQuery($this->_sqlStatements, $params, $types, $this->queryCacheProfile); + return $conn->executeQuery($this->sqlStatements, $params, $types, $this->queryCacheProfile); } } diff --git a/lib/Doctrine/ORM/Query/Exec/SingleTableDeleteUpdateExecutor.php b/lib/Doctrine/ORM/Query/Exec/SingleTableDeleteUpdateExecutor.php index e0183dd6879..e39447abb97 100644 --- a/lib/Doctrine/ORM/Query/Exec/SingleTableDeleteUpdateExecutor.php +++ b/lib/Doctrine/ORM/Query/Exec/SingleTableDeleteUpdateExecutor.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Exec; @@ -41,9 +26,9 @@ class SingleTableDeleteUpdateExecutor extends AbstractSqlExecutor public function __construct(AST\Node $AST, $sqlWalker) { if ($AST instanceof AST\UpdateStatement) { - $this->_sqlStatements = $sqlWalker->walkUpdateStatement($AST); + $this->sqlStatements = $sqlWalker->walkUpdateStatement($AST); } else if ($AST instanceof AST\DeleteStatement) { - $this->_sqlStatements = $sqlWalker->walkDeleteStatement($AST); + $this->sqlStatements = $sqlWalker->walkDeleteStatement($AST); } } @@ -52,6 +37,6 @@ public function __construct(AST\Node $AST, $sqlWalker) */ public function execute(Connection $conn, array $params, array $types) { - return $conn->executeUpdate($this->_sqlStatements, $params, $types); + return $conn->executeUpdate($this->sqlStatements, $params, $types); } } diff --git a/lib/Doctrine/ORM/Query/Expr.php b/lib/Doctrine/ORM/Query/Expr.php index eada610580d..a20f04a652e 100644 --- a/lib/Doctrine/ORM/Query/Expr.php +++ b/lib/Doctrine/ORM/Query/Expr.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query; @@ -445,7 +430,7 @@ public function in($x, $y) if (is_array($y)) { foreach ($y as &$literal) { if ( ! ($literal instanceof Expr\Literal)) { - $literal = $this->_quoteLiteral($literal); + $literal = $this->quoteLiteral($literal); } } } @@ -466,7 +451,7 @@ public function notIn($x, $y) if (is_array($y)) { foreach ($y as &$literal) { if ( ! ($literal instanceof Expr\Literal)) { - $literal = $this->_quoteLiteral($literal); + $literal = $this->quoteLiteral($literal); } } } @@ -601,7 +586,7 @@ public function length($x) */ public function literal($literal) { - return new Expr\Literal($this->_quoteLiteral($literal)); + return new Expr\Literal($this->quoteLiteral($literal)); } /** @@ -611,7 +596,7 @@ public function literal($literal) * * @return string */ - private function _quoteLiteral($literal) + private function quoteLiteral($literal) { if (is_numeric($literal) && !is_string($literal)) { return (string) $literal; diff --git a/lib/Doctrine/ORM/Query/Expr/Andx.php b/lib/Doctrine/ORM/Query/Expr/Andx.php index dd91916a671..8132f34572b 100644 --- a/lib/Doctrine/ORM/Query/Expr/Andx.php +++ b/lib/Doctrine/ORM/Query/Expr/Andx.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Expr; diff --git a/lib/Doctrine/ORM/Query/Expr/Base.php b/lib/Doctrine/ORM/Query/Expr/Base.php index d1303138360..17be88eff2c 100644 --- a/lib/Doctrine/ORM/Query/Expr/Base.php +++ b/lib/Doctrine/ORM/Query/Expr/Base.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Expr; @@ -107,7 +92,7 @@ public function add($arg) */ public function count() { - return count($this->parts); + return \count($this->parts); } /** @@ -115,7 +100,7 @@ public function count() */ public function __toString() { - if ($this->count() == 1) { + if (1 === $this->count()) { return (string) $this->parts[0]; } diff --git a/lib/Doctrine/ORM/Query/Expr/Comparison.php b/lib/Doctrine/ORM/Query/Expr/Comparison.php index 4103dcea9eb..a6b54f16981 100644 --- a/lib/Doctrine/ORM/Query/Expr/Comparison.php +++ b/lib/Doctrine/ORM/Query/Expr/Comparison.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Expr; diff --git a/lib/Doctrine/ORM/Query/Expr/Composite.php b/lib/Doctrine/ORM/Query/Expr/Composite.php index 6b8a04fa5cf..7fa2ac0e23c 100644 --- a/lib/Doctrine/ORM/Query/Expr/Composite.php +++ b/lib/Doctrine/ORM/Query/Expr/Composite.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Expr; diff --git a/lib/Doctrine/ORM/Query/Expr/From.php b/lib/Doctrine/ORM/Query/Expr/From.php index 9dcce9bbe27..711eca3f49c 100644 --- a/lib/Doctrine/ORM/Query/Expr/From.php +++ b/lib/Doctrine/ORM/Query/Expr/From.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Expr; diff --git a/lib/Doctrine/ORM/Query/Expr/Func.php b/lib/Doctrine/ORM/Query/Expr/Func.php index b4ed07cd3b2..80ba9f5d5d2 100644 --- a/lib/Doctrine/ORM/Query/Expr/Func.php +++ b/lib/Doctrine/ORM/Query/Expr/Func.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Expr; diff --git a/lib/Doctrine/ORM/Query/Expr/GroupBy.php b/lib/Doctrine/ORM/Query/Expr/GroupBy.php index efa3582bdb2..75e7e676817 100644 --- a/lib/Doctrine/ORM/Query/Expr/GroupBy.php +++ b/lib/Doctrine/ORM/Query/Expr/GroupBy.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Expr; diff --git a/lib/Doctrine/ORM/Query/Expr/Join.php b/lib/Doctrine/ORM/Query/Expr/Join.php index 7a59e247ae0..13a0672d936 100644 --- a/lib/Doctrine/ORM/Query/Expr/Join.php +++ b/lib/Doctrine/ORM/Query/Expr/Join.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Expr; diff --git a/lib/Doctrine/ORM/Query/Expr/Literal.php b/lib/Doctrine/ORM/Query/Expr/Literal.php index 98cee79d7ed..d449f378cc7 100644 --- a/lib/Doctrine/ORM/Query/Expr/Literal.php +++ b/lib/Doctrine/ORM/Query/Expr/Literal.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Expr; diff --git a/lib/Doctrine/ORM/Query/Expr/Math.php b/lib/Doctrine/ORM/Query/Expr/Math.php index 9bf800de8fe..cb74b8a3774 100644 --- a/lib/Doctrine/ORM/Query/Expr/Math.php +++ b/lib/Doctrine/ORM/Query/Expr/Math.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Expr; diff --git a/lib/Doctrine/ORM/Query/Expr/OrderBy.php b/lib/Doctrine/ORM/Query/Expr/OrderBy.php index a5f8ef95765..0bae6323d55 100644 --- a/lib/Doctrine/ORM/Query/Expr/OrderBy.php +++ b/lib/Doctrine/ORM/Query/Expr/OrderBy.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Expr; @@ -83,7 +68,7 @@ public function add($sort, $order = null) */ public function count() { - return count($this->parts); + return \count($this->parts); } /** diff --git a/lib/Doctrine/ORM/Query/Expr/Orx.php b/lib/Doctrine/ORM/Query/Expr/Orx.php index d36abfa922c..23a6b97c703 100644 --- a/lib/Doctrine/ORM/Query/Expr/Orx.php +++ b/lib/Doctrine/ORM/Query/Expr/Orx.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Expr; diff --git a/lib/Doctrine/ORM/Query/Expr/Select.php b/lib/Doctrine/ORM/Query/Expr/Select.php index 8ab5153f1f6..bbad9d8a58f 100644 --- a/lib/Doctrine/ORM/Query/Expr/Select.php +++ b/lib/Doctrine/ORM/Query/Expr/Select.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Expr; diff --git a/lib/Doctrine/ORM/Query/Filter/SQLFilter.php b/lib/Doctrine/ORM/Query/Filter/SQLFilter.php index c48edd43faf..e75eb623379 100644 --- a/lib/Doctrine/ORM/Query/Filter/SQLFilter.php +++ b/lib/Doctrine/ORM/Query/Filter/SQLFilter.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query\Filter; diff --git a/lib/Doctrine/ORM/Query/FilterCollection.php b/lib/Doctrine/ORM/Query/FilterCollection.php index ca7f1ac3289..e72fb6cb8f5 100644 --- a/lib/Doctrine/ORM/Query/FilterCollection.php +++ b/lib/Doctrine/ORM/Query/FilterCollection.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query; @@ -50,7 +35,7 @@ class FilterCollection /** * The EntityManager that "owns" this FilterCollection instance. * - * @var \Doctrine\ORM\EntityManager + * @var \Doctrine\ORM\EntityManagerInterface */ private $em; diff --git a/lib/Doctrine/ORM/Query/Lexer.php b/lib/Doctrine/ORM/Query/Lexer.php index b889ecfaea6..ade4344bbed 100644 --- a/lib/Doctrine/ORM/Query/Lexer.php +++ b/lib/Doctrine/ORM/Query/Lexer.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query; diff --git a/lib/Doctrine/ORM/Query/Parameter.php b/lib/Doctrine/ORM/Query/Parameter.php index 39e2a7a4f21..64681333530 100644 --- a/lib/Doctrine/ORM/Query/Parameter.php +++ b/lib/Doctrine/ORM/Query/Parameter.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query; @@ -58,7 +43,7 @@ class Parameter */ public function __construct($name, $value, $type = null) { - $this->name = trim($name, ':'); + $this->name = trim((string) $name, ':'); $this->setValue($value, $type); } diff --git a/lib/Doctrine/ORM/Query/ParameterTypeInferer.php b/lib/Doctrine/ORM/Query/ParameterTypeInferer.php index 597c7e2ea07..2a6530a46f9 100644 --- a/lib/Doctrine/ORM/Query/ParameterTypeInferer.php +++ b/lib/Doctrine/ORM/Query/ParameterTypeInferer.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query; diff --git a/lib/Doctrine/ORM/Query/Parser.php b/lib/Doctrine/ORM/Query/Parser.php index c21b2de9623..ca5130c2cf2 100644 --- a/lib/Doctrine/ORM/Query/Parser.php +++ b/lib/Doctrine/ORM/Query/Parser.php @@ -1,25 +1,13 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query; +use Doctrine\ORM\Mapping\AssociationMetadata; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\FieldMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; use Doctrine\ORM\Query; use Doctrine\ORM\Query\AST\Functions; @@ -134,7 +122,7 @@ class Parser /** * The EntityManager. * - * @var \Doctrine\ORM\EntityManager + * @var \Doctrine\ORM\EntityManagerInterface */ private $em; @@ -239,7 +227,7 @@ public function getParserResult() /** * Gets the EntityManager used by the parser. * - * @return \Doctrine\ORM\EntityManager + * @return \Doctrine\ORM\EntityManagerInterface */ public function getEntityManager() { @@ -479,7 +467,7 @@ public function semanticalError($message = '', $token = null) $length = ($pos !== false) ? $pos - $token['position'] : $distance; $tokenPos = (isset($token['position']) && $token['position'] > 0) ? $token['position'] : '-1'; - $tokenStr = substr($dql, $token['position'], $length); + $tokenStr = substr($dql, (int) $token['position'], $length); // Building informative message $message = 'line 0, col ' . $tokenPos . " near '" . $tokenStr . "': Error: " . $message; @@ -670,24 +658,21 @@ private function processDeferredPartialObjectExpressions() $class = $this->queryComponents[$expr->identificationVariable]['metadata']; foreach ($expr->partialFieldSet as $field) { - if (isset($class->fieldMappings[$field])) { - continue; - } + $property = $class->getProperty($field); - if (isset($class->associationMappings[$field]) && - $class->associationMappings[$field]['isOwningSide'] && - $class->associationMappings[$field]['type'] & ClassMetadata::TO_ONE) { + if ($property instanceof FieldMetadata || + ($property instanceof ToOneAssociationMetadata && $property->isOwningSide())) { continue; } $this->semanticalError( - "There is no mapped field named '$field' on class " . $class->name . ".", $deferredItem['token'] + "There is no mapped field named '$field' on class " . $class->getClassName() . ".", $deferredItem['token'] ); } if (array_intersect($class->identifier, $expr->partialFieldSet) != $class->identifier) { $this->semanticalError( - "The partial field selection of class " . $class->name . " must contain the identifier.", + "The partial field selection of class " . $class->getClassName() . " must contain the identifier.", $deferredItem['token'] ); } @@ -753,22 +738,23 @@ private function processDeferredPathExpressions() $field = $pathExpression->field = $class->identifier[0]; } + $property = $class->getProperty($field); + // Check if field or association exists - if ( ! isset($class->associationMappings[$field]) && ! isset($class->fieldMappings[$field])) { + if (! $property) { $this->semanticalError( - 'Class ' . $class->name . ' has no field or association named ' . $field, + 'Class ' . $class->getClassName() . ' has no field or association named ' . $field, $deferredItem['token'] ); } $fieldType = AST\PathExpression::TYPE_STATE_FIELD; - if (isset($class->associationMappings[$field])) { - $assoc = $class->associationMappings[$field]; - - $fieldType = ($assoc['type'] & ClassMetadata::TO_ONE) + if ($property instanceof AssociationMetadata) { + $fieldType = $property instanceof ToOneAssociationMetadata ? AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION - : AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION; + : AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION + ; } // Validate if PathExpression is one of the expected types @@ -795,7 +781,7 @@ private function processDeferredPathExpressions() // Build the error message $semanticalError = 'Invalid PathExpression. '; - $semanticalError .= (count($expectedStringTypes) == 1) + $semanticalError .= \count($expectedStringTypes) === 1 ? 'Must be a ' . $expectedStringTypes[0] . '.' : implode(' or ', $expectedStringTypes) . ' expected.'; @@ -812,7 +798,7 @@ private function processDeferredPathExpressions() */ private function processRootEntityAliasSelected() { - if ( ! count($this->identVariableExpressions)) { + if ( ! $this->identVariableExpressions) { return; } @@ -1050,8 +1036,8 @@ public function JoinAssociationPathExpression() $qComp = $this->queryComponents[$identVariable]; $class = $qComp['metadata']; - if ( ! $class->hasAssociation($field)) { - $this->semanticalError('Class ' . $class->name . ' has no association named ' . $field); + if (! (($property = $class->getProperty($field)) !== null && $property instanceof AssociationMetadata)) { + $this->semanticalError('Class ' . $class->getClassName() . ' has no association named ' . $field); } return new AST\JoinAssociationPathExpression($identVariable, $field); @@ -1629,13 +1615,14 @@ public function SubselectIdentificationVariableDeclaration() $field = $associationPathExpression->associationField; $class = $this->queryComponents[$identificationVariable]['metadata']; - $targetClass = $this->em->getClassMetadata($class->associationMappings[$field]['targetEntity']); + $association = $class->getProperty($field); + $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); // Building queryComponent $joinQueryComponent = array( 'metadata' => $targetClass, 'parent' => $identificationVariable, - 'relation' => $class->getAssociationMapping($field), + 'relation' => $association, 'map' => null, 'nestingLevel' => $this->nestingLevel, 'token' => $this->lexer->lookahead @@ -1768,13 +1755,14 @@ public function JoinAssociationDeclaration() $field = $joinAssociationPathExpression->associationField; $class = $this->queryComponents[$identificationVariable]['metadata']; - $targetClass = $this->em->getClassMetadata($class->associationMappings[$field]['targetEntity']); + $association = $class->getProperty($field); + $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); // Building queryComponent $joinQueryComponent = [ 'metadata' => $targetClass, 'parent' => $joinAssociationPathExpression->identificationVariable, - 'relation' => $class->getAssociationMapping($field), + 'relation' => $association, 'map' => null, 'nestingLevel' => $this->nestingLevel, 'token' => $this->lexer->lookahead @@ -2392,7 +2380,7 @@ public function ConditionalExpression() // Phase 1 AST optimization: Prevent AST\ConditionalExpression // if only one AST\ConditionalTerm is defined - if (count($conditionalTerms) == 1) { + if (\count($conditionalTerms) === 1) { return $conditionalTerms[0]; } @@ -2417,7 +2405,7 @@ public function ConditionalTerm() // Phase 1 AST optimization: Prevent AST\ConditionalTerm // if only one AST\ConditionalFactor is defined - if (count($conditionalFactors) == 1) { + if (\count($conditionalFactors) === 1) { return $conditionalFactors[0]; } @@ -2740,7 +2728,7 @@ public function SimpleArithmeticExpression() // Phase 1 AST optimization: Prevent AST\SimpleArithmeticExpression // if only one AST\ArithmeticTerm is defined - if (count($terms) == 1) { + if (\count($terms) === 1) { return $terms[0]; } @@ -2766,7 +2754,7 @@ public function ArithmeticTerm() // Phase 1 AST optimization: Prevent AST\ArithmeticTerm // if only one AST\ArithmeticFactor is defined - if (count($factors) == 1) { + if (\count($factors) === 1) { return $factors[0]; } @@ -3357,7 +3345,7 @@ public function FunctionDeclaration() switch (true) { case $customFunctionDeclaration !== null: return $customFunctionDeclaration; - + case (isset(self::$_STRING_FUNCTIONS[$funcName])): return $this->FunctionsReturningStrings(); diff --git a/lib/Doctrine/ORM/Query/ParserResult.php b/lib/Doctrine/ORM/Query/ParserResult.php index 84ad17822bc..c1585d87ab1 100644 --- a/lib/Doctrine/ORM/Query/ParserResult.php +++ b/lib/Doctrine/ORM/Query/ParserResult.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query; @@ -37,21 +22,21 @@ class ParserResult * * @var \Doctrine\ORM\Query\Exec\AbstractSqlExecutor */ - private $_sqlExecutor; + private $sqlExecutor; /** * The ResultSetMapping that describes how to map the SQL result set. * * @var \Doctrine\ORM\Query\ResultSetMapping */ - private $_resultSetMapping; + private $resultSetMapping; /** * The mappings of DQL parameter names/positions to SQL parameter positions. * * @var array */ - private $_parameterMappings = []; + private $parameterMappings = []; /** * Initializes a new instance of the ParserResult class. @@ -59,7 +44,7 @@ class ParserResult */ public function __construct() { - $this->_resultSetMapping = new ResultSetMapping; + $this->resultSetMapping = new ResultSetMapping; } /** @@ -70,7 +55,7 @@ public function __construct() */ public function getResultSetMapping() { - return $this->_resultSetMapping; + return $this->resultSetMapping; } /** @@ -82,7 +67,7 @@ public function getResultSetMapping() */ public function setResultSetMapping(ResultSetMapping $rsm) { - $this->_resultSetMapping = $rsm; + $this->resultSetMapping = $rsm; } /** @@ -94,7 +79,7 @@ public function setResultSetMapping(ResultSetMapping $rsm) */ public function setSqlExecutor($executor) { - $this->_sqlExecutor = $executor; + $this->sqlExecutor = $executor; } /** @@ -104,7 +89,7 @@ public function setSqlExecutor($executor) */ public function getSqlExecutor() { - return $this->_sqlExecutor; + return $this->sqlExecutor; } /** @@ -118,7 +103,7 @@ public function getSqlExecutor() */ public function addParameterMapping($dqlPosition, $sqlPosition) { - $this->_parameterMappings[$dqlPosition][] = $sqlPosition; + $this->parameterMappings[$dqlPosition][] = $sqlPosition; } /** @@ -128,7 +113,7 @@ public function addParameterMapping($dqlPosition, $sqlPosition) */ public function getParameterMappings() { - return $this->_parameterMappings; + return $this->parameterMappings; } /** @@ -140,6 +125,6 @@ public function getParameterMappings() */ public function getSqlParameterPositions($dqlPosition) { - return $this->_parameterMappings[$dqlPosition]; + return $this->parameterMappings[$dqlPosition]; } } diff --git a/lib/Doctrine/ORM/Query/Printer.php b/lib/Doctrine/ORM/Query/Printer.php index d92ad850f5b..5151c4c440a 100644 --- a/lib/Doctrine/ORM/Query/Printer.php +++ b/lib/Doctrine/ORM/Query/Printer.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query; @@ -34,14 +19,14 @@ class Printer * * @var int */ - protected $_indent = 0; + protected $indent = 0; /** * Defines whether parse tree is printed (default, false) or not (true). * * @var bool */ - protected $_silent; + protected $silent; /** * Constructs a new parse tree printer. @@ -50,7 +35,7 @@ class Printer */ public function __construct($silent = false) { - $this->_silent = $silent; + $this->silent = $silent; } /** @@ -66,7 +51,7 @@ public function __construct($silent = false) public function startProduction($name) { $this->println('(' . $name); - $this->_indent++; + $this->indent++; } /** @@ -78,7 +63,7 @@ public function startProduction($name) */ public function endProduction() { - $this->_indent--; + $this->indent--; $this->println(')'); } @@ -91,8 +76,8 @@ public function endProduction() */ public function println($str) { - if ( ! $this->_silent) { - echo str_repeat(' ', $this->_indent), $str, "\n"; + if ( ! $this->silent) { + echo str_repeat(' ', $this->indent), $str, "\n"; } } } diff --git a/lib/Doctrine/ORM/Query/QueryException.php b/lib/Doctrine/ORM/Query/QueryException.php index b78e27bcfee..39e10ac4b64 100644 --- a/lib/Doctrine/ORM/Query/QueryException.php +++ b/lib/Doctrine/ORM/Query/QueryException.php @@ -1,23 +1,9 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query; +use Doctrine\ORM\Mapping\AssociationMetadata; use Doctrine\ORM\Query\AST\PathExpression; @@ -219,15 +205,18 @@ public static function associationPathInverseSideNotSupported(PathExpression $pa } /** - * @param array $assoc + * @param AssociationMetadata $association * * @return QueryException */ - public static function iterateWithFetchJoinNotAllowed($assoc) + public static function iterateWithFetchJoinNotAllowed(AssociationMetadata $association) { return new self( - "Iterate with fetch join in class " . $assoc['sourceEntity'] . - " using association " . $assoc['fieldName'] . " not allowed." + sprintf( + 'Iterate with fetch join in class %s using association %s not allowed.', + $association->getSourceEntity(), + $association->getName() + ) ); } diff --git a/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php b/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php index 8b00d998eae..d85cdd9b06c 100644 --- a/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php +++ b/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query; @@ -146,10 +131,11 @@ public function walkComparison(Comparison $comparison) } $parameterName = str_replace('.', '_', $comparison->getField()); + $parameterCount = \count($this->parameters); foreach ($this->parameters as $parameter) { if ($parameter->getName() === $parameterName) { - $parameterName .= '_' . count($this->parameters); + $parameterName .= '_' . $parameterCount; break; } } diff --git a/lib/Doctrine/ORM/Query/ResultSetMapping.php b/lib/Doctrine/ORM/Query/ResultSetMapping.php index efffa674c2d..62a439cfa06 100644 --- a/lib/Doctrine/ORM/Query/ResultSetMapping.php +++ b/lib/Doctrine/ORM/Query/ResultSetMapping.php @@ -1,23 +1,10 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query; +use Doctrine\DBAL\Types\Type; +use Doctrine\ORM\Mapping\AssociationMetadata; /** * A ResultSetMapping describes how a result set of an SQL query maps to a Doctrine result. @@ -161,13 +148,6 @@ class ResultSetMapping */ public $newObjectMappings = []; - /** - * Maps metadata parameter names to the metadata attribute. - * - * @var array - */ - public $metadataParameterMapping = []; - /** * Adds an entity result to this ResultSetMapping. * @@ -368,13 +348,13 @@ public function addJoinedEntityResult($class, $alias, $parentAlias, $relation) * * @param string $columnName The name of the column in the SQL result set. * @param string $alias The result alias with which the scalar result should be placed in the result structure. - * @param string $type The column type + * @param Type $type The column type * * @return ResultSetMapping This ResultSetMapping instance. * * @todo Rename: addScalar */ - public function addScalarResult($columnName, $alias, $type = 'string') + public function addScalarResult($columnName, $alias, Type $type) { $this->scalarMappings[$columnName] = $alias; $this->typeMappings[$columnName] = $type; @@ -386,17 +366,6 @@ public function addScalarResult($columnName, $alias, $type = 'string') return $this; } - /** - * Adds a metadata parameter mappings. - * - * @param mixed $parameter The parameter name in the SQL result set. - * @param string $attribute The metadata attribute. - */ - public function addMetadataParameterMapping($parameter, $attribute) - { - $this->metadataParameterMapping[$parameter] = $attribute; - } - /** * Checks whether a column with a given name is mapped as a scalar result. * @@ -451,7 +420,7 @@ public function getDeclaringClass($columnName) /** * @param string $alias * - * @return string + * @return AssociationMetadata */ public function getRelation($alias) { @@ -555,25 +524,20 @@ public function isMixedResult() * @param string $columnName The name of the column in the SQL result set. * @param string $fieldName The name of the field on the declaring class. * @param bool $isIdentifierColumn - * @param string $type The column type + * @param Type $type The column type * * @return ResultSetMapping This ResultSetMapping instance. - * - * @todo Make all methods of this class require all parameters and not infer anything */ - public function addMetaResult($alias, $columnName, $fieldName, $isIdentifierColumn = false, $type = null) + public function addMetaResult($alias, $columnName, $fieldName, $isIdentifierColumn, Type $type) { $this->metaMappings[$columnName] = $fieldName; $this->columnOwnerMap[$columnName] = $alias; + $this->typeMappings[$columnName] = $type; if ($isIdentifierColumn) { $this->isIdentifierColumn[$alias][$columnName] = true; } - if ($type) { - $this->typeMappings[$columnName] = $type; - } - return $this; } } diff --git a/lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php b/lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php index 887d02c6f5a..d55b508b8f3 100644 --- a/lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php +++ b/lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php @@ -1,27 +1,18 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query; +use Doctrine\DBAL\Types\Type; use Doctrine\ORM\EntityManagerInterface; -use Doctrine\ORM\Mapping\ClassMetadataInfo; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\FieldMetadata; +use Doctrine\ORM\Mapping\InheritanceType; +use Doctrine\ORM\Mapping\JoinColumnMetadata; use Doctrine\ORM\Mapping\MappingException; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; use Doctrine\ORM\Utility\PersisterHelper; /** @@ -97,13 +88,17 @@ public function __construct(EntityManagerInterface $em, $defaultRenameMode = sel * * @return void */ - public function addRootEntityFromClassMetadata($class, $alias, $renamedColumns = [], $renameMode = null) + public function addRootEntityFromClassMetadata( + string $class, + string $alias, + array $renamedColumns = [], + int $renameMode = null + ) { - $renameMode = $renameMode ?: $this->defaultRenameMode; - $columnAliasMap = $this->getColumnAliasMap($class, $renameMode, $renamedColumns); + $renameMode = $renameMode ?: (empty($renamedColumns) ? $this->defaultRenameMode : self::COLUMN_RENAMING_CUSTOM); $this->addEntityResult($class, $alias); - $this->addAllClassFields($class, $alias, $columnAliasMap); + $this->addAllClassFields($class, $alias, $renamedColumns, $renameMode); } /** @@ -119,13 +114,19 @@ public function addRootEntityFromClassMetadata($class, $alias, $renamedColumns = * * @return void */ - public function addJoinedEntityFromClassMetadata($class, $alias, $parentAlias, $relation, $renamedColumns = [], $renameMode = null) + public function addJoinedEntityFromClassMetadata( + string $class, + string $alias, + string $parentAlias, + string $relation, + array $renamedColumns = [], + int $renameMode = null + ) { - $renameMode = $renameMode ?: $this->defaultRenameMode; - $columnAliasMap = $this->getColumnAliasMap($class, $renameMode, $renamedColumns); + $renameMode = $renameMode ?: (empty($renamedColumns) ? $this->defaultRenameMode : self::COLUMN_RENAMING_CUSTOM); $this->addJoinedEntityResult($class, $alias, $parentAlias, $relation); - $this->addAllClassFields($class, $alias, $columnAliasMap); + $this->addAllClassFields($class, $alias, $renamedColumns, $renameMode); } /** @@ -133,61 +134,84 @@ public function addJoinedEntityFromClassMetadata($class, $alias, $parentAlias, $ * * @param string $class * @param string $alias - * @param array $columnAliasMap + * @param array $customRenameColumns * * @return void * * @throws \InvalidArgumentException */ - protected function addAllClassFields($class, $alias, $columnAliasMap = []) + protected function addAllClassFields(string $class, string $alias, array $customRenameColumns, int $renameMode) : void { + /** @var ClassMetadata $classMetadata */ $classMetadata = $this->em->getClassMetadata($class); $platform = $this->em->getConnection()->getDatabasePlatform(); - if ( ! $this->isInheritanceSupported($classMetadata)) { - throw new \InvalidArgumentException('ResultSetMapping builder does not currently support your inheritance scheme.'); + if (! $this->isInheritanceSupported($classMetadata)) { + throw new \InvalidArgumentException( + 'ResultSetMapping builder does not currently support your inheritance scheme.' + ); } + foreach ($classMetadata->getDeclaredPropertiesIterator() as $property) { + switch (true) { + case ($property instanceof FieldMetadata): + $columnName = $property->getColumnName(); + $columnAlias = $platform->getSQLResultCasing( + $this->getColumnAlias($columnName, $renameMode, $customRenameColumns) + ); + + if (isset($this->fieldMappings[$columnAlias])) { + throw new \InvalidArgumentException( + sprintf("The column '%s' conflicts with another column in the mapper.", $columnName) + ); + } - foreach ($classMetadata->getColumnNames() as $columnName) { - $propertyName = $classMetadata->getFieldName($columnName); - $columnAlias = $platform->getSQLResultCasing($columnAliasMap[$columnName]); + $this->addFieldResult($alias, $columnAlias, $property->getName()); + break; - if (isset($this->fieldMappings[$columnAlias])) { - throw new \InvalidArgumentException("The column '$columnName' conflicts with another column in the mapper."); - } + case ($property instanceof ToOneAssociationMetadata && $property->isOwningSide()): + $targetClass = $this->em->getClassMetadata($property->getTargetEntity()); - $this->addFieldResult($alias, $columnAlias, $propertyName); - } + foreach ($property->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $columnName = $joinColumn->getColumnName(); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + $columnAlias = $platform->getSQLResultCasing( + $this->getColumnAlias($columnName, $renameMode, $customRenameColumns) + ); - foreach ($classMetadata->associationMappings as $associationMapping) { - if ($associationMapping['isOwningSide'] && $associationMapping['type'] & ClassMetadataInfo::TO_ONE) { - $targetClass = $this->em->getClassMetadata($associationMapping['targetEntity']); - $isIdentifier = isset($associationMapping['id']) && $associationMapping['id'] === true; + if (isset($this->metaMappings[$columnAlias])) { + throw new \InvalidArgumentException( + sprintf("The column '%s' conflicts with another column in the mapper.", $columnName) + ); + } - foreach ($associationMapping['joinColumns'] as $joinColumn) { - $columnName = $joinColumn['name']; - $columnAlias = $platform->getSQLResultCasing($columnAliasMap[$columnName]); - $columnType = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); + } - if (isset($this->metaMappings[$columnAlias])) { - throw new \InvalidArgumentException("The column '$columnAlias' conflicts with another column in the mapper."); + $this->addMetaResult($alias, $columnAlias, $columnName, $property->isPrimaryKey(), $joinColumn->getType()); } - - $this->addMetaResult($alias, $columnAlias, $columnName, $isIdentifier, $columnType); - } + break; } } } - private function isInheritanceSupported(ClassMetadataInfo $classMetadata) + /** + * Checks if inheritance if supported. + * + * @param ClassMetadata $metadata + * + * @return boolean + */ + private function isInheritanceSupported(ClassMetadata $metadata) { - if ($classMetadata->isInheritanceTypeSingleTable() - && in_array($classMetadata->name, $classMetadata->discriminatorMap, true)) { + if ($metadata->inheritanceType === InheritanceType::SINGLE_TABLE + && in_array($metadata->getClassName(), $metadata->discriminatorMap, true)) { return true; } - return ! ($classMetadata->isInheritanceTypeSingleTable() || $classMetadata->isInheritanceTypeJoined()); + return ! in_array($metadata->inheritanceType, [InheritanceType::SINGLE_TABLE, InheritanceType::JOINED]); } /** @@ -206,8 +230,7 @@ private function getColumnAlias($columnName, $mode, array $customRenameColumns) return $columnName . $this->sqlCounter++; case self::COLUMN_RENAMING_CUSTOM: - return isset($customRenameColumns[$columnName]) - ? $customRenameColumns[$columnName] : $columnName; + return $customRenameColumns[$columnName] ?? $columnName; case self::COLUMN_RENAMING_NONE: return $columnName; @@ -215,136 +238,72 @@ private function getColumnAlias($columnName, $mode, array $customRenameColumns) } } - /** - * Retrieves a class columns and join columns aliases that are used in the SELECT clause. - * - * This depends on the renaming mode selected by the user. - * - * @param string $className - * @param int $mode - * @param array $customRenameColumns - * - * @return array - */ - private function getColumnAliasMap($className, $mode, array $customRenameColumns) - { - if ($customRenameColumns) { // for BC with 2.2-2.3 API - $mode = self::COLUMN_RENAMING_CUSTOM; - } - - $columnAlias = []; - $class = $this->em->getClassMetadata($className); - - foreach ($class->getColumnNames() as $columnName) { - $columnAlias[$columnName] = $this->getColumnAlias($columnName, $mode, $customRenameColumns); - } - - foreach ($class->associationMappings as $associationMapping) { - if ($associationMapping['isOwningSide'] && $associationMapping['type'] & ClassMetadataInfo::TO_ONE) { - foreach ($associationMapping['joinColumns'] as $joinColumn) { - $columnName = $joinColumn['name']; - $columnAlias[$columnName] = $this->getColumnAlias($columnName, $mode, $customRenameColumns); - } - } - } - - return $columnAlias; - } - /** * Adds the mappings of the results of native SQL queries to the result set. * - * @param ClassMetadataInfo $class - * @param array $queryMapping + * @param ClassMetadata $class + * @param array $queryMapping * * @return ResultSetMappingBuilder */ - public function addNamedNativeQueryMapping(ClassMetadataInfo $class, array $queryMapping) + public function addNamedNativeQueryMapping(ClassMetadata $class, array $queryMapping) { if (isset($queryMapping['resultClass'])) { - return $this->addNamedNativeQueryResultClassMapping($class, $queryMapping['resultClass']); - } + $entityClass = ($queryMapping['resultClass'] === '__CLASS__') + ? $class + : $this->em->getClassMetadata($queryMapping['resultClass']) + ; - return $this->addNamedNativeQueryResultSetMapping($class, $queryMapping['resultSetMapping']); - } + $this->addEntityResult($entityClass->getClassName(), 'e0'); + $this->addNamedNativeQueryEntityResultMapping($entityClass, [], 'e0'); - /** - * Adds the class mapping of the results of native SQL queries to the result set. - * - * @param ClassMetadataInfo $class - * @param string $resultClassName - * - * @return ResultSetMappingBuilder - */ - public function addNamedNativeQueryResultClassMapping(ClassMetadataInfo $class, $resultClassName) - { - $classMetadata = $this->em->getClassMetadata($resultClassName); - $shortName = $classMetadata->reflClass->getShortName(); - $alias = strtolower($shortName[0]).'0'; - - $this->addEntityResult($class->name, $alias); - - if ($classMetadata->discriminatorColumn) { - $discrColumn = $classMetadata->discriminatorColumn; - - $this->setDiscriminatorColumn($alias, $discrColumn['name']); - $this->addMetaResult($alias, $discrColumn['name'], $discrColumn['fieldName'], false, $discrColumn['type']); + return $this; } - foreach ($classMetadata->getColumnNames() as $key => $columnName) { - $propertyName = $classMetadata->getFieldName($columnName); - - $this->addFieldResult($alias, $columnName, $propertyName); - } - - foreach ($classMetadata->associationMappings as $associationMapping) { - if ($associationMapping['isOwningSide'] && $associationMapping['type'] & ClassMetadataInfo::TO_ONE) { - $targetClass = $this->em->getClassMetadata($associationMapping['targetEntity']); - - foreach ($associationMapping['joinColumns'] as $joinColumn) { - $columnName = $joinColumn['name']; - $columnType = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); - - $this->addMetaResult($alias, $columnName, $columnName, $classMetadata->isIdentifier($columnName), $columnType); - } - } - } - - return $this; + return $this->addNamedNativeQueryResultSetMapping($class, $queryMapping['resultSetMapping']); } /** * Adds the result set mapping of the results of native SQL queries to the result set. * - * @param ClassMetadataInfo $class - * @param string $resultSetMappingName + * @param ClassMetadata $class + * @param string $resultSetMappingName * * @return ResultSetMappingBuilder */ - public function addNamedNativeQueryResultSetMapping(ClassMetadataInfo $class, $resultSetMappingName) + public function addNamedNativeQueryResultSetMapping(ClassMetadata $class, $resultSetMappingName) { $counter = 0; $resultMapping = $class->getSqlResultSetMapping($resultSetMappingName); - $rootShortName = $class->reflClass->getShortName(); - $rootAlias = strtolower($rootShortName[0]) . $counter; - + $rootAlias = 'e' . $counter; if (isset($resultMapping['entities'])) { foreach ($resultMapping['entities'] as $key => $entityMapping) { - $classMetadata = $this->em->getClassMetadata($entityMapping['entityClass']); + $entityMapping['entityClass'] = ($entityMapping['entityClass'] === '__CLASS__') + ? $class->getClassName() + : $entityMapping['entityClass'] + ; + + $classMetadata = $this->em->getClassMetadata($entityMapping['entityClass']); - if ($class->reflClass->name == $classMetadata->reflClass->name) { - $this->addEntityResult($classMetadata->name, $rootAlias); + if ($class->getClassName() === $classMetadata->getClassName()) { + $this->addEntityResult($classMetadata->getClassName(), $rootAlias); $this->addNamedNativeQueryEntityResultMapping($classMetadata, $entityMapping, $rootAlias); } else { - $shortName = $classMetadata->reflClass->getShortName(); - $joinAlias = strtolower($shortName[0]) . ++ $counter; - $associations = $class->getAssociationsByTargetClass($classMetadata->name); + $joinAlias = 'e' . ++$counter; $this->addNamedNativeQueryEntityResultMapping($classMetadata, $entityMapping, $joinAlias); - foreach ($associations as $relation => $mapping) { - $this->addJoinedEntityResult($mapping['targetEntity'], $joinAlias, $rootAlias, $relation); + foreach ($class->getDeclaredPropertiesIterator() as $fieldName => $association) { + if (! ($association instanceof AssociationMetadata)) { + continue; + } + + if ($association->getTargetEntity() !== $classMetadata->getClassName()) { + continue; + } + + $this->addJoinedEntityResult($association->getTargetEntity(), $joinAlias, $rootAlias, $fieldName); } } @@ -353,11 +312,8 @@ public function addNamedNativeQueryResultSetMapping(ClassMetadataInfo $class, $r if (isset($resultMapping['columns'])) { foreach ($resultMapping['columns'] as $entityMapping) { - $type = isset($class->fieldNames[$entityMapping['name']]) - ? PersisterHelper::getTypeOfColumn($entityMapping['name'], $class, $this->em) - : 'string'; - - $this->addScalarResult($entityMapping['name'], $entityMapping['name'], $type); + // @todo guilhermeblanco Collect type information from mapped column + $this->addScalarResult($entityMapping['name'], $entityMapping['name'], Type::getType('string')); } } @@ -367,26 +323,30 @@ public function addNamedNativeQueryResultSetMapping(ClassMetadataInfo $class, $r /** * Adds the entity result mapping of the results of native SQL queries to the result set. * - * @param ClassMetadataInfo $classMetadata - * @param array $entityMapping - * @param string $alias + * @param ClassMetadata $classMetadata + * @param array $entityMapping + * @param string $alias * * @return ResultSetMappingBuilder * * @throws MappingException * @throws \InvalidArgumentException */ - public function addNamedNativeQueryEntityResultMapping(ClassMetadataInfo $classMetadata, array $entityMapping, $alias) + public function addNamedNativeQueryEntityResultMapping(ClassMetadata $classMetadata, array $entityMapping, $alias) { - if (isset($entityMapping['discriminatorColumn']) && $entityMapping['discriminatorColumn']) { - $discriminatorColumn = $entityMapping['discriminatorColumn']; - $discriminatorType = $classMetadata->discriminatorColumn['type']; + $platform = $this->em->getConnection()->getDatabasePlatform(); + + // Always fetch discriminator column. It's required for Proxy loading. We only adjust naming if provided + if ($classMetadata->discriminatorColumn) { + $discrColumn = $classMetadata->discriminatorColumn; + $discrColumnName = $entityMapping['discriminatorColumn'] ?? $discrColumn->getColumnName(); + $discrColumnType = $discrColumn->getType(); - $this->setDiscriminatorColumn($alias, $discriminatorColumn); - $this->addMetaResult($alias, $discriminatorColumn, $discriminatorColumn, false, $discriminatorType); + $this->setDiscriminatorColumn($alias, $discrColumnName); + $this->addMetaResult($alias, $discrColumnName, $discrColumnName, false, $discrColumnType); } - if (isset($entityMapping['fields']) && !empty($entityMapping['fields'])) { + if (isset($entityMapping['fields']) && ! empty($entityMapping['fields'])) { foreach ($entityMapping['fields'] as $field) { $fieldName = $field['name']; $relation = null; @@ -395,31 +355,75 @@ public function addNamedNativeQueryEntityResultMapping(ClassMetadataInfo $classM list($relation, $fieldName) = explode('.', $fieldName); } - if (isset($classMetadata->associationMappings[$relation])) { - if ($relation) { - $associationMapping = $classMetadata->associationMappings[$relation]; - $joinAlias = $alias.$relation; - $parentAlias = $alias; + $property = $classMetadata->getProperty($fieldName); - $this->addJoinedEntityResult($associationMapping['targetEntity'], $joinAlias, $parentAlias, $relation); - $this->addFieldResult($joinAlias, $field['column'], $fieldName); - } else { - $this->addFieldResult($alias, $field['column'], $fieldName, $classMetadata->name); - } - } else { - if ( ! isset($classMetadata->fieldMappings[$fieldName])) { - throw new \InvalidArgumentException("Entity '".$classMetadata->name."' has no field '".$fieldName."'. "); + if (! $relation && $property instanceof FieldMetadata) { + $this->addFieldResult($alias, $field['column'], $fieldName, $classMetadata->getClassName()); + + continue; + } + + $property = $classMetadata->getProperty($relation); + + if (! $property) { + throw new \InvalidArgumentException( + "Entity '".$classMetadata->getClassName()."' has no field '".$relation."'. " + ); + } + + if ($property instanceof AssociationMetadata) { + if (! $relation) { + $this->addFieldResult($alias, $field['column'], $fieldName, $classMetadata->getClassName()); + + continue; } - $this->addFieldResult($alias, $field['column'], $fieldName, $classMetadata->name); + $joinAlias = $alias.$relation; + $parentAlias = $alias; + + $this->addJoinedEntityResult($property->getTargetEntity(), $joinAlias, $parentAlias, $relation); + $this->addFieldResult($joinAlias, $field['column'], $fieldName); } } - } else { - foreach ($classMetadata->getColumnNames() as $columnName) { - $propertyName = $classMetadata->getFieldName($columnName); - - $this->addFieldResult($alias, $columnName, $propertyName); + foreach ($classMetadata->getDeclaredPropertiesIterator() as $property) { + switch (true) { + case ($property instanceof FieldMetadata): + $columnName = $property->getColumnName(); + $columnAlias = $platform->getSQLResultCasing($columnName); + + if (isset($this->fieldMappings[$columnAlias])) { + throw new \InvalidArgumentException( + sprintf("The column '%s' conflicts with another column in the mapper.", $columnName) + ); + } + + $this->addFieldResult($alias, $columnAlias, $property->getName()); + break; + + case ($property instanceof ToOneAssociationMetadata && $property->isOwningSide()): + $targetClass = $this->em->getClassMetadata($property->getTargetEntity()); + + foreach ($property->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $columnName = $joinColumn->getColumnName(); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + $columnAlias = $platform->getSQLResultCasing($columnName); + + if (isset($this->metaMappings[$columnAlias])) { + throw new \InvalidArgumentException( + sprintf("The column '%s' conflicts with another column in the mapper.", $columnName) + ); + } + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); + } + + $this->addMetaResult($alias, $columnAlias, $columnName, $property->isPrimaryKey(), $joinColumn->getType()); + } + break; + } } } @@ -452,7 +456,8 @@ public function generateSelectClause($tableAliases = []) if (isset($this->fieldMappings[$columnName])) { $class = $this->em->getClassMetadata($this->declaringClasses[$columnName]); - $sql .= $class->fieldMappings[$this->fieldMappings[$columnName]]['columnName']; + $field = $this->fieldMappings[$columnName]; + $sql .= $class->getProperty($field)->getColumnName(); } else if (isset($this->metaMappings[$columnName])) { $sql .= $this->metaMappings[$columnName]; } else if (isset($this->discriminatorColumns[$dqlAlias])) { diff --git a/lib/Doctrine/ORM/Query/SqlWalker.php b/lib/Doctrine/ORM/Query/SqlWalker.php index 98f58ad8c69..ca1169fa0dc 100644 --- a/lib/Doctrine/ORM/Query/SqlWalker.php +++ b/lib/Doctrine/ORM/Query/SqlWalker.php @@ -1,28 +1,20 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query; use Doctrine\DBAL\LockMode; use Doctrine\DBAL\Types\Type; +use Doctrine\ORM\Mapping\AssociationMetadata; use Doctrine\ORM\Mapping\ClassMetadata; -use Doctrine\ORM\Mapping\ClassMetadataInfo; +use Doctrine\ORM\Mapping\FieldMetadata; +use Doctrine\ORM\Mapping\InheritanceType; +use Doctrine\ORM\Mapping\JoinColumnMetadata; +use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata; +use Doctrine\ORM\Mapping\OneToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; use Doctrine\ORM\OptimisticLockException; use Doctrine\ORM\Query; use Doctrine\ORM\Utility\PersisterHelper; @@ -92,7 +84,7 @@ class SqlWalker implements TreeWalker private $parserResult; /** - * @var \Doctrine\ORM\EntityManager + * @var \Doctrine\ORM\EntityManagerInterface */ private $em; @@ -168,13 +160,6 @@ class SqlWalker implements TreeWalker */ private $platform; - /** - * The quote strategy. - * - * @var \Doctrine\ORM\Mapping\QuoteStrategy - */ - private $quoteStrategy; - /** * {@inheritDoc} */ @@ -187,7 +172,6 @@ public function __construct($query, $parserResult, array $queryComponents) $this->em = $query->getEntityManager(); $this->conn = $this->em->getConnection(); $this->platform = $this->conn->getDatabasePlatform(); - $this->quoteStrategy = $this->em->getConfiguration()->getQuoteStrategy(); } /** @@ -213,7 +197,7 @@ public function getConnection() /** * Gets the EntityManager used by the walker. * - * @return \Doctrine\ORM\EntityManager + * @return \Doctrine\ORM\EntityManagerInterface */ public function getEntityManager() { @@ -263,14 +247,14 @@ public function getExecutor($AST) case ($AST instanceof AST\DeleteStatement): $primaryClass = $this->em->getClassMetadata($AST->deleteClause->abstractSchemaName); - return ($primaryClass->isInheritanceTypeJoined()) + return ($primaryClass->inheritanceType === InheritanceType::JOINED) ? new Exec\MultiTableDeleteExecutor($AST, $this) : new Exec\SingleTableDeleteUpdateExecutor($AST, $this); case ($AST instanceof AST\UpdateStatement): $primaryClass = $this->em->getClassMetadata($AST->updateClause->abstractSchemaName); - return ($primaryClass->isInheritanceTypeJoined()) + return ($primaryClass->inheritanceType === InheritanceType::JOINED) ? new Exec\MultiTableUpdateExecutor($AST, $this) : new Exec\SingleTableDeleteUpdateExecutor($AST, $this); @@ -291,9 +275,8 @@ public function getSQLTableAlias($tableName, $dqlAlias = '') { $tableName .= ($dqlAlias) ? '@[' . $dqlAlias . ']' : ''; - if ( ! isset($this->tableAliasMap[$tableName])) { - $this->tableAliasMap[$tableName] = (preg_match('/[a-z]/i', $tableName[0]) ? strtolower($tableName[0]) : 't') - . $this->tableAliasCounter++ . '_'; + if (! isset($this->tableAliasMap[$tableName])) { + $this->tableAliasMap[$tableName] = 't' . $this->tableAliasCounter++; } return $this->tableAliasMap[$tableName]; @@ -321,13 +304,12 @@ public function setSQLTableAlias($tableName, $alias, $dqlAlias = '') /** * Gets an SQL column alias for a column name. * - * @param string $columnName - * * @return string */ - public function getSQLColumnAlias($columnName) + public function getSQLColumnAlias() { - return $this->quoteStrategy->getColumnAlias($columnName, $this->aliasCounter++, $this->platform); + return $this->platform->getSQLResultCasing('c' . $this->aliasCounter++); + } /** @@ -339,25 +321,29 @@ public function getSQLColumnAlias($columnName) * * @return string The SQL. */ - private function _generateClassTableInheritanceJoins($class, $dqlAlias) + private function generateClassTableInheritanceJoins($class, $dqlAlias) { $sql = ''; $baseTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias); // INNER JOIN parent class tables - foreach ($class->parentClasses as $parentClassName) { - $parentClass = $this->em->getClassMetadata($parentClassName); + $parentClass = $class; + + while (($parentClass = $parentClass->getParent()) !== null) { + $tableName = $parentClass->table->getQuotedQualifiedName($this->platform); $tableAlias = $this->getSQLTableAlias($parentClass->getTableName(), $dqlAlias); // If this is a joined association we must use left joins to preserve the correct result. $sql .= isset($this->queryComponents[$dqlAlias]['relation']) ? ' LEFT ' : ' INNER '; - $sql .= 'JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->platform) . ' ' . $tableAlias . ' ON '; + $sql .= 'JOIN ' . $tableName . ' ' . $tableAlias . ' ON '; $sqlParts = []; - foreach ($this->quoteStrategy->getIdentifierColumnNames($class, $this->platform) as $columnName) { - $sqlParts[] = $baseTableAlias . '.' . $columnName . ' = ' . $tableAlias . '.' . $columnName; + foreach ($class->getIdentifierColumns($this->em) as $column) { + $quotedColumnName = $this->platform->quoteIdentifier($column->getColumnName()); + + $sqlParts[] = $baseTableAlias . '.' . $quotedColumnName . ' = ' . $tableAlias . '.' . $quotedColumnName; } // Add filters on the root class @@ -374,16 +360,19 @@ private function _generateClassTableInheritanceJoins($class, $dqlAlias) } // LEFT JOIN child class tables - foreach ($class->subClasses as $subClassName) { + foreach ($class->getSubClasses() as $subClassName) { $subClass = $this->em->getClassMetadata($subClassName); + $tableName = $subClass->table->getQuotedQualifiedName($this->platform); $tableAlias = $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias); - $sql .= ' LEFT JOIN ' . $this->quoteStrategy->getTableName($subClass, $this->platform) . ' ' . $tableAlias . ' ON '; + $sql .= ' LEFT JOIN ' . $tableName . ' ' . $tableAlias . ' ON '; $sqlParts = []; - foreach ($this->quoteStrategy->getIdentifierColumnNames($subClass, $this->platform) as $columnName) { - $sqlParts[] = $baseTableAlias . '.' . $columnName . ' = ' . $tableAlias . '.' . $columnName; + foreach ($subClass->getIdentifierColumns($this->em) as $column) { + $quotedColumnName = $this->platform->quoteIdentifier($column->getColumnName()); + + $sqlParts[] = $baseTableAlias . '.' . $quotedColumnName . ' = ' . $tableAlias . '.' . $quotedColumnName; } $sql .= implode(' AND ', $sqlParts); @@ -395,26 +384,23 @@ private function _generateClassTableInheritanceJoins($class, $dqlAlias) /** * @return string */ - private function _generateOrderedCollectionOrderByItems() + private function generateOrderedCollectionOrderByItems() { $orderedColumns = []; foreach ($this->selectedClasses as $selectedClass) { - $dqlAlias = $selectedClass['dqlAlias']; - $qComp = $this->queryComponents[$dqlAlias]; + $dqlAlias = $selectedClass['dqlAlias']; + $qComp = $this->queryComponents[$dqlAlias]; + $association = $qComp['relation']; - if ( ! isset($qComp['relation']['orderBy'])) { + if (! ($association instanceof ToManyAssociationMetadata)) { continue; } - $persister = $this->em->getUnitOfWork()->getEntityPersister($qComp['metadata']->name); - - foreach ($qComp['relation']['orderBy'] as $fieldName => $orientation) { - $columnName = $this->quoteStrategy->getColumnName($fieldName, $qComp['metadata'], $this->platform); - $tableName = ($qComp['metadata']->isInheritanceTypeJoined()) - ? $persister->getOwningTable($fieldName) - : $qComp['metadata']->getTableName(); - + foreach ($association->getOrderBy() as $fieldName => $orientation) { + $property = $qComp['metadata']->getProperty($fieldName); + $tableName = $property->getTableName(); + $columnName = $this->platform->quoteIdentifier($property->getColumnName()); $orderedColumn = $this->getSQLTableAlias($tableName, $dqlAlias) . '.' . $columnName; // OrderByClause should replace an ordered relation. see - DDC-2475 @@ -437,14 +423,16 @@ private function _generateOrderedCollectionOrderByItems() * * @return string */ - private function _generateDiscriminatorColumnConditionSQL(array $dqlAliases) + private function generateDiscriminatorColumnConditionSQL(array $dqlAliases) { $sqlParts = []; foreach ($dqlAliases as $dqlAlias) { $class = $this->queryComponents[$dqlAlias]['metadata']; - if ( ! $class->isInheritanceTypeSingleTable()) continue; + if ($class->inheritanceType !== InheritanceType::SINGLE_TABLE) { + continue; + } $conn = $this->em->getConnection(); $values = []; @@ -453,20 +441,27 @@ private function _generateDiscriminatorColumnConditionSQL(array $dqlAliases) $values[] = $conn->quote($class->discriminatorValue); } - foreach ($class->subClasses as $subclassName) { + foreach ($class->getSubClasses() as $subclassName) { $values[] = $conn->quote($this->em->getClassMetadata($subclassName)->discriminatorValue); } - $sqlTableAlias = ($this->useSqlTableAliases) - ? $this->getSQLTableAlias($class->getTableName(), $dqlAlias) . '.' + $discrColumn = $class->discriminatorColumn; + $discrColumnType = $discrColumn->getType(); + $quotedColumnName = $this->platform->quoteIdentifier($discrColumn->getColumnName()); + $sqlTableAlias = ($this->useSqlTableAliases) + ? $this->getSQLTableAlias($discrColumn->getTableName(), $dqlAlias) . '.' : ''; - $sqlParts[] = $sqlTableAlias . $class->discriminatorColumn['name'] . ' IN (' . implode(', ', $values) . ')'; + $sqlParts[] = sprintf( + '%s IN (%s)', + $discrColumnType->convertToDatabaseValueSQL($sqlTableAlias . $quotedColumnName, $this->platform), + implode(', ', $values) + ); } $sql = implode(' AND ', $sqlParts); - return (count($sqlParts) > 1) ? '(' . $sql . ')' : $sql; + return isset($sqlParts[1]) ? '(' . $sql . ')' : $sql; } /** @@ -479,31 +474,35 @@ private function _generateDiscriminatorColumnConditionSQL(array $dqlAliases) */ private function generateFilterConditionSQL(ClassMetadata $targetEntity, $targetTableAlias) { - if (!$this->em->hasFilters()) { + if (! $this->em->hasFilters()) { return ''; } - switch($targetEntity->inheritanceType) { - case ClassMetadata::INHERITANCE_TYPE_NONE: + switch ($targetEntity->inheritanceType) { + case InheritanceType::NONE: break; - case ClassMetadata::INHERITANCE_TYPE_JOINED: + + case InheritanceType::JOINED: // The classes in the inheritance will be added to the query one by one, // but only the root node is getting filtered - if ($targetEntity->name !== $targetEntity->rootEntityName) { + if ($targetEntity->getClassName() !== $targetEntity->getRootClassName()) { return ''; } break; - case ClassMetadata::INHERITANCE_TYPE_SINGLE_TABLE: + + case InheritanceType::SINGLE_TABLE: // With STI the table will only be queried once, make sure that the filters // are added to the root entity - $targetEntity = $this->em->getClassMetadata($targetEntity->rootEntityName); + $targetEntity = $this->em->getClassMetadata($targetEntity->getRootClassName()); break; + default: //@todo: throw exception? return ''; } $filterClauses = []; + foreach ($this->em->getFilters()->getEnabledFilters() as $filter) { if ('' !== $filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias)) { $filterClauses[] = '(' . $filterExpr . ')'; @@ -537,7 +536,7 @@ public function walkSelectStatement(AST\SelectStatement $AST) $sql .= $this->walkOrderByClause($AST->orderByClause); } - if ( ! $AST->orderByClause && ($orderBySql = $this->_generateOrderedCollectionOrderByItems())) { + if ( ! $AST->orderByClause && ($orderBySql = $this->generateOrderedCollectionOrderByItems())) { $sql .= ' ORDER BY ' . $orderBySql; } @@ -562,8 +561,8 @@ public function walkSelectStatement(AST\SelectStatement $AST) } foreach ($this->selectedClasses as $selectedClass) { - if ( ! $selectedClass['class']->isVersioned) { - throw OptimisticLockException::lockFailed($selectedClass['class']->name); + if ( ! $selectedClass['class']->isVersioned()) { + throw OptimisticLockException::lockFailed($selectedClass['class']->getClassName()); } } @@ -608,8 +607,10 @@ public function walkEntityIdentificationVariable($identVariable) $tableAlias = $this->getSQLTableAlias($class->getTableName(), $identVariable); $sqlParts = []; - foreach ($this->quoteStrategy->getIdentifierColumnNames($class, $this->platform) as $columnName) { - $sqlParts[] = $tableAlias . '.' . $columnName; + foreach ($class->getIdentifierColumns($this->em) as $column) { + $quotedColumnName = $this->platform->quoteIdentifier($column->getColumnName()); + + $sqlParts[] = $tableAlias . '.' . $quotedColumnName; } return implode(', ', $sqlParts); @@ -627,11 +628,14 @@ public function walkIdentificationVariable($identificationVariable, $fieldName = { $class = $this->queryComponents[$identificationVariable]['metadata']; - if ( - $fieldName !== null && $class->isInheritanceTypeJoined() && - isset($class->fieldMappings[$fieldName]['inherited']) - ) { - $class = $this->em->getClassMetadata($class->fieldMappings[$fieldName]['inherited']); + if (!$fieldName) { + return $this->getSQLTableAlias($class->getTableName(), $identificationVariable); + } + + $property = $class->getProperty($fieldName); + + if ($class->inheritanceType === InheritanceType::JOINED && $class->isInheritedProperty($fieldName)) { + $class = $property->getDeclaringClass(); } return $this->getSQLTableAlias($class->getTableName(), $identificationVariable); @@ -648,43 +652,43 @@ public function walkPathExpression($pathExpr) switch ($pathExpr->type) { case AST\PathExpression::TYPE_STATE_FIELD: $fieldName = $pathExpr->field; - $dqlAlias = $pathExpr->identificationVariable; - $class = $this->queryComponents[$dqlAlias]['metadata']; + $dqlAlias = $pathExpr->identificationVariable; + $class = $this->queryComponents[$dqlAlias]['metadata']; + $property = $class->getProperty($fieldName); if ($this->useSqlTableAliases) { $sql .= $this->walkIdentificationVariable($dqlAlias, $fieldName) . '.'; } - $sql .= $this->quoteStrategy->getColumnName($fieldName, $class, $this->platform); + $sql .= $this->platform->quoteIdentifier($property->getColumnName()); break; case AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION: // 1- the owning side: // Just use the foreign key, i.e. u.group_id - $fieldName = $pathExpr->field; - $dqlAlias = $pathExpr->identificationVariable; - $class = $this->queryComponents[$dqlAlias]['metadata']; - - if (isset($class->associationMappings[$fieldName]['inherited'])) { - $class = $this->em->getClassMetadata($class->associationMappings[$fieldName]['inherited']); - } + $fieldName = $pathExpr->field; + $dqlAlias = $pathExpr->identificationVariable; + $class = $this->queryComponents[$dqlAlias]['metadata']; + $association = $class->getProperty($fieldName); - $assoc = $class->associationMappings[$fieldName]; - - if ( ! $assoc['isOwningSide']) { + if (! $association->isOwningSide()) { throw QueryException::associationPathInverseSideNotSupported($pathExpr); } + $joinColumns = $association->getJoinColumns(); + // COMPOSITE KEYS NOT (YET?) SUPPORTED - if (count($assoc['sourceToTargetKeyColumns']) > 1) { + if (count($joinColumns) > 1) { throw QueryException::associationPathCompositeKeyNotSupported(); } + $joinColumn = reset($joinColumns); + if ($this->useSqlTableAliases) { - $sql .= $this->getSQLTableAlias($class->getTableName(), $dqlAlias) . '.'; + $sql .= $this->getSQLTableAlias($joinColumn->getTableName(), $dqlAlias) . '.'; } - $sql .= reset($assoc['targetToSourceKeyColumns']); + $sql .= $this->platform->quoteIdentifier($joinColumn->getColumnName()); break; default: @@ -719,56 +723,65 @@ public function walkSelectClause($selectClause) // Register as entity or joined entity result if ($this->queryComponents[$dqlAlias]['relation'] === null) { - $this->rsm->addEntityResult($class->name, $dqlAlias, $resultAlias); + $this->rsm->addEntityResult($class->getClassName(), $dqlAlias, $resultAlias); } else { $this->rsm->addJoinedEntityResult( - $class->name, + $class->getClassName(), $dqlAlias, $this->queryComponents[$dqlAlias]['parent'], - $this->queryComponents[$dqlAlias]['relation']['fieldName'] + $this->queryComponents[$dqlAlias]['relation']->getName() ); } - if ($class->isInheritanceTypeSingleTable() || $class->isInheritanceTypeJoined()) { + if ($class->inheritanceType === InheritanceType::SINGLE_TABLE || $class->inheritanceType === InheritanceType::JOINED) { // Add discriminator columns to SQL - $rootClass = $this->em->getClassMetadata($class->rootEntityName); - $tblAlias = $this->getSQLTableAlias($rootClass->getTableName(), $dqlAlias); - $discrColumn = $rootClass->discriminatorColumn; - $columnAlias = $this->getSQLColumnAlias($discrColumn['name']); - - $sqlSelectExpressions[] = $tblAlias . '.' . $discrColumn['name'] . ' AS ' . $columnAlias; - - $this->rsm->setDiscriminatorColumn($dqlAlias, $columnAlias); - $this->rsm->addMetaResult($dqlAlias, $columnAlias, $discrColumn['fieldName'], false, $discrColumn['type']); - } + $discrColumn = $class->discriminatorColumn; + $discrColumnName = $discrColumn->getColumnName(); + $discrColumnType = $discrColumn->getType(); + $quotedColumnName = $this->platform->quoteIdentifier($discrColumn->getColumnName()); + $sqlTableAlias = $this->getSQLTableAlias($discrColumn->getTableName(), $dqlAlias); + $sqlColumnAlias = $this->getSQLColumnAlias(); + + $sqlSelectExpressions[] = sprintf( + '%s AS %s', + $discrColumnType->convertToDatabaseValueSQL($sqlTableAlias . '.' . $quotedColumnName, $this->platform), + $sqlColumnAlias + ); - // Add foreign key columns to SQL, if necessary - if ( ! $addMetaColumns && ! $class->containsForeignIdentifier) { - continue; + $this->rsm->setDiscriminatorColumn($dqlAlias, $sqlColumnAlias); + $this->rsm->addMetaResult($dqlAlias, $sqlColumnAlias, $discrColumnName, false, $discrColumnType); } // Add foreign key columns of class and also parent classes - foreach ($class->associationMappings as $assoc) { - if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) { + foreach ($class->getDeclaredPropertiesIterator() as $association) { + if (! ($association instanceof ToOneAssociationMetadata && $association->isOwningSide())) { continue; - } else if ( !$addMetaColumns && !isset($assoc['id'])) { + } else if (! $addMetaColumns && ! $association->isPrimaryKey()) { continue; } - $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); - $isIdentifier = (isset($assoc['id']) && $assoc['id'] === true); - $owningClass = (isset($assoc['inherited'])) ? $this->em->getClassMetadata($assoc['inherited']) : $class; - $sqlTableAlias = $this->getSQLTableAlias($owningClass->getTableName(), $dqlAlias); + $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); - foreach ($assoc['joinColumns'] as $joinColumn) { - $columnName = $joinColumn['name']; - $columnAlias = $this->getSQLColumnAlias($columnName); - $columnType = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); + foreach ($association->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $columnName = $joinColumn->getColumnName(); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + $quotedColumnName = $this->platform->quoteIdentifier($columnName); + $columnAlias = $this->getSQLColumnAlias(); + $sqlTableAlias = $this->getSQLTableAlias($joinColumn->getTableName(), $dqlAlias); + + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); + } - $quotedColumnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); - $sqlSelectExpressions[] = $sqlTableAlias . '.' . $quotedColumnName . ' AS ' . $columnAlias; + $sqlSelectExpressions[] = sprintf( + '%s.%s AS %s', + $sqlTableAlias, + $quotedColumnName, + $columnAlias + ); - $this->rsm->addMetaResult($dqlAlias, $columnAlias, $columnName, $isIdentifier, $columnType); + $this->rsm->addMetaResult($dqlAlias, $columnAlias, $columnName, $association->isPrimaryKey(), $joinColumn->getType()); } } @@ -778,27 +791,41 @@ public function walkSelectClause($selectClause) } // Add foreign key columns of subclasses - foreach ($class->subClasses as $subClassName) { - $subClass = $this->em->getClassMetadata($subClassName); - $sqlTableAlias = $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias); + foreach ($class->getSubClasses() as $subClassName) { + $subClass = $this->em->getClassMetadata($subClassName); - foreach ($subClass->associationMappings as $assoc) { + foreach ($subClass->getDeclaredPropertiesIterator() as $association) { // Skip if association is inherited - if (isset($assoc['inherited'])) continue; + if ($subClass->isInheritedProperty($association->getName())) { + continue; + } - if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) { - $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); + if (! ($association instanceof ToOneAssociationMetadata && $association->isOwningSide())) { + continue; + } - foreach ($assoc['joinColumns'] as $joinColumn) { - $columnName = $joinColumn['name']; - $columnAlias = $this->getSQLColumnAlias($columnName); - $columnType = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); + $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); - $quotedColumnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $subClass, $this->platform); - $sqlSelectExpressions[] = $sqlTableAlias . '.' . $quotedColumnName . ' AS ' . $columnAlias; + foreach ($association->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $columnName = $joinColumn->getColumnName(); + $referencedColumnName = $joinColumn->getReferencedColumnName(); + $quotedColumnName = $this->platform->quoteIdentifier($columnName); + $columnAlias = $this->getSQLColumnAlias(); + $sqlTableAlias = $this->getSQLTableAlias($joinColumn->getTableName(), $dqlAlias); - $this->rsm->addMetaResult($dqlAlias, $columnAlias, $columnName, $subClass->isIdentifier($columnName), $columnType); + if (! $joinColumn->getType()) { + $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em)); } + + $sqlSelectExpressions[] = sprintf( + '%s.%s AS %s', + $sqlTableAlias, + $quotedColumnName, + $columnAlias + ); + + $this->rsm->addMetaResult($dqlAlias, $columnAlias, $columnName, $association->isPrimaryKey(), $joinColumn->getType()); } } } @@ -884,14 +911,16 @@ public function walkRangeVariableDeclaration($rangeVariableDeclaration) $this->rootAliases[] = $dqlAlias; } + $tableName = $class->table->getQuotedQualifiedName($this->platform); + $tableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias); + $sql = $this->platform->appendLockHint( - $this->quoteStrategy->getTableName($class, $this->platform) . ' ' . - $this->getSQLTableAlias($class->getTableName(), $dqlAlias), + $tableName . ' ' . $tableAlias, $this->query->getHint(Query::HINT_LOCK_MODE) ); - if ($class->isInheritanceTypeJoined()) { - $sql .= $this->_generateClassTableInheritanceJoins($class, $dqlAlias); + if ($class->inheritanceType === InheritanceType::JOINED) { + $sql .= $this->generateClassTableInheritanceJoins($class, $dqlAlias); } return $sql; @@ -916,129 +945,155 @@ public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joi $joinedDqlAlias = $joinAssociationDeclaration->aliasIdentificationVariable; $indexBy = $joinAssociationDeclaration->indexBy; - $relation = $this->queryComponents[$joinedDqlAlias]['relation']; - $targetClass = $this->em->getClassMetadata($relation['targetEntity']); - $sourceClass = $this->em->getClassMetadata($relation['sourceEntity']); - $targetTableName = $this->quoteStrategy->getTableName($targetClass, $this->platform); + $association = $this->queryComponents[$joinedDqlAlias]['relation']; + $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); + $sourceClass = $this->em->getClassMetadata($association->getSourceEntity()); + $targetTableName = $targetClass->table->getQuotedQualifiedName($this->platform); $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName(), $joinedDqlAlias); $sourceTableAlias = $this->getSQLTableAlias($sourceClass->getTableName(), $associationPathExpression->identificationVariable); // Ensure we got the owning side, since it has all mapping info - $assoc = ( ! $relation['isOwningSide']) ? $targetClass->associationMappings[$relation['mappedBy']] : $relation; - - if ($this->query->getHint(Query::HINT_INTERNAL_ITERATION) == true && (!$this->query->getHint(self::HINT_DISTINCT) || isset($this->selectedClasses[$joinedDqlAlias]))) { - if ($relation['type'] == ClassMetadata::ONE_TO_MANY || $relation['type'] == ClassMetadata::MANY_TO_MANY) { - throw QueryException::iterateWithFetchJoinNotAllowed($assoc); + $owningAssociation = ! $association->isOwningSide() + ? $targetClass->getProperty($association->getMappedBy()) + : $association + ; + + if ($this->query->getHint(Query::HINT_INTERNAL_ITERATION) == true && + (!$this->query->getHint(self::HINT_DISTINCT) || isset($this->selectedClasses[$joinedDqlAlias]))) { + if ($association instanceof ToManyAssociationMetadata) { + throw QueryException::iterateWithFetchJoinNotAllowed($owningAssociation); } } $targetTableJoin = null; - // This condition is not checking ClassMetadata::MANY_TO_ONE, because by definition it cannot + // This condition is not checking ManyToOneAssociationMetadata, because by definition it cannot // be the owning side and previously we ensured that $assoc is always the owning side of the associations. // The owning side is necessary at this point because only it contains the JoinColumn information. - switch (true) { - case ($assoc['type'] & ClassMetadata::TO_ONE): - $conditions = []; - - foreach ($assoc['joinColumns'] as $joinColumn) { - $quotedSourceColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform); - $quotedTargetColumn = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $targetClass, $this->platform); - - if ($relation['isOwningSide']) { - $conditions[] = $sourceTableAlias . '.' . $quotedSourceColumn . ' = ' . $targetTableAlias . '.' . $quotedTargetColumn; - - continue; - } - - $conditions[] = $sourceTableAlias . '.' . $quotedTargetColumn . ' = ' . $targetTableAlias . '.' . $quotedSourceColumn; - } - - // Apply remaining inheritance restrictions - $discrSql = $this->_generateDiscriminatorColumnConditionSQL([$joinedDqlAlias]); - - if ($discrSql) { - $conditions[] = $discrSql; - } - - // Apply the filters - $filterExpr = $this->generateFilterConditionSQL($targetClass, $targetTableAlias); + if ($owningAssociation instanceof ToOneAssociationMetadata) { + $conditions = []; + + foreach ($owningAssociation->getJoinColumns() as $joinColumn) { + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName()); + + if ($association->isOwningSide()) { + $conditions[] = sprintf( + '%s.%s = %s.%s', + $sourceTableAlias, + $quotedColumnName, + $targetTableAlias, + $quotedReferencedColumnName + ); - if ($filterExpr) { - $conditions[] = $filterExpr; + continue; } - $targetTableJoin = [ - 'table' => $targetTableName . ' ' . $targetTableAlias, - 'condition' => implode(' AND ', $conditions), - ]; - break; + $conditions[] = sprintf( + '%s.%s = %s.%s', + $sourceTableAlias, + $quotedReferencedColumnName, + $targetTableAlias, + $quotedColumnName + ); + } - case ($assoc['type'] == ClassMetadata::MANY_TO_MANY): - // Join relation table - $joinTable = $assoc['joinTable']; - $joinTableAlias = $this->getSQLTableAlias($joinTable['name'], $joinedDqlAlias); - $joinTableName = $this->quoteStrategy->getJoinTableName($assoc, $sourceClass, $this->platform); + // Apply remaining inheritance restrictions + $discrSql = $this->generateDiscriminatorColumnConditionSQL([$joinedDqlAlias]); - $conditions = []; - $relationColumns = ($relation['isOwningSide']) - ? $assoc['joinTable']['joinColumns'] - : $assoc['joinTable']['inverseJoinColumns']; + if ($discrSql) { + $conditions[] = $discrSql; + } - foreach ($relationColumns as $joinColumn) { - $quotedSourceColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform); - $quotedTargetColumn = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $targetClass, $this->platform); + // Apply the filters + $filterExpr = $this->generateFilterConditionSQL($targetClass, $targetTableAlias); - $conditions[] = $sourceTableAlias . '.' . $quotedTargetColumn . ' = ' . $joinTableAlias . '.' . $quotedSourceColumn; - } + if ($filterExpr) { + $conditions[] = $filterExpr; + } - $sql .= $joinTableName . ' ' . $joinTableAlias . ' ON ' . implode(' AND ', $conditions); + $targetTableJoin = [ + 'table' => $targetTableName . ' ' . $targetTableAlias, + 'condition' => implode(' AND ', $conditions), + ]; + } else if ($owningAssociation instanceof ManyToManyAssociationMetadata) { + // Join relation table + $joinTable = $owningAssociation->getJoinTable(); + $joinTableName = $joinTable->getQuotedQualifiedName($this->platform); + $joinTableAlias = $this->getSQLTableAlias($joinTable->getName(), $joinedDqlAlias); + + $conditions = []; + $joinColumns = $association->isOwningSide() + ? $joinTable->getJoinColumns() + : $joinTable->getInverseJoinColumns() + ; - // Join target table - $sql .= ($joinType == AST\Join::JOIN_TYPE_LEFT || $joinType == AST\Join::JOIN_TYPE_LEFTOUTER) ? ' LEFT JOIN ' : ' INNER JOIN '; + foreach ($joinColumns as $joinColumn) { + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName()); + + $conditions[] = sprintf( + '%s.%s = %s.%s', + $sourceTableAlias, + $quotedReferencedColumnName, + $joinTableAlias, + $quotedColumnName + ); + } - $conditions = []; - $relationColumns = ($relation['isOwningSide']) - ? $assoc['joinTable']['inverseJoinColumns'] - : $assoc['joinTable']['joinColumns']; + $sql .= $joinTableName . ' ' . $joinTableAlias . ' ON ' . implode(' AND ', $conditions); - foreach ($relationColumns as $joinColumn) { - $quotedSourceColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform); - $quotedTargetColumn = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $targetClass, $this->platform); + // Join target table + $sql .= ($joinType == AST\Join::JOIN_TYPE_LEFT || $joinType == AST\Join::JOIN_TYPE_LEFTOUTER) ? ' LEFT JOIN ' : ' INNER JOIN '; - $conditions[] = $targetTableAlias . '.' . $quotedTargetColumn . ' = ' . $joinTableAlias . '.' . $quotedSourceColumn; - } + $conditions = []; + $joinColumns = $association->isOwningSide() + ? $joinTable->getInverseJoinColumns() + : $joinTable->getJoinColumns() + ; - // Apply remaining inheritance restrictions - $discrSql = $this->_generateDiscriminatorColumnConditionSQL([$joinedDqlAlias]); + foreach ($joinColumns as $joinColumn) { + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName()); + + $conditions[] = sprintf( + '%s.%s = %s.%s', + $targetTableAlias, + $quotedReferencedColumnName, + $joinTableAlias, + $quotedColumnName + ); + } - if ($discrSql) { - $conditions[] = $discrSql; - } + // Apply remaining inheritance restrictions + $discrSql = $this->generateDiscriminatorColumnConditionSQL([$joinedDqlAlias]); - // Apply the filters - $filterExpr = $this->generateFilterConditionSQL($targetClass, $targetTableAlias); + if ($discrSql) { + $conditions[] = $discrSql; + } - if ($filterExpr) { - $conditions[] = $filterExpr; - } + // Apply the filters + $filterExpr = $this->generateFilterConditionSQL($targetClass, $targetTableAlias); - $targetTableJoin = [ - 'table' => $targetTableName . ' ' . $targetTableAlias, - 'condition' => implode(' AND ', $conditions), - ]; - break; + if ($filterExpr) { + $conditions[] = $filterExpr; + } - default: - throw new \BadMethodCallException('Type of association must be one of *_TO_ONE or MANY_TO_MANY'); + $targetTableJoin = [ + 'table' => $targetTableName . ' ' . $targetTableAlias, + 'condition' => implode(' AND ', $conditions), + ]; + } else { + throw new \BadMethodCallException('Type of association must be one of *_TO_ONE or MANY_TO_MANY'); } // Handle WITH clause $withCondition = (null === $condExpr) ? '' : ('(' . $this->walkConditionalExpression($condExpr) . ')'); - if ($targetClass->isInheritanceTypeJoined()) { - $ctiJoins = $this->_generateClassTableInheritanceJoins($targetClass, $joinedDqlAlias); + if ($targetClass->inheritanceType === InheritanceType::JOINED) { + $ctiJoins = $this->generateClassTableInheritanceJoins($targetClass, $joinedDqlAlias); + // If we have WITH condition, we need to build nested joins for target class table and cti joins if ($withCondition) { $sql .= '(' . $targetTableJoin['table'] . $ctiJoins . ') ON ' . $targetTableJoin['condition']; @@ -1057,8 +1112,8 @@ public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joi if ($indexBy) { // For Many-To-One or One-To-One associations this obviously makes no sense, but is ignored silently. $this->walkIndexBy($indexBy); - } else if (isset($relation['indexBy'])) { - $this->rsm->addIndexBy($joinedDqlAlias, $relation['indexBy']); + } else if ($association instanceof ToManyAssociationMetadata && $association->getIndexedBy()) { + $this->rsm->addIndexBy($joinedDqlAlias, $association->getIndexedBy()); } return $sql; @@ -1079,7 +1134,7 @@ public function walkOrderByClause($orderByClause) { $orderByItems = array_map([$this, 'walkOrderByItem'], $orderByClause->orderByItems); - if (($collectionOrderByItems = $this->_generateOrderedCollectionOrderByItems()) !== '') { + if (($collectionOrderByItems = $this->generateOrderedCollectionOrderByItems()) !== '') { $orderByItems = array_merge($orderByItems, (array) $collectionOrderByItems); } @@ -1130,21 +1185,21 @@ public function walkJoin($join) case ($joinDeclaration instanceof \Doctrine\ORM\Query\AST\RangeVariableDeclaration): $class = $this->em->getClassMetadata($joinDeclaration->abstractSchemaName); $dqlAlias = $joinDeclaration->aliasIdentificationVariable; - $tableAlias = $this->getSQLTableAlias($class->table['name'], $dqlAlias); + $tableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias); $conditions = []; if ($join->conditionalExpression) { $conditions[] = '(' . $this->walkConditionalExpression($join->conditionalExpression) . ')'; } - $condExprConjunction = ($class->isInheritanceTypeJoined() && $joinType != AST\Join::JOIN_TYPE_LEFT && $joinType != AST\Join::JOIN_TYPE_LEFTOUTER) + $condExprConjunction = ($class->inheritanceType === InheritanceType::JOINED && $joinType !== AST\Join::JOIN_TYPE_LEFT && $joinType !== AST\Join::JOIN_TYPE_LEFTOUTER) ? ' AND ' : ' ON '; $sql .= $this->walkRangeVariableDeclaration($joinDeclaration); // Apply remaining inheritance restrictions - $discrSql = $this->_generateDiscriminatorColumnConditionSQL([$dqlAlias]); + $discrSql = $this->generateDiscriminatorColumnConditionSQL([$dqlAlias]); if ($discrSql) { $conditions[] = $discrSql; @@ -1270,33 +1325,29 @@ public function walkSelectExpression($selectExpression) throw QueryException::invalidPathExpression($expr); } - $fieldName = $expr->field; - $dqlAlias = $expr->identificationVariable; - $qComp = $this->queryComponents[$dqlAlias]; - $class = $qComp['metadata']; - - $resultAlias = $selectExpression->fieldIdentificationVariable ?: $fieldName; - $tableName = ($class->isInheritanceTypeJoined()) - ? $this->em->getUnitOfWork()->getEntityPersister($class->name)->getOwningTable($fieldName) - : $class->getTableName(); - - $sqlTableAlias = $this->getSQLTableAlias($tableName, $dqlAlias); - $fieldMapping = $class->fieldMappings[$fieldName]; - $columnName = $this->quoteStrategy->getColumnName($fieldName, $class, $this->platform); - $columnAlias = $this->getSQLColumnAlias($fieldMapping['columnName']); - $col = $sqlTableAlias . '.' . $columnName; - - if (isset($fieldMapping['requireSQLConversion'])) { - $type = Type::getType($fieldMapping['type']); - $col = $type->convertToPHPValueSQL($col, $this->conn->getDatabasePlatform()); - } + $fieldName = $expr->field; + $dqlAlias = $expr->identificationVariable; + $qComp = $this->queryComponents[$dqlAlias]; + $class = $qComp['metadata']; + $property = $class->getProperty($fieldName); + $columnAlias = $this->getSQLColumnAlias(); + $resultAlias = $selectExpression->fieldIdentificationVariable ?: $fieldName; + $col = sprintf( + '%s.%s', + $this->getSQLTableAlias($property->getTableName(), $dqlAlias), + $this->platform->quoteIdentifier($property->getColumnName()) + ); - $sql .= $col . ' AS ' . $columnAlias; + $sql .= sprintf( + '%s AS %s', + $property->getType()->convertToPHPValueSQL($col, $this->conn->getDatabasePlatform()), + $columnAlias + ); $this->scalarResultAliasMap[$resultAlias] = $columnAlias; if ( ! $hidden) { - $this->rsm->addScalarResult($columnAlias, $resultAlias, $fieldMapping['type']); + $this->rsm->addScalarResult($columnAlias, $resultAlias, $property->getType()); $this->scalarFields[$dqlAlias][$fieldName] = $columnAlias; } @@ -1313,7 +1364,7 @@ public function walkSelectExpression($selectExpression) case ($expr instanceof AST\CoalesceExpression): case ($expr instanceof AST\GeneralCaseExpression): case ($expr instanceof AST\SimpleCaseExpression): - $columnAlias = $this->getSQLColumnAlias('sclr'); + $columnAlias = $this->getSQLColumnAlias(); $resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++; $sql .= $expr->dispatch($this) . ' AS ' . $columnAlias; @@ -1321,13 +1372,14 @@ public function walkSelectExpression($selectExpression) $this->scalarResultAliasMap[$resultAlias] = $columnAlias; if ( ! $hidden) { - // We cannot resolve field type here; assume 'string'. - $this->rsm->addScalarResult($columnAlias, $resultAlias, 'string'); + // Conceptually we could resolve field type here by traverse through AST to retrieve field type, + // but this is not a feasible solution; assume 'string'. + $this->rsm->addScalarResult($columnAlias, $resultAlias, Type::getType('string')); } break; case ($expr instanceof AST\Subselect): - $columnAlias = $this->getSQLColumnAlias('sclr'); + $columnAlias = $this->getSQLColumnAlias(); $resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++; $sql .= '(' . $this->walkSubselect($expr) . ') AS ' . $columnAlias; @@ -1336,7 +1388,7 @@ public function walkSelectExpression($selectExpression) if ( ! $hidden) { // We cannot resolve field type here; assume 'string'. - $this->rsm->addScalarResult($columnAlias, $resultAlias, 'string'); + $this->rsm->addScalarResult($columnAlias, $resultAlias, Type::getType('string')); } break; @@ -1369,58 +1421,62 @@ public function walkSelectExpression($selectExpression) $sqlParts = []; // Select all fields from the queried class - foreach ($class->fieldMappings as $fieldName => $mapping) { - if ($partialFieldSet && ! in_array($fieldName, $partialFieldSet)) { + foreach ($class->getDeclaredPropertiesIterator() as $fieldName => $property) { + if (! ($property instanceof FieldMetadata)) { continue; } - $tableName = (isset($mapping['inherited'])) - ? $this->em->getClassMetadata($mapping['inherited'])->getTableName() - : $class->getTableName(); - - $sqlTableAlias = $this->getSQLTableAlias($tableName, $dqlAlias); - $columnAlias = $this->getSQLColumnAlias($mapping['columnName']); - $quotedColumnName = $this->quoteStrategy->getColumnName($fieldName, $class, $this->platform); - - $col = $sqlTableAlias . '.' . $quotedColumnName; - - if (isset($mapping['requireSQLConversion'])) { - $type = Type::getType($mapping['type']); - $col = $type->convertToPHPValueSQL($col, $this->platform); + if ($partialFieldSet && ! in_array($fieldName, $partialFieldSet)) { + continue; } - $sqlParts[] = $col . ' AS '. $columnAlias; + $columnAlias = $this->getSQLColumnAlias(); + $col = sprintf( + '%s.%s', + $this->getSQLTableAlias($property->getTableName(), $dqlAlias), + $this->platform->quoteIdentifier($property->getColumnName()) + ); + + $sqlParts[] = sprintf( + '%s AS %s', + $property->getType()->convertToPHPValueSQL($col, $this->platform), + $columnAlias + ); $this->scalarResultAliasMap[$resultAlias][] = $columnAlias; - $this->rsm->addFieldResult($dqlAlias, $columnAlias, $fieldName, $class->name); + $this->rsm->addFieldResult($dqlAlias, $columnAlias, $fieldName, $class->getClassName()); } // Add any additional fields of subclasses (excluding inherited fields) // 1) on Single Table Inheritance: always, since its marginal overhead // 2) on Class Table Inheritance only if partial objects are disallowed, // since it requires outer joining subtables. - if ($class->isInheritanceTypeSingleTable() || ! $this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)) { - foreach ($class->subClasses as $subClassName) { - $subClass = $this->em->getClassMetadata($subClassName); - $sqlTableAlias = $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias); + if ($class->inheritanceType === InheritanceType::SINGLE_TABLE || ! $this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)) { + foreach ($class->getSubClasses() as $subClassName) { + $subClass = $this->em->getClassMetadata($subClassName); - foreach ($subClass->fieldMappings as $fieldName => $mapping) { - if (isset($mapping['inherited']) || ($partialFieldSet && !in_array($fieldName, $partialFieldSet))) { + foreach ($subClass->getDeclaredPropertiesIterator() as $fieldName => $property) { + if (! ($property instanceof FieldMetadata)) { continue; } - $columnAlias = $this->getSQLColumnAlias($mapping['columnName']); - $quotedColumnName = $this->quoteStrategy->getColumnName($fieldName, $subClass, $this->platform); - - $col = $sqlTableAlias . '.' . $quotedColumnName; - - if (isset($mapping['requireSQLConversion'])) { - $type = Type::getType($mapping['type']); - $col = $type->convertToPHPValueSQL($col, $this->platform); + if ($subClass->isInheritedProperty($fieldName) || ($partialFieldSet && !in_array($fieldName, $partialFieldSet))) { + continue; } - $sqlParts[] = $col . ' AS ' . $columnAlias; + $columnAlias = $this->getSQLColumnAlias(); + $col = sprintf( + '%s.%s', + $this->getSQLTableAlias($property->getTableName(), $dqlAlias), + $this->platform->quoteIdentifier($property->getColumnName()) + ); + + $sqlParts[] = sprintf( + '%s AS %s', + $property->getType()->convertToPHPValueSQL($col, $this->platform), + $columnAlias + ); $this->scalarResultAliasMap[$resultAlias][] = $columnAlias; @@ -1514,8 +1570,8 @@ public function walkNewObject($newObjectExpression, $newObjectResultAlias=null) foreach ($newObjectExpression->args as $argIndex => $e) { $resultAlias = $this->scalarResultCounter++; - $columnAlias = $this->getSQLColumnAlias('sclr'); - $fieldType = 'string'; + $columnAlias = $this->getSQLColumnAlias(); + $fieldType = Type::getType('string'); switch (true) { case ($e instanceof AST\NewObjectExpression): @@ -1530,27 +1586,27 @@ public function walkNewObject($newObjectExpression, $newObjectResultAlias=null) $dqlAlias = $e->identificationVariable; $qComp = $this->queryComponents[$dqlAlias]; $class = $qComp['metadata']; - $fieldType = $class->fieldMappings[$e->field]['type']; + $fieldType = $class->getProperty($e->field)->getType(); - $sqlSelectExpressions[] = trim($e->dispatch($this)) . ' AS ' . $columnAlias; + $sqlSelectExpressions[] = trim((string) $e->dispatch($this)) . ' AS ' . $columnAlias; break; case ($e instanceof AST\Literal): switch ($e->type) { case AST\Literal::BOOLEAN: - $fieldType = 'boolean'; + $fieldType = Type::getType('boolean'); break; case AST\Literal::NUMERIC: - $fieldType = is_float($e->value) ? 'float' : 'integer'; + $fieldType = Type::getType(is_float($e->value) ? 'float' : 'integer'); break; } - $sqlSelectExpressions[] = trim($e->dispatch($this)) . ' AS ' . $columnAlias; + $sqlSelectExpressions[] = trim((string) $e->dispatch($this)) . ' AS ' . $columnAlias; break; default: - $sqlSelectExpressions[] = trim($e->dispatch($this)) . ' AS ' . $columnAlias; + $sqlSelectExpressions[] = trim((string) $e->dispatch($this)) . ' AS ' . $columnAlias; break; } @@ -1600,7 +1656,7 @@ public function walkSimpleSelectExpression($simpleSelectExpression) case ($expr instanceof AST\SimpleCaseExpression): $alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++; - $columnAlias = $this->getSQLColumnAlias('sclr'); + $columnAlias = $this->getSQLColumnAlias(); $this->scalarResultAliasMap[$alias] = $columnAlias; $sql .= $expr->dispatch($this) . ' AS ' . $columnAlias; @@ -1667,21 +1723,27 @@ public function walkGroupByItem($groupByItem) } // IdentificationVariable - $sqlParts = []; + /** @var ClassMetadata $classMetadata */ + $classMetadata = $this->queryComponents[$groupByItem]['metadata']; + $sqlParts = []; - foreach ($this->queryComponents[$groupByItem]['metadata']->fieldNames as $field) { - $item = new AST\PathExpression(AST\PathExpression::TYPE_STATE_FIELD, $groupByItem, $field); - $item->type = AST\PathExpression::TYPE_STATE_FIELD; + foreach ($classMetadata->getDeclaredPropertiesIterator() as $property) { + switch (true) { + case ($property instanceof FieldMetadata): + $type = AST\PathExpression::TYPE_STATE_FIELD; + $item = new AST\PathExpression($type, $groupByItem, $property->getName()); + $item->type = $type; - $sqlParts[] = $this->walkPathExpression($item); - } + $sqlParts[] = $this->walkPathExpression($item); + break; - foreach ($this->queryComponents[$groupByItem]['metadata']->associationMappings as $mapping) { - if ($mapping['isOwningSide'] && $mapping['type'] & ClassMetadataInfo::TO_ONE) { - $item = new AST\PathExpression(AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, $groupByItem, $mapping['fieldName']); - $item->type = AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION; + case ($property instanceof ToOneAssociationMetadata && $property->isOwningSide()): + $type = AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION; + $item = new AST\PathExpression($type, $groupByItem, $property->getName()); + $item->type = $type; - $sqlParts[] = $this->walkPathExpression($item); + $sqlParts[] = $this->walkPathExpression($item); + break; } } @@ -1695,9 +1757,10 @@ public function walkDeleteClause(AST\DeleteClause $deleteClause) { $class = $this->em->getClassMetadata($deleteClause->abstractSchemaName); $tableName = $class->getTableName(); - $sql = 'DELETE FROM ' . $this->quoteStrategy->getTableName($class, $this->platform); + $sql = 'DELETE FROM ' . $class->table->getQuotedQualifiedName($this->platform); $this->setSQLTableAlias($tableName, $tableName, $deleteClause->aliasIdentificationVariable); + $this->rootAliases[] = $deleteClause->aliasIdentificationVariable; return $sql; @@ -1710,7 +1773,7 @@ public function walkUpdateClause($updateClause) { $class = $this->em->getClassMetadata($updateClause->abstractSchemaName); $tableName = $class->getTableName(); - $sql = 'UPDATE ' . $this->quoteStrategy->getTableName($class, $this->platform); + $sql = 'UPDATE ' . $class->table->getQuotedQualifiedName($this->platform); $this->setSQLTableAlias($tableName, $tableName, $updateClause->aliasIdentificationVariable); $this->rootAliases[] = $updateClause->aliasIdentificationVariable; @@ -1756,20 +1819,20 @@ public function walkUpdateItem($updateItem) public function walkWhereClause($whereClause) { $condSql = null !== $whereClause ? $this->walkConditionalExpression($whereClause->conditionalExpression) : ''; - $discrSql = $this->_generateDiscriminatorColumnConditionSQL($this->rootAliases); + $discrSql = $this->generateDiscriminatorColumnConditionSql($this->rootAliases); if ($this->em->hasFilters()) { $filterClauses = []; foreach ($this->rootAliases as $dqlAlias) { $class = $this->queryComponents[$dqlAlias]['metadata']; - $tableAlias = $this->getSQLTableAlias($class->table['name'], $dqlAlias); + $tableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias); if ($filterExpr = $this->generateFilterConditionSQL($class, $tableAlias)) { $filterClauses[] = $filterExpr; } } - if (count($filterClauses)) { + if ($filterClauses) { if ($condSql) { $condSql = '(' . $condSql . ') AND '; } @@ -1889,76 +1952,105 @@ public function walkCollectionMemberExpression($collMemberExpr) throw new \BadMethodCallException("Not implemented"); } - $assoc = $class->associationMappings[$fieldName]; + $association = $class->getProperty($fieldName); + $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); + $owningAssociation = $association->isOwningSide() + ? $association + : $targetClass->getProperty($association->getMappedBy()) + ; - if ($assoc['type'] == ClassMetadata::ONE_TO_MANY) { - $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); + if ($association instanceof OneToManyAssociationMetadata) { + $targetTableName = $targetClass->table->getQuotedQualifiedName($this->platform); $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName()); $sourceTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias); - $sql .= $this->quoteStrategy->getTableName($targetClass, $this->platform) . ' ' . $targetTableAlias . ' WHERE '; + $sql .= $targetTableName . ' ' . $targetTableAlias . ' WHERE '; - $owningAssoc = $targetClass->associationMappings[$assoc['mappedBy']]; - $sqlParts = []; - - foreach ($owningAssoc['targetToSourceKeyColumns'] as $targetColumn => $sourceColumn) { - $targetColumn = $this->quoteStrategy->getColumnName($class->fieldNames[$targetColumn], $class, $this->platform); + $sqlParts = []; - $sqlParts[] = $sourceTableAlias . '.' . $targetColumn . ' = ' . $targetTableAlias . '.' . $sourceColumn; + foreach ($owningAssociation->getJoinColumns() as $joinColumn) { + $sqlParts[] = sprintf( + '%s.%s = %s.%s', + $sourceTableAlias, + $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName()), + $targetTableAlias, + $this->platform->quoteIdentifier($joinColumn->getColumnName()) + ); } - foreach ($this->quoteStrategy->getIdentifierColumnNames($targetClass, $this->platform) as $targetColumnName) { + foreach ($targetClass->getIdentifierColumns($this->em) as $targetColumn) { + $quotedTargetColumnName = $this->platform->quoteIdentifier($targetColumn->getColumnName()); + if (isset($dqlParamKey)) { $this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++); } - $sqlParts[] = $targetTableAlias . '.' . $targetColumnName . ' = ' . $entitySql; + $sqlParts[] = $targetTableAlias . '.' . $quotedTargetColumnName . ' = ' . $entitySql; } $sql .= implode(' AND ', $sqlParts); } else { // many-to-many - $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); - - $owningAssoc = $assoc['isOwningSide'] ? $assoc : $targetClass->associationMappings[$assoc['mappedBy']]; - $joinTable = $owningAssoc['joinTable']; - // SQL table aliases - $joinTableAlias = $this->getSQLTableAlias($joinTable['name']); + $joinTable = $owningAssociation->getJoinTable(); + $joinTableName = $joinTable->getQuotedQualifiedName($this->platform); + $joinTableAlias = $this->getSQLTableAlias($joinTable->getName()); + $targetTableName = $targetClass->table->getQuotedQualifiedName($this->platform); $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName()); $sourceTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias); // join to target table - $sql .= $this->quoteStrategy->getJoinTableName($owningAssoc, $targetClass, $this->platform) . ' ' . $joinTableAlias - . ' INNER JOIN ' . $this->quoteStrategy->getTableName($targetClass, $this->platform) . ' ' . $targetTableAlias . ' ON '; + $sql .= $joinTableName . ' ' . $joinTableAlias . ' INNER JOIN ' . $targetTableName . ' ' . $targetTableAlias . ' ON '; // join conditions - $joinColumns = $assoc['isOwningSide'] ? $joinTable['inverseJoinColumns'] : $joinTable['joinColumns']; $joinSqlParts = []; + $joinColumns = $association->isOwningSide() + ? $joinTable->getInverseJoinColumns() + : $joinTable->getJoinColumns() + ; foreach ($joinColumns as $joinColumn) { - $targetColumn = $this->quoteStrategy->getColumnName($targetClass->fieldNames[$joinColumn['referencedColumnName']], $targetClass, $this->platform); - - $joinSqlParts[] = $joinTableAlias . '.' . $joinColumn['name'] . ' = ' . $targetTableAlias . '.' . $targetColumn; + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName()); + + $joinSqlParts[] = sprintf( + '%s.%s = %s.%s', + $joinTableAlias, + $quotedColumnName, + $targetTableAlias, + $quotedReferencedColumnName + ); } $sql .= implode(' AND ', $joinSqlParts); $sql .= ' WHERE '; - $joinColumns = $assoc['isOwningSide'] ? $joinTable['joinColumns'] : $joinTable['inverseJoinColumns']; $sqlParts = []; + $joinColumns = $association->isOwningSide() + ? $joinTable->getJoinColumns() + : $joinTable->getInverseJoinColumns() + ; foreach ($joinColumns as $joinColumn) { - $targetColumn = $this->quoteStrategy->getColumnName($class->fieldNames[$joinColumn['referencedColumnName']], $class, $this->platform); - - $sqlParts[] = $joinTableAlias . '.' . $joinColumn['name'] . ' = ' . $sourceTableAlias . '.' . $targetColumn; + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName()); + + $sqlParts[] = sprintf( + '%s.%s = %s.%s', + $joinTableAlias, + $quotedColumnName, + $sourceTableAlias, + $quotedReferencedColumnName + ); } - foreach ($this->quoteStrategy->getIdentifierColumnNames($targetClass, $this->platform) as $targetColumnName) { + foreach ($targetClass->getIdentifierColumns($this->em) as $targetColumn) { + $quotedTargetColumnName = $this->platform->quoteIdentifier($targetColumn->getColumnName()); + if (isset($dqlParamKey)) { $this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++); } - $sqlParts[] = $targetTableAlias . '.' . $targetColumnName . ' IN (' . $entitySql . ')'; + $sqlParts[] = $targetTableAlias . '.' . $quotedTargetColumnName . ' = ' . $entitySql; } $sql .= implode(' AND ', $sqlParts); @@ -2020,41 +2112,33 @@ public function walkInExpression($inExpr) */ public function walkInstanceOfExpression($instanceOfExpr) { - $sql = ''; - - $dqlAlias = $instanceOfExpr->identificationVariable; - $discrClass = $class = $this->queryComponents[$dqlAlias]['metadata']; - - if ($class->discriminatorColumn) { - $discrClass = $this->em->getClassMetadata($class->rootEntityName); - } - - if ($this->useSqlTableAliases) { - $sql .= $this->getSQLTableAlias($discrClass->getTableName(), $dqlAlias) . '.'; - } - - $sql .= $class->discriminatorColumn['name'] . ($instanceOfExpr->not ? ' NOT IN ' : ' IN '); + $dqlAlias = $instanceOfExpr->identificationVariable; + $class = $this->queryComponents[$dqlAlias]['metadata']; + $discrMap = array_flip($class->discriminatorMap); + $discrColumn = $class->discriminatorColumn; + $discrColumnType = $discrColumn->getType(); + $quotedColumnName = $this->platform->quoteIdentifier($discrColumn->getColumnName()); + $sqlTableAlias = $this->useSqlTableAliases + ? $this->getSQLTableAlias($discrColumn->getTableName(), $dqlAlias) . '.' + : ''; $sqlParameterList = []; foreach ($instanceOfExpr->value as $parameter) { if ($parameter instanceof AST\InputParameter) { - $this->rsm->addMetadataParameterMapping($parameter->name, 'discriminatorValue'); - $sqlParameterList[] = $this->walkInputParameter($parameter); continue; } // Get name from ClassMetadata to resolve aliases. - $entityClassName = $this->em->getClassMetadata($parameter)->name; + $entityClass = $this->em->getClassMetadata($parameter); + $entityClassName = $entityClass->getClassName(); $discriminatorValue = $class->discriminatorValue; - if ($entityClassName !== $class->name) { - $discrMap = array_flip($class->discriminatorMap); - + if ($entityClassName !== $class->getClassName()) { if ( ! isset($discrMap[$entityClassName])) { - throw QueryException::instanceOfUnrelatedClass($entityClassName, $class->rootEntityName); + throw QueryException::instanceOfUnrelatedClass($entityClassName, $class->getRootClassName()); } $discriminatorValue = $discrMap[$entityClassName]; @@ -2063,9 +2147,12 @@ public function walkInstanceOfExpression($instanceOfExpr) $sqlParameterList[] = $this->conn->quote($discriminatorValue); } - $sql .= '(' . implode(', ', $sqlParameterList) . ')'; - - return $sql; + return sprintf( + '%s %sIN (%s)', + $discrColumnType->convertToDatabaseValueSQL($sqlTableAlias . $quotedColumnName, $this->platform), + ($instanceOfExpr->not ? 'NOT ' : ''), + implode(', ', $sqlParameterList) + ); } /** diff --git a/lib/Doctrine/ORM/Query/TreeWalker.php b/lib/Doctrine/ORM/Query/TreeWalker.php index 9ddd86b0432..8a6ab8bdc34 100644 --- a/lib/Doctrine/ORM/Query/TreeWalker.php +++ b/lib/Doctrine/ORM/Query/TreeWalker.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query; diff --git a/lib/Doctrine/ORM/Query/TreeWalkerAdapter.php b/lib/Doctrine/ORM/Query/TreeWalkerAdapter.php index deee03ab53d..8073fa06e79 100644 --- a/lib/Doctrine/ORM/Query/TreeWalkerAdapter.php +++ b/lib/Doctrine/ORM/Query/TreeWalkerAdapter.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query; @@ -33,30 +18,30 @@ abstract class TreeWalkerAdapter implements TreeWalker * * @var \Doctrine\ORM\AbstractQuery */ - private $_query; + private $query; /** * The ParserResult of the original query that was produced by the Parser. * * @var \Doctrine\ORM\Query\ParserResult */ - private $_parserResult; + private $parserResult; /** * The query components of the original query (the "symbol table") that was produced by the Parser. * * @var array */ - private $_queryComponents; + private $queryComponents; /** * {@inheritdoc} */ public function __construct($query, $parserResult, array $queryComponents) { - $this->_query = $query; - $this->_parserResult = $parserResult; - $this->_queryComponents = $queryComponents; + $this->query = $query; + $this->parserResult = $parserResult; + $this->queryComponents = $queryComponents; } /** @@ -64,7 +49,7 @@ public function __construct($query, $parserResult, array $queryComponents) */ public function getQueryComponents() { - return $this->_queryComponents; + return $this->queryComponents; } /** @@ -78,15 +63,7 @@ public function setQueryComponent($dqlAlias, array $queryComponent) throw QueryException::invalidQueryComponent($dqlAlias); } - $this->_queryComponents[$dqlAlias] = $queryComponent; - } - - /** - * @return array - */ - protected function _getQueryComponents() - { - return $this->_queryComponents; + $this->queryComponents[$dqlAlias] = $queryComponent; } /** @@ -94,9 +71,9 @@ protected function _getQueryComponents() * * @return \Doctrine\ORM\AbstractQuery */ - protected function _getQuery() + protected function getQuery() { - return $this->_query; + return $this->query; } /** @@ -104,9 +81,9 @@ protected function _getQuery() * * @return \Doctrine\ORM\Query\ParserResult */ - protected function _getParserResult() + protected function getParserResult() { - return $this->_parserResult; + return $this->parserResult; } /** diff --git a/lib/Doctrine/ORM/Query/TreeWalkerChain.php b/lib/Doctrine/ORM/Query/TreeWalkerChain.php index 074aa938709..0b68ae30287 100644 --- a/lib/Doctrine/ORM/Query/TreeWalkerChain.php +++ b/lib/Doctrine/ORM/Query/TreeWalkerChain.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query; @@ -34,28 +19,28 @@ class TreeWalkerChain implements TreeWalker * * @var TreeWalker[] */ - private $_walkers; + private $walkers; /** * The original Query. * * @var \Doctrine\ORM\AbstractQuery */ - private $_query; + private $query; /** * The ParserResult of the original query that was produced by the Parser. * * @var \Doctrine\ORM\Query\ParserResult */ - private $_parserResult; + private $parserResult; /** * The query components of the original query (the "symbol table") that was produced by the Parser. * * @var array */ - private $_queryComponents; + private $queryComponents; /** * Returns the internal queryComponents array. @@ -64,7 +49,7 @@ class TreeWalkerChain implements TreeWalker */ public function getQueryComponents() { - return $this->_queryComponents; + return $this->queryComponents; } /** @@ -78,7 +63,7 @@ public function setQueryComponent($dqlAlias, array $queryComponent) throw QueryException::invalidQueryComponent($dqlAlias); } - $this->_queryComponents[$dqlAlias] = $queryComponent; + $this->queryComponents[$dqlAlias] = $queryComponent; } /** @@ -86,10 +71,10 @@ public function setQueryComponent($dqlAlias, array $queryComponent) */ public function __construct($query, $parserResult, array $queryComponents) { - $this->_query = $query; - $this->_parserResult = $parserResult; - $this->_queryComponents = $queryComponents; - $this->_walkers = new TreeWalkerChainIterator($this, $query, $parserResult); + $this->query = $query; + $this->parserResult = $parserResult; + $this->queryComponents = $queryComponents; + $this->walkers = new TreeWalkerChainIterator($this, $query, $parserResult); } /** @@ -101,7 +86,7 @@ public function __construct($query, $parserResult, array $queryComponents) */ public function addTreeWalker($walkerClass) { - $this->_walkers[] = $walkerClass; + $this->walkers[] = $walkerClass; } /** @@ -109,10 +94,10 @@ public function addTreeWalker($walkerClass) */ public function walkSelectStatement(AST\SelectStatement $AST) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkSelectStatement($AST); - $this->_queryComponents = $walker->getQueryComponents(); + $this->queryComponents = $walker->getQueryComponents(); } } @@ -121,7 +106,7 @@ public function walkSelectStatement(AST\SelectStatement $AST) */ public function walkSelectClause($selectClause) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkSelectClause($selectClause); } } @@ -131,7 +116,7 @@ public function walkSelectClause($selectClause) */ public function walkFromClause($fromClause) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkFromClause($fromClause); } } @@ -141,7 +126,7 @@ public function walkFromClause($fromClause) */ public function walkFunction($function) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkFunction($function); } } @@ -151,7 +136,7 @@ public function walkFunction($function) */ public function walkOrderByClause($orderByClause) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkOrderByClause($orderByClause); } } @@ -161,7 +146,7 @@ public function walkOrderByClause($orderByClause) */ public function walkOrderByItem($orderByItem) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkOrderByItem($orderByItem); } } @@ -171,7 +156,7 @@ public function walkOrderByItem($orderByItem) */ public function walkHavingClause($havingClause) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkHavingClause($havingClause); } } @@ -181,7 +166,7 @@ public function walkHavingClause($havingClause) */ public function walkJoin($join) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkJoin($join); } } @@ -191,7 +176,7 @@ public function walkJoin($join) */ public function walkSelectExpression($selectExpression) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkSelectExpression($selectExpression); } } @@ -201,7 +186,7 @@ public function walkSelectExpression($selectExpression) */ public function walkQuantifiedExpression($qExpr) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkQuantifiedExpression($qExpr); } } @@ -211,7 +196,7 @@ public function walkQuantifiedExpression($qExpr) */ public function walkSubselect($subselect) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkSubselect($subselect); } } @@ -221,7 +206,7 @@ public function walkSubselect($subselect) */ public function walkSubselectFromClause($subselectFromClause) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkSubselectFromClause($subselectFromClause); } } @@ -231,7 +216,7 @@ public function walkSubselectFromClause($subselectFromClause) */ public function walkSimpleSelectClause($simpleSelectClause) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkSimpleSelectClause($simpleSelectClause); } } @@ -241,7 +226,7 @@ public function walkSimpleSelectClause($simpleSelectClause) */ public function walkSimpleSelectExpression($simpleSelectExpression) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkSimpleSelectExpression($simpleSelectExpression); } } @@ -251,7 +236,7 @@ public function walkSimpleSelectExpression($simpleSelectExpression) */ public function walkAggregateExpression($aggExpression) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkAggregateExpression($aggExpression); } } @@ -261,7 +246,7 @@ public function walkAggregateExpression($aggExpression) */ public function walkGroupByClause($groupByClause) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkGroupByClause($groupByClause); } } @@ -271,7 +256,7 @@ public function walkGroupByClause($groupByClause) */ public function walkGroupByItem($groupByItem) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkGroupByItem($groupByItem); } } @@ -281,7 +266,7 @@ public function walkGroupByItem($groupByItem) */ public function walkUpdateStatement(AST\UpdateStatement $AST) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkUpdateStatement($AST); } } @@ -291,7 +276,7 @@ public function walkUpdateStatement(AST\UpdateStatement $AST) */ public function walkDeleteStatement(AST\DeleteStatement $AST) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkDeleteStatement($AST); } } @@ -301,7 +286,7 @@ public function walkDeleteStatement(AST\DeleteStatement $AST) */ public function walkDeleteClause(AST\DeleteClause $deleteClause) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkDeleteClause($deleteClause); } } @@ -311,7 +296,7 @@ public function walkDeleteClause(AST\DeleteClause $deleteClause) */ public function walkUpdateClause($updateClause) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkUpdateClause($updateClause); } } @@ -321,7 +306,7 @@ public function walkUpdateClause($updateClause) */ public function walkUpdateItem($updateItem) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkUpdateItem($updateItem); } } @@ -331,7 +316,7 @@ public function walkUpdateItem($updateItem) */ public function walkWhereClause($whereClause) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkWhereClause($whereClause); } } @@ -341,7 +326,7 @@ public function walkWhereClause($whereClause) */ public function walkConditionalExpression($condExpr) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkConditionalExpression($condExpr); } } @@ -351,7 +336,7 @@ public function walkConditionalExpression($condExpr) */ public function walkConditionalTerm($condTerm) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkConditionalTerm($condTerm); } } @@ -361,7 +346,7 @@ public function walkConditionalTerm($condTerm) */ public function walkConditionalFactor($factor) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkConditionalFactor($factor); } } @@ -371,7 +356,7 @@ public function walkConditionalFactor($factor) */ public function walkConditionalPrimary($condPrimary) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkConditionalPrimary($condPrimary); } } @@ -381,7 +366,7 @@ public function walkConditionalPrimary($condPrimary) */ public function walkExistsExpression($existsExpr) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkExistsExpression($existsExpr); } } @@ -391,7 +376,7 @@ public function walkExistsExpression($existsExpr) */ public function walkCollectionMemberExpression($collMemberExpr) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkCollectionMemberExpression($collMemberExpr); } } @@ -401,7 +386,7 @@ public function walkCollectionMemberExpression($collMemberExpr) */ public function walkEmptyCollectionComparisonExpression($emptyCollCompExpr) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkEmptyCollectionComparisonExpression($emptyCollCompExpr); } } @@ -411,7 +396,7 @@ public function walkEmptyCollectionComparisonExpression($emptyCollCompExpr) */ public function walkNullComparisonExpression($nullCompExpr) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkNullComparisonExpression($nullCompExpr); } } @@ -421,7 +406,7 @@ public function walkNullComparisonExpression($nullCompExpr) */ public function walkInExpression($inExpr) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkInExpression($inExpr); } } @@ -431,7 +416,7 @@ public function walkInExpression($inExpr) */ public function walkInstanceOfExpression($instanceOfExpr) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkInstanceOfExpression($instanceOfExpr); } } @@ -441,7 +426,7 @@ public function walkInstanceOfExpression($instanceOfExpr) */ public function walkLiteral($literal) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkLiteral($literal); } } @@ -451,7 +436,7 @@ public function walkLiteral($literal) */ public function walkBetweenExpression($betweenExpr) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkBetweenExpression($betweenExpr); } } @@ -461,7 +446,7 @@ public function walkBetweenExpression($betweenExpr) */ public function walkLikeExpression($likeExpr) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkLikeExpression($likeExpr); } } @@ -471,7 +456,7 @@ public function walkLikeExpression($likeExpr) */ public function walkStateFieldPathExpression($stateFieldPathExpression) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkStateFieldPathExpression($stateFieldPathExpression); } } @@ -481,7 +466,7 @@ public function walkStateFieldPathExpression($stateFieldPathExpression) */ public function walkComparisonExpression($compExpr) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkComparisonExpression($compExpr); } } @@ -491,7 +476,7 @@ public function walkComparisonExpression($compExpr) */ public function walkInputParameter($inputParam) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkInputParameter($inputParam); } } @@ -501,7 +486,7 @@ public function walkInputParameter($inputParam) */ public function walkArithmeticExpression($arithmeticExpr) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkArithmeticExpression($arithmeticExpr); } } @@ -511,7 +496,7 @@ public function walkArithmeticExpression($arithmeticExpr) */ public function walkArithmeticTerm($term) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkArithmeticTerm($term); } } @@ -521,7 +506,7 @@ public function walkArithmeticTerm($term) */ public function walkStringPrimary($stringPrimary) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkStringPrimary($stringPrimary); } } @@ -531,7 +516,7 @@ public function walkStringPrimary($stringPrimary) */ public function walkArithmeticFactor($factor) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkArithmeticFactor($factor); } } @@ -541,7 +526,7 @@ public function walkArithmeticFactor($factor) */ public function walkSimpleArithmeticExpression($simpleArithmeticExpr) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkSimpleArithmeticExpression($simpleArithmeticExpr); } } @@ -551,7 +536,7 @@ public function walkSimpleArithmeticExpression($simpleArithmeticExpr) */ public function walkPathExpression($pathExpr) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkPathExpression($pathExpr); } } @@ -561,7 +546,7 @@ public function walkPathExpression($pathExpr) */ public function walkResultVariable($resultVariable) { - foreach ($this->_walkers as $walker) { + foreach ($this->walkers as $walker) { $walker->walkResultVariable($resultVariable); } } diff --git a/lib/Doctrine/ORM/Query/TreeWalkerChainIterator.php b/lib/Doctrine/ORM/Query/TreeWalkerChainIterator.php index e72e1d4dc4a..3bab50edff8 100644 --- a/lib/Doctrine/ORM/Query/TreeWalkerChainIterator.php +++ b/lib/Doctrine/ORM/Query/TreeWalkerChainIterator.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Query; diff --git a/lib/Doctrine/ORM/QueryBuilder.php b/lib/Doctrine/ORM/QueryBuilder.php index 894fbc32f74..ac0398465cc 100644 --- a/lib/Doctrine/ORM/QueryBuilder.php +++ b/lib/Doctrine/ORM/QueryBuilder.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; @@ -50,14 +35,14 @@ class QueryBuilder * * @var EntityManagerInterface */ - private $_em; + private $em; /** * The array of DQL parts collected. * * @var array */ - private $_dqlParts = [ + private $dqlParts = [ 'distinct' => false, 'select' => [], 'from' => [], @@ -74,21 +59,21 @@ class QueryBuilder * * @var integer */ - private $_type = self::SELECT; + private $type = self::SELECT; /** * The state of the query object. Can be dirty or clean. * * @var integer */ - private $_state = self::STATE_CLEAN; + private $state = self::STATE_CLEAN; /** * The complete DQL string for this query. * * @var string */ - private $_dql; + private $dql; /** * The query parameters. @@ -102,14 +87,14 @@ class QueryBuilder * * @var integer */ - private $_firstResult = null; + private $firstResult = null; /** * The maximum number of results to retrieve. * * @var integer */ - private $_maxResults = null; + private $maxResults = null; /** * Keeps root entity alias names for join entities. @@ -151,7 +136,7 @@ class QueryBuilder */ public function __construct(EntityManagerInterface $em) { - $this->_em = $em; + $this->em = $em; $this->parameters = new ArrayCollection(); } @@ -174,7 +159,7 @@ public function __construct(EntityManagerInterface $em) */ public function expr() { - return $this->_em->getExpressionBuilder(); + return $this->em->getExpressionBuilder(); } /** @@ -271,17 +256,17 @@ public function setCacheMode($cacheMode) */ public function getType() { - return $this->_type; + return $this->type; } /** * Gets the associated EntityManager for this query builder. * - * @return EntityManager + * @return EntityManagerInterface */ public function getEntityManager() { - return $this->_em; + return $this->em; } /** @@ -291,7 +276,7 @@ public function getEntityManager() */ public function getState() { - return $this->_state; + return $this->state; } /** @@ -308,27 +293,27 @@ public function getState() */ public function getDQL() { - if ($this->_dql !== null && $this->_state === self::STATE_CLEAN) { - return $this->_dql; + if ($this->dql !== null && $this->state === self::STATE_CLEAN) { + return $this->dql; } - switch ($this->_type) { + switch ($this->type) { case self::DELETE: - $dql = $this->_getDQLForDelete(); + $dql = $this->getDQLForDelete(); break; case self::UPDATE: - $dql = $this->_getDQLForUpdate(); + $dql = $this->getDQLForUpdate(); break; case self::SELECT: default: - $dql = $this->_getDQLForSelect(); + $dql = $this->getDQLForSelect(); break; } - $this->_state = self::STATE_CLEAN; - $this->_dql = $dql; + $this->state = self::STATE_CLEAN; + $this->dql = $dql; return $dql; } @@ -349,10 +334,10 @@ public function getDQL() public function getQuery() { $parameters = clone $this->parameters; - $query = $this->_em->createQuery($this->getDQL()) + $query = $this->em->createQuery($this->getDQL()) ->setParameters($parameters) - ->setFirstResult($this->_firstResult) - ->setMaxResults($this->_maxResults); + ->setFirstResult($this->firstResult) + ->setMaxResults($this->maxResults); if ($this->lifetime) { $query->setLifetime($this->lifetime); @@ -446,7 +431,7 @@ public function getRootAliases() { $aliases = []; - foreach ($this->_dqlParts['from'] as &$fromClause) { + foreach ($this->dqlParts['from'] as &$fromClause) { if (is_string($fromClause)) { $spacePos = strrpos($fromClause, ' '); $from = substr($fromClause, 0, $spacePos); @@ -498,7 +483,7 @@ public function getRootEntities() { $entities = []; - foreach ($this->_dqlParts['from'] as &$fromClause) { + foreach ($this->dqlParts['from'] as &$fromClause) { if (is_string($fromClause)) { $spacePos = strrpos($fromClause, ' '); $from = substr($fromClause, 0, $spacePos); @@ -541,7 +526,7 @@ function ($parameter) use ($key) } ); - if (count($filteredParameters)) { + if (! $filteredParameters->isEmpty()) { /* @var Query\Parameter $parameter */ $parameter = $filteredParameters->first(); $parameter->setValue($value, $type); @@ -622,7 +607,7 @@ function ($parameter) use ($key) } ); - return count($filteredParameters) ? $filteredParameters->first() : null; + return $filteredParameters->isEmpty() ? null : $filteredParameters->first(); } /** @@ -634,7 +619,7 @@ function ($parameter) use ($key) */ public function setFirstResult($firstResult) { - $this->_firstResult = $firstResult; + $this->firstResult = $firstResult; return $this; } @@ -647,7 +632,7 @@ public function setFirstResult($firstResult) */ public function getFirstResult() { - return $this->_firstResult; + return $this->firstResult; } /** @@ -659,7 +644,7 @@ public function getFirstResult() */ public function setMaxResults($maxResults) { - $this->_maxResults = $maxResults; + $this->maxResults = $maxResults; return $this; } @@ -672,7 +657,7 @@ public function setMaxResults($maxResults) */ public function getMaxResults() { - return $this->_maxResults; + return $this->maxResults; } /** @@ -696,7 +681,7 @@ public function add($dqlPartName, $dqlPart, $append = false) ); } - $isMultiple = is_array($this->_dqlParts[$dqlPartName]) + $isMultiple = is_array($this->dqlParts[$dqlPartName]) && !($dqlPartName == 'join' && !$append); // Allow adding any part retrieved from self::getDQLParts(). @@ -722,15 +707,15 @@ public function add($dqlPartName, $dqlPart, $append = false) if (is_array($dqlPart)) { $key = key($dqlPart); - $this->_dqlParts[$dqlPartName][$key][] = $dqlPart[$key]; + $this->dqlParts[$dqlPartName][$key][] = $dqlPart[$key]; } else { - $this->_dqlParts[$dqlPartName][] = $dqlPart; + $this->dqlParts[$dqlPartName][] = $dqlPart; } } else { - $this->_dqlParts[$dqlPartName] = ($isMultiple) ? [$dqlPart] : $dqlPart; + $this->dqlParts[$dqlPartName] = ($isMultiple) ? [$dqlPart] : $dqlPart; } - $this->_state = self::STATE_DIRTY; + $this->state = self::STATE_DIRTY; return $this; } @@ -752,7 +737,7 @@ public function add($dqlPartName, $dqlPart, $append = false) */ public function select($select = null) { - $this->_type = self::SELECT; + $this->type = self::SELECT; if (empty($select)) { return $this; @@ -779,7 +764,7 @@ public function select($select = null) */ public function distinct($flag = true) { - $this->_dqlParts['distinct'] = (bool) $flag; + $this->dqlParts['distinct'] = (bool) $flag; return $this; } @@ -801,7 +786,7 @@ public function distinct($flag = true) */ public function addSelect($select = null) { - $this->_type = self::SELECT; + $this->type = self::SELECT; if (empty($select)) { return $this; @@ -830,7 +815,7 @@ public function addSelect($select = null) */ public function delete($delete = null, $alias = null) { - $this->_type = self::DELETE; + $this->type = self::DELETE; if ( ! $delete) { return $this; @@ -857,7 +842,7 @@ public function delete($delete = null, $alias = null) */ public function update($update = null, $alias = null) { - $this->_type = self::UPDATE; + $this->type = self::UPDATE; if ( ! $update) { return $this; @@ -920,7 +905,7 @@ public function indexBy($alias, $indexBy) ); } - foreach ($this->_dqlParts['from'] as &$fromClause) { + foreach ($this->dqlParts['from'] as &$fromClause) { /* @var Expr\From $fromClause */ if ($fromClause->getAlias() !== $alias) { continue; @@ -1353,7 +1338,7 @@ public function addCriteria(Criteria $criteria) */ public function getDQLPart($queryPartName) { - return $this->_dqlParts[$queryPartName]; + return $this->dqlParts[$queryPartName]; } /** @@ -1365,40 +1350,40 @@ public function getDQLPart($queryPartName) */ public function getDQLParts() { - return $this->_dqlParts; + return $this->dqlParts; } /** * @return string */ - private function _getDQLForDelete() + private function getDQLForDelete() { return 'DELETE' - . $this->_getReducedDQLQueryPart('from', ['pre' => ' ', 'separator' => ', ']) - . $this->_getReducedDQLQueryPart('where', ['pre' => ' WHERE ']) - . $this->_getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ', 'separator' => ', ']); + . $this->getReducedDQLQueryPart('from', ['pre' => ' ', 'separator' => ', ']) + . $this->getReducedDQLQueryPart('where', ['pre' => ' WHERE ']) + . $this->getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ', 'separator' => ', ']); } /** * @return string */ - private function _getDQLForUpdate() + private function getDQLForUpdate() { return 'UPDATE' - . $this->_getReducedDQLQueryPart('from', ['pre' => ' ', 'separator' => ', ']) - . $this->_getReducedDQLQueryPart('set', ['pre' => ' SET ', 'separator' => ', ']) - . $this->_getReducedDQLQueryPart('where', ['pre' => ' WHERE ']) - . $this->_getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ', 'separator' => ', ']); + . $this->getReducedDQLQueryPart('from', ['pre' => ' ', 'separator' => ', ']) + . $this->getReducedDQLQueryPart('set', ['pre' => ' SET ', 'separator' => ', ']) + . $this->getReducedDQLQueryPart('where', ['pre' => ' WHERE ']) + . $this->getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ', 'separator' => ', ']); } /** * @return string */ - private function _getDQLForSelect() + private function getDQLForSelect() { $dql = 'SELECT' - . ($this->_dqlParts['distinct']===true ? ' DISTINCT' : '') - . $this->_getReducedDQLQueryPart('select', ['pre' => ' ', 'separator' => ', ']); + . ($this->dqlParts['distinct']===true ? ' DISTINCT' : '') + . $this->getReducedDQLQueryPart('select', ['pre' => ' ', 'separator' => ', ']); $fromParts = $this->getDQLPart('from'); $joinParts = $this->getDQLPart('join'); @@ -1422,10 +1407,10 @@ private function _getDQLForSelect() } $dql .= implode(', ', $fromClauses) - . $this->_getReducedDQLQueryPart('where', ['pre' => ' WHERE ']) - . $this->_getReducedDQLQueryPart('groupBy', ['pre' => ' GROUP BY ', 'separator' => ', ']) - . $this->_getReducedDQLQueryPart('having', ['pre' => ' HAVING ']) - . $this->_getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ', 'separator' => ', ']); + . $this->getReducedDQLQueryPart('where', ['pre' => ' WHERE ']) + . $this->getReducedDQLQueryPart('groupBy', ['pre' => ' GROUP BY ', 'separator' => ', ']) + . $this->getReducedDQLQueryPart('having', ['pre' => ' HAVING ']) + . $this->getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ', 'separator' => ', ']); return $dql; } @@ -1436,7 +1421,7 @@ private function _getDQLForSelect() * * @return string */ - private function _getReducedDQLQueryPart($queryPartName, $options = []) + private function getReducedDQLQueryPart($queryPartName, $options = []) { $queryPart = $this->getDQLPart($queryPartName); @@ -1459,7 +1444,7 @@ private function _getReducedDQLQueryPart($queryPartName, $options = []) public function resetDQLParts($parts = null) { if (null === $parts) { - $parts = array_keys($this->_dqlParts); + $parts = array_keys($this->dqlParts); } foreach ($parts as $part) { @@ -1478,8 +1463,8 @@ public function resetDQLParts($parts = null) */ public function resetDQLPart($part) { - $this->_dqlParts[$part] = is_array($this->_dqlParts[$part]) ? [] : null; - $this->_state = self::STATE_DIRTY; + $this->dqlParts[$part] = is_array($this->dqlParts[$part]) ? [] : null; + $this->state = self::STATE_DIRTY; return $this; } @@ -1502,15 +1487,15 @@ public function __toString() */ public function __clone() { - foreach ($this->_dqlParts as $part => $elements) { - if (is_array($this->_dqlParts[$part])) { - foreach ($this->_dqlParts[$part] as $idx => $element) { + foreach ($this->dqlParts as $part => $elements) { + if (is_array($this->dqlParts[$part])) { + foreach ($this->dqlParts[$part] as $idx => $element) { if (is_object($element)) { - $this->_dqlParts[$part][$idx] = clone $element; + $this->dqlParts[$part][$idx] = clone $element; } } } else if (is_object($elements)) { - $this->_dqlParts[$part] = clone $elements; + $this->dqlParts[$part] = clone $elements; } } diff --git a/lib/Doctrine/ORM/Reflection/ReflectionService.php b/lib/Doctrine/ORM/Reflection/ReflectionService.php new file mode 100644 index 00000000000..9078501746f --- /dev/null +++ b/lib/Doctrine/ORM/Reflection/ReflectionService.php @@ -0,0 +1,73 @@ + + */ +interface ReflectionService +{ + /** + * Returns an array of the parent classes (not interfaces) for the given class. + * + * @param string $className + * + * @throws \InvalidArgumentException If provided argument is not a valid class name. + * + * @return array + */ + public function getParentClasses(string $className) : array; + + /** + * Returns the shortname of a class. + * + * @param string $className + * + * @return string + */ + public function getClassShortName(string $className) : string; + + /** + * @param string $className + * + * @return string + */ + public function getClassNamespace(string $className) : string; + + /** + * Returns a reflection class instance or null. + * + * @param string $className + * + * @return \ReflectionClass|null + */ + public function getClass(string $className) : ?\ReflectionClass; + + /** + * Returns an accessible property (setAccessible(true)) or null. + * + * @param string $className + * @param string $propertyName + * + * @return \ReflectionProperty|null + */ + public function getAccessibleProperty(string $className, string $propertyName) : ?\ReflectionProperty; + + /** + * Checks if the class have a public method with the given name. + * + * @param mixed $className + * @param mixed $methodName + * + * @return bool + */ + public function hasPublicMethod(string $className, string $methodName) : bool; +} diff --git a/lib/Doctrine/ORM/Reflection/RuntimePublicReflectionProperty.php b/lib/Doctrine/ORM/Reflection/RuntimePublicReflectionProperty.php new file mode 100644 index 00000000000..310ac794d15 --- /dev/null +++ b/lib/Doctrine/ORM/Reflection/RuntimePublicReflectionProperty.php @@ -0,0 +1,62 @@ + + * @since 2.4 + */ +class RuntimePublicReflectionProperty extends \ReflectionProperty +{ + /** + * {@inheritDoc} + * + * Checks is the value actually exist before fetching it. + * This is to avoid calling `__get` on the provided $object if it + * is a {@see \Doctrine\ORM\Proxy\Proxy}. + */ + public function getValue($object = null) + { + $name = $this->getName(); + + if ($object instanceof Proxy && ! $object->__isInitialized()) { + $originalInitialized = $object->__isInitialized(); + + $object->__setInitialized(true); + $val = isset($object->$name) ? $object->$name : null; + $object->__setInitialized($originalInitialized); + + return $val; + } + + return isset($object->$name) ? parent::getValue($object) : null; + } + + /** + * {@inheritDoc} + * + * Avoids triggering lazy loading via `__set` if the provided object + * is a {@see \Doctrine\ORM\Proxy\Proxy}. + * @link https://bugs.php.net/bug.php?id=63463 + */ + public function setValue($object, $value = null) + { + if ($object instanceof Proxy && ! $object->__isInitialized()) { + $originalInitialized = $object->__isInitialized(); + + $object->__setInitialized(true); + parent::setValue($object, $value); + $object->__setInitialized($originalInitialized); + + return; + } + + parent::setValue($object, $value); + } +} diff --git a/lib/Doctrine/ORM/Reflection/RuntimeReflectionService.php b/lib/Doctrine/ORM/Reflection/RuntimeReflectionService.php new file mode 100644 index 00000000000..9a371783070 --- /dev/null +++ b/lib/Doctrine/ORM/Reflection/RuntimeReflectionService.php @@ -0,0 +1,86 @@ + + */ +class RuntimeReflectionService implements ReflectionService +{ + /** + * {@inheritdoc} + */ + public function getParentClasses(string $className) : array + { + if (! class_exists($className)) { + throw MappingException::nonExistingClass($className); + } + + return class_parents($className); + } + + /** + * {@inheritdoc} + */ + public function getClassShortName(string $className) : string + { + $reflectionClass = new \ReflectionClass($className); + + return $reflectionClass->getShortName(); + } + + /** + * {@inheritdoc} + */ + public function getClassNamespace(string $className) : string + { + $reflectionClass = new \ReflectionClass($className); + + return $reflectionClass->getNamespaceName(); + } + + /** + * {@inheritdoc} + */ + public function getClass(string $className) : ?\ReflectionClass + { + return new \ReflectionClass($className); + } + + /** + * {@inheritdoc} + */ + public function getAccessibleProperty(string $className, string $propertyName) : ?\ReflectionProperty + { + $reflectionProperty = new \ReflectionProperty($className, $propertyName); + + if ($reflectionProperty->isPublic()) { + $reflectionProperty = new RuntimePublicReflectionProperty($className, $propertyName); + } + + $reflectionProperty->setAccessible(true); + + return $reflectionProperty; + } + + /** + * {@inheritdoc} + */ + public function hasPublicMethod(string $className, string $methodName) : bool + { + try { + $reflectionMethod = new \ReflectionMethod($className, $methodName); + } catch (\ReflectionException $e) { + return false; + } + + return $reflectionMethod->isPublic(); + } +} diff --git a/lib/Doctrine/ORM/Reflection/StaticReflectionService.php b/lib/Doctrine/ORM/Reflection/StaticReflectionService.php new file mode 100644 index 00000000000..fc6fa17ffbf --- /dev/null +++ b/lib/Doctrine/ORM/Reflection/StaticReflectionService.php @@ -0,0 +1,71 @@ + + */ +class StaticReflectionService implements ReflectionService +{ + /** + * {@inheritDoc} + */ + public function getParentClasses(string $className) : array + { + return []; + } + + /** + * {@inheritDoc} + */ + public function getClassShortName(string $className) : string + { + if (strpos($className, '\\') !== false) { + $className = substr($className, strrpos($className, "\\")+1); + } + return $className; + } + + /** + * {@inheritDoc} + */ + public function getClassNamespace(string $className) : string + { + $namespace = ''; + + if (strpos($className, '\\') !== false) { + $namespace = strrev(substr( strrev($className), strpos(strrev($className), '\\')+1 )); + } + + return $namespace; + } + + /** + * {@inheritDoc} + */ + public function getClass(string $className) : ?\ReflectionClass + { + return null; + } + + /** + * {@inheritDoc} + */ + public function getAccessibleProperty(string $className, string $propertyName) : ?\ReflectionProperty + { + return null; + } + + /** + * {@inheritDoc} + */ + public function hasPublicMethod(string $className, string $methodName) : bool + { + return true; + } +} diff --git a/lib/Doctrine/ORM/Repository/DefaultRepositoryFactory.php b/lib/Doctrine/ORM/Repository/DefaultRepositoryFactory.php index 680962413fc..04409b89b14 100644 --- a/lib/Doctrine/ORM/Repository/DefaultRepositoryFactory.php +++ b/lib/Doctrine/ORM/Repository/DefaultRepositoryFactory.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Repository; @@ -41,7 +26,7 @@ final class DefaultRepositoryFactory implements RepositoryFactory */ public function getRepository(EntityManagerInterface $entityManager, $entityName) { - $repositoryHash = $entityManager->getClassMetadata($entityName)->getName() . spl_object_hash($entityManager); + $repositoryHash = $entityManager->getClassMetadata($entityName)->getClassName() . spl_object_hash($entityManager); if (isset($this->repositoryList[$repositoryHash])) { return $this->repositoryList[$repositoryHash]; @@ -62,7 +47,7 @@ private function createRepository(EntityManagerInterface $entityManager, $entity { /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */ $metadata = $entityManager->getClassMetadata($entityName); - $repositoryClassName = $metadata->customRepositoryClassName + $repositoryClassName = $metadata->getCustomRepositoryClassName() ?: $entityManager->getConfiguration()->getDefaultRepositoryClassName(); return new $repositoryClassName($entityManager, $metadata); diff --git a/lib/Doctrine/ORM/Repository/RepositoryFactory.php b/lib/Doctrine/ORM/Repository/RepositoryFactory.php index f3af43ebe0d..6977ec97a62 100644 --- a/lib/Doctrine/ORM/Repository/RepositoryFactory.php +++ b/lib/Doctrine/ORM/Repository/RepositoryFactory.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Repository; @@ -38,4 +23,4 @@ interface RepositoryFactory * @return \Doctrine\Common\Persistence\ObjectRepository */ public function getRepository(EntityManagerInterface $entityManager, $entityName); -} \ No newline at end of file +} diff --git a/lib/Doctrine/ORM/Sequencing/BigIntegerIdentityGenerator.php b/lib/Doctrine/ORM/Sequencing/BigIntegerIdentityGenerator.php new file mode 100644 index 00000000000..c8d03c72cf8 --- /dev/null +++ b/lib/Doctrine/ORM/Sequencing/BigIntegerIdentityGenerator.php @@ -0,0 +1,51 @@ +sequenceName = $sequenceName; + } + + /** + * {@inheritdoc} + */ + public function generate(EntityManagerInterface $em, $entity) + { + return (string) $em->getConnection()->lastInsertId($this->sequenceName); + } + + /** + * {@inheritdoc} + */ + public function isPostInsertGenerator() + { + return true; + } +} + diff --git a/lib/Doctrine/ORM/Sequencing/Generator.php b/lib/Doctrine/ORM/Sequencing/Generator.php new file mode 100644 index 00000000000..e29b60fc629 --- /dev/null +++ b/lib/Doctrine/ORM/Sequencing/Generator.php @@ -0,0 +1,33 @@ +sequenceName = $sequenceName; + } + + /** + * {@inheritDoc} + */ + public function generate(EntityManagerInterface $em, $entity) + { + return (int) $em->getConnection()->lastInsertId($this->sequenceName); + } + + /** + * {@inheritdoc} + */ + public function isPostInsertGenerator() + { + return true; + } +} diff --git a/lib/Doctrine/ORM/Sequencing/Planning/ColumnValueGeneratorExecutor.php b/lib/Doctrine/ORM/Sequencing/Planning/ColumnValueGeneratorExecutor.php new file mode 100644 index 00000000000..b9249adc52a --- /dev/null +++ b/lib/Doctrine/ORM/Sequencing/Planning/ColumnValueGeneratorExecutor.php @@ -0,0 +1,40 @@ +column = $column; + $this->generator = $generator; + } + + public function execute(EntityManagerInterface $entityManager, /*object*/ $entity) : array + { + $value = $this->generator->generate($entityManager, $entity); + + $platform = $entityManager->getConnection()->getDatabasePlatform(); + $convertedValue = $this->column->getType()->convertToPHPValue($value, $platform); + + return [$this->column->getColumnName() => $convertedValue]; + } + + public function isDeferred() : bool + { + return $this->generator->isPostInsertGenerator(); + } +} diff --git a/lib/Doctrine/ORM/Sequencing/Planning/CompositeValueGenerationPlan.php b/lib/Doctrine/ORM/Sequencing/Planning/CompositeValueGenerationPlan.php new file mode 100644 index 00000000000..0f4cc931c68 --- /dev/null +++ b/lib/Doctrine/ORM/Sequencing/Planning/CompositeValueGenerationPlan.php @@ -0,0 +1,71 @@ +class = $metadata; + $this->executors = $executors; + } + + public function executeImmediate(EntityManagerInterface $entityManager, /*object*/ $entity): void + { + foreach ($this->executors as $executor) { + if ($executor->isDeferred()) { + continue; + } + + $this->dispatchExecutor($executor, $entity, $entityManager); + } + } + + public function executeDeferred(EntityManagerInterface $entityManager, /*object*/ $entity): void + { + foreach ($this->executors as $executor) { + if (! $executor->isDeferred()) { + continue; + } + + $this->dispatchExecutor($executor, $entity, $entityManager); + } + } + + private function dispatchExecutor(ValueGenerationExecutor $executor, /*object*/ $entity, EntityManagerInterface $entityManager): void + { + foreach ($executor->execute($entityManager, $entity) as $columnName => $value) { + // TODO LocalColumnMetadata are currently shadowed and only exposed as FieldMetadata + /** @var FieldMetadata $column */ + $column = $this->class->getColumn($columnName); + $column->setValue($entity, $value); + } + } + + public function containsDeferred(): bool + { + foreach ($this->executors as $executor) { + if ($executor->isDeferred()) { + return true; + } + } + + return false; + } +} diff --git a/lib/Doctrine/ORM/Sequencing/Planning/NoopValueGenerationPlan.php b/lib/Doctrine/ORM/Sequencing/Planning/NoopValueGenerationPlan.php new file mode 100644 index 00000000000..a770184bbd2 --- /dev/null +++ b/lib/Doctrine/ORM/Sequencing/Planning/NoopValueGenerationPlan.php @@ -0,0 +1,26 @@ +class = $class; + $this->executor = $executor; + } + + public function executeImmediate(EntityManagerInterface $entityManager, /*object*/ $entity): void + { + if (! $this->executor->isDeferred()) { + $this->dispatchExecutor($entity, $entityManager); + } + } + + public function executeDeferred(EntityManagerInterface $entityManager, /*object*/ $entity) : void + { + if ($this->executor->isDeferred()) { + $this->dispatchExecutor($entity, $entityManager); + } + } + private function dispatchExecutor(/*object*/ $entity, EntityManagerInterface $entityManager): void + { + foreach ($this->executor->execute($entityManager, $entity) as $columnName => $value) { + // TODO LocalColumnMetadata are currently shadowed and only exposed as FieldMetadata + /** @var FieldMetadata $column */ + $column = $this->class->getColumn($columnName); + $column->setValue($entity, $value); + } + } + + public function containsDeferred(): bool + { + return $this->executor->isDeferred(); + } +} diff --git a/lib/Doctrine/ORM/Sequencing/Planning/ValueGenerationExecutor.php b/lib/Doctrine/ORM/Sequencing/Planning/ValueGenerationExecutor.php new file mode 100644 index 00000000000..f432cac320a --- /dev/null +++ b/lib/Doctrine/ORM/Sequencing/Planning/ValueGenerationExecutor.php @@ -0,0 +1,18 @@ + + */ +class SequenceGenerator implements Generator, Serializable +{ + /** + * The allocation size of the sequence. + * + * @var int + */ + private $allocationSize; + + /** + * The name of the sequence. + * + * @var string + */ + private $sequenceName; + + /** + * @var int + */ + private $nextValue = 0; + + /** + * @var int|null + */ + private $maxValue = null; + + /** + * Initializes a new sequence generator. + * + * @param string $sequenceName The name of the sequence. + * @param integer $allocationSize The allocation size of the sequence. + */ + public function __construct($sequenceName, $allocationSize) + { + $this->sequenceName = $sequenceName; + $this->allocationSize = $allocationSize; + } + + /** + * {@inheritdoc} + */ + public function generate(EntityManagerInterface $em, $entity) + { + if ($this->maxValue === null || $this->nextValue == $this->maxValue) { + // Allocate new values + $conn = $em->getConnection(); + $sql = $conn->getDatabasePlatform()->getSequenceNextValSQL($this->sequenceName); + + // Using `query` to force usage of the master server in MasterSlaveConnection + $this->nextValue = (int) $conn->query($sql)->fetchColumn(); + $this->maxValue = $this->nextValue + $this->allocationSize; + } + + return $this->nextValue++; + } + + /** + * Gets the maximum value of the currently allocated bag of values. + * + * @return integer|null + */ + public function getCurrentMaxValue() + { + return $this->maxValue; + } + + /** + * Gets the next value that will be returned by generate(). + * + * @return integer + */ + public function getNextValue() + { + return $this->nextValue; + } + + /** + * @return string + */ + public function serialize() + { + return serialize( + [ + 'allocationSize' => $this->allocationSize, + 'sequenceName' => $this->sequenceName + ] + ); + } + + /** + * @param string $serialized + * + * @return void + */ + public function unserialize($serialized) + { + $array = unserialize($serialized); + + $this->sequenceName = $array['sequenceName']; + $this->allocationSize = $array['allocationSize']; + } + + /** + * {@inheritdoc} + */ + public function isPostInsertGenerator() + { + return false; + } +} diff --git a/lib/Doctrine/ORM/Sequencing/TableGenerator.php b/lib/Doctrine/ORM/Sequencing/TableGenerator.php new file mode 100644 index 00000000000..7fa509fd5d8 --- /dev/null +++ b/lib/Doctrine/ORM/Sequencing/TableGenerator.php @@ -0,0 +1,102 @@ + + * @author Guilherme Blanco + * @author Jonathan Wage + * @author Roman Borschel + */ +class TableGenerator implements Generator +{ + /** + * @var string + */ + private $tableName; + + /** + * @var string + */ + private $sequenceName; + + /** + * @var int + */ + private $allocationSize; + + /** + * @var int|null + */ + private $nextValue; + + /** + * @var int|null + */ + private $maxValue; + + /** + * @param string $tableName + * @param string $sequenceName + * @param int $allocationSize + */ + public function __construct($tableName, $sequenceName = 'default', $allocationSize = 10) + { + $this->tableName = $tableName; + $this->sequenceName = $sequenceName; + $this->allocationSize = $allocationSize; + } + + /** + * {@inheritdoc} + */ + public function generate(EntityManagerInterface $em, $entity) + { + if ($this->maxValue === null || $this->nextValue === $this->maxValue) { + // Allocate new values + $conn = $em->getConnection(); + + if ($conn->getTransactionNestingLevel() === 0) { + // use select for update + $platform = $conn->getDatabasePlatform(); + $sql = $platform->getTableHiLoCurrentValSql($this->tableName, $this->sequenceName); + $currentLevel = $conn->fetchColumn($sql); + + if ($currentLevel !== null) { + $this->nextValue = $currentLevel; + $this->maxValue = $this->nextValue + $this->allocationSize; + + $updateSql = $platform->getTableHiLoUpdateNextValSql( + $this->tableName, $this->sequenceName, $this->allocationSize + ); + + if ($conn->executeUpdate($updateSql, [1 => $currentLevel, 2 => $currentLevel+1]) !== 1) { + // no affected rows, concurrency issue, throw exception + } + } else { + // no current level returned, TableGenerator seems to be broken, throw exception + } + } else { + // only table locks help here, implement this or throw exception? + // or do we want to work with table locks exclusively? + } + } + + return $this->nextValue++; + } + + /** + * {@inheritdoc} + */ + public function isPostInsertGenerator() + { + return false; + } +} diff --git a/lib/Doctrine/ORM/Sequencing/UuidGenerator.php b/lib/Doctrine/ORM/Sequencing/UuidGenerator.php new file mode 100644 index 00000000000..0475cc3c119 --- /dev/null +++ b/lib/Doctrine/ORM/Sequencing/UuidGenerator.php @@ -0,0 +1,35 @@ + + */ +class UuidGenerator implements Generator +{ + /** + * {@inheritdoc} + */ + public function generate(EntityManagerInterface $em, $entity) + { + $conn = $em->getConnection(); + $sql = 'SELECT ' . $conn->getDatabasePlatform()->getGuidExpression(); + + return $conn->query($sql)->fetchColumn(0); + } + + /** + * {@inheritdoc} + */ + public function isPostInsertGenerator() + { + return false; + } +} diff --git a/lib/Doctrine/ORM/Tools/AttachEntityListenersListener.php b/lib/Doctrine/ORM/Tools/AttachEntityListenersListener.php index cf7cc8b8b95..6d0616f1203 100644 --- a/lib/Doctrine/ORM/Tools/AttachEntityListenersListener.php +++ b/lib/Doctrine/ORM/Tools/AttachEntityListenersListener.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools; @@ -66,14 +51,16 @@ public function loadClassMetadata(LoadClassMetadataEventArgs $event) /** @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */ $metadata = $event->getClassMetadata(); - if ( ! isset($this->entityListeners[$metadata->name])) { + if ( ! isset($this->entityListeners[$metadata->getClassName()])) { return; } - foreach ($this->entityListeners[$metadata->name] as $listener) { - $metadata->addEntityListener($listener['event'], $listener['class'], $listener['method']); + foreach ($this->entityListeners[$metadata->getClassName()] as $listener) { + $listenerClassName = $metadata->fullyQualifiedClassName($listener['class']); + + $metadata->addEntityListener($listener['event'], $listenerClassName, $listener['method']); } - unset($this->entityListeners[$metadata->name]); + unset($this->entityListeners[$metadata->getClassName()]); } } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/CollectionRegionCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/CollectionRegionCommand.php index f12bfa5602d..8217a7321b8 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/CollectionRegionCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/CollectionRegionCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command\ClearCache; diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/EntityRegionCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/EntityRegionCommand.php index 0258b7de223..965aaabcdb4 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/EntityRegionCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/EntityRegionCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command\ClearCache; diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/MetadataCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/MetadataCommand.php index 5bc0c859d63..c8d06233bba 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/MetadataCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/MetadataCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command\ClearCache; diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryCommand.php index 5828d077163..ec624e365f4 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command\ClearCache; diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryRegionCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryRegionCommand.php index 0637c7a4a07..2c822f74068 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryRegionCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryRegionCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command\ClearCache; diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/ResultCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/ResultCommand.php index 55b89efa8eb..8a13dc884e6 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/ResultCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/ResultCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command\ClearCache; diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommand.php deleted file mode 100644 index 6c81de940de..00000000000 --- a/lib/Doctrine/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommand.php +++ /dev/null @@ -1,231 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Tools\Console\Command; - -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; -use Doctrine\ORM\Tools\Export\ClassMetadataExporter; -use Doctrine\ORM\Tools\ConvertDoctrine1Schema; -use Doctrine\ORM\Tools\EntityGenerator; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Command\Command; - -/** - * Command to convert a Doctrine 1 schema to a Doctrine 2 mapping file. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - */ -class ConvertDoctrine1SchemaCommand extends Command -{ - /** - * @var EntityGenerator|null - */ - private $entityGenerator = null; - - /** - * @var ClassMetadataExporter|null - */ - private $metadataExporter = null; - - /** - * @return EntityGenerator - */ - public function getEntityGenerator() - { - if ($this->entityGenerator == null) { - $this->entityGenerator = new EntityGenerator(); - } - - return $this->entityGenerator; - } - - /** - * @param EntityGenerator $entityGenerator - * - * @return void - */ - public function setEntityGenerator(EntityGenerator $entityGenerator) - { - $this->entityGenerator = $entityGenerator; - } - - /** - * @return ClassMetadataExporter - */ - public function getMetadataExporter() - { - if ($this->metadataExporter == null) { - $this->metadataExporter = new ClassMetadataExporter(); - } - - return $this->metadataExporter; - } - - /** - * @param ClassMetadataExporter $metadataExporter - * - * @return void - */ - public function setMetadataExporter(ClassMetadataExporter $metadataExporter) - { - $this->metadataExporter = $metadataExporter; - } - - /** - * {@inheritdoc} - */ - protected function configure() - { - $this - ->setName('orm:convert-d1-schema') - ->setAliases(['orm:convert:d1-schema']) - ->setDescription('Converts Doctrine 1.X schema into a Doctrine 2.X schema.') - ->setDefinition( - [ - new InputArgument( - 'from-path', InputArgument::REQUIRED, 'The path of Doctrine 1.X schema information.' - ), - new InputArgument( - 'to-type', InputArgument::REQUIRED, 'The destination Doctrine 2.X mapping type.' - ), - new InputArgument( - 'dest-path', InputArgument::REQUIRED, - 'The path to generate your Doctrine 2.X mapping information.' - ), - new InputOption( - 'from', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, - 'Optional paths of Doctrine 1.X schema information.', - [] - ), - new InputOption( - 'extend', null, InputOption::VALUE_OPTIONAL, - 'Defines a base class to be extended by generated entity classes.' - ), - new InputOption( - 'num-spaces', null, InputOption::VALUE_OPTIONAL, - 'Defines the number of indentation spaces', 4 - ) - ] - ) - ->setHelp(<<getArgument('from-path')], $input->getOption('from')); - - // Process destination directory - $destPath = realpath($input->getArgument('dest-path')); - - $toType = $input->getArgument('to-type'); - $extend = $input->getOption('extend'); - $numSpaces = $input->getOption('num-spaces'); - - $this->convertDoctrine1Schema($fromPaths, $destPath, $toType, $numSpaces, $extend, $output); - } - - /** - * @param array $fromPaths - * @param string $destPath - * @param string $toType - * @param int $numSpaces - * @param string|null $extend - * @param OutputInterface $output - * - * @throws \InvalidArgumentException - */ - public function convertDoctrine1Schema(array $fromPaths, $destPath, $toType, $numSpaces, $extend, OutputInterface $output) - { - foreach ($fromPaths as &$dirName) { - $dirName = realpath($dirName); - - if ( ! file_exists($dirName)) { - throw new \InvalidArgumentException( - sprintf("Doctrine 1.X schema directory '%s' does not exist.", $dirName) - ); - } - - if ( ! is_readable($dirName)) { - throw new \InvalidArgumentException( - sprintf("Doctrine 1.X schema directory '%s' does not have read permissions.", $dirName) - ); - } - } - - if ( ! file_exists($destPath)) { - throw new \InvalidArgumentException( - sprintf("Doctrine 2.X mapping destination directory '%s' does not exist.", $destPath) - ); - } - - if ( ! is_writable($destPath)) { - throw new \InvalidArgumentException( - sprintf("Doctrine 2.X mapping destination directory '%s' does not have write permissions.", $destPath) - ); - } - - $cme = $this->getMetadataExporter(); - $exporter = $cme->getExporter($toType, $destPath); - - if (strtolower($toType) === 'annotation') { - $entityGenerator = $this->getEntityGenerator(); - $exporter->setEntityGenerator($entityGenerator); - - $entityGenerator->setNumSpaces($numSpaces); - - if ($extend !== null) { - $entityGenerator->setClassToExtend($extend); - } - } - - $converter = new ConvertDoctrine1Schema($fromPaths); - $metadata = $converter->getMetadata(); - - if ($metadata) { - $output->writeln(''); - - foreach ($metadata as $class) { - $output->writeln(sprintf('Processing entity "%s"', $class->name)); - } - - $exporter->setMetadata($metadata); - $exporter->export(); - - $output->writeln(PHP_EOL . sprintf( - 'Converting Doctrine 1.X schema to "%s" mapping type in "%s"', $toType, $destPath - )); - } else { - $output->writeln('No Metadata Classes to process.'); - } - } -} diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ConvertMappingCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ConvertMappingCommand.php index 798dbe72858..3add8ddc702 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ConvertMappingCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ConvertMappingCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command; @@ -98,7 +83,7 @@ protected function configure() entities with foreign keys as primary keys and many of the semantical operations on associations such as cascade. -Hint: There is no need to convert YAML or XML mapping files to annotations +Hint: There is no need to convert XML mapping files to annotations every time you make changes. All mapping drivers are first class citizens in Doctrine 2 and can be used as runtime mapping for the ORM. @@ -173,7 +158,7 @@ protected function execute(InputInterface $input, OutputInterface $output) if (count($metadata)) { foreach ($metadata as $class) { - $output->writeln(sprintf('Processing entity "%s"', $class->name)); + $output->writeln(sprintf('Processing entity "%s"', $class->getClassName())); } $exporter->setMetadata($metadata); diff --git a/lib/Doctrine/ORM/Tools/Console/Command/EnsureProductionSettingsCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/EnsureProductionSettingsCommand.php index 499565a018a..a13c30f7b3c 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/EnsureProductionSettingsCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/EnsureProductionSettingsCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command; diff --git a/lib/Doctrine/ORM/Tools/Console/Command/GenerateEntitiesCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/GenerateEntitiesCommand.php index 080bfc97ace..f27c84b47a4 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/GenerateEntitiesCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/GenerateEntitiesCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command; @@ -103,10 +88,9 @@ protected function configure() the entity-generator and code your entities manually. Important: Even if you specified Inheritance options in your -XML or YAML Mapping files the generator cannot generate the base and -child classes for you correctly, because it doesn't know which -class is supposed to extend which. You have to adjust the entity -code manually for inheritance to work! +XML Mapping files the generator cannot generate the base and child classes +for you correctly, because it doesn't know which class is supposed to extend +which. You have to adjust the entity code manually for inheritance to work! EOT ); } @@ -155,7 +139,7 @@ protected function execute(InputInterface $input, OutputInterface $output) foreach ($metadatas as $metadata) { $output->writeln( - sprintf('Processing entity "%s"', $metadata->name) + sprintf('Processing entity "%s"', $metadata->getClassName()) ); } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/GenerateProxiesCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/GenerateProxiesCommand.php index 9475bca71b7..1c1aec02c6d 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/GenerateProxiesCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/GenerateProxiesCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command; @@ -101,7 +86,7 @@ protected function execute(InputInterface $input, OutputInterface $output) if ( count($metadatas)) { foreach ($metadatas as $metadata) { $output->writeln( - sprintf('Processing entity "%s"', $metadata->name) + sprintf('Processing entity "%s"', $metadata->getClassName()) ); } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/GenerateRepositoriesCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/GenerateRepositoriesCommand.php index 1da7a85c141..f9a0887d472 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/GenerateRepositoriesCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/GenerateRepositoriesCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command; @@ -99,12 +84,12 @@ protected function execute(InputInterface $input, OutputInterface $output) $generator->setDefaultRepositoryName($repositoryName); foreach ($metadatas as $metadata) { - if ($metadata->customRepositoryClassName) { + if ($metadata->getCustomRepositoryClassName()) { $output->writeln( - sprintf('Processing repository "%s"', $metadata->customRepositoryClassName) + sprintf('Processing repository "%s"', $metadata->getCustomRepositoryClassName()) ); - $generator->writeEntityRepositoryClass($metadata->customRepositoryClassName, $destPath); + $generator->writeEntityRepositoryClass($metadata->getCustomRepositoryClassName(), $destPath); $numRepositories++; } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/InfoCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/InfoCommand.php index 560d18718b5..20bc31d5f40 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/InfoCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/InfoCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command; @@ -54,7 +39,7 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { - /* @var $entityManager \Doctrine\ORM\EntityManager */ + /* @var $entityManager \Doctrine\ORM\EntityManagerInterface */ $entityManager = $this->getHelper('em')->getEntityManager(); $entityClassNames = $entityManager->getConfiguration() diff --git a/lib/Doctrine/ORM/Tools/Console/Command/MappingDescribeCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/MappingDescribeCommand.php index 6f2761e0dc6..5e50bc563b6 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/MappingDescribeCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/MappingDescribeCommand.php @@ -1,26 +1,17 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command; use Doctrine\Common\Persistence\Mapping\MappingException; use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\ColumnMetadata; +use Doctrine\ORM\Mapping\ComponentMetadata; +use Doctrine\ORM\Mapping\FieldMetadata; +use Doctrine\ORM\Mapping\TableMetadata; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Input\InputArgument; @@ -83,46 +74,49 @@ private function displayEntity($entityName, EntityManagerInterface $entityManage $table->setHeaders(['Field', 'Value']); - $metadata = $this->getClassMetadata($entityName, $entityManager); + $metadata = $this->getClassMetadata($entityName, $entityManager); + $parentValue = $metadata->getParent() === null ? 'None' : ''; array_map( [$table, 'addRow'], array_merge( [ - $this->formatField('Name', $metadata->name), - $this->formatField('Root entity name', $metadata->rootEntityName), - $this->formatField('Custom generator definition', $metadata->customGeneratorDefinition), - $this->formatField('Custom repository class', $metadata->customRepositoryClassName), + $this->formatField('Name', $metadata->getClassName()), + $this->formatField('Root entity name', $metadata->getRootClassName()), + $this->formatField('Custom repository class', $metadata->getCustomRepositoryClassName()), $this->formatField('Mapped super class?', $metadata->isMappedSuperclass), $this->formatField('Embedded class?', $metadata->isEmbeddedClass), - $this->formatField('Parent classes', $metadata->parentClasses), - $this->formatField('Sub classes', $metadata->subClasses), - $this->formatField('Embedded classes', $metadata->subClasses), - $this->formatField('Named queries', $metadata->namedQueries), - $this->formatField('Named native queries', $metadata->namedNativeQueries), - $this->formatField('SQL result set mappings', $metadata->sqlResultSetMappings), - $this->formatField('Identifier', $metadata->identifier), + $this->formatField('Parent classes', $parentValue), + ], + $this->formatParentClasses($metadata), + [ + $this->formatField('Sub classes', $metadata->getSubClasses()), + $this->formatField('Embedded classes', $metadata->getSubClasses()), + $this->formatField('Named queries', $metadata->getNamedQueries()), + $this->formatField('Named native queries', $metadata->getNamedNativeQueries()), + $this->formatField('SQL result set mappings', $metadata->getSqlResultSetMappings()), + $this->formatField('Identifier', $metadata->getIdentifier()), $this->formatField('Inheritance type', $metadata->inheritanceType), - $this->formatField('Discriminator column', $metadata->discriminatorColumn), + $this->formatField('Discriminator column', ''), + ], + $this->formatColumn($metadata->discriminatorColumn), + [ $this->formatField('Discriminator value', $metadata->discriminatorValue), $this->formatField('Discriminator map', $metadata->discriminatorMap), - $this->formatField('Generator type', $metadata->generatorType), - $this->formatField('Table', $metadata->table), - $this->formatField('Composite identifier?', $metadata->isIdentifierComposite), - $this->formatField('Foreign identifier?', $metadata->containsForeignIdentifier), - $this->formatField('Sequence generator definition', $metadata->sequenceGeneratorDefinition), - $this->formatField('Table generator definition', $metadata->tableGeneratorDefinition), + $this->formatField('Table', ''), + ], + $this->formatTable($metadata->table), + [ + $this->formatField('Composite identifier?', $metadata->isIdentifierComposite()), $this->formatField('Change tracking policy', $metadata->changeTrackingPolicy), - $this->formatField('Versioned?', $metadata->isVersioned), - $this->formatField('Version field', $metadata->versionField), - $this->formatField('Read only?', $metadata->isReadOnly), + $this->formatField('Versioned?', $metadata->isVersioned()), + $this->formatField('Version field', ($metadata->isVersioned() ? $metadata->versionProperty->getName() : '')), + $this->formatField('Read only?', $metadata->isReadOnly()), $this->formatEntityListeners($metadata->entityListeners), ], - [$this->formatField('Association mappings:', '')], - $this->formatMappings($metadata->associationMappings), - [$this->formatField('Field mappings:', '')], - $this->formatMappings($metadata->fieldMappings) + [$this->formatField('Property mappings:', '')], + $this->formatPropertyMappings($metadata->getDeclaredPropertiesIterator()) ) ); @@ -193,6 +187,49 @@ function ($mappedEntity) use ($entityName) { return $entityManager->getClassMetadata(current($matches)); } + /** + * @param ComponentMetadata $metadata + * + * @return array + */ + private function formatParentClasses(ComponentMetadata $metadata) + { + $output = []; + $parentClass = $metadata; + + while (($parentClass = $parentClass->getParent()) !== null) { + /** @var ClassMetadata $parentClass */ + $attributes = []; + + if ($parentClass->isEmbeddedClass) { + $attributes[] = 'Embedded'; + } + + if ($parentClass->isMappedSuperclass) { + $attributes[] = 'Mapped superclass'; + } + + if ($parentClass->inheritanceType) { + $attributes[] = ucfirst(strtolower($parentClass->inheritanceType)); + } + + if ($parentClass->isReadOnly()) { + $attributes[] = 'Read-only'; + } + + if ($parentClass->isVersioned()) { + $attributes[] = 'Versioned'; + } + + $output[] = $this->formatField( + sprintf(' %s', $parentClass->getParent()), + ($parentClass->isRootEntity() ? '(Root) ' : '') . $this->formatValue($attributes) + ); + } + + return $output; + } + /** * Format the given value for console output * @@ -261,7 +298,7 @@ private function formatField($label, $value) * * @return array */ - private function formatMappings(array $propertyMappings) + private function formatAssociationMappings(array $propertyMappings) { $output = []; @@ -276,6 +313,67 @@ private function formatMappings(array $propertyMappings) return $output; } + + /** + * Format the property mappings + * + * @param iterable $propertyMappings + * + * @return array + */ + private function formatPropertyMappings(iterable $propertyMappings) + { + $output = []; + + foreach ($propertyMappings as $propertyName => $property) { + $output[] = $this->formatField(sprintf(' %s', $propertyName), ''); + + if ($property instanceof FieldMetadata) { + $output = array_merge($output, $this->formatColumn($property)); + } else if ($property instanceof AssociationMetadata) { + // @todo guilhermeblanco Fix me! We are trying to iterate through an AssociationMetadata instance + foreach ($property as $field => $value) { + $output[] = $this->formatField(sprintf(' %s', $field), $this->formatValue($value)); + } + + } + } + + return $output; + } + + /** + * @param ColumnMetadata|null $columnMetadata + * + * @return array|string + */ + private function formatColumn(ColumnMetadata $columnMetadata = null) + { + $output = []; + + if (null === $columnMetadata) { + $output[] = 'Null'; + + return $output; + } + + $output[] = $this->formatField(' type', $this->formatValue($columnMetadata->getTypeName())); + $output[] = $this->formatField(' tableName', $this->formatValue($columnMetadata->getTableName())); + $output[] = $this->formatField(' columnName', $this->formatValue($columnMetadata->getColumnName())); + $output[] = $this->formatField(' columnDefinition', $this->formatValue($columnMetadata->getColumnDefinition())); + $output[] = $this->formatField(' isPrimaryKey', $this->formatValue($columnMetadata->isPrimaryKey())); + $output[] = $this->formatField(' isNullable', $this->formatValue($columnMetadata->isNullable())); + $output[] = $this->formatField(' isUnique', $this->formatValue($columnMetadata->isUnique())); + $output[] = $this->formatField(' options', $this->formatValue($columnMetadata->getOptions())); + + if ($columnMetadata instanceof FieldMetadata) { + $output[] = $this->formatField(' Generator type', $this->formatValue($columnMetadata->getValueGenerator()->getType())); + $output[] = $this->formatField(' Generator definition', $this->formatValue($columnMetadata->getValueGenerator()->getDefinition())); + } + + return $output; + } + /** * Format the entity listeners * @@ -295,4 +393,28 @@ function ($entityListener) { ) ); } + + /** + * @param TableMetadata|null $tableMetadata + * + * @return array|string + */ + private function formatTable(TableMetadata $tableMetadata = null) + { + $output = []; + + if (null === $tableMetadata) { + $output[] = 'Null'; + + return $output; + } + + $output[] = $this->formatField(' schema', $this->formatValue($tableMetadata->getSchema())); + $output[] = $this->formatField(' name', $this->formatValue($tableMetadata->getName())); + $output[] = $this->formatField(' indexes', $this->formatValue($tableMetadata->getIndexes())); + $output[] = $this->formatField(' uniqueConstaints', $this->formatValue($tableMetadata->getUniqueConstraints())); + $output[] = $this->formatField(' options', $this->formatValue($tableMetadata->getOptions())); + + return $output; + } } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/RunDqlCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/RunDqlCommand.php index b246850a9c1..0e25444a38a 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/RunDqlCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/RunDqlCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command; diff --git a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/AbstractCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/AbstractCommand.php index dc7e7ec7e86..9ba97d05963 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/AbstractCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/AbstractCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command\SchemaTool; @@ -53,7 +38,7 @@ protected function execute(InputInterface $input, OutputInterface $output) { $emHelper = $this->getHelper('em'); - /* @var $em \Doctrine\ORM\EntityManager */ + /* @var $em \Doctrine\ORM\EntityManagerInterface */ $em = $emHelper->getEntityManager(); $metadatas = $em->getMetadataFactory()->getAllMetadata(); diff --git a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/CreateCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/CreateCommand.php index 73fbcbabbc7..862a5169107 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/CreateCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/CreateCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command\SchemaTool; diff --git a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/DropCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/DropCommand.php index e283470391e..58529130535 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/DropCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/DropCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command\SchemaTool; diff --git a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/UpdateCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/UpdateCommand.php index 6ba2e41f8e9..e168a41a23a 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/UpdateCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/UpdateCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command\SchemaTool; diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ValidateSchemaCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ValidateSchemaCommand.php index 57b16fc1c46..35efe9403ab 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ValidateSchemaCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ValidateSchemaCommand.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Command; diff --git a/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php b/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php index c6a265cc079..2023102b609 100644 --- a/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php +++ b/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php @@ -1,28 +1,13 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console; use Doctrine\DBAL\Tools\Console as DBALConsole; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper; -use Doctrine\ORM\Version; +use PackageVersions\Versions; use Symfony\Component\Console\Application; use Symfony\Component\Console\Helper\HelperSet; @@ -70,10 +55,11 @@ public static function run(HelperSet $helperSet, array $commands = []) : void * @param array $commands * * @return \Symfony\Component\Console\Application + * @throws \OutOfBoundsException */ public static function createApplication(HelperSet $helperSet, array $commands = []) : Application { - $cli = new Application('Doctrine Command Line Interface', Version::VERSION); + $cli = new Application('Doctrine Command Line Interface', Versions::getVersion('doctrine/orm')); $cli->setCatchExceptions(true); $cli->setHelperSet($helperSet); self::addCommands($cli); @@ -107,7 +93,6 @@ public static function addCommands(Application $cli) : void new Command\SchemaTool\UpdateCommand(), new Command\SchemaTool\DropCommand(), new Command\EnsureProductionSettingsCommand(), - new Command\ConvertDoctrine1SchemaCommand(), new Command\GenerateRepositoriesCommand(), new Command\GenerateEntitiesCommand(), new Command\GenerateProxiesCommand(), diff --git a/lib/Doctrine/ORM/Tools/Console/Helper/EntityManagerHelper.php b/lib/Doctrine/ORM/Tools/Console/Helper/EntityManagerHelper.php index 267304b984c..e7dc1610c37 100644 --- a/lib/Doctrine/ORM/Tools/Console/Helper/EntityManagerHelper.php +++ b/lib/Doctrine/ORM/Tools/Console/Helper/EntityManagerHelper.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console\Helper; @@ -39,7 +24,7 @@ class EntityManagerHelper extends Helper * * @var EntityManagerInterface */ - protected $_em; + protected $em; /** * Constructor. @@ -48,7 +33,7 @@ class EntityManagerHelper extends Helper */ public function __construct(EntityManagerInterface $em) { - $this->_em = $em; + $this->em = $em; } /** @@ -58,7 +43,7 @@ public function __construct(EntityManagerInterface $em) */ public function getEntityManager() { - return $this->_em; + return $this->em; } /** diff --git a/lib/Doctrine/ORM/Tools/Console/MetadataFilter.php b/lib/Doctrine/ORM/Tools/Console/MetadataFilter.php index 88357e35c94..420187025b0 100644 --- a/lib/Doctrine/ORM/Tools/Console/MetadataFilter.php +++ b/lib/Doctrine/ORM/Tools/Console/MetadataFilter.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Console; @@ -76,7 +61,7 @@ public function accept() $metadata = $it->current(); foreach ($this->filter as $filter) { - $pregResult = preg_match("/$filter/", $metadata->name); + $pregResult = preg_match("/$filter/", $metadata->getClassName()); if ($pregResult === false) { throw new \RuntimeException( diff --git a/lib/Doctrine/ORM/Tools/ConvertDoctrine1Schema.php b/lib/Doctrine/ORM/Tools/ConvertDoctrine1Schema.php deleted file mode 100644 index 408cb52d238..00000000000 --- a/lib/Doctrine/ORM/Tools/ConvertDoctrine1Schema.php +++ /dev/null @@ -1,344 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Tools; - -use Doctrine\ORM\Mapping\ClassMetadataInfo; -use Doctrine\Common\Util\Inflector; -use Doctrine\DBAL\Types\Type; -use Symfony\Component\Yaml\Yaml; - -/** - * Class to help with converting Doctrine 1 schema files to Doctrine 2 mapping files - * - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - */ -class ConvertDoctrine1Schema -{ - /** - * @var array - */ - private $from; - - /** - * @var array - */ - private $legacyTypeMap = [ - // TODO: This list may need to be updated - 'clob' => 'text', - 'timestamp' => 'datetime', - 'enum' => 'string' - ]; - - /** - * Constructor passes the directory or array of directories - * to convert the Doctrine 1 schema files from. - * - * @param array $from - * - * @author Jonathan Wage - */ - public function __construct($from) - { - $this->from = (array) $from; - } - - /** - * Gets an array of ClassMetadataInfo instances from the passed - * Doctrine 1 schema. - * - * @return array An array of ClassMetadataInfo instances - */ - public function getMetadata() - { - $schema = []; - foreach ($this->from as $path) { - if (is_dir($path)) { - $files = glob($path . '/*.yml'); - foreach ($files as $file) { - $schema = array_merge($schema, (array) Yaml::parse(file_get_contents($file))); - } - } else { - $schema = array_merge($schema, (array) Yaml::parse(file_get_contents($path))); - } - } - - $metadatas = []; - foreach ($schema as $className => $mappingInformation) { - $metadatas[] = $this->convertToClassMetadataInfo($className, $mappingInformation); - } - - return $metadatas; - } - - /** - * @param string $className - * @param array $mappingInformation - * - * @return \Doctrine\ORM\Mapping\ClassMetadataInfo - */ - private function convertToClassMetadataInfo($className, $mappingInformation) - { - $metadata = new ClassMetadataInfo($className); - - $this->convertTableName($className, $mappingInformation, $metadata); - $this->convertColumns($className, $mappingInformation, $metadata); - $this->convertIndexes($className, $mappingInformation, $metadata); - $this->convertRelations($className, $mappingInformation, $metadata); - - return $metadata; - } - - /** - * @param string $className - * @param array $model - * @param ClassMetadataInfo $metadata - * - * @return void - */ - private function convertTableName($className, array $model, ClassMetadataInfo $metadata) - { - if (isset($model['tableName']) && $model['tableName']) { - $e = explode('.', $model['tableName']); - - if (count($e) > 1) { - $metadata->table['schema'] = $e[0]; - $metadata->table['name'] = $e[1]; - } else { - $metadata->table['name'] = $e[0]; - } - } - } - - /** - * @param string $className - * @param array $model - * @param ClassMetadataInfo $metadata - * - * @return void - */ - private function convertColumns($className, array $model, ClassMetadataInfo $metadata) - { - $id = false; - - if (isset($model['columns']) && $model['columns']) { - foreach ($model['columns'] as $name => $column) { - $fieldMapping = $this->convertColumn($className, $name, $column, $metadata); - - if (isset($fieldMapping['id']) && $fieldMapping['id']) { - $id = true; - } - } - } - - if ( ! $id) { - $fieldMapping = [ - 'fieldName' => 'id', - 'columnName' => 'id', - 'type' => 'integer', - 'id' => true - ]; - $metadata->mapField($fieldMapping); - $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); - } - } - - /** - * @param string $className - * @param string $name - * @param string|array $column - * @param ClassMetadataInfo $metadata - * - * @return array - * - * @throws ToolsException - */ - private function convertColumn($className, $name, $column, ClassMetadataInfo $metadata) - { - if (is_string($column)) { - $string = $column; - $column = []; - $column['type'] = $string; - } - - if ( ! isset($column['name'])) { - $column['name'] = $name; - } - - // check if a column alias was used (column_name as field_name) - if (preg_match("/(\w+)\sas\s(\w+)/i", $column['name'], $matches)) { - $name = $matches[1]; - $column['name'] = $name; - $column['alias'] = $matches[2]; - } - - if (preg_match("/([a-zA-Z]+)\(([0-9]+)\)/", $column['type'], $matches)) { - $column['type'] = $matches[1]; - $column['length'] = $matches[2]; - } - - $column['type'] = strtolower($column['type']); - // check if legacy column type (1.x) needs to be mapped to a 2.0 one - if (isset($this->legacyTypeMap[$column['type']])) { - $column['type'] = $this->legacyTypeMap[$column['type']]; - } - - if ( ! Type::hasType($column['type'])) { - throw ToolsException::couldNotMapDoctrine1Type($column['type']); - } - - $fieldMapping = []; - - if (isset($column['primary'])) { - $fieldMapping['id'] = true; - } - - $fieldMapping['fieldName'] = isset($column['alias']) ? $column['alias'] : $name; - $fieldMapping['columnName'] = $column['name']; - $fieldMapping['type'] = $column['type']; - - if (isset($column['length'])) { - $fieldMapping['length'] = $column['length']; - } - - $allowed = ['precision', 'scale', 'unique', 'options', 'notnull', 'version']; - - foreach ($column as $key => $value) { - if (in_array($key, $allowed)) { - $fieldMapping[$key] = $value; - } - } - - $metadata->mapField($fieldMapping); - - if (isset($column['autoincrement'])) { - $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); - } elseif (isset($column['sequence'])) { - $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE); - - $definition = [ - 'sequenceName' => is_array($column['sequence']) ? $column['sequence']['name']:$column['sequence'] - ]; - - if (isset($column['sequence']['size'])) { - $definition['allocationSize'] = $column['sequence']['size']; - } - - if (isset($column['sequence']['value'])) { - $definition['initialValue'] = $column['sequence']['value']; - } - - $metadata->setSequenceGeneratorDefinition($definition); - } - - return $fieldMapping; - } - - /** - * @param string $className - * @param array $model - * @param ClassMetadataInfo $metadata - * - * @return void - */ - private function convertIndexes($className, array $model, ClassMetadataInfo $metadata) - { - if (empty($model['indexes'])) { - return; - } - - foreach ($model['indexes'] as $name => $index) { - $type = (isset($index['type']) && $index['type'] == 'unique') - ? 'uniqueConstraints' : 'indexes'; - - $metadata->table[$type][$name] = [ - 'columns' => $index['fields'] - ]; - } - } - - /** - * @param string $className - * @param array $model - * @param ClassMetadataInfo $metadata - * - * @return void - */ - private function convertRelations($className, array $model, ClassMetadataInfo $metadata) - { - if (empty($model['relations'])) { - return; - } - - foreach ($model['relations'] as $name => $relation) { - if ( ! isset($relation['alias'])) { - $relation['alias'] = $name; - } - if ( ! isset($relation['class'])) { - $relation['class'] = $name; - } - if ( ! isset($relation['local'])) { - $relation['local'] = Inflector::tableize($relation['class']); - } - if ( ! isset($relation['foreign'])) { - $relation['foreign'] = 'id'; - } - if ( ! isset($relation['foreignAlias'])) { - $relation['foreignAlias'] = $className; - } - - if (isset($relation['refClass'])) { - $type = 'many'; - $foreignType = 'many'; - $joinColumns = []; - } else { - $type = isset($relation['type']) ? $relation['type'] : 'one'; - $foreignType = isset($relation['foreignType']) ? $relation['foreignType'] : 'many'; - $joinColumns = [ - [ - 'name' => $relation['local'], - 'referencedColumnName' => $relation['foreign'], - 'onDelete' => isset($relation['onDelete']) ? $relation['onDelete'] : null, - ] - ]; - } - - if ($type == 'one' && $foreignType == 'one') { - $method = 'mapOneToOne'; - } elseif ($type == 'many' && $foreignType == 'many') { - $method = 'mapManyToMany'; - } else { - $method = 'mapOneToMany'; - } - - $associationMapping = []; - $associationMapping['fieldName'] = $relation['alias']; - $associationMapping['targetEntity'] = $relation['class']; - $associationMapping['mappedBy'] = $relation['foreignAlias']; - $associationMapping['joinColumns'] = $joinColumns; - - $metadata->$method($associationMapping); - } - } -} diff --git a/lib/Doctrine/ORM/Tools/DebugUnitOfWorkListener.php b/lib/Doctrine/ORM/Tools/DebugUnitOfWorkListener.php index 50113826183..5d2a989a961 100644 --- a/lib/Doctrine/ORM/Tools/DebugUnitOfWorkListener.php +++ b/lib/Doctrine/ORM/Tools/DebugUnitOfWorkListener.php @@ -1,28 +1,15 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools; use Doctrine\Common\Persistence\Proxy; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Event\OnFlushEventArgs; +use Doctrine\ORM\Mapping\AssociationMetadata; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; use Doctrine\ORM\PersistentCollection; use Doctrine\ORM\UnitOfWork; @@ -79,13 +66,15 @@ public function dumpIdentityMap(EntityManagerInterface $em) $identityMap = $uow->getIdentityMap(); $fh = fopen($this->file, 'xb+'); - if (count($identityMap) == 0) { + + if (count($identityMap) === 0) { fwrite($fh, "Flush Operation [".$this->context."] - Empty identity map.\n"); return; } fwrite($fh, "Flush Operation [".$this->context."] - Dumping identity map:\n"); + foreach ($identityMap as $className => $map) { fwrite($fh, "Class: ". $className . "\n"); @@ -95,25 +84,31 @@ public function dumpIdentityMap(EntityManagerInterface $em) $cm = $em->getClassMetadata($className); - foreach ($cm->associationMappings as $field => $assoc) { + foreach ($cm->getDeclaredPropertiesIterator() as $field => $association) { + if (! ($association instanceof AssociationMetadata)) { + continue; + } + fwrite($fh, " " . $field . " "); - $value = $cm->getFieldValue($entity, $field); - if ($assoc['type'] & ClassMetadata::TO_ONE) { - if ($value === null) { - fwrite($fh, " NULL\n"); - } else { - if ($value instanceof Proxy && !$value->__isInitialized()) { - fwrite($fh, "[PROXY] "); - } + $value = $association->getValue($entity); + + if ($value === null) { + fwrite($fh, " NULL\n"); + + continue; + } - fwrite($fh, $this->getIdString($value, $uow) . " " . spl_object_hash($value) . "\n"); + if ($association instanceof ToOneAssociationMetadata) { + if ($value instanceof Proxy && !$value->__isInitialized()) { + fwrite($fh, "[PROXY] "); } + + fwrite($fh, $this->getIdString($value, $uow) . " " . spl_object_hash($value) . "\n"); } else { $initialized = !($value instanceof PersistentCollection) || $value->isInitialized(); - if ($value === null) { - fwrite($fh, " NULL\n"); - } elseif ($initialized) { + + if ($initialized) { fwrite($fh, "[INITIALIZED] " . $this->getType($value). " " . count($value) . " elements\n"); foreach ($value as $obj) { @@ -121,6 +116,7 @@ public function dumpIdentityMap(EntityManagerInterface $em) } } else { fwrite($fh, "[PROXY] " . $this->getType($value) . " unknown element size\n"); + foreach ($value->unwrap() as $obj) { fwrite($fh, " " . $this->getIdString($obj, $uow) . " " . spl_object_hash($obj)."\n"); } diff --git a/lib/Doctrine/ORM/Tools/DisconnectedClassMetadataFactory.php b/lib/Doctrine/ORM/Tools/DisconnectedClassMetadataFactory.php index 7a3ec6f893c..efcfa9549f3 100644 --- a/lib/Doctrine/ORM/Tools/DisconnectedClassMetadataFactory.php +++ b/lib/Doctrine/ORM/Tools/DisconnectedClassMetadataFactory.php @@ -1,29 +1,15 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools; -use Doctrine\Common\Persistence\Mapping\StaticReflectionService; +use Doctrine\ORM\Reflection\ReflectionService; +use Doctrine\ORM\Reflection\StaticReflectionService; use Doctrine\ORM\Mapping\ClassMetadataFactory; /** - * The DisconnectedClassMetadataFactory is used to create ClassMetadataInfo objects + * The DisconnectedClassMetadataFactory is used to create ClassMetadata objects * that do not require the entity class actually exist. This allows us to * load some mapping information and use it to do things like generate code * from the mapping information. @@ -39,10 +25,14 @@ class DisconnectedClassMetadataFactory extends ClassMetadataFactory { /** - * @return \Doctrine\Common\Persistence\Mapping\StaticReflectionService + * @return ReflectionService */ - public function getReflectionService() + public function getReflectionService() : ReflectionService { - return new StaticReflectionService(); + if ($this->reflectionService === null) { + $this->reflectionService = new StaticReflectionService(); + } + + return $this->reflectionService; } } diff --git a/lib/Doctrine/ORM/Tools/EntityGenerator.php b/lib/Doctrine/ORM/Tools/EntityGenerator.php index fafa51f3daa..94050f25c01 100644 --- a/lib/Doctrine/ORM/Tools/EntityGenerator.php +++ b/lib/Doctrine/ORM/Tools/EntityGenerator.php @@ -1,31 +1,32 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools; +use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\ChangeTrackingPolicy; use Doctrine\Common\Collections\Collection; use Doctrine\Common\Util\Inflector; use Doctrine\DBAL\Types\Type; -use Doctrine\ORM\Mapping\ClassMetadataInfo; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\FetchMode; +use Doctrine\ORM\Mapping\FieldMetadata; +use Doctrine\ORM\Mapping\GeneratorType; +use Doctrine\ORM\Mapping\InheritanceType; +use Doctrine\ORM\Mapping\JoinColumnMetadata; +use Doctrine\ORM\Mapping\JoinTableMetadata; +use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ManyToOneAssociationMetadata; +use Doctrine\ORM\Mapping\OneToManyAssociationMetadata; +use Doctrine\ORM\Mapping\OneToOneAssociationMetadata; +use Doctrine\ORM\Mapping\Property; +use Doctrine\ORM\Mapping\ToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; /** - * Generic class used to generate PHP5 entity classes from ClassMetadataInfo instances. + * Generic class used to generate PHP5 entity classes from ClassMetadata instances. * * [php] * $classes = $em->getClassMetadataFactory()->getAllMetadata(); @@ -70,7 +71,7 @@ class EntityGenerator protected $extension = '.php'; /** - * Whether or not the current ClassMetadataInfo instance is new or old. + * Whether or not the current ClassMetadata instance is new or old. * * @var boolean */ @@ -169,44 +170,6 @@ class EntityGenerator Type::BOOLEAN => 'bool', ]; - /** - * Hash-map to handle generator types string. - * - * @var array - */ - protected static $generatorStrategyMap = [ - ClassMetadataInfo::GENERATOR_TYPE_AUTO => 'AUTO', - ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE => 'SEQUENCE', - ClassMetadataInfo::GENERATOR_TYPE_TABLE => 'TABLE', - ClassMetadataInfo::GENERATOR_TYPE_IDENTITY => 'IDENTITY', - ClassMetadataInfo::GENERATOR_TYPE_NONE => 'NONE', - ClassMetadataInfo::GENERATOR_TYPE_UUID => 'UUID', - ClassMetadataInfo::GENERATOR_TYPE_CUSTOM => 'CUSTOM' - ]; - - /** - * Hash-map to handle the change tracking policy string. - * - * @var array - */ - protected static $changeTrackingPolicyMap = [ - ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT => 'DEFERRED_IMPLICIT', - ClassMetadataInfo::CHANGETRACKING_DEFERRED_EXPLICIT => 'DEFERRED_EXPLICIT', - ClassMetadataInfo::CHANGETRACKING_NOTIFY => 'NOTIFY', - ]; - - /** - * Hash-map to handle the inheritance type string. - * - * @var array - */ - protected static $inheritanceTypeMap = [ - ClassMetadataInfo::INHERITANCE_TYPE_NONE => 'NONE', - ClassMetadataInfo::INHERITANCE_TYPE_JOINED => 'JOINED', - ClassMetadataInfo::INHERITANCE_TYPE_SINGLE_TABLE => 'SINGLE_TABLE', - ClassMetadataInfo::INHERITANCE_TYPE_TABLE_PER_CLASS => 'TABLE_PER_CLASS', - ]; - /** * @var string */ @@ -339,7 +302,7 @@ public function __construct() } /** - * Generates and writes entity classes for the given array of ClassMetadataInfo instances. + * Generates and writes entity classes for the given array of ClassMetadata instances. * * @param array $metadatas * @param string $outputDirectory @@ -354,18 +317,18 @@ public function generate(array $metadatas, $outputDirectory) } /** - * Generates and writes entity class to disk for the given ClassMetadataInfo instance. + * Generates and writes entity class to disk for the given ClassMetadata instance. * - * @param ClassMetadataInfo $metadata - * @param string $outputDirectory + * @param ClassMetadata $metadata + * @param string $outputDirectory * * @return void * * @throws \RuntimeException */ - public function writeEntityClass(ClassMetadataInfo $metadata, $outputDirectory) + public function writeEntityClass(ClassMetadata $metadata, $outputDirectory) { - $path = $outputDirectory . '/' . str_replace('\\', DIRECTORY_SEPARATOR, $metadata->name) . $this->extension; + $path = $outputDirectory . '/' . str_replace('\\', DIRECTORY_SEPARATOR, $metadata->getClassName()) . $this->extension; $dir = dirname($path); if ( ! is_dir($dir)) { @@ -377,7 +340,7 @@ public function writeEntityClass(ClassMetadataInfo $metadata, $outputDirectory) if ( ! $this->isNew) { $this->parseTokensInEntityFile(file_get_contents($path)); } else { - $this->staticReflection[$metadata->name] = ['properties' => [], 'methods' => []]; + $this->staticReflection[$metadata->getClassName()] = ['properties' => [], 'methods' => []]; } if ($this->backupExisting && file_exists($path)) { @@ -398,13 +361,13 @@ public function writeEntityClass(ClassMetadataInfo $metadata, $outputDirectory) } /** - * Generates a PHP5 Doctrine 2 entity class from the given ClassMetadataInfo instance. + * Generates a PHP5 Doctrine 2 entity class from the given ClassMetadata instance. * - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - public function generateEntityClass(ClassMetadataInfo $metadata) + public function generateEntityClass(ClassMetadata $metadata) { $placeHolders = [ '', @@ -428,14 +391,14 @@ public function generateEntityClass(ClassMetadataInfo $metadata) } /** - * Generates the updated code for the given ClassMetadataInfo and entity at path. + * Generates the updated code for the given ClassMetadata and entity at path. * - * @param ClassMetadataInfo $metadata - * @param string $path + * @param ClassMetadata $metadata + * @param string $path * * @return string */ - public function generateUpdatedEntityClass(ClassMetadataInfo $metadata, $path) + public function generateUpdatedEntityClass(ClassMetadata $metadata, $path) { $currentCode = file_get_contents($path); @@ -598,11 +561,11 @@ protected function getType($type) } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function generateEntityNamespace(ClassMetadataInfo $metadata) + protected function generateEntityNamespace(ClassMetadata $metadata) { if ($this->hasNamespace($metadata)) { return 'namespace ' . $this->getNamespace($metadata) .';'; @@ -612,50 +575,45 @@ protected function generateEntityNamespace(ClassMetadataInfo $metadata) protected function generateEntityUse() { if ($this->generateAnnotations) { - return "\n".'use Doctrine\ORM\Mapping as ORM;'."\n"; + return "\n".'use Doctrine\ORM\Annotation as ORM;'."\n"; } else { return ""; } } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function generateEntityClassName(ClassMetadataInfo $metadata) + protected function generateEntityClassName(ClassMetadata $metadata) { return 'class ' . $this->getClassName($metadata) . ($this->extendsClass() ? ' extends ' . $this->getClassToExtendName() : null); } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function generateEntityBody(ClassMetadataInfo $metadata) + protected function generateEntityBody(ClassMetadata $metadata) { - $fieldMappingProperties = $this->generateEntityFieldMappingProperties($metadata); + $properties = $this->generateEntityProperties($metadata); $embeddedProperties = $this->generateEntityEmbeddedProperties($metadata); - $associationMappingProperties = $this->generateEntityAssociationMappingProperties($metadata); $stubMethods = $this->generateEntityStubMethods ? $this->generateEntityStubMethods($metadata) : null; $lifecycleCallbackMethods = $this->generateEntityLifecycleCallbackMethods($metadata); $code = []; - if ($fieldMappingProperties) { - $code[] = $fieldMappingProperties; + if ($properties) { + $code[] = $properties; } if ($embeddedProperties) { $code[] = $embeddedProperties; } - if ($associationMappingProperties) { - $code[] = $associationMappingProperties; - } - $code[] = $this->generateEntityConstructor($metadata); if ($stubMethods) { @@ -670,11 +628,11 @@ protected function generateEntityBody(ClassMetadataInfo $metadata) } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function generateEntityConstructor(ClassMetadataInfo $metadata) + protected function generateEntityConstructor(ClassMetadata $metadata) { if ($this->hasMethod('__construct', $metadata)) { return ''; @@ -686,9 +644,9 @@ protected function generateEntityConstructor(ClassMetadataInfo $metadata) $collections = []; - foreach ($metadata->associationMappings as $mapping) { - if ($mapping['type'] & ClassMetadataInfo::TO_MANY) { - $collections[] = '$this->'.$mapping['fieldName'].' = new \Doctrine\Common\Collections\ArrayCollection();'; + foreach ($metadata->getDeclaredPropertiesIterator() as $association) { + if ($association instanceof ToManyAssociationMetadata) { + $collections[] = sprintf('$this->%s = new \%s();', $association->getName(), ArrayCollection::class); } } @@ -700,11 +658,11 @@ protected function generateEntityConstructor(ClassMetadataInfo $metadata) } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - private function generateEmbeddableConstructor(ClassMetadataInfo $metadata) + private function generateEmbeddableConstructor(ClassMetadata $metadata) { $paramTypes = []; $paramVariables = []; @@ -715,19 +673,19 @@ private function generateEmbeddableConstructor(ClassMetadataInfo $metadata) $requiredFields = []; $optionalFields = []; - foreach ($metadata->fieldMappings as $fieldMapping) { - if (empty($fieldMapping['nullable'])) { - $requiredFields[] = $fieldMapping; + foreach ($metadata->getDeclaredPropertiesIterator() as $property) { + if (! $property->isNullable()) { + $requiredFields[] = $property; continue; } - $optionalFields[] = $fieldMapping; + $optionalFields[] = $property; } - $fieldMappings = array_merge($requiredFields, $optionalFields); + $mappings = array_merge($requiredFields, $optionalFields); - foreach ($metadata->embeddedClasses as $fieldName => $embeddedClass) { + /*foreach ($metadata->embeddedClasses as $fieldName => $embeddedClass) { $paramType = '\\' . ltrim($embeddedClass['class'], '\\'); $paramVariable = '$' . $fieldName; @@ -735,30 +693,32 @@ private function generateEmbeddableConstructor(ClassMetadataInfo $metadata) $paramVariables[] = $paramVariable; $params[] = $paramType . ' ' . $paramVariable; $fields[] = '$this->' . $fieldName . ' = ' . $paramVariable . ';'; - } + }*/ - foreach ($fieldMappings as $fieldMapping) { - if (isset($fieldMapping['declaredField']) && - isset($metadata->embeddedClasses[$fieldMapping['declaredField']]) - ) { + foreach ($mappings as $property) { + /*if (isset($fieldMapping['declaredField']) && isset($metadata->embeddedClasses[$fieldMapping['declaredField']])) { continue; - } + }*/ - $paramTypes[] = $this->getType($fieldMapping['type']) . (!empty($fieldMapping['nullable']) ? '|null' : ''); - $param = '$' . $fieldMapping['fieldName']; + $fieldName = $property->getName(); + $fieldType = $property->getTypeName(); + $mappedType = $this->getType($fieldType); + $param = '$' . $fieldName; + + $paramTypes[] = $mappedType . ($property->isNullable() ? '|null' : ''); $paramVariables[] = $param; - if ($fieldMapping['type'] === 'datetime') { - $param = $this->getType($fieldMapping['type']) . ' ' . $param; + if ($fieldType === 'datetime') { + $param = $mappedType . ' ' . $param; } - if (!empty($fieldMapping['nullable'])) { + if ($property->isNullable()) { $param .= ' = null'; } $params[] = $param; - $fields[] = '$this->' . $fieldMapping['fieldName'] . ' = $' . $fieldMapping['fieldName'] . ';'; + $fields[] = '$this->' . $fieldName . ' = $' . $fieldName . ';'; } $maxParamTypeLength = max(array_map('strlen', $paramTypes)); @@ -849,16 +809,17 @@ protected function parseTokensInEntityFile($src) } /** - * @param string $property - * @param ClassMetadataInfo $metadata + * @param string $property + * @param ClassMetadata $metadata * * @return bool */ - protected function hasProperty($property, ClassMetadataInfo $metadata) + protected function hasProperty($property, ClassMetadata $metadata) { - if ($this->extendsClass() || (!$this->isNew && class_exists($metadata->name))) { + if ($this->extendsClass() || (!$this->isNew && class_exists($metadata->getClassName()))) { // don't generate property if its already on the base class. - $reflClass = new \ReflectionClass($this->getClassToExtend() ?: $metadata->name); + $reflClass = new \ReflectionClass($this->getClassToExtend() ?: $metadata->getClassName()); + if ($reflClass->hasProperty($property)) { return true; } @@ -872,22 +833,22 @@ protected function hasProperty($property, ClassMetadataInfo $metadata) } return ( - isset($this->staticReflection[$metadata->name]) && - in_array($property, $this->staticReflection[$metadata->name]['properties'], true) + isset($this->staticReflection[$metadata->getClassName()]) && + in_array($property, $this->staticReflection[$metadata->getClassName()]['properties'], true) ); } /** - * @param string $method - * @param ClassMetadataInfo $metadata + * @param string $method + * @param ClassMetadata $metadata * * @return bool */ - protected function hasMethod($method, ClassMetadataInfo $metadata) + protected function hasMethod($method, ClassMetadata $metadata) { - if ($this->extendsClass() || (!$this->isNew && class_exists($metadata->name))) { + if ($this->extendsClass() || (!$this->isNew && class_exists($metadata->getClassName()))) { // don't generate method if its already on the base class. - $reflClass = new \ReflectionClass($this->getClassToExtend() ?: $metadata->name); + $reflClass = new \ReflectionClass($this->getClassToExtend() ?: $metadata->getClassName()); if ($reflClass->hasMethod($method)) { return true; @@ -902,27 +863,24 @@ protected function hasMethod($method, ClassMetadataInfo $metadata) } return ( - isset($this->staticReflection[$metadata->name]) && - in_array(strtolower($method), $this->staticReflection[$metadata->name]['methods'], true) + isset($this->staticReflection[$metadata->getClassName()]) && + in_array(strtolower($method), $this->staticReflection[$metadata->getClassName()]['methods'], true) ); } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return array */ - protected function getTraits(ClassMetadataInfo $metadata) + protected function getTraits(ClassMetadata $metadata) { - if (! ($metadata->reflClass !== null || class_exists($metadata->name))) { + if (! ($metadata->getReflectionClass() !== null || class_exists($metadata->getClassName()))) { return []; } - $reflClass = $metadata->reflClass === null - ? new \ReflectionClass($metadata->name) - : $metadata->reflClass; - - $traits = []; + $reflClass = $metadata->getReflectionClass() ?? new \ReflectionClass($metadata->getClassName()); + $traits = []; while ($reflClass !== false) { $traits = array_merge($traits, $reflClass->getTraits()); @@ -934,13 +892,13 @@ protected function getTraits(ClassMetadataInfo $metadata) } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return bool */ - protected function hasNamespace(ClassMetadataInfo $metadata) + protected function hasNamespace(ClassMetadata $metadata) { - return (bool) strpos($metadata->name, '\\'); + return (bool) strpos($metadata->getClassName(), '\\'); } /** @@ -970,32 +928,32 @@ protected function getClassToExtendName() } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function getClassName(ClassMetadataInfo $metadata) + protected function getClassName(ClassMetadata $metadata) { - return ($pos = strrpos($metadata->name, '\\')) - ? substr($metadata->name, $pos + 1, strlen($metadata->name)) : $metadata->name; + return ($pos = strrpos($metadata->getClassName(), '\\')) + ? substr($metadata->getClassName(), $pos + 1, strlen($metadata->getClassName())) : $metadata->getClassName(); } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function getNamespace(ClassMetadataInfo $metadata) + protected function getNamespace(ClassMetadata $metadata) { - return substr($metadata->name, 0, strrpos($metadata->name, '\\')); + return substr($metadata->getClassName(), 0, strrpos($metadata->getClassName(), '\\')); } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function generateEntityDocBlock(ClassMetadataInfo $metadata) + protected function generateEntityDocBlock(ClassMetadata $metadata) { $lines = []; $lines[] = '/**'; @@ -1029,11 +987,11 @@ protected function generateEntityDocBlock(ClassMetadataInfo $metadata) } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function generateEntityAnnotation(ClassMetadataInfo $metadata) + protected function generateEntityAnnotation(ClassMetadata $metadata) { $prefix = '@' . $this->annotationsPrefix; @@ -1041,45 +999,45 @@ protected function generateEntityAnnotation(ClassMetadataInfo $metadata) return $prefix . 'Embeddable'; } - $customRepository = $metadata->customRepositoryClassName - ? '(repositoryClass="' . $metadata->customRepositoryClassName . '")' + $customRepository = $metadata->getCustomRepositoryClassName() + ? '(repositoryClass="' . $metadata->getCustomRepositoryClassName() . '")' : ''; return $prefix . ($metadata->isMappedSuperclass ? 'MappedSuperclass' : 'Entity') . $customRepository; } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function generateTableAnnotation(ClassMetadataInfo $metadata) + protected function generateTableAnnotation(ClassMetadata $metadata) { - if ($metadata->isEmbeddedClass) { + if ($metadata->isEmbeddedClass || $metadata->isMappedSuperclass) { return ''; } $table = []; - if (isset($metadata->table['schema'])) { - $table[] = 'schema="' . $metadata->table['schema'] . '"'; + if ($metadata->table->getSchema()) { + $table[] = 'schema="' . $metadata->table->getSchema() . '"'; } - if (isset($metadata->table['name'])) { - $table[] = 'name="' . $metadata->table['name'] . '"'; + if ($metadata->table->getName()) { + $table[] = 'name="' . $metadata->table->getName() . '"'; } - if (isset($metadata->table['options']) && $metadata->table['options']) { - $table[] = 'options={' . $this->exportTableOptions((array) $metadata->table['options']) . '}'; + if ($metadata->table->getOptions()) { + $table[] = 'options={' . $this->exportTableOptions($metadata->table->getOptions()) . '}'; } - if (isset($metadata->table['uniqueConstraints']) && $metadata->table['uniqueConstraints']) { - $constraints = $this->generateTableConstraints('UniqueConstraint', $metadata->table['uniqueConstraints']); + if ($metadata->table->getUniqueConstraints()) { + $constraints = $this->generateTableConstraints('UniqueConstraint', $metadata->table->getUniqueConstraints()); $table[] = 'uniqueConstraints={' . $constraints . '}'; } - if (isset($metadata->table['indexes']) && $metadata->table['indexes']) { - $constraints = $this->generateTableConstraints('Index', $metadata->table['indexes']); + if ($metadata->table->getIndexes()) { + $constraints = $this->generateTableConstraints('Index', $metadata->table->getIndexes()); $table[] = 'indexes={' . $constraints . '}'; } @@ -1095,11 +1053,14 @@ protected function generateTableAnnotation(ClassMetadataInfo $metadata) protected function generateTableConstraints($constraintName, array $constraints) { $annotations = []; + foreach ($constraints as $name => $constraint) { $columns = []; + foreach ($constraint['columns'] as $column) { $columns[] = '"' . $column . '"'; } + $annotations[] = '@' . $this->annotationsPrefix . $constraintName . '(name="' . $name . '", columns={' . implode(', ', $columns) . '})'; } @@ -1107,42 +1068,46 @@ protected function generateTableConstraints($constraintName, array $constraints) } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function generateInheritanceAnnotation(ClassMetadataInfo $metadata) + protected function generateInheritanceAnnotation(ClassMetadata $metadata) { - if ($metadata->inheritanceType != ClassMetadataInfo::INHERITANCE_TYPE_NONE) { + if ($metadata->inheritanceType !== InheritanceType::NONE) { return '@' . $this->annotationsPrefix . 'InheritanceType("'.$this->getInheritanceTypeString($metadata->inheritanceType).'")'; } } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function generateDiscriminatorColumnAnnotation(ClassMetadataInfo $metadata) + protected function generateDiscriminatorColumnAnnotation(ClassMetadata $metadata) { - if ($metadata->inheritanceType != ClassMetadataInfo::INHERITANCE_TYPE_NONE) { + if ($metadata->inheritanceType !== InheritanceType::NONE) { $discrColumn = $metadata->discriminatorColumn; - $columnDefinition = 'name="' . $discrColumn['name'] - . '", type="' . $discrColumn['type'] - . '", length=' . $discrColumn['length']; + + $columnDefinition = sprintf( + 'name="%s", type="%s", length=%d', + $discrColumn->getColumnName(), + $discrColumn->getTypeName(), + $discrColumn->getLength() + ); return '@' . $this->annotationsPrefix . 'DiscriminatorColumn(' . $columnDefinition . ')'; } } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function generateDiscriminatorMapAnnotation(ClassMetadataInfo $metadata) + protected function generateDiscriminatorMapAnnotation(ClassMetadata $metadata) { - if ($metadata->inheritanceType != ClassMetadataInfo::INHERITANCE_TYPE_NONE) { + if ($metadata->inheritanceType !== InheritanceType::NONE) { $inheritanceClassMap = []; foreach ($metadata->discriminatorMap as $type => $class) { @@ -1154,38 +1119,15 @@ protected function generateDiscriminatorMapAnnotation(ClassMetadataInfo $metadat } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function generateEntityStubMethods(ClassMetadataInfo $metadata) + protected function generateEntityStubMethods(ClassMetadata $metadata) { $methods = []; - foreach ($metadata->fieldMappings as $fieldMapping) { - if (isset($fieldMapping['declaredField']) && - isset($metadata->embeddedClasses[$fieldMapping['declaredField']]) - ) { - continue; - } - - $nullableField = $this->nullableFieldExpression($fieldMapping); - - if (( ! isset($fieldMapping['id']) || - ! $fieldMapping['id'] || - $metadata->generatorType == ClassMetadataInfo::GENERATOR_TYPE_NONE - ) && (! $metadata->isEmbeddedClass || ! $this->embeddablesImmutable) - && $code = $this->generateEntityStubMethod($metadata, 'set', $fieldMapping['fieldName'], $fieldMapping['type'], $nullableField) - ) { - $methods[] = $code; - } - - if ($code = $this->generateEntityStubMethod($metadata, 'get', $fieldMapping['fieldName'], $fieldMapping['type'], $nullableField)) { - $methods[] = $code; - } - } - - foreach ($metadata->embeddedClasses as $fieldName => $embeddedClass) { + /*foreach ($metadata->embeddedClasses as $fieldName => $embeddedClass) { if (isset($embeddedClass['declaredField'])) { continue; } @@ -1199,25 +1141,41 @@ protected function generateEntityStubMethods(ClassMetadataInfo $metadata) if ($code = $this->generateEntityStubMethod($metadata, 'get', $fieldName, $embeddedClass['class'])) { $methods[] = $code; } - } + }*/ + + foreach ($metadata->getDeclaredPropertiesIterator() as $fieldName => $property) { + if ($property instanceof FieldMetadata) { + $nullable = $property->isNullable() ? 'null' : null; + + if ($code = $this->generateEntityStubMethod($metadata, 'get', $fieldName, $property->getTypeName(), $nullable)) { + $methods[] = $code; + } - foreach ($metadata->associationMappings as $associationMapping) { - if ($associationMapping['type'] & ClassMetadataInfo::TO_ONE) { - $nullable = $this->isAssociationIsNullable($associationMapping) ? 'null' : null; - if ($code = $this->generateEntityStubMethod($metadata, 'set', $associationMapping['fieldName'], $associationMapping['targetEntity'], $nullable)) { + if (( ! $property->isPrimaryKey() || ! $property->hasValueGenerator()) && + ( ! $metadata->isEmbeddedClass || ! $this->embeddablesImmutable) && + $code = $this->generateEntityStubMethod($metadata, 'set', $fieldName, $property->getTypeName(), $nullable)) { $methods[] = $code; } - if ($code = $this->generateEntityStubMethod($metadata, 'get', $associationMapping['fieldName'], $associationMapping['targetEntity'], $nullable)) { + } else if ($property instanceof ToOneAssociationMetadata) { + $nullable = $this->isAssociationIsNullable($property) ? 'null' : null; + + if ($code = $this->generateEntityStubMethod($metadata, 'set', $fieldName, $property->getTargetEntity(), $nullable)) { + $methods[] = $code; + } + + if ($code = $this->generateEntityStubMethod($metadata, 'get', $fieldName, $property->getTargetEntity(), $nullable)) { $methods[] = $code; } - } elseif ($associationMapping['type'] & ClassMetadataInfo::TO_MANY) { - if ($code = $this->generateEntityStubMethod($metadata, 'add', $associationMapping['fieldName'], $associationMapping['targetEntity'])) { + } else if ($property instanceof ToManyAssociationMetadata) { + if ($code = $this->generateEntityStubMethod($metadata, 'add', $fieldName, $property->getTargetEntity())) { $methods[] = $code; } - if ($code = $this->generateEntityStubMethod($metadata, 'remove', $associationMapping['fieldName'], $associationMapping['targetEntity'])) { + + if ($code = $this->generateEntityStubMethod($metadata, 'remove', $fieldName, $property->getTargetEntity())) { $methods[] = $code; } - if ($code = $this->generateEntityStubMethod($metadata, 'get', $associationMapping['fieldName'], Collection::class)) { + + if ($code = $this->generateEntityStubMethod($metadata, 'get', $fieldName, Collection::class)) { $methods[] = $code; } } @@ -1227,25 +1185,23 @@ protected function generateEntityStubMethods(ClassMetadataInfo $metadata) } /** - * @param array $associationMapping + * @param AssociationMetadata $association * * @return bool */ - protected function isAssociationIsNullable(array $associationMapping) + protected function isAssociationIsNullable(AssociationMetadata $association) { - if (isset($associationMapping['id']) && $associationMapping['id']) { + if ($association->isPrimaryKey()) { return false; } - if (isset($associationMapping['joinColumns'])) { - $joinColumns = $associationMapping['joinColumns']; - } else { - //@todo there is no way to retrieve targetEntity metadata - $joinColumns = []; - } + $joinColumns = $association instanceof ToOneAssociationMetadata + ? $association->getJoinColumns() + : [] + ; foreach ($joinColumns as $joinColumn) { - if (isset($joinColumn['nullable']) && !$joinColumn['nullable']) { + if (! $joinColumn->isNullable()) { return false; } } @@ -1254,11 +1210,11 @@ protected function isAssociationIsNullable(array $associationMapping) } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function generateEntityLifecycleCallbackMethods(ClassMetadataInfo $metadata) + protected function generateEntityLifecycleCallbackMethods(ClassMetadata $metadata) { if (empty($metadata->lifecycleCallbacks)) { return ''; @@ -1276,89 +1232,77 @@ protected function generateEntityLifecycleCallbackMethods(ClassMetadataInfo $met } /** - * @param ClassMetadataInfo $metadata - * - * @return string - */ - protected function generateEntityAssociationMappingProperties(ClassMetadataInfo $metadata) - { - $lines = []; - - foreach ($metadata->associationMappings as $associationMapping) { - if ($this->hasProperty($associationMapping['fieldName'], $metadata)) { - continue; - } - - $lines[] = $this->generateAssociationMappingPropertyDocBlock($associationMapping, $metadata); - $lines[] = $this->spaces . $this->fieldVisibility . ' $' . $associationMapping['fieldName'] - . ($associationMapping['type'] == 'manyToMany' ? ' = array()' : null) . ";\n"; - } - - return implode("\n", $lines); - } - - /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function generateEntityFieldMappingProperties(ClassMetadataInfo $metadata) + protected function generateEntityProperties(ClassMetadata $metadata) { $lines = []; - foreach ($metadata->fieldMappings as $fieldMapping) { - if ($this->hasProperty($fieldMapping['fieldName'], $metadata) || - $metadata->isInheritedField($fieldMapping['fieldName']) || + foreach ($metadata->getDeclaredPropertiesIterator() as $fieldName => $property) { + if ($this->hasProperty($fieldName, $metadata) || + $metadata->isInheritedProperty($fieldName) /*|| ( isset($fieldMapping['declaredField']) && isset($metadata->embeddedClasses[$fieldMapping['declaredField']]) - ) + )*/ ) { continue; } - $lines[] = $this->generateFieldMappingPropertyDocBlock($fieldMapping, $metadata); - $lines[] = $this->spaces . $this->fieldVisibility . ' $' . $fieldMapping['fieldName'] - . (isset($fieldMapping['options']['default']) ? ' = ' . var_export($fieldMapping['options']['default'], true) : null) . ";\n"; + if ($property instanceof FieldMetadata) { + $options = $property->getOptions(); + $defaultValue = isset($options['default']) ? ' = ' . var_export($options['default'], true) : null; + + $lines[] = $this->generateFieldMappingPropertyDocBlock($property, $metadata); + } else { + $defaultValue = ($property instanceof ManyToManyAssociationMetadata ? ' = array()' : null); + + $lines[] = $this->generateAssociationMappingPropertyDocBlock($property, $metadata); + } + + $lines[] = $this->spaces . $this->fieldVisibility . ' $' . $fieldName . $defaultValue . ";\n"; } return implode("\n", $lines); } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function generateEntityEmbeddedProperties(ClassMetadataInfo $metadata) + protected function generateEntityEmbeddedProperties(ClassMetadata $metadata) { $lines = []; - foreach ($metadata->embeddedClasses as $fieldName => $embeddedClass) { + /*foreach ($metadata->embeddedClasses as $fieldName => $embeddedClass) { if (isset($embeddedClass['declaredField']) || $this->hasProperty($fieldName, $metadata)) { continue; } $lines[] = $this->generateEmbeddedPropertyDocBlock($embeddedClass); $lines[] = $this->spaces . $this->fieldVisibility . ' $' . $fieldName . ";\n"; - } + }*/ return implode("\n", $lines); } /** - * @param ClassMetadataInfo $metadata - * @param string $type - * @param string $fieldName - * @param string|null $typeHint - * @param string|null $defaultValue + * @param ClassMetadata $metadata + * @param string $type + * @param string $fieldName + * @param string|null $typeHint + * @param string|null $defaultValue * * @return string */ - protected function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, $fieldName, $typeHint = null, $defaultValue = null) + protected function generateEntityStubMethod(ClassMetadata $metadata, $type, $fieldName, $typeHint = null, $defaultValue = null) { $methodName = $type . Inflector::classify($fieldName); $variableName = Inflector::camelize($fieldName); + if (in_array($type, ["add", "remove"])) { $methodName = Inflector::singularize($methodName); $variableName = Inflector::singularize($variableName); @@ -1367,7 +1311,7 @@ protected function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, if ($this->hasMethod($methodName, $metadata)) { return ''; } - $this->staticReflection[$metadata->name]['methods'][] = strtolower($methodName); + $this->staticReflection[$metadata->getClassName()]['methods'][] = strtolower($methodName); $var = sprintf('%sMethodTemplate', $type); $template = static::$$var; @@ -1402,18 +1346,18 @@ protected function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, } /** - * @param string $name - * @param string $methodName - * @param ClassMetadataInfo $metadata + * @param string $name + * @param string $methodName + * @param ClassMetadata $metadata * * @return string */ - protected function generateLifecycleCallbackMethod($name, $methodName, ClassMetadataInfo $metadata) + protected function generateLifecycleCallbackMethod($name, $methodName, ClassMetadata $metadata) { if ($this->hasMethod($methodName, $metadata)) { return ''; } - $this->staticReflection[$metadata->name]['methods'][] = $methodName; + $this->staticReflection[$metadata->getClassName()]['methods'][] = $methodName; $replacements = [ '' => $this->annotationsPrefix . ucfirst($name), @@ -1430,106 +1374,185 @@ protected function generateLifecycleCallbackMethod($name, $methodName, ClassMeta } /** - * @param array $joinColumn + * @param Property $metadata * * @return string */ - protected function generateJoinColumnAnnotation(array $joinColumn) + protected function generateIdentifierAnnotation(Property $metadata) + { + $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'Id'; + + if ($metadata instanceof FieldMetadata) { + if ($generatorType = $this->getIdGeneratorTypeString($metadata->getValueGenerator()->getType())) { + $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'GeneratedValue(strategy="' . $generatorType . '")'; + } + + if ($metadata->getValueGenerator()->getType()) { + $generator = []; + + if (isset($metadata->getValueGenerator()->getDefinition()['sequenceName'])) { + $generator[] = 'sequenceName="' . $metadata->getValueGenerator()->getDefinition()['sequenceName'] . '"'; + } + + if (isset($metadata->getValueGenerator()->getDefinition()['allocationSize'])) { + $generator[] = 'allocationSize=' . $metadata->getValueGenerator()->getDefinition()['allocationSize']; + } + + $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'SequenceGenerator(' . implode(', ', $generator) . ')'; + } + } + + return implode(PHP_EOL, $lines); + } + + /** + * @param JoinTableMetadata $joinTable + * + * @return string + */ + protected function generateJoinTableAnnotation(JoinTableMetadata $joinTable) + { + $lines = []; + $joinTableAnnot = []; + $joinTableAnnot[] = 'name="' . $joinTable->getName() . '"'; + + if (! empty($joinTable->getSchema())) { + $joinTableAnnot[] = 'schema="' . $joinTable->getSchema() . '"'; + } + + $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'JoinTable(' . implode(', ', $joinTableAnnot) . ','; + $lines[] = $this->spaces . ' * joinColumns={'; + + $joinColumnsLines = []; + + foreach ($joinTable->getJoinColumns() as $joinColumn) { + $joinColumnsLines[] = $this->spaces . ' * ' . $this->generateJoinColumnAnnotation($joinColumn); + } + + $lines[] = implode(",". PHP_EOL, $joinColumnsLines); + $lines[] = $this->spaces . ' * },'; + $lines[] = $this->spaces . ' * inverseJoinColumns={'; + + $inverseJoinColumnsLines = []; + + foreach ($joinTable->getInverseJoinColumns() as $joinColumn) { + $inverseJoinColumnsLines[] = $this->spaces . ' * ' . $this->generateJoinColumnAnnotation($joinColumn); + } + + $lines[] = implode(",". PHP_EOL, $inverseJoinColumnsLines); + $lines[] = $this->spaces . ' * }'; + $lines[] = $this->spaces . ' * )'; + + return implode(PHP_EOL, $lines); + } + + /** + * @param JoinColumnMetadata $joinColumn + * + * @return string + */ + protected function generateJoinColumnAnnotation(JoinColumnMetadata $joinColumn) { $joinColumnAnnot = []; - if (isset($joinColumn['name'])) { - $joinColumnAnnot[] = 'name="' . $joinColumn['name'] . '"'; + $joinColumnAnnot[] = 'name="' . $joinColumn->getColumnName() . '"'; + $joinColumnAnnot[] = 'referencedColumnName="' . $joinColumn->getReferencedColumnName() . '"'; + + if ($joinColumn->isUnique()) { + $joinColumnAnnot[] = 'unique=true'; } - if (isset($joinColumn['referencedColumnName'])) { - $joinColumnAnnot[] = 'referencedColumnName="' . $joinColumn['referencedColumnName'] . '"'; + if (!$joinColumn->isNullable()) { + $joinColumnAnnot[] = 'nullable=false'; } - if (isset($joinColumn['unique']) && $joinColumn['unique']) { - $joinColumnAnnot[] = 'unique=' . ($joinColumn['unique'] ? 'true' : 'false'); + if (!empty($joinColumn->getOnDelete())) { + $joinColumnAnnot[] = 'onDelete="' . $joinColumn->getOnDelete() . '"'; } - if (isset($joinColumn['nullable'])) { - $joinColumnAnnot[] = 'nullable=' . ($joinColumn['nullable'] ? 'true' : 'false'); + if ($joinColumn->getColumnDefinition()) { + $joinColumnAnnot[] = 'columnDefinition="' . $joinColumn->getColumnDefinition() . '"'; } - if (isset($joinColumn['onDelete'])) { - $joinColumnAnnot[] = 'onDelete="' . ($joinColumn['onDelete'] . '"'); + $options = []; + + if ($joinColumn->getOptions()) { + foreach ($joinColumn->getOptions() as $key => $value) { + $options[] = sprintf('"%s"=%s', $key, str_replace("'", '"', var_export($value, true))); + } } - if (isset($joinColumn['columnDefinition'])) { - $joinColumnAnnot[] = 'columnDefinition="' . $joinColumn['columnDefinition'] . '"'; + if ($options) { + $joinColumnAnnot[] = 'options={'.implode(',', $options).'}'; } return '@' . $this->annotationsPrefix . 'JoinColumn(' . implode(', ', $joinColumnAnnot) . ')'; } /** - * @param array $associationMapping - * @param ClassMetadataInfo $metadata + * @param AssociationMetadata $association + * @param ClassMetadata $metadata * * @return string */ - protected function generateAssociationMappingPropertyDocBlock(array $associationMapping, ClassMetadataInfo $metadata) + protected function generateAssociationMappingPropertyDocBlock(AssociationMetadata $association, ClassMetadata $metadata) { $lines = []; $lines[] = $this->spaces . '/**'; - if ($associationMapping['type'] & ClassMetadataInfo::TO_MANY) { + if ($association instanceof ToManyAssociationMetadata) { $lines[] = $this->spaces . ' * @var \Doctrine\Common\Collections\Collection'; } else { - $lines[] = $this->spaces . ' * @var \\' . ltrim($associationMapping['targetEntity'], '\\'); + $lines[] = $this->spaces . ' * @var \\' . ltrim($association->getTargetEntity(), '\\'); } if ($this->generateAnnotations) { $lines[] = $this->spaces . ' *'; - if (isset($associationMapping['id']) && $associationMapping['id']) { - $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'Id'; - - if ($generatorType = $this->getIdGeneratorTypeString($metadata->generatorType)) { - $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'GeneratedValue(strategy="' . $generatorType . '")'; - } + if ($association->isPrimaryKey()) { + $lines[] = $this->generateIdentifierAnnotation($association); } $type = null; - switch ($associationMapping['type']) { - case ClassMetadataInfo::ONE_TO_ONE: - $type = 'OneToOne'; - break; - case ClassMetadataInfo::MANY_TO_ONE: - $type = 'ManyToOne'; - break; - case ClassMetadataInfo::ONE_TO_MANY: - $type = 'OneToMany'; - break; - case ClassMetadataInfo::MANY_TO_MANY: - $type = 'ManyToMany'; - break; + + if ($association instanceof OneToOneAssociationMetadata) { + $type = 'OneToOne'; + } else if ($association instanceof ManyToOneAssociationMetadata) { + $type = 'ManyToOne'; + } else if ($association instanceof OneToManyAssociationMetadata) { + $type = 'OneToMany'; + } else if ($association instanceof ManyToManyAssociationMetadata) { + $type = 'ManyToMany'; } + $typeOptions = []; - if (isset($associationMapping['targetEntity'])) { - $typeOptions[] = 'targetEntity="' . $associationMapping['targetEntity'] . '"'; + $typeOptions[] = 'targetEntity="' . $association->getTargetEntity() . '"'; + + if ($association->getMappedBy()) { + $typeOptions[] = 'mappedBy="' . $association->getMappedBy() . '"'; } - if (isset($associationMapping['inversedBy'])) { - $typeOptions[] = 'inversedBy="' . $associationMapping['inversedBy'] . '"'; + if ($association->getInversedBy()) { + $typeOptions[] = 'inversedBy="' . $association->getInversedBy() . '"'; } - if (isset($associationMapping['mappedBy'])) { - $typeOptions[] = 'mappedBy="' . $associationMapping['mappedBy'] . '"'; + if ($association instanceof ToManyAssociationMetadata && $association->getIndexedBy()) { + $typeOptions[] = 'indexBy="' . $association->getIndexedBy() . '"'; } - if ($associationMapping['cascade']) { + if ($association->isOrphanRemoval()) { + $typeOptions[] = 'orphanRemoval=true'; + } + + if ($association->getCascade()) { $cascades = []; - if ($associationMapping['isCascadePersist']) $cascades[] = '"persist"'; - if ($associationMapping['isCascadeRemove']) $cascades[] = '"remove"'; - if ($associationMapping['isCascadeDetach']) $cascades[] = '"detach"'; - if ($associationMapping['isCascadeMerge']) $cascades[] = '"merge"'; - if ($associationMapping['isCascadeRefresh']) $cascades[] = '"refresh"'; + foreach (['remove', 'persist', 'refresh'] as $cascadeType) { + if (in_array($cascadeType, $association->getCascade())) { + $cascades[] = sprintf('"%s"', $cascadeType); + } + } if (count($cascades) === 5) { $cascades = ['"all"']; @@ -1538,27 +1561,18 @@ protected function generateAssociationMappingPropertyDocBlock(array $association $typeOptions[] = 'cascade={' . implode(',', $cascades) . '}'; } - if (isset($associationMapping['orphanRemoval']) && $associationMapping['orphanRemoval']) { - $typeOptions[] = 'orphanRemoval=' . ($associationMapping['orphanRemoval'] ? 'true' : 'false'); - } - - if (isset($associationMapping['fetch']) && $associationMapping['fetch'] !== ClassMetadataInfo::FETCH_LAZY) { - $fetchMap = [ - ClassMetadataInfo::FETCH_EXTRA_LAZY => 'EXTRA_LAZY', - ClassMetadataInfo::FETCH_EAGER => 'EAGER', - ]; - - $typeOptions[] = 'fetch="' . $fetchMap[$associationMapping['fetch']] . '"'; + if ($association->getFetchMode() !== FetchMode::LAZY) { + $typeOptions[] = 'fetch="' . $association->getFetchMode() . '"'; } $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . '' . $type . '(' . implode(', ', $typeOptions) . ')'; - if (isset($associationMapping['joinColumns']) && $associationMapping['joinColumns']) { + if ($association instanceof ToOneAssociationMetadata && $association->getJoinColumns()) { $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'JoinColumns({'; $joinColumnsLines = []; - foreach ($associationMapping['joinColumns'] as $joinColumn) { + foreach ($association->getJoinColumns() as $joinColumn) { if ($joinColumnAnnot = $this->generateJoinColumnAnnotation($joinColumn)) { $joinColumnsLines[] = $this->spaces . ' * ' . $joinColumnAnnot; } @@ -1568,47 +1582,22 @@ protected function generateAssociationMappingPropertyDocBlock(array $association $lines[] = $this->spaces . ' * })'; } - if (isset($associationMapping['joinTable']) && $associationMapping['joinTable']) { - $joinTable = []; - $joinTable[] = 'name="' . $associationMapping['joinTable']['name'] . '"'; - - if (isset($associationMapping['joinTable']['schema'])) { - $joinTable[] = 'schema="' . $associationMapping['joinTable']['schema'] . '"'; + if ($association instanceof ToManyAssociationMetadata) { + if ($association instanceof ManyToManyAssociationMetadata && $association->getJoinTable()) { + $lines[] = $this->generateJoinTableAnnotation($association->getJoinTable()); } - $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'JoinTable(' . implode(', ', $joinTable) . ','; - $lines[] = $this->spaces . ' * joinColumns={'; + if ($association->getOrderBy()) { + $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'OrderBy({'; + $orderBy = []; - $joinColumnsLines = []; - - foreach ($associationMapping['joinTable']['joinColumns'] as $joinColumn) { - $joinColumnsLines[] = $this->spaces . ' * ' . $this->generateJoinColumnAnnotation($joinColumn); - } - - $lines[] = implode(",". PHP_EOL, $joinColumnsLines); - $lines[] = $this->spaces . ' * },'; - $lines[] = $this->spaces . ' * inverseJoinColumns={'; - - $inverseJoinColumnsLines = []; - - foreach ($associationMapping['joinTable']['inverseJoinColumns'] as $joinColumn) { - $inverseJoinColumnsLines[] = $this->spaces . ' * ' . $this->generateJoinColumnAnnotation($joinColumn); - } - - $lines[] = implode(",". PHP_EOL, $inverseJoinColumnsLines); - $lines[] = $this->spaces . ' * }'; - $lines[] = $this->spaces . ' * )'; - } - - if (isset($associationMapping['orderBy'])) { - $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'OrderBy({'; + foreach ($association->getOrderBy() as $name => $direction) { + $orderBy[] = $this->spaces . ' * "' . $name . '"="' . $direction . '"'; + } - foreach ($associationMapping['orderBy'] as $name => $direction) { - $lines[] = $this->spaces . ' * "' . $name . '"="' . $direction . '",'; + $lines[] = implode(',' . PHP_EOL, $orderBy); + $lines[] = $this->spaces . ' * })'; } - - $lines[count($lines) - 1] = substr($lines[count($lines) - 1], 0, strlen($lines[count($lines) - 1]) - 1); - $lines[] = $this->spaces . ' * })'; } } @@ -1618,94 +1607,75 @@ protected function generateAssociationMappingPropertyDocBlock(array $association } /** - * @param array $fieldMapping - * @param ClassMetadataInfo $metadata + * @param FieldMetadata $propertyMetadata + * @param ClassMetadata $metadata * * @return string */ - protected function generateFieldMappingPropertyDocBlock(array $fieldMapping, ClassMetadataInfo $metadata) + protected function generateFieldMappingPropertyDocBlock(FieldMetadata $propertyMetadata, ClassMetadata $metadata) { + $fieldType = $propertyMetadata->getTypeName(); + $lines = []; + $lines[] = $this->spaces . '/**'; $lines[] = $this->spaces . ' * @var ' - . $this->getType($fieldMapping['type']) - . ($this->nullableFieldExpression($fieldMapping) ? '|null' : ''); + . $this->getType($fieldType) + . ($propertyMetadata->isNullable() ? '|null' : ''); if ($this->generateAnnotations) { + $column = []; $lines[] = $this->spaces . ' *'; - $column = []; - if (isset($fieldMapping['columnName'])) { - $column[] = 'name="' . $fieldMapping['columnName'] . '"'; + if ($propertyMetadata->getColumnName()) { + $column[] = 'name="' . $propertyMetadata->getColumnName() . '"'; } - if (isset($fieldMapping['type'])) { - $column[] = 'type="' . $fieldMapping['type'] . '"'; + $column[] = 'type="' . $fieldType . '"'; + + if (is_int($propertyMetadata->getLength())) { + $column[] = 'length=' . $propertyMetadata->getLength(); + } + + if (is_int($propertyMetadata->getPrecision())) { + $column[] = 'precision=' . $propertyMetadata->getPrecision(); } - if (isset($fieldMapping['length'])) { - $column[] = 'length=' . $fieldMapping['length']; + if (is_int($propertyMetadata->getScale())) { + $column[] = 'scale=' . $propertyMetadata->getScale(); } - if (isset($fieldMapping['precision'])) { - $column[] = 'precision=' . $fieldMapping['precision']; + if ($propertyMetadata->isNullable()) { + $column[] = 'nullable=' . var_export($propertyMetadata->isNullable(), true); } - if (isset($fieldMapping['scale'])) { - $column[] = 'scale=' . $fieldMapping['scale']; + if ($propertyMetadata->isUnique()) { + $column[] = 'unique=' . var_export($propertyMetadata->isUnique(), true); } - if (isset($fieldMapping['nullable'])) { - $column[] = 'nullable=' . var_export($fieldMapping['nullable'], true); + if ($propertyMetadata->getColumnDefinition()) { + $column[] = 'columnDefinition="' . $propertyMetadata->getColumnDefinition() . '"'; } $options = []; - if (isset($fieldMapping['options']['unsigned']) && $fieldMapping['options']['unsigned']) { - $options[] = '"unsigned"=true'; + if ($propertyMetadata->getOptions()) { + foreach ($propertyMetadata->getOptions() as $key => $value) { + $options[] = sprintf('"%s"=%s', $key, str_replace("'", '"', var_export($value, true))); + } } if ($options) { $column[] = 'options={'.implode(',', $options).'}'; } - if (isset($fieldMapping['columnDefinition'])) { - $column[] = 'columnDefinition="' . $fieldMapping['columnDefinition'] . '"'; - } - - if (isset($fieldMapping['unique'])) { - $column[] = 'unique=' . var_export($fieldMapping['unique'], true); - } - $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'Column(' . implode(', ', $column) . ')'; - if (isset($fieldMapping['id']) && $fieldMapping['id']) { - $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'Id'; - - if ($generatorType = $this->getIdGeneratorTypeString($metadata->generatorType)) { - $lines[] = $this->spaces.' * @' . $this->annotationsPrefix . 'GeneratedValue(strategy="' . $generatorType . '")'; - } - - if ($metadata->sequenceGeneratorDefinition) { - $sequenceGenerator = []; - - if (isset($metadata->sequenceGeneratorDefinition['sequenceName'])) { - $sequenceGenerator[] = 'sequenceName="' . $metadata->sequenceGeneratorDefinition['sequenceName'] . '"'; - } - - if (isset($metadata->sequenceGeneratorDefinition['allocationSize'])) { - $sequenceGenerator[] = 'allocationSize=' . $metadata->sequenceGeneratorDefinition['allocationSize']; - } - - if (isset($metadata->sequenceGeneratorDefinition['initialValue'])) { - $sequenceGenerator[] = 'initialValue=' . $metadata->sequenceGeneratorDefinition['initialValue']; - } - - $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'SequenceGenerator(' . implode(', ', $sequenceGenerator) . ')'; - } + if ($propertyMetadata->isPrimaryKey()) { + $lines[] = $this->generateIdentifierAnnotation($propertyMetadata); } - if (isset($fieldMapping['version']) && $fieldMapping['version']) { + if ($metadata->isVersioned() && $metadata->versionProperty->getName() === $propertyMetadata->getName()) { $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'Version'; } } @@ -1776,11 +1746,11 @@ protected function prefixCodeWithSpaces($code, $num = 1) */ protected function getInheritanceTypeString($type) { - if ( ! isset(static::$inheritanceTypeMap[$type])) { + if ( ! defined(sprintf('%s::%s', InheritanceType::class, $type))) { throw new \InvalidArgumentException(sprintf('Invalid provided InheritanceType: %s', $type)); } - return static::$inheritanceTypeMap[$type]; + return $type; } /** @@ -1792,11 +1762,11 @@ protected function getInheritanceTypeString($type) */ protected function getChangeTrackingPolicyString($type) { - if ( ! isset(static::$changeTrackingPolicyMap[$type])) { + if ( ! defined(sprintf('%s::%s', ChangeTrackingPolicy::class, $type))) { throw new \InvalidArgumentException(sprintf('Invalid provided ChangeTrackingPolicy: %s', $type)); } - return static::$changeTrackingPolicyMap[$type]; + return $type; } /** @@ -1804,29 +1774,15 @@ protected function getChangeTrackingPolicyString($type) * * @return string The literal string for the generator type. * - * @throws \InvalidArgumentException When the generator type does not exist. + * @throws \InvalidArgumentException When the generator type does not exist. */ protected function getIdGeneratorTypeString($type) { - if ( ! isset(static::$generatorStrategyMap[$type])) { + if ( ! defined(sprintf('%s::%s', GeneratorType::class, $type))) { throw new \InvalidArgumentException(sprintf('Invalid provided IdGeneratorType: %s', $type)); } - return static::$generatorStrategyMap[$type]; - } - - /** - * @param array $fieldMapping - * - * @return string|null - */ - private function nullableFieldExpression(array $fieldMapping) - { - if (isset($fieldMapping['nullable']) && true === $fieldMapping['nullable']) { - return 'null'; - } - - return null; + return $type; } /** @@ -1841,11 +1797,12 @@ private function exportTableOptions(array $options) $optionsStr = []; foreach ($options as $name => $option) { - if (is_array($option)) { - $optionsStr[] = '"' . $name . '"={' . $this->exportTableOptions($option) . '}'; - } else { - $optionsStr[] = '"' . $name . '"="' . (string) $option . '"'; - } + $optionValue = is_array($option) + ? '{' . $this->exportTableOptions($option) . '}' + : '"' . (string) $option . '"' + ; + + $optionsStr[] = sprintf('"%s"=%s', $name, $optionValue); } return implode(',', $optionsStr); diff --git a/lib/Doctrine/ORM/Tools/EntityRepositoryGenerator.php b/lib/Doctrine/ORM/Tools/EntityRepositoryGenerator.php index dbfcbc6d49f..028026515c9 100644 --- a/lib/Doctrine/ORM/Tools/EntityRepositoryGenerator.php +++ b/lib/Doctrine/ORM/Tools/EntityRepositoryGenerator.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools; @@ -77,7 +62,7 @@ public function generateEntityRepositoryClass($fullClassName) */ private function getClassNamespace($fullClassName) { - $namespace = substr($fullClassName, 0, strrpos($fullClassName, '\\')); + $namespace = substr($fullClassName, 0, (int) strrpos($fullClassName, '\\')); return $namespace; } diff --git a/lib/Doctrine/ORM/Tools/Event/GenerateSchemaEventArgs.php b/lib/Doctrine/ORM/Tools/Event/GenerateSchemaEventArgs.php index ed03e32d9dc..c3fdf43d19e 100644 --- a/lib/Doctrine/ORM/Tools/Event/GenerateSchemaEventArgs.php +++ b/lib/Doctrine/ORM/Tools/Event/GenerateSchemaEventArgs.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Event; diff --git a/lib/Doctrine/ORM/Tools/Event/GenerateSchemaTableEventArgs.php b/lib/Doctrine/ORM/Tools/Event/GenerateSchemaTableEventArgs.php index e2c38f9c592..343abc9bf0a 100644 --- a/lib/Doctrine/ORM/Tools/Event/GenerateSchemaTableEventArgs.php +++ b/lib/Doctrine/ORM/Tools/Event/GenerateSchemaTableEventArgs.php @@ -1,21 +1,6 @@ . - */ +declare(strict_types=1); + namespace Doctrine\ORM\Tools\Event; use Doctrine\Common\EventArgs; diff --git a/lib/Doctrine/ORM/Tools/Export/ClassMetadataExporter.php b/lib/Doctrine/ORM/Tools/Export/ClassMetadataExporter.php index ab44263cdf4..01f7ee1ad9d 100644 --- a/lib/Doctrine/ORM/Tools/Export/ClassMetadataExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/ClassMetadataExporter.php @@ -1,27 +1,12 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Export; /** * Class used for converting your mapping information between the - * supported formats: yaml, xml, and php/annotation. + * supported formats: xml and php/annotation. * * @link www.doctrine-project.org * @since 2.0 @@ -34,8 +19,6 @@ class ClassMetadataExporter */ private static $_exporterDrivers = [ 'xml' => Driver\XmlExporter::class, - 'yaml' => Driver\YamlExporter::class, - 'yml' => Driver\YamlExporter::class, 'php' => Driver\PhpExporter::class, 'annotation' => Driver\AnnotationExporter::class ]; @@ -56,7 +39,7 @@ public static function registerExportDriver($name, $class) /** * Gets an exporter driver instance. * - * @param string $type The type to get (yml, xml, etc.). + * @param string $type The type to get (xml, etc.). * @param string|null $dest The directory where the exporter will export to. * * @return Driver\AbstractExporter diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/AbstractExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/AbstractExporter.php index 100e16fd00f..9bc5ef0a30a 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/AbstractExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/AbstractExporter.php @@ -1,25 +1,10 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Export\Driver; -use Doctrine\ORM\Mapping\ClassMetadataInfo; +use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Tools\Export\ExportException; /** @@ -35,29 +20,29 @@ abstract class AbstractExporter /** * @var array */ - protected $_metadata = []; + protected $metadata = []; /** * @var string|null */ - protected $_outputDir; + protected $outputDir; /** * @var string|null */ - protected $_extension; + protected $extension; /** * @var bool */ - protected $_overwriteExistingFiles = false; + protected $overwriteExistingFiles = false; /** * @param string|null $dir */ public function __construct($dir = null) { - $this->_outputDir = $dir; + $this->outputDir = $dir; } /** @@ -67,21 +52,21 @@ public function __construct($dir = null) */ public function setOverwriteExistingFiles($overwrite) { - $this->_overwriteExistingFiles = $overwrite; + $this->overwriteExistingFiles = $overwrite; } /** * Converts a single ClassMetadata instance to the exported format * and returns it. * - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - abstract public function exportClassMetadata(ClassMetadataInfo $metadata); + abstract public function exportClassMetadata(ClassMetadata $metadata); /** - * Sets the array of ClassMetadataInfo instances to export. + * Sets the array of ClassMetadata instances to export. * * @param array $metadata * @@ -89,7 +74,7 @@ abstract public function exportClassMetadata(ClassMetadataInfo $metadata); */ public function setMetadata(array $metadata) { - $this->_metadata = $metadata; + $this->metadata = $metadata; } /** @@ -99,15 +84,15 @@ public function setMetadata(array $metadata) */ public function getExtension() { - return $this->_extension; + return $this->extension; } /** * Sets the directory to output the mapping files to. * * [php] - * $exporter = new YamlExporter($metadata); - * $exporter->setOutputDir(__DIR__ . '/yaml'); + * $exporter = new XmlExporter($metadata); + * $exporter->setOutputDir(__DIR__ . '/xml'); * $exporter->export(); * * @param string $dir @@ -116,7 +101,7 @@ public function getExtension() */ public function setOutputDir($dir) { - $this->_outputDir = $dir; + $this->outputDir = $dir; } /** @@ -129,19 +114,19 @@ public function setOutputDir($dir) */ public function export() { - if ( ! is_dir($this->_outputDir)) { - mkdir($this->_outputDir, 0775, true); + if ( ! is_dir($this->outputDir)) { + mkdir($this->outputDir, 0775, true); } - foreach ($this->_metadata as $metadata) { + foreach ($this->metadata as $metadata) { // In case output is returned, write it to a file, skip otherwise if ($output = $this->exportClassMetadata($metadata)) { - $path = $this->_generateOutputPath($metadata); + $path = $this->generateOutputPath($metadata); $dir = dirname($path); if ( ! is_dir($dir)) { mkdir($dir, 0775, true); } - if (file_exists($path) && !$this->_overwriteExistingFiles) { + if (file_exists($path) && !$this->overwriteExistingFiles) { throw ExportException::attemptOverwriteExistingFile($path); } file_put_contents($path, $output); @@ -151,23 +136,23 @@ public function export() } /** - * Generates the path to write the class for the given ClassMetadataInfo instance. + * Generates the path to write the class for the given ClassMetadata instance. * - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function _generateOutputPath(ClassMetadataInfo $metadata) + protected function generateOutputPath(ClassMetadata $metadata) { - return $this->_outputDir . '/' . str_replace('\\', '.', $metadata->name) . $this->_extension; + return $this->outputDir . '/' . str_replace('\\', '.', $metadata->getClassName()) . $this->extension; } /** * Sets the directory to output the mapping files to. * * [php] - * $exporter = new YamlExporter($metadata, __DIR__ . '/yaml'); - * $exporter->setExtension('.yml'); + * $exporter = new XmlExporter($metadata, __DIR__ . '/xml'); + * $exporter->setExtension('.xml'); * $exporter->export(); * * @param string $extension @@ -176,94 +161,6 @@ protected function _generateOutputPath(ClassMetadataInfo $metadata) */ public function setExtension($extension) { - $this->_extension = $extension; - } - - /** - * @param int $type - * - * @return string - */ - protected function _getInheritanceTypeString($type) - { - switch ($type) { - case ClassMetadataInfo::INHERITANCE_TYPE_NONE: - return 'NONE'; - - case ClassMetadataInfo::INHERITANCE_TYPE_JOINED: - return 'JOINED'; - - case ClassMetadataInfo::INHERITANCE_TYPE_SINGLE_TABLE: - return 'SINGLE_TABLE'; - - case ClassMetadataInfo::INHERITANCE_TYPE_TABLE_PER_CLASS: - return 'PER_CLASS'; - } - } - - /** - * @param int $mode - * - * @return string - */ - protected function _getFetchModeString($mode) - { - switch ($mode) { - case ClassMetadataInfo::FETCH_EAGER: - return 'EAGER'; - - case ClassMetadataInfo::FETCH_EXTRA_LAZY: - return 'EXTRA_LAZY'; - - case ClassMetadataInfo::FETCH_LAZY: - return 'LAZY'; - } - } - - /** - * @param int $policy - * - * @return string - */ - protected function _getChangeTrackingPolicyString($policy) - { - switch ($policy) { - case ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT: - return 'DEFERRED_IMPLICIT'; - - case ClassMetadataInfo::CHANGETRACKING_DEFERRED_EXPLICIT: - return 'DEFERRED_EXPLICIT'; - - case ClassMetadataInfo::CHANGETRACKING_NOTIFY: - return 'NOTIFY'; - } - } - - /** - * @param int $type - * - * @return string - */ - protected function _getIdGeneratorTypeString($type) - { - switch ($type) { - case ClassMetadataInfo::GENERATOR_TYPE_AUTO: - return 'AUTO'; - - case ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE: - return 'SEQUENCE'; - - case ClassMetadataInfo::GENERATOR_TYPE_TABLE: - return 'TABLE'; - - case ClassMetadataInfo::GENERATOR_TYPE_IDENTITY: - return 'IDENTITY'; - - case ClassMetadataInfo::GENERATOR_TYPE_UUID: - return 'UUID'; - - case ClassMetadataInfo::GENERATOR_TYPE_CUSTOM: - return 'CUSTOM'; - } + $this->extension = $extension; } } diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/AnnotationExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/AnnotationExporter.php index 044a1da53a8..c14c296677c 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/AnnotationExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/AnnotationExporter.php @@ -1,25 +1,10 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Export\Driver; -use Doctrine\ORM\Mapping\ClassMetadataInfo; +use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Tools\EntityGenerator; /** @@ -34,47 +19,47 @@ class AnnotationExporter extends AbstractExporter /** * @var string */ - protected $_extension = '.php'; + protected $extension = '.php'; /** * @var EntityGenerator|null */ - private $_entityGenerator; + private $entityGenerator; /** * {@inheritdoc} */ - public function exportClassMetadata(ClassMetadataInfo $metadata) + public function exportClassMetadata(ClassMetadata $metadata) { - if ( ! $this->_entityGenerator) { + if ( ! $this->entityGenerator) { throw new \RuntimeException('For the AnnotationExporter you must set an EntityGenerator instance with the setEntityGenerator() method.'); } - $this->_entityGenerator->setGenerateAnnotations(true); - $this->_entityGenerator->setGenerateStubMethods(false); - $this->_entityGenerator->setRegenerateEntityIfExists(false); - $this->_entityGenerator->setUpdateEntityIfExists(false); + $this->entityGenerator->setGenerateAnnotations(true); + $this->entityGenerator->setGenerateStubMethods(false); + $this->entityGenerator->setRegenerateEntityIfExists(false); + $this->entityGenerator->setUpdateEntityIfExists(false); - return $this->_entityGenerator->generateEntityClass($metadata); + return $this->entityGenerator->generateEntityClass($metadata); } /** - * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return string */ - protected function _generateOutputPath(ClassMetadataInfo $metadata) + protected function generateOutputPath(ClassMetadata $metadata) { - return $this->_outputDir . '/' . str_replace('\\', '/', $metadata->name) . $this->_extension; + return $this->outputDir . '/' . str_replace('\\', '/', $metadata->getClassName()) . $this->extension; } /** - * @param \Doctrine\ORM\Tools\EntityGenerator $entityGenerator + * @param EntityGenerator $entityGenerator * * @return void */ public function setEntityGenerator(EntityGenerator $entityGenerator) { - $this->_entityGenerator = $entityGenerator; + $this->entityGenerator = $entityGenerator; } } diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/PhpExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/PhpExporter.php index 69db59f784a..f62ba8cb1f4 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/PhpExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/PhpExporter.php @@ -19,7 +19,16 @@ namespace Doctrine\ORM\Tools\Export\Driver; -use Doctrine\ORM\Mapping\ClassMetadataInfo; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\FieldMetadata; +use Doctrine\ORM\Mapping\JoinColumnMetadata; +use Doctrine\ORM\Mapping\JoinTableMetadata; +use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ManyToOneAssociationMetadata; +use Doctrine\ORM\Mapping\OneToManyAssociationMetadata; +use Doctrine\ORM\Mapping\OneToOneAssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; /** * ClassMetadata exporter for PHP code. @@ -33,17 +42,19 @@ class PhpExporter extends AbstractExporter /** * @var string */ - protected $_extension = '.php'; + protected $extension = '.php'; /** * {@inheritdoc} */ - public function exportClassMetadata(ClassMetadataInfo $metadata) + public function exportClassMetadata(ClassMetadata $metadata) { $lines = []; $lines[] = 'isMappedSuperclass) { @@ -51,112 +62,255 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } if ($metadata->inheritanceType) { - $lines[] = '$metadata->setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_' . $this->_getInheritanceTypeString($metadata->inheritanceType) . ');'; + $lines[] = '$metadata->setInheritanceType(Mapping\InheritanceType::' . $metadata->inheritanceType . ');'; } if ($metadata->customRepositoryClassName) { - $lines[] = "\$metadata->customRepositoryClassName = '" . $metadata->customRepositoryClassName . "';"; + $lines[] = '$metadata->customRepositoryClassName = "' . $metadata->customRepositoryClassName . '";'; } if ($metadata->table) { - $lines[] = '$metadata->setPrimaryTable(' . $this->_varExport($metadata->table) . ');'; + $table = $metadata->table; + + $lines[] = '$table = new Mapping\TableMetadata();'; + $lines[] = null; + + if (! empty($table->getSchema())) { + $lines[] = '$table->setSchema("' . $table->getSchema() . '");'; + } + + $lines[] = '$table->setName("' . $table->getName() . '");'; + $lines[] = '$table->setOptions(' . $this->varExport($table->getOptions()) . ');'; + + foreach ($table->getIndexes() as $index) { + $lines[] = '$table->addIndex(' . $this->varExport($index) . ');'; + } + + foreach ($table->getUniqueConstraints() as $constraint) { + $lines[] = '$table->addUniqueConstraint(' . $this->varExport($constraint) . ');'; + } + + $lines[] = null; + $lines[] = '$metadata->setTable($table);'; } if ($metadata->discriminatorColumn) { - $lines[] = '$metadata->setDiscriminatorColumn(' . $this->_varExport($metadata->discriminatorColumn) . ');'; + $discrColumn = $metadata->discriminatorColumn; + + $lines[] = '$discrColumn = new Mapping\DiscriminatorColumnMetadata();'; + $lines[] = null; + $lines[] = '$discrColumn->setColumnName("' . $discrColumn->getColumnName() . '");'; + $lines[] = '$discrColumn->setType(Type::getType("' . $discrColumn->getTypeName() . '"));'; + $lines[] = '$discrColumn->setTableName("' . $discrColumn->getTableName() . '");'; + + if (! empty($discrColumn->getColumnDefinition())) { + $lines[] = '$property->setColumnDefinition("' . $discrColumn->getColumnDefinition() . '");'; + } + + if (! empty($discrColumn->getLength())) { + $lines[] = '$property->setLength(' . $discrColumn->getLength() . ');'; + } + + if (! empty($discrColumn->getScale())) { + $lines[] = '$property->setScale(' . $discrColumn->getScale() . ');'; + } + + if (! empty($discrColumn->getPrecision())) { + $lines[] = '$property->setPrecision(' . $discrColumn->getPrecision() . ');'; + } + + $lines[] = '$discrColumn->setOptions(' . $this->varExport($discrColumn->getOptions()) . ');'; + $lines[] = '$discrColumn->setNullable(' . $this->varExport($discrColumn->isNullable()) . ');'; + $lines[] = '$discrColumn->setUnique(' . $this->varExport($discrColumn->isUnique()) . ');'; + $lines[] = null; + $lines[] = '$metadata->setDiscriminatorColumn($discrColumn);'; } if ($metadata->discriminatorMap) { - $lines[] = '$metadata->setDiscriminatorMap(' . $this->_varExport($metadata->discriminatorMap) . ');'; + $lines[] = '$metadata->setDiscriminatorMap(' . $this->varExport($metadata->discriminatorMap) . ');'; } if ($metadata->changeTrackingPolicy) { - $lines[] = '$metadata->setChangeTrackingPolicy(ClassMetadataInfo::CHANGETRACKING_' . $this->_getChangeTrackingPolicyString($metadata->changeTrackingPolicy) . ');'; + $lines[] = '$metadata->setChangeTrackingPolicy(Mapping\ChangeTrackingPolicy::' . $metadata->changeTrackingPolicy . ');'; } if ($metadata->lifecycleCallbacks) { foreach ($metadata->lifecycleCallbacks as $event => $callbacks) { foreach ($callbacks as $callback) { - $lines[] = "\$metadata->addLifecycleCallback('$callback', '$event');"; + $lines[] = '$metadata->addLifecycleCallback("' . $callback . '", "' . $event . '");'; } } } - foreach ($metadata->fieldMappings as $fieldMapping) { - $lines[] = '$metadata->mapField(' . $this->_varExport($fieldMapping) . ');'; + if (! $metadata->isIdentifierComposite()) { + $lines[] = '$metadata->setIdGeneratorType(Mapping\GeneratorType::' . $metadata->generatorType . ');'; } - if ( ! $metadata->isIdentifierComposite && $generatorType = $this->_getIdGeneratorTypeString($metadata->generatorType)) { - $lines[] = '$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_' . $generatorType . ');'; + foreach ($metadata->getProperties() as $property) { + if ($property instanceof FieldMetadata) { + $this->exportFieldMetadata($metadata, $property, $lines); + } else if ($property instanceof AssociationMetadata) { + $this->exportAssociationMetadata($metadata, $property, $lines); + } } - foreach ($metadata->associationMappings as $associationMapping) { - $cascade = ['remove', 'persist', 'refresh', 'merge', 'detach']; - foreach ($cascade as $key => $value) { - if ( ! $associationMapping['isCascade'.ucfirst($value)]) { - unset($cascade[$key]); - } + return implode(PHP_EOL, $lines); + } + + private function exportFieldMetadata(ClassMetadata $metadata, FieldMetadata $property, array &$lines) + { + $lines[] = sprintf( + '$property = new Mapping\%sFieldMetadata("%s");', + ($metadata->versionProperty === $property) ? 'Version' : '', + $property->getName() + ); + + $lines[] = null; + $lines[] = '$property->setColumnName("' . $property->getColumnName() . '");'; + $lines[] = '$property->setType(Type::getType("' . $property->getTypeName() . '"));'; + $lines[] = '$property->setTableName("' . $property->getTableName() . '");'; + + if (! empty($property->getColumnDefinition())) { + $lines[] = '$property->setColumnDefinition("' . $property->getColumnDefinition() . '");'; + } + + if (! empty($property->getLength())) { + $lines[] = '$property->setLength(' . $property->getLength() . ');'; + } + + if (! empty($property->getScale())) { + $lines[] = '$property->setScale(' . $property->getScale() . ');'; + } + + if (! empty($property->getPrecision())) { + $lines[] = '$property->setPrecision(' . $property->getPrecision() . ');'; + } + + $lines[] = '$property->setOptions(' . $this->varExport($property->getOptions()) . ');'; + $lines[] = '$property->setPrimaryKey(' . $this->varExport($property->isPrimaryKey()) . ');'; + $lines[] = '$property->setNullable(' . $this->varExport($property->isNullable()) . ');'; + $lines[] = '$property->setUnique(' . $this->varExport($property->isUnique()) . ');'; + $lines[] = null; + $lines[] = '$metadata->addProperty($property);'; + } + + private function exportAssociationMetadata(ClassMetadata $metadata, AssociationMetadata $association, array &$lines) + { + $cascade = ['remove', 'persist', 'refresh']; + + foreach ($cascade as $key => $value) { + if ( ! in_array($value, $association->getCascade())) { + unset($cascade[$key]); } + } - if (count($cascade) === 5) { - $cascade = ['all']; + if (count($cascade) === 5) { + $cascade = ['all']; + } + + if ($association instanceof OneToOneAssociationMetadata) { + $this->exportJoinColumns($association->getJoinColumns(), $lines, 'joinColumns'); + + $lines[] = '$association = new Mapping\OneToOneAssociationMetadata("' . $association->getName() . '");'; + $lines[] = null; + $lines[] = '$association->setJoinColumns($joinColumns);'; + } else if ($association instanceof ManyToOneAssociationMetadata) { + $this->exportJoinColumns($association->getJoinColumns(), $lines, 'joinColumns'); + + $lines[] = '$association = new Mapping\ManyToOneAssociationMetadata("' . $association->getName() . '");'; + $lines[] = null; + $lines[] = '$association->setJoinColumns($joinColumns);'; + } else if ($association instanceof OneToManyAssociationMetadata) { + $lines[] = '$association = new Mapping\OneToManyAssociationMetadata("' . $association->getName() . '");'; + $lines[] = null; + $lines[] = '$association->setOrderBy(' . $this->varExport($association->getOrderBy()) . ');'; + } else if ($association instanceof ManyToManyAssociationMetadata) { + if ($association->getJoinTable()) { + $this->exportJoinTable($association->getJoinTable(), $lines); } - $method = null; - $associationMappingArray = [ - 'fieldName' => $associationMapping['fieldName'], - 'targetEntity' => $associationMapping['targetEntity'], - 'cascade' => $cascade, - ]; + $lines[] = '$association = new Mapping\ManyToManyAssociationMetadata("' . $association->getName() . '");'; + $lines[] = null; - if (isset($associationMapping['fetch'])) { - $associationMappingArray['fetch'] = $associationMapping['fetch']; + if ($association->getJoinTable()) { + $lines[] = '$association->setJoinTable($joinTable);'; } - if ($associationMapping['type'] & ClassMetadataInfo::TO_ONE) { - $method = 'mapOneToOne'; - $oneToOneMappingArray = [ - 'mappedBy' => $associationMapping['mappedBy'], - 'inversedBy' => $associationMapping['inversedBy'], - 'joinColumns' => $associationMapping['isOwningSide'] ? $associationMapping['joinColumns'] : [], - 'orphanRemoval' => $associationMapping['orphanRemoval'], - ]; - - $associationMappingArray = array_merge($associationMappingArray, $oneToOneMappingArray); - } elseif ($associationMapping['type'] == ClassMetadataInfo::ONE_TO_MANY) { - $method = 'mapOneToMany'; - $potentialAssociationMappingIndexes = [ - 'mappedBy', - 'orphanRemoval', - 'orderBy', - ]; - $oneToManyMappingArray = []; - foreach ($potentialAssociationMappingIndexes as $index) { - if (isset($associationMapping[$index])) { - $oneToManyMappingArray[$index] = $associationMapping[$index]; - } - } - $associationMappingArray = array_merge($associationMappingArray, $oneToManyMappingArray); - } elseif ($associationMapping['type'] == ClassMetadataInfo::MANY_TO_MANY) { - $method = 'mapManyToMany'; - $potentialAssociationMappingIndexes = [ - 'mappedBy', - 'joinTable', - 'orderBy', - ]; - $manyToManyMappingArray = []; - foreach ($potentialAssociationMappingIndexes as $index) { - if (isset($associationMapping[$index])) { - $manyToManyMappingArray[$index] = $associationMapping[$index]; - } - } - $associationMappingArray = array_merge($associationMappingArray, $manyToManyMappingArray); + if ($association->getIndexedBy()) { + $lines[] = '$association->setIndexedBy("' . $association->getIndexedBy() . '");'; } - $lines[] = '$metadata->' . $method . '(' . $this->_varExport($associationMappingArray) . ');'; + $lines[] = '$association->setOrderBy(' . $this->varExport($association->getOrderBy()) . ');'; + } + + $lines[] = '$association->setTargetEntity("' . $association->getTargetEntity() . '");'; + $lines[] = '$association->setFetchMode("' . $association->getFetchMode() . '");'; + + if ($association->getMappedBy()) { + $lines[] = '$association->setMappedBy("' . $association->getMappedBy() . '");'; + } + + if ($association->getInversedBy()) { + $lines[] = '$association->setInversedBy("' . $association->getInversedBy() . '");'; + } + + $lines[] = '$association->setCascade(' . $this->varExport($cascade) . ');'; + $lines[] = '$association->setOrphanRemoval(' . $this->varExport($association->isOrphanRemoval()) . ');'; + $lines[] = '$association->setPrimaryKey(' . $this->varExport($association->isPrimaryKey()) . ');'; + $lines[] = null; + $lines[] = '$metadata->addProperty($association);'; + } + + private function exportJoinTable(JoinTableMetadata $joinTable, array &$lines) + { + $lines[] = null; + $lines[] = '$joinTable = new Mapping\JoinTableMetadata();'; + $lines[] = null; + $lines[] = '$joinTable->setName("' . $joinTable->getName() . '");'; + + if (! empty($joinTable->getSchema())) { + $lines[] = '$joinTable->setSchema("' . $joinTable->getSchema() . '");'; } - return implode("\n", $lines); + $lines[] = '$joinTable->setOptions(' . $this->varExport($joinTable->getOptions()) . ');'; + + $this->exportJoinColumns($joinTable->getJoinColumns(), $lines, 'joinColumns'); + + $lines[] = null; + $lines[] = 'foreach ($joinColumns as $joinColumn) {'; + $lines[] = ' $joinTable->addJoinColumn($joinColumn);'; + $lines[] = '}'; + $lines[] = null; + + $this->exportJoinColumns($joinTable->getInverseJoinColumns(), $lines, 'inverseJoinColumns'); + + $lines[] = null; + $lines[] = 'foreach ($inverseJoinColumns as $inverseJoinColumn) {'; + $lines[] = ' $joinTable->addInverseJoinColumn($inverseJoinColumn);'; + $lines[] = '}'; + } + + private function exportJoinColumns(array $joinColumns, array &$lines, $variableName) + { + $lines[] = '$' . $variableName . ' = array();'; + + foreach ($joinColumns as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $lines[] = '$joinColumn = new Mapping\JoinColumnMetadata();'; + $lines[] = null; + $lines[] = '$joinColumn->setTableName("' . $joinColumn->getTableName() . '");'; + $lines[] = '$joinColumn->setColumnName("' . $joinColumn->getColumnName() . '");'; + $lines[] = '$joinColumn->setReferencedColumnName("' . $joinColumn->getReferencedColumnName() . '");'; + $lines[] = '$joinColumn->setAliasedName("' . $joinColumn->getAliasedName() . '");'; + $lines[] = '$joinColumn->setColumnDefinition("' . $joinColumn->getColumnDefinition() . '");'; + $lines[] = '$joinColumn->setOnDelete("' . $joinColumn->getOnDelete() . '");'; + $lines[] = '$joinColumn->setOptions(' . $this->varExport($joinColumn->getOptions()) . ');'; + $lines[] = '$joinColumn->setNullable("' . $joinColumn->isNullable() . '");'; + $lines[] = '$joinColumn->setUnique("' . $joinColumn->isUnique() . '");'; + $lines[] = '$joinColumn->setPrimaryKey("' . $joinColumn->isPrimaryKey() . '");'; + $lines[] = null; + $lines[] = '$' . $variableName . '[] = $joinColumn;'; + } } /** @@ -164,7 +318,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) * * @return string */ - protected function _varExport($var) + protected function varExport($var) { $export = var_export($var, true); $export = str_replace("\n", PHP_EOL . str_repeat(' ', 8), $export); diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/XmlExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/XmlExporter.php index c4eb8f63792..d4beaf5dac6 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/XmlExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/XmlExporter.php @@ -1,25 +1,22 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Export\Driver; -use Doctrine\ORM\Mapping\ClassMetadataInfo; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\ChangeTrackingPolicy; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\FieldMetadata; +use Doctrine\ORM\Mapping\GeneratorType; +use Doctrine\ORM\Mapping\InheritanceType; +use Doctrine\ORM\Mapping\JoinColumnMetadata; +use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ManyToOneAssociationMetadata; +use Doctrine\ORM\Mapping\OneToManyAssociationMetadata; +use Doctrine\ORM\Mapping\OneToOneAssociationMetadata; +use Doctrine\ORM\Mapping\ToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; /** * ClassMetadata exporter for Doctrine XML mapping files. @@ -33,12 +30,12 @@ class XmlExporter extends AbstractExporter /** * @var string */ - protected $_extension = '.dcm.xml'; + protected $extension = '.dcm.xml'; /** * {@inheritdoc} */ - public function exportClassMetadata(ClassMetadataInfo $metadata) + public function exportClassMetadata(ClassMetadata $metadata) { $xml = new \SimpleXmlElement("addChild('entity'); } - if ($metadata->customRepositoryClassName) { - $root->addAttribute('repository-class', $metadata->customRepositoryClassName); + if ($metadata->getCustomRepositoryClassName()) { + $root->addAttribute('repository-class', $metadata->getCustomRepositoryClassName()); } - $root->addAttribute('name', $metadata->name); + $root->addAttribute('name', $metadata->getClassName()); - if (isset($metadata->table['name'])) { - $root->addAttribute('table', $metadata->table['name']); + if ($metadata->table->getName()) { + $root->addAttribute('table', $metadata->table->getName()); } - if (isset($metadata->table['schema'])) { - $root->addAttribute('schema', $metadata->table['schema']); + if ($metadata->table->getSchema()) { + $root->addAttribute('schema', $metadata->table->getSchema()); } - if ($metadata->inheritanceType && $metadata->inheritanceType !== ClassMetadataInfo::INHERITANCE_TYPE_NONE) { - $root->addAttribute('inheritance-type', $this->_getInheritanceTypeString($metadata->inheritanceType)); + if ($metadata->inheritanceType && $metadata->inheritanceType !== InheritanceType::NONE) { + $root->addAttribute('inheritance-type', $metadata->inheritanceType); } - if (isset($metadata->table['options'])) { + if ($metadata->table->getOptions()) { $optionsXml = $root->addChild('options'); - $this->exportTableOptions($optionsXml, $metadata->table['options']); + $this->exportTableOptions($optionsXml, $metadata->table->getOptions()); } if ($metadata->discriminatorColumn) { + $discrColumn = $metadata->discriminatorColumn; $discriminatorColumnXml = $root->addChild('discriminator-column'); - $discriminatorColumnXml->addAttribute('name', $metadata->discriminatorColumn['name']); - $discriminatorColumnXml->addAttribute('type', $metadata->discriminatorColumn['type']); - if (isset($metadata->discriminatorColumn['length'])) { - $discriminatorColumnXml->addAttribute('length', $metadata->discriminatorColumn['length']); + $discriminatorColumnXml->addAttribute('name', $discrColumn->getColumnName()); + $discriminatorColumnXml->addAttribute('type', $discrColumn->getTypeName()); + + if (is_int($discrColumn->getLength())) { + $discriminatorColumnXml->addAttribute('length', (string) $discrColumn->getLength()); + } + + if (is_int($discrColumn->getScale())) { + $discriminatorColumnXml->addAttribute('scale', (string) $discrColumn->getScale()); + } + + if (is_int($discrColumn->getPrecision())) { + $discriminatorColumnXml->addAttribute('precision', (string) $discrColumn->getPrecision()); } } @@ -90,307 +97,355 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) foreach ($metadata->discriminatorMap as $value => $className) { $discriminatorMappingXml = $discriminatorMapXml->addChild('discriminator-mapping'); - $discriminatorMappingXml->addAttribute('value', $value); + $discriminatorMappingXml->addAttribute('value', (string) $value); $discriminatorMappingXml->addAttribute('class', $className); } } - $trackingPolicy = $this->_getChangeTrackingPolicyString($metadata->changeTrackingPolicy); - - if ( $trackingPolicy != 'DEFERRED_IMPLICIT') { - $root->addChild('change-tracking-policy', $trackingPolicy); + if ($metadata->changeTrackingPolicy !== ChangeTrackingPolicy::DEFERRED_IMPLICIT) { + $root->addChild('change-tracking-policy', $metadata->changeTrackingPolicy); } - if (isset($metadata->table['indexes'])) { + if ($metadata->table->getIndexes()) { $indexesXml = $root->addChild('indexes'); - foreach ($metadata->table['indexes'] as $name => $index) { + foreach ($metadata->table->getIndexes() as $name => $index) { $indexXml = $indexesXml->addChild('index'); + $indexXml->addAttribute('name', $name); $indexXml->addAttribute('columns', implode(',', $index['columns'])); - if (isset($index['flags'])) { + + if ($index['unique']) { + $indexXml->addAttribute('unique', 'true'); + } + + if ($index['flags']) { $indexXml->addAttribute('flags', implode(',', $index['flags'])); } + + if ($index['options']) { + $optionsXml = $indexXml->addChild('options'); + + foreach ($index['options'] as $key => $value) { + $optionXml = $optionsXml->addChild('option', $value); + + $optionXml->addAttribute('name', $key); + } + } } } - if (isset($metadata->table['uniqueConstraints'])) { + if ($metadata->table->getUniqueConstraints()) { $uniqueConstraintsXml = $root->addChild('unique-constraints'); - foreach ($metadata->table['uniqueConstraints'] as $name => $unique) { + foreach ($metadata->table->getUniqueConstraints() as $name => $constraint) { $uniqueConstraintXml = $uniqueConstraintsXml->addChild('unique-constraint'); + $uniqueConstraintXml->addAttribute('name', $name); - $uniqueConstraintXml->addAttribute('columns', implode(',', $unique['columns'])); - } - } + $uniqueConstraintXml->addAttribute('columns', implode(',', $constraint['columns'])); - $fields = $metadata->fieldMappings; + if ($constraint['flags']) { + $uniqueConstraintXml->addAttribute('flags', implode(',', $constraint['flags'])); + } - $id = []; - foreach ($fields as $name => $field) { - if (isset($field['id']) && $field['id']) { - $id[$name] = $field; - unset($fields[$name]); - } - } + if ($constraint['options']) { + $optionsXml = $uniqueConstraintXml->addChild('options'); + + foreach ($constraint['options'] as $key => $value) { + $optionXml = $optionsXml->addChild('option', $value); - foreach ($metadata->associationMappings as $name => $assoc) { - if (isset($assoc['id']) && $assoc['id']) { - $id[$name] = [ - 'fieldName' => $name, - 'associationKey' => true - ]; + $optionXml->addAttribute('name', $key); + } + } } } - if ( ! $metadata->isIdentifierComposite && $idGeneratorType = $this->_getIdGeneratorTypeString($metadata->generatorType)) { - $id[$metadata->getSingleIdentifierFieldName()]['generator']['strategy'] = $idGeneratorType; + $properties = iterator_to_array($metadata->getDeclaredPropertiesIterator()); + $id = []; + + foreach ($properties as $name => $property) { + if ($property->isPrimaryKey()) { + $id[$name] = $property; + + unset($properties[$name]); + } } if ($id) { - foreach ($id as $field) { + foreach ($id as $property) { $idXml = $root->addChild('id'); - $idXml->addAttribute('name', $field['fieldName']); - if (isset($field['type'])) { - $idXml->addAttribute('type', $field['type']); - } + $idXml->addAttribute('name', $property->getName()); - if (isset($field['columnName'])) { - $idXml->addAttribute('column', $field['columnName']); - } + if ($property instanceof AssociationMetadata) { + $idXml->addAttribute('association-key', 'true'); - if (isset($field['length'])) { - $idXml->addAttribute('length', $field['length']); + continue; } - if (isset($field['associationKey']) && $field['associationKey']) { - $idXml->addAttribute('association-key', 'true'); + $idXml->addAttribute('type', $property->getTypeName()); + $idXml->addAttribute('column', $property->getColumnName()); + + if (is_int($property->getLength())) { + $idXml->addAttribute('length', $property->getLength()); } - if ($idGeneratorType = $this->_getIdGeneratorTypeString($metadata->generatorType)) { + if ($property->hasValueGenerator()) { $generatorXml = $idXml->addChild('generator'); - $generatorXml->addAttribute('strategy', $idGeneratorType); - $this->exportSequenceInformation($idXml, $metadata); + $generatorXml->addAttribute('strategy', $property->getValueGenerator()->getType()); + + $this->exportSequenceInformation($idXml, $property); } } } - if ($fields) { - foreach ($fields as $field) { - $fieldXml = $root->addChild('field'); - $fieldXml->addAttribute('name', $field['fieldName']); - $fieldXml->addAttribute('type', $field['type']); - - if (isset($field['columnName'])) { - $fieldXml->addAttribute('column', $field['columnName']); - } + $orderMap = [ + FieldMetadata::class, + OneToOneAssociationMetadata::class, + OneToManyAssociationMetadata::class, + ManyToOneAssociationMetadata::class, + ManyToManyAssociationMetadata::class, + ]; - if (isset($field['length'])) { - $fieldXml->addAttribute('length', $field['length']); - } - if (isset($field['precision'])) { - $fieldXml->addAttribute('precision', $field['precision']); - } - if (isset($field['scale'])) { - $fieldXml->addAttribute('scale', $field['scale']); - } + uasort($properties, function($m1, $m2) use (&$orderMap) { + $a1 = array_search(get_class($m1), $orderMap); + $a2 = array_search(get_class($m2), $orderMap); - if (isset($field['unique']) && $field['unique']) { - $fieldXml->addAttribute('unique', $field['unique'] ? 'true' : 'false'); - } + return strcmp((string) $a1, (string) $a2); + }); - if (isset($field['options'])) { - $optionsXml = $fieldXml->addChild('options'); - foreach ($field['options'] as $key => $value) { - $optionXml = $optionsXml->addChild('option', $value); - $optionXml->addAttribute('name', $key); - } - } + foreach ($properties as $property) { + if ($property instanceof FieldMetadata) { + $this->exportFieldMetadata($root, $metadata, $property); + } else if ($property instanceof AssociationMetadata) { + $this->exportAssociationMetadata($root, $metadata, $property); + } + } - if (isset($field['version'])) { - $fieldXml->addAttribute('version', $field['version']); - } + if (isset($metadata->lifecycleCallbacks) && count($metadata->lifecycleCallbacks)>0) { + $lifecycleCallbacksXml = $root->addChild('lifecycle-callbacks'); - if (isset($field['columnDefinition'])) { - $fieldXml->addAttribute('column-definition', $field['columnDefinition']); - } + foreach ($metadata->lifecycleCallbacks as $name => $methods) { + foreach ($methods as $method) { + $lifecycleCallbackXml = $lifecycleCallbacksXml->addChild('lifecycle-callback'); - if (isset($field['nullable'])) { - $fieldXml->addAttribute('nullable', $field['nullable'] ? 'true' : 'false'); + $lifecycleCallbackXml->addAttribute('type', $name); + $lifecycleCallbackXml->addAttribute('method', $method); } } } - $orderMap = [ - ClassMetadataInfo::ONE_TO_ONE, - ClassMetadataInfo::ONE_TO_MANY, - ClassMetadataInfo::MANY_TO_ONE, - ClassMetadataInfo::MANY_TO_MANY, - ]; + return $this->asXml($xml); + } - uasort($metadata->associationMappings, function($m1, $m2) use (&$orderMap){ - $a1 = array_search($m1['type'], $orderMap); - $a2 = array_search($m2['type'], $orderMap); + /** + * @param \SimpleXMLElement $root + * @param ClassMetadata $metadata + * @param FieldMetadata $property + */ + private function exportFieldMetadata( + \SimpleXMLElement $root, + ClassMetadata $metadata, + FieldMetadata $property + ) + { + $fieldXml = $root->addChild('field'); - return strcmp($a1, $a2); - }); + $fieldXml->addAttribute('name', $property->getName()); + $fieldXml->addAttribute('type', $property->getTypeName()); + $fieldXml->addAttribute('column', $property->getColumnName()); - foreach ($metadata->associationMappings as $associationMapping) { - $associationMappingXml = null; - if ($associationMapping['type'] == ClassMetadataInfo::ONE_TO_ONE) { - $associationMappingXml = $root->addChild('one-to-one'); - } elseif ($associationMapping['type'] == ClassMetadataInfo::MANY_TO_ONE) { - $associationMappingXml = $root->addChild('many-to-one'); - } elseif ($associationMapping['type'] == ClassMetadataInfo::ONE_TO_MANY) { - $associationMappingXml = $root->addChild('one-to-many'); - } elseif ($associationMapping['type'] == ClassMetadataInfo::MANY_TO_MANY) { - $associationMappingXml = $root->addChild('many-to-many'); - } + if ($property->isNullable()) { + $fieldXml->addAttribute('nullable', 'true'); + } - $associationMappingXml->addAttribute('field', $associationMapping['fieldName']); - $associationMappingXml->addAttribute('target-entity', $associationMapping['targetEntity']); + if ($property->isUnique()) { + $fieldXml->addAttribute('unique', 'true'); + } - if (isset($associationMapping['mappedBy'])) { - $associationMappingXml->addAttribute('mapped-by', $associationMapping['mappedBy']); - } + if (is_int($property->getLength())) { + $fieldXml->addAttribute('length', (string) $property->getLength()); + } - if (isset($associationMapping['inversedBy'])) { - $associationMappingXml->addAttribute('inversed-by', $associationMapping['inversedBy']); - } + if (is_int($property->getPrecision())) { + $fieldXml->addAttribute('precision', (string) $property->getPrecision()); + } - if (isset($associationMapping['indexBy'])) { - $associationMappingXml->addAttribute('index-by', $associationMapping['indexBy']); - } + if (is_int($property->getScale())) { + $fieldXml->addAttribute('scale', (string) $property->getScale()); + } - if (isset($associationMapping['orphanRemoval']) && $associationMapping['orphanRemoval'] !== false) { - $associationMappingXml->addAttribute('orphan-removal', 'true'); - } + if ($metadata->isVersioned() && $metadata->versionProperty->getName() === $property->getName()) { + $fieldXml->addAttribute('version', 'true'); + } - if (isset($associationMapping['fetch'])) { - $associationMappingXml->addAttribute('fetch', $this->_getFetchModeString($associationMapping['fetch'])); - } + if ($property->getColumnDefinition()) { + $fieldXml->addAttribute('column-definition', $property->getColumnDefinition()); + } - $cascade = []; - if ($associationMapping['isCascadeRemove']) { - $cascade[] = 'cascade-remove'; - } + if ($property->getOptions()) { + $optionsXml = $fieldXml->addChild('options'); - if ($associationMapping['isCascadePersist']) { - $cascade[] = 'cascade-persist'; - } + foreach ($property->getOptions() as $key => $value) { + $optionXml = $optionsXml->addChild('option', (string) $value); - if ($associationMapping['isCascadeRefresh']) { - $cascade[] = 'cascade-refresh'; + $optionXml->addAttribute('name', $key); } + } + } - if ($associationMapping['isCascadeMerge']) { - $cascade[] = 'cascade-merge'; - } + /** + * @param \SimpleXMLElement $root + * @param ClassMetadata $metadata + * @param AssociationMetadata $association + */ + private function exportAssociationMetadata( + \SimpleXMLElement $root, + ClassMetadata $metadata, + AssociationMetadata $association + ) { + if ($association instanceof OneToOneAssociationMetadata) { + $associationMappingXml = $root->addChild('one-to-one'); + } elseif ($association instanceof OneToManyAssociationMetadata) { + $associationMappingXml = $root->addChild('one-to-many'); + } elseif ($association instanceof ManyToOneAssociationMetadata) { + $associationMappingXml = $root->addChild('many-to-one'); + } else { + $associationMappingXml = $root->addChild('many-to-many'); + } - if ($associationMapping['isCascadeDetach']) { - $cascade[] = 'cascade-detach'; + $associationMappingXml->addAttribute('field', $association->getName()); + $associationMappingXml->addAttribute('target-entity', $association->getTargetEntity()); + $associationMappingXml->addAttribute('fetch', $association->getFetchMode()); + + $this->exportCascade($associationMappingXml, $association->getCascade()); + + if ($association->getMappedBy()) { + $associationMappingXml->addAttribute('mapped-by', $association->getMappedBy()); + } + + if ($association->getInversedBy()) { + $associationMappingXml->addAttribute('inversed-by', $association->getInversedBy()); + } + + if ($association->isOrphanRemoval()) { + $associationMappingXml->addAttribute('orphan-removal', 'true'); + } + + if ($association instanceof ToManyAssociationMetadata) { + if ($association instanceof ManyToManyAssociationMetadata && $association->getJoinTable()) { + $joinTableXml = $associationMappingXml->addChild('join-table'); + $joinTable = $association->getJoinTable(); + + $joinTableXml->addAttribute('name', $joinTable->getName()); + + $this->exportJoinColumns($joinTableXml, $joinTable->getJoinColumns(), 'join-columns'); + $this->exportJoinColumns($joinTableXml, $joinTable->getInverseJoinColumns(), 'inverse-join-columns'); } - if (count($cascade) === 5) { - $cascade = ['cascade-all']; + if ($association->getIndexedBy()) { + $associationMappingXml->addAttribute('index-by', $association->getIndexedBy()); } - if ($cascade) { - $cascadeXml = $associationMappingXml->addChild('cascade'); + if ($association->getOrderBy()) { + $orderByXml = $associationMappingXml->addChild('order-by'); - foreach ($cascade as $type) { - $cascadeXml->addChild($type); + foreach ($association->getOrderBy() as $name => $direction) { + $orderByFieldXml = $orderByXml->addChild('order-by-field'); + + $orderByFieldXml->addAttribute('name', $name); + $orderByFieldXml->addAttribute('direction', $direction); } } + } - if (isset($associationMapping['joinTable']) && $associationMapping['joinTable']) { - $joinTableXml = $associationMappingXml->addChild('join-table'); - $joinTableXml->addAttribute('name', $associationMapping['joinTable']['name']); - $joinColumnsXml = $joinTableXml->addChild('join-columns'); - - foreach ($associationMapping['joinTable']['joinColumns'] as $joinColumn) { - $joinColumnXml = $joinColumnsXml->addChild('join-column'); - $joinColumnXml->addAttribute('name', $joinColumn['name']); - $joinColumnXml->addAttribute('referenced-column-name', $joinColumn['referencedColumnName']); + if ($association instanceof ToOneAssociationMetadata) { + if ($association->getJoinColumns()) { + $this->exportJoinColumns($associationMappingXml, $association->getJoinColumns()); + } + } + } - if (isset($joinColumn['onDelete'])) { - $joinColumnXml->addAttribute('on-delete', $joinColumn['onDelete']); - } - } + /** + * @param \SimpleXMLElement $associationXml + * @param array $joinColumns + * @param string $joinColumnsName + */ + private function exportJoinColumns( + \SimpleXMLElement $associationXml, + array $joinColumns, + $joinColumnsName = 'join-columns' + ) + { + $joinColumnsXml = $associationXml->addChild($joinColumnsName); - $inverseJoinColumnsXml = $joinTableXml->addChild('inverse-join-columns'); + foreach ($joinColumns as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $joinColumnXml = $joinColumnsXml->addChild('join-column'); - foreach ($associationMapping['joinTable']['inverseJoinColumns'] as $inverseJoinColumn) { - $inverseJoinColumnXml = $inverseJoinColumnsXml->addChild('join-column'); - $inverseJoinColumnXml->addAttribute('name', $inverseJoinColumn['name']); - $inverseJoinColumnXml->addAttribute('referenced-column-name', $inverseJoinColumn['referencedColumnName']); + $joinColumnXml->addAttribute('name', $joinColumn->getColumnName()); + $joinColumnXml->addAttribute('referenced-column-name', $joinColumn->getReferencedColumnName()); - if (isset($inverseJoinColumn['onDelete'])) { - $inverseJoinColumnXml->addAttribute('on-delete', $inverseJoinColumn['onDelete']); - } + if (! empty($joinColumn->getAliasedName())) { + $joinColumnXml->addAttribute('field-name', $joinColumn->getAliasedName()); + } - if (isset($inverseJoinColumn['columnDefinition'])) { - $inverseJoinColumnXml->addAttribute('column-definition', $inverseJoinColumn['columnDefinition']); - } + if (! empty($joinColumn->getOnDelete())) { + $joinColumnXml->addAttribute('on-delete', $joinColumn->getOnDelete()); + } - if (isset($inverseJoinColumn['nullable'])) { - $inverseJoinColumnXml->addAttribute('nullable', $inverseJoinColumn['nullable']); - } + if (! empty($joinColumn->getColumnDefinition())) { + $joinColumnXml->addAttribute('column-definition', $joinColumn->getColumnDefinition()); + } - if (isset($inverseJoinColumn['orderBy'])) { - $inverseJoinColumnXml->addAttribute('order-by', $inverseJoinColumn['orderBy']); - } - } + if ($joinColumn->isNullable()) { + $joinColumnXml->addAttribute('nullable', (string) $joinColumn->isNullable()); } - if (isset($associationMapping['joinColumns'])) { - $joinColumnsXml = $associationMappingXml->addChild('join-columns'); - foreach ($associationMapping['joinColumns'] as $joinColumn) { - $joinColumnXml = $joinColumnsXml->addChild('join-column'); - $joinColumnXml->addAttribute('name', $joinColumn['name']); - $joinColumnXml->addAttribute('referenced-column-name', $joinColumn['referencedColumnName']); + if ($joinColumn->isUnique()) { + $joinColumnXml->addAttribute('unique', (string) $joinColumn->isUnique()); + } - if (isset($joinColumn['onDelete'])) { - $joinColumnXml->addAttribute('on-delete', $joinColumn['onDelete']); - } + if ($joinColumn->getOptions()) { + $optionsXml = $joinColumnXml->addChild('options'); - if (isset($joinColumn['columnDefinition'])) { - $joinColumnXml->addAttribute('column-definition', $joinColumn['columnDefinition']); - } + foreach ($joinColumn->getOptions() as $key => $value) { + $optionXml = $optionsXml->addChild('option', (string) $value); - if (isset($joinColumn['nullable'])) { - $joinColumnXml->addAttribute('nullable', $joinColumn['nullable']); - } + $optionXml->addAttribute('name', $key); } } - if (isset($associationMapping['orderBy'])) { - $orderByXml = $associationMappingXml->addChild('order-by'); + } + } - foreach ($associationMapping['orderBy'] as $name => $direction) { - $orderByFieldXml = $orderByXml->addChild('order-by-field'); - $orderByFieldXml->addAttribute('name', $name); - $orderByFieldXml->addAttribute('direction', $direction); - } + /** + * @param \SimpleXMLElement $associationXml + * @param array $associationCascades + */ + private function exportCascade(\SimpleXMLElement $associationXml, array $associationCascades) + { + $cascades = []; + + foreach (['persist', 'remove', 'refresh'] as $type) { + if (in_array($type, $associationCascades)) { + $cascades[] = 'cascade-' . $type; } } - if (isset($metadata->lifecycleCallbacks) && count($metadata->lifecycleCallbacks)>0) { - $lifecycleCallbacksXml = $root->addChild('lifecycle-callbacks'); + if (count($cascades) === 5) { + $cascades = ['cascade-all']; + } - foreach ($metadata->lifecycleCallbacks as $name => $methods) { - foreach ($methods as $method) { - $lifecycleCallbackXml = $lifecycleCallbacksXml->addChild('lifecycle-callback'); - $lifecycleCallbackXml->addAttribute('type', $name); - $lifecycleCallbackXml->addAttribute('method', $method); - } + if ($cascades) { + $cascadeXml = $associationXml->addChild('cascade'); + + foreach ($cascades as $type) { + $cascadeXml->addChild($type); } } - - return $this->_asXml($xml); } /** @@ -419,23 +474,22 @@ private function exportTableOptions(\SimpleXMLElement $parentXml, array $options * Export sequence information (if available/configured) into the current identifier XML node * * @param \SimpleXMLElement $identifierXmlNode - * @param ClassMetadataInfo $metadata + * @param FieldMetadata $metadata * * @return void */ - private function exportSequenceInformation(\SimpleXMLElement $identifierXmlNode, ClassMetadataInfo $metadata) + private function exportSequenceInformation(\SimpleXMLElement $identifierXmlNode, FieldMetadata $metadata) { - $sequenceDefinition = $metadata->sequenceGeneratorDefinition; + $sequenceDefinition = $metadata->getValueGenerator()->getDefinition(); - if (! ($metadata->generatorType === ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE && $sequenceDefinition)) { + if (! ($metadata->getValueGenerator()->getType() === GeneratorType::SEQUENCE && $sequenceDefinition)) { return; } $sequenceGeneratorXml = $identifierXmlNode->addChild('sequence-generator'); $sequenceGeneratorXml->addAttribute('sequence-name', $sequenceDefinition['sequenceName']); - $sequenceGeneratorXml->addAttribute('allocation-size', $sequenceDefinition['allocationSize']); - $sequenceGeneratorXml->addAttribute('initial-value', $sequenceDefinition['initialValue']); + $sequenceGeneratorXml->addAttribute('allocation-size', (string) $sequenceDefinition['allocationSize']); } /** @@ -443,9 +497,10 @@ private function exportSequenceInformation(\SimpleXMLElement $identifierXmlNode, * * @return string $xml */ - private function _asXml($simpleXml) + private function asXml($simpleXml) { $dom = new \DOMDocument('1.0', 'UTF-8'); + $dom->loadXML($simpleXml->asXML()); $dom->formatOutput = true; diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/YamlExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/YamlExporter.php deleted file mode 100644 index b9a38f9046f..00000000000 --- a/lib/Doctrine/ORM/Tools/Export/Driver/YamlExporter.php +++ /dev/null @@ -1,235 +0,0 @@ -. - */ - -namespace Doctrine\ORM\Tools\Export\Driver; - -use Symfony\Component\Yaml\Yaml; -use Doctrine\ORM\Mapping\ClassMetadataInfo; - -/** - * ClassMetadata exporter for Doctrine YAML mapping files. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Jonathan Wage - */ -class YamlExporter extends AbstractExporter -{ - /** - * @var string - */ - protected $_extension = '.dcm.yml'; - - /** - * {@inheritdoc} - */ - public function exportClassMetadata(ClassMetadataInfo $metadata) - { - $array = []; - - if ($metadata->isMappedSuperclass) { - $array['type'] = 'mappedSuperclass'; - } else { - $array['type'] = 'entity'; - } - - $array['table'] = $metadata->table['name']; - - if (isset($metadata->table['schema'])) { - $array['schema'] = $metadata->table['schema']; - } - - $inheritanceType = $metadata->inheritanceType; - - if ($inheritanceType !== ClassMetadataInfo::INHERITANCE_TYPE_NONE) { - $array['inheritanceType'] = $this->_getInheritanceTypeString($inheritanceType); - } - - if ($column = $metadata->discriminatorColumn) { - $array['discriminatorColumn'] = $column; - } - - if ($map = $metadata->discriminatorMap) { - $array['discriminatorMap'] = $map; - } - - if ($metadata->changeTrackingPolicy !== ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT) { - $array['changeTrackingPolicy'] = $this->_getChangeTrackingPolicyString($metadata->changeTrackingPolicy); - } - - if (isset($metadata->table['indexes'])) { - $array['indexes'] = $metadata->table['indexes']; - } - - if ($metadata->customRepositoryClassName) { - $array['repositoryClass'] = $metadata->customRepositoryClassName; - } - - if (isset($metadata->table['uniqueConstraints'])) { - $array['uniqueConstraints'] = $metadata->table['uniqueConstraints']; - } - - if (isset($metadata->table['options'])) { - $array['options'] = $metadata->table['options']; - } - - $fieldMappings = $metadata->fieldMappings; - - $ids = []; - foreach ($fieldMappings as $name => $fieldMapping) { - $fieldMapping['column'] = $fieldMapping['columnName']; - - unset($fieldMapping['columnName'], $fieldMapping['fieldName']); - - if ($fieldMapping['column'] == $name) { - unset($fieldMapping['column']); - } - - if (isset($fieldMapping['id']) && $fieldMapping['id']) { - $ids[$name] = $fieldMapping; - unset($fieldMappings[$name]); - continue; - } - - $fieldMappings[$name] = $fieldMapping; - } - - if ( ! $metadata->isIdentifierComposite && $idGeneratorType = $this->_getIdGeneratorTypeString($metadata->generatorType)) { - $ids[$metadata->getSingleIdentifierFieldName()]['generator']['strategy'] = $idGeneratorType; - } - - $array['id'] = $ids; - - if ($fieldMappings) { - if ( ! isset($array['fields'])) { - $array['fields'] = []; - } - $array['fields'] = array_merge($array['fields'], $fieldMappings); - } - - foreach ($metadata->associationMappings as $name => $associationMapping) { - $cascade = []; - - if ($associationMapping['isCascadeRemove']) { - $cascade[] = 'remove'; - } - - if ($associationMapping['isCascadePersist']) { - $cascade[] = 'persist'; - } - - if ($associationMapping['isCascadeRefresh']) { - $cascade[] = 'refresh'; - } - - if ($associationMapping['isCascadeMerge']) { - $cascade[] = 'merge'; - } - - if ($associationMapping['isCascadeDetach']) { - $cascade[] = 'detach'; - } - if (count($cascade) === 5) { - $cascade = ['all']; - } - - $associationMappingArray = [ - 'targetEntity' => $associationMapping['targetEntity'], - 'cascade' => $cascade, - ]; - - if (isset($associationMapping['fetch'])) { - $associationMappingArray['fetch'] = $this->_getFetchModeString($associationMapping['fetch']); - } - - if (isset($mapping['id']) && $mapping['id'] === true) { - $array['id'][$name]['associationKey'] = true; - } - - if ($associationMapping['type'] & ClassMetadataInfo::TO_ONE) { - $joinColumns = $associationMapping['isOwningSide'] ? $associationMapping['joinColumns'] : []; - $newJoinColumns = []; - - foreach ($joinColumns as $joinColumn) { - $newJoinColumns[$joinColumn['name']]['referencedColumnName'] = $joinColumn['referencedColumnName']; - - if (isset($joinColumn['onDelete'])) { - $newJoinColumns[$joinColumn['name']]['onDelete'] = $joinColumn['onDelete']; - } - } - - $oneToOneMappingArray = [ - 'mappedBy' => $associationMapping['mappedBy'], - 'inversedBy' => $associationMapping['inversedBy'], - 'joinColumns' => $newJoinColumns, - 'orphanRemoval' => $associationMapping['orphanRemoval'], - ]; - - $associationMappingArray = array_merge($associationMappingArray, $oneToOneMappingArray); - - if ($associationMapping['type'] & ClassMetadataInfo::ONE_TO_ONE) { - $array['oneToOne'][$name] = $associationMappingArray; - } else { - $array['manyToOne'][$name] = $associationMappingArray; - } - } elseif ($associationMapping['type'] == ClassMetadataInfo::ONE_TO_MANY) { - $oneToManyMappingArray = [ - 'mappedBy' => $associationMapping['mappedBy'], - 'inversedBy' => $associationMapping['inversedBy'], - 'orphanRemoval' => $associationMapping['orphanRemoval'], - 'orderBy' => isset($associationMapping['orderBy']) ? $associationMapping['orderBy'] : null - ]; - - $associationMappingArray = array_merge($associationMappingArray, $oneToManyMappingArray); - $array['oneToMany'][$name] = $associationMappingArray; - } elseif ($associationMapping['type'] == ClassMetadataInfo::MANY_TO_MANY) { - $manyToManyMappingArray = [ - 'mappedBy' => $associationMapping['mappedBy'], - 'inversedBy' => $associationMapping['inversedBy'], - 'joinTable' => isset($associationMapping['joinTable']) ? $associationMapping['joinTable'] : null, - 'orderBy' => isset($associationMapping['orderBy']) ? $associationMapping['orderBy'] : null - ]; - - $associationMappingArray = array_merge($associationMappingArray, $manyToManyMappingArray); - $array['manyToMany'][$name] = $associationMappingArray; - } - } - if (isset($metadata->lifecycleCallbacks)) { - $array['lifecycleCallbacks'] = $metadata->lifecycleCallbacks; - } - - return $this->yamlDump([$metadata->name => $array], 10); - } - - /** - * Dumps a PHP array to a YAML string. - * - * The yamlDump method, when supplied with an array, will do its best - * to convert the array into friendly YAML. - * - * @param array $array PHP array - * @param integer $inline [optional] The level where you switch to inline YAML - * - * @return string A YAML string representing the original PHP array - */ - protected function yamlDump($array, $inline = 2) - { - return Yaml::dump($array, $inline); - } -} diff --git a/lib/Doctrine/ORM/Tools/Export/ExportException.php b/lib/Doctrine/ORM/Tools/Export/ExportException.php index 853159f17de..0ffecef51ad 100644 --- a/lib/Doctrine/ORM/Tools/Export/ExportException.php +++ b/lib/Doctrine/ORM/Tools/Export/ExportException.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Export; diff --git a/lib/Doctrine/ORM/Tools/Pagination/CountOutputWalker.php b/lib/Doctrine/ORM/Tools/Pagination/CountOutputWalker.php index f3db053ca29..520df68d78d 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/CountOutputWalker.php +++ b/lib/Doctrine/ORM/Tools/Pagination/CountOutputWalker.php @@ -1,24 +1,11 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Pagination; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\FieldMetadata; use Doctrine\ORM\Query\SqlWalker; use Doctrine\ORM\Query\AST\SelectStatement; @@ -117,21 +104,22 @@ public function walkSelectStatement(SelectStatement $AST) // For every identifier, find out the SQL alias by combing through the ResultSetMapping $sqlIdentifier = []; - foreach ($rootIdentifier as $property) { - if (isset($rootClass->fieldMappings[$property])) { - foreach (array_keys($this->rsm->fieldMappings, $property) as $alias) { + foreach ($rootIdentifier as $identifier) { + $property = $rootClass->getProperty($identifier); + + if ($property instanceof FieldMetadata) { + foreach (array_keys($this->rsm->fieldMappings, $identifier) as $alias) { if ($this->rsm->columnOwnerMap[$alias] == $rootAlias) { - $sqlIdentifier[$property] = $alias; + $sqlIdentifier[$identifier] = $alias; } } - } - - if (isset($rootClass->associationMappings[$property])) { - $joinColumn = $rootClass->associationMappings[$property]['joinColumns'][0]['name']; + } else if ($property instanceof AssociationMetadata) { + $joinColumns = $property->getJoinColumns(); + $joinColumn = reset($joinColumns); - foreach (array_keys($this->rsm->metaMappings, $joinColumn) as $alias) { - if ($this->rsm->columnOwnerMap[$alias] == $rootAlias) { - $sqlIdentifier[$property] = $alias; + foreach (array_keys($this->rsm->metaMappings, $joinColumn->getColumnName()) as $alias) { + if ($this->rsm->columnOwnerMap[$alias] === $rootAlias) { + $sqlIdentifier[$identifier] = $alias; } } } diff --git a/lib/Doctrine/ORM/Tools/Pagination/CountWalker.php b/lib/Doctrine/ORM/Tools/Pagination/CountWalker.php index a8f26001aba..23ded204973 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/CountWalker.php +++ b/lib/Doctrine/ORM/Tools/Pagination/CountWalker.php @@ -1,24 +1,12 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Pagination; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\FieldMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; use Doctrine\ORM\Query\TreeWalkerAdapter; use Doctrine\ORM\Query\AST\SelectStatement; use Doctrine\ORM\Query\AST\SelectExpression; @@ -56,7 +44,7 @@ public function walkSelectStatement(SelectStatement $AST) throw new \RuntimeException('Cannot count query that uses a HAVING clause. Use the output walkers for pagination'); } - $queryComponents = $this->_getQueryComponents(); + $queryComponents = $this->getQueryComponents(); // Get the root entity and alias from the AST fromClause $from = $AST->fromClause->identificationVariableDeclarations; @@ -64,23 +52,29 @@ public function walkSelectStatement(SelectStatement $AST) throw new \RuntimeException("Cannot count query which selects two FROM components, cannot make distinction"); } - $fromRoot = reset($from); - $rootAlias = $fromRoot->rangeVariableDeclaration->aliasIdentificationVariable; - $rootClass = $queryComponents[$rootAlias]['metadata']; - $identifierFieldName = $rootClass->getSingleIdentifierFieldName(); + $fromRoot = reset($from); + $rootAlias = $fromRoot->rangeVariableDeclaration->aliasIdentificationVariable; + $rootClass = $queryComponents[$rootAlias]['metadata']; + $property = $rootClass->getProperty($rootClass->getSingleIdentifierFieldName()); + $pathType = PathExpression::TYPE_STATE_FIELD; - $pathType = PathExpression::TYPE_STATE_FIELD; - if (isset($rootClass->associationMappings[$identifierFieldName])) { - $pathType = PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION; + if ($property instanceof AssociationMetadata) { + $pathType = $property instanceof ToOneAssociationMetadata + ? PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION + : PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION + ; } $pathExpression = new PathExpression( - PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, $rootAlias, - $identifierFieldName + PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, + $rootAlias, + $property->getName() ); + $pathExpression->type = $pathType; - $distinct = $this->_getQuery()->getHint(self::HINT_DISTINCT); + $distinct = $this->getQuery()->getHint(self::HINT_DISTINCT); + $AST->selectClause->selectExpressions = [ new SelectExpression( new AggregateExpression('count', $pathExpression, $distinct), null diff --git a/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryOutputWalker.php b/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryOutputWalker.php index 034b33b2c16..768c92e1abc 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryOutputWalker.php +++ b/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryOutputWalker.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Pagination; @@ -24,6 +9,9 @@ use Doctrine\DBAL\Platforms\PostgreSqlPlatform; use Doctrine\DBAL\Platforms\SQLAnywherePlatform; use Doctrine\DBAL\Platforms\SQLServerPlatform; +use Doctrine\DBAL\Types\Type; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\FieldMetadata; use Doctrine\ORM\Query\AST\OrderByClause; use Doctrine\ORM\Query\AST\PartialObjectExpression; use Doctrine\ORM\Query\AST\SelectExpression; @@ -71,17 +59,10 @@ class LimitSubqueryOutputWalker extends SqlWalker private $maxResults; /** - * @var \Doctrine\ORM\EntityManager + * @var \Doctrine\ORM\EntityManagerInterface */ private $em; - /** - * The quote strategy. - * - * @var \Doctrine\ORM\Mapping\QuoteStrategy - */ - private $quoteStrategy; - /** * @var array */ @@ -106,17 +87,20 @@ class LimitSubqueryOutputWalker extends SqlWalker */ public function __construct($query, $parserResult, array $queryComponents) { - $this->platform = $query->getEntityManager()->getConnection()->getDatabasePlatform(); - $this->rsm = $parserResult->getResultSetMapping(); + $this->platform = $query->getEntityManager()->getConnection()->getDatabasePlatform(); + $this->rsm = $parserResult->getResultSetMapping(); $this->queryComponents = $queryComponents; // Reset limit and offset $this->firstResult = $query->getFirstResult(); - $this->maxResults = $query->getMaxResults(); - $query->setFirstResult(null)->setMaxResults(null); + $this->maxResults = $query->getMaxResults(); + + $query + ->setFirstResult(null) + ->setMaxResults(null) + ; - $this->em = $query->getEntityManager(); - $this->quoteStrategy = $this->em->getConfiguration()->getQuoteStrategy(); + $this->em = $query->getEntityManager(); parent::__construct($query, $parserResult, $queryComponents); } @@ -158,7 +142,9 @@ private function rebuildOrderByForRowNumber(SelectStatement $AST) $orderByItem->expression = $selectAliasToExpressionMap[$orderByItem->expression]; } } + $func = new RowNumberOverFunction('dctrn_rownum'); + $func->orderByClause = $AST->orderByClause; $AST->selectClause->selectExpressions[] = new SelectExpression($func, 'dctrn_rownum', true); @@ -180,6 +166,7 @@ public function walkSelectStatement(SelectStatement $AST) if ($this->platformSupportsRowNumber()) { return $this->walkSelectStatementWithRowNumber($AST); } + return $this->walkSelectStatementWithoutRowNumber($AST); } @@ -198,44 +185,44 @@ public function walkSelectStatementWithRowNumber(SelectStatement $AST) $hasOrderBy = false; $outerOrderBy = ' ORDER BY dctrn_minrownum ASC'; $orderGroupBy = ''; + if ($AST->orderByClause instanceof OrderByClause) { $hasOrderBy = true; + $this->rebuildOrderByForRowNumber($AST); } - $innerSql = $this->getInnerSQL($AST); - - $sqlIdentifier = $this->getSQLIdentifier($AST); + $innerSql = $this->getInnerSQL($AST); + $sqlIdentifier = $this->getSQLIdentifier($AST); + $sqlAliasIdentifier = array_map(function ($info) { return $info['alias']; }, $sqlIdentifier); if ($hasOrderBy) { - $orderGroupBy = ' GROUP BY ' . implode(', ', $sqlIdentifier); - $sqlIdentifier[] = 'MIN(' . $this->walkResultVariable('dctrn_rownum') . ') AS dctrn_minrownum'; + $orderGroupBy = ' GROUP BY ' . implode(', ', $sqlAliasIdentifier); + $sqlPiece = 'MIN(' . $this->walkResultVariable('dctrn_rownum') . ') AS dctrn_minrownum'; + + $sqlAliasIdentifier[] = $sqlPiece; + $sqlIdentifier[] = [ + 'alias' => $sqlPiece, + 'type' => Type::getType('integer'), + ]; } // Build the counter query - $sql = sprintf( - 'SELECT DISTINCT %s FROM (%s) dctrn_result', - implode(', ', $sqlIdentifier), - $innerSql - ); + $sql = sprintf('SELECT DISTINCT %s FROM (%s) dctrn_result', implode(', ', $sqlAliasIdentifier), $innerSql); if ($hasOrderBy) { $sql .= $orderGroupBy . $outerOrderBy; } // Apply the limit and offset. - $sql = $this->platform->modifyLimitQuery( - $sql, - $this->maxResults, - $this->firstResult - ); + $sql = $this->platform->modifyLimitQuery($sql, $this->maxResults, $this->firstResult); // Add the columns to the ResultSetMapping. It's not really nice but // it works. Preferably I'd clear the RSM or simply create a new one // but that is not possible from inside the output walker, so we dirty // up the one we have. - foreach ($sqlIdentifier as $property => $alias) { - $this->rsm->addScalarResult($alias, $property); + foreach ($sqlIdentifier as $property => $propertyMapping) { + $this->rsm->addScalarResult($propertyMapping['alias'], $property, $propertyMapping['type']); } return $sql; @@ -267,16 +254,15 @@ public function walkSelectStatementWithoutRowNumber(SelectStatement $AST, $addMi $orderByClause = $AST->orderByClause; $AST->orderByClause = null; - $innerSql = $this->getInnerSQL($AST); - - $sqlIdentifier = $this->getSQLIdentifier($AST); + $innerSql = $this->getInnerSQL($AST); + $sqlIdentifier = $this->getSQLIdentifier($AST); + $sqlAliasIdentifier = array_map(function ($info) { return $info['alias']; }, $sqlIdentifier); // Build the counter query - $sql = sprintf('SELECT DISTINCT %s FROM (%s) dctrn_result', - implode(', ', $sqlIdentifier), $innerSql); + $sql = sprintf('SELECT DISTINCT %s FROM (%s) dctrn_result', implode(', ', $sqlAliasIdentifier), $innerSql); // http://www.doctrine-project.org/jira/browse/DDC-1958 - $sql = $this->preserveSqlOrdering($sqlIdentifier, $innerSql, $sql, $orderByClause); + $sql = $this->preserveSqlOrdering($sqlAliasIdentifier, $innerSql, $sql, $orderByClause); // Apply the limit and offset. $sql = $this->platform->modifyLimitQuery( @@ -287,8 +273,8 @@ public function walkSelectStatementWithoutRowNumber(SelectStatement $AST, $addMi // it works. Preferably I'd clear the RSM or simply create a new one // but that is not possible from inside the output walker, so we dirty // up the one we have. - foreach ($sqlIdentifier as $property => $alias) { - $this->rsm->addScalarResult($alias, $property); + foreach ($sqlIdentifier as $property => $propertyMapping) { + $this->rsm->addScalarResult($propertyMapping['alias'], $property, $propertyMapping['type']); } // Restore orderByClause @@ -320,12 +306,15 @@ private function addMissingItemsFromOrderByToSelect(SelectStatement $AST) // Get a map of referenced identifiers to field names. $selects = []; + foreach ($orderByPathExpressions as $pathExpression) { $idVar = $pathExpression->identificationVariable; $field = $pathExpression->field; - if (!isset($selects[$idVar])) { + + if ( ! isset($selects[$idVar])) { $selects[$idVar] = []; } + $selects[$idVar][$field] = true; } @@ -334,10 +323,13 @@ private function addMissingItemsFromOrderByToSelect(SelectStatement $AST) foreach ($AST->selectClause->selectExpressions as $selectExpression) { if ($selectExpression instanceof SelectExpression) { $idVar = $selectExpression->expression; - if (!is_string($idVar)) { + + if ( ! is_string($idVar)) { continue; } + $field = $selectExpression->fieldIdentificationVariable; + if ($field === null) { // No need to add this select, as we're already fetching the whole object. unset($selects[$idVar]); @@ -349,7 +341,9 @@ private function addMissingItemsFromOrderByToSelect(SelectStatement $AST) // Add select items which were not excluded to the AST's select clause. foreach ($selects as $idVar => $fields) { - $AST->selectClause->selectExpressions[] = new SelectExpression(new PartialObjectExpression($idVar, array_keys($fields)), null, true); + $selectExpression = new SelectExpression(new PartialObjectExpression($idVar, array_keys($fields)), null, true); + + $AST->selectClause->selectExpressions[] = $selectExpression; } } @@ -430,48 +424,25 @@ private function recreateInnerSql( */ private function generateSqlAliasReplacements() : array { - $aliasMap = $searchPatterns = $replacements = $metadataList = []; - - // Generate DQL alias -> SQL table alias mapping - foreach (\array_keys($this->rsm->aliasMap) as $dqlAlias) { - $metadataList[$dqlAlias] = $class = $this->queryComponents[$dqlAlias]['metadata']; - $aliasMap[$dqlAlias] = $this->getSQLTableAlias($class->getTableName(), $dqlAlias); - } + $platform = $this->em->getConnection()->getDatabasePlatform(); + $searchPatterns = $replacements = []; // Generate search patterns for each field's path expression in the order by clause foreach ($this->rsm->fieldMappings as $fieldAlias => $fieldName) { $dqlAliasForFieldAlias = $this->rsm->columnOwnerMap[$fieldAlias]; - $class = $metadataList[$dqlAliasForFieldAlias]; + $class = $this->queryComponents[$dqlAliasForFieldAlias]['metadata']; // If the field is from a joined child table, we won't be ordering on it. - if (! isset($class->fieldMappings[$fieldName])) { + if (($property = $class->getProperty($fieldName)) === null) { continue; } - $fieldMapping = $class->fieldMappings[$fieldName]; - - // Get the proper column name as will appear in the select list - $columnName = $this->quoteStrategy->getColumnName( - $fieldName, - $metadataList[$dqlAliasForFieldAlias], - $this->em->getConnection()->getDatabasePlatform() - ); - - // Get the SQL table alias for the entity and field - $sqlTableAliasForFieldAlias = $aliasMap[$dqlAliasForFieldAlias]; - - if (isset($fieldMapping['declared']) && $fieldMapping['declared'] !== $class->name) { - // Field was declared in a parent class, so we need to get the proper SQL table alias - // for the joined parent table. - $otherClassMetadata = $this->em->getClassMetadata($fieldMapping['declared']); - - if (! $otherClassMetadata->isMappedSuperclass) { - $sqlTableAliasForFieldAlias = $this->getSQLTableAlias($otherClassMetadata->getTableName(), $dqlAliasForFieldAlias); - } - } + // Get the SQL table alias for the entity and field and the column name as will appear in the select list + $tableAlias = $this->getSQLTableAlias($property->getTableName(), $dqlAliasForFieldAlias); + $columnName = $platform->quoteIdentifier($property->getColumnName()); // Compose search and replace patterns - $searchPatterns[] = \sprintf(self::ORDER_BY_PATH_EXPRESSION, $sqlTableAliasForFieldAlias, $columnName); + $searchPatterns[] = \sprintf(self::ORDER_BY_PATH_EXPRESSION, $tableAlias, $columnName); $replacements[] = $fieldAlias; } @@ -532,6 +503,7 @@ private function getSQLIdentifier(SelectStatement $AST) // Get the root entity and alias from the AST fromClause. $from = $AST->fromClause->identificationVariableDeclarations; + if (count($from) !== 1) { throw new \RuntimeException('Cannot count query which selects two FROM components, cannot make distinction'); } @@ -543,21 +515,29 @@ private function getSQLIdentifier(SelectStatement $AST) // For every identifier, find out the SQL alias by combing through the ResultSetMapping $sqlIdentifier = []; - foreach ($rootIdentifier as $property) { - if (isset($rootClass->fieldMappings[$property])) { - foreach (array_keys($this->rsm->fieldMappings, $property) as $alias) { - if ($this->rsm->columnOwnerMap[$alias] == $rootAlias) { - $sqlIdentifier[$property] = $alias; - } - } - } - if (isset($rootClass->associationMappings[$property])) { - $joinColumn = $rootClass->associationMappings[$property]['joinColumns'][0]['name']; + foreach ($rootIdentifier as $identifier) { + $property = $rootClass->getProperty($identifier); - foreach (array_keys($this->rsm->metaMappings, $joinColumn) as $alias) { - if ($this->rsm->columnOwnerMap[$alias] == $rootAlias) { - $sqlIdentifier[$property] = $alias; + if ($property instanceof FieldMetadata) { + foreach (array_keys($this->rsm->fieldMappings, $identifier) as $alias) { + if ($this->rsm->columnOwnerMap[$alias] === $rootAlias) { + $sqlIdentifier[$identifier] = [ + 'type' => $property->getType(), + 'alias' => $alias, + ]; + } + } + } else if ($property instanceof AssociationMetadata) { + $joinColumns = $property->getJoinColumns(); + $joinColumn = reset($joinColumns); + + foreach (array_keys($this->rsm->metaMappings, $joinColumn->getColumnName()) as $alias) { + if ($this->rsm->columnOwnerMap[$alias] === $rootAlias) { + $sqlIdentifier[$identifier] = [ + 'type' => $this->rsm->typeMappings[$alias], + 'alias' => $alias, + ]; } } } diff --git a/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryWalker.php b/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryWalker.php index 1874eb88dde..82b47029fa2 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryWalker.php +++ b/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryWalker.php @@ -1,26 +1,13 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Pagination; use Doctrine\DBAL\Types\Type; -use Doctrine\ORM\Mapping\ClassMetadataInfo; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\ToManyAssociationMetadata; use Doctrine\ORM\Query; use Doctrine\ORM\Query\TreeWalkerAdapter; use Doctrine\ORM\Query\AST\Functions\IdentityFunction; @@ -49,7 +36,7 @@ class LimitSubqueryWalker extends TreeWalkerAdapter * * @var int */ - private $_aliasCounter = 0; + private $aliasCounter = 0; /** * Walks down a SelectStatement AST node, modifying it to retrieve DISTINCT ids @@ -63,7 +50,7 @@ class LimitSubqueryWalker extends TreeWalkerAdapter */ public function walkSelectStatement(SelectStatement $AST) { - $queryComponents = $this->_getQueryComponents(); + $queryComponents = $this->getQueryComponents(); // Get the root entity and alias from the AST fromClause $from = $AST->fromClause->identificationVariableDeclarations; $fromRoot = reset($from); @@ -81,21 +68,21 @@ public function walkSelectStatement(SelectStatement $AST) } } - $identifier = $rootClass->getSingleIdentifierFieldName(); + $property = $rootClass->getProperty($rootClass->getSingleIdentifierFieldName()); - if (isset($rootClass->associationMappings[$identifier])) { - throw new \RuntimeException("Paginating an entity with foreign key as identifier only works when using the Output Walkers. Call Paginator#setUseOutputWalkers(true) before iterating the paginator."); + if ($property instanceof AssociationMetadata) { + throw new \RuntimeException( + "Paginating an entity with foreign key as identifier only works when using the Output Walkers. " . + "Call Paginator#setUseOutputWalkers(true) before iterating the paginator." + ); } - $this->_getQuery()->setHint( - self::IDENTIFIER_TYPE, - Type::getType($rootClass->fieldMappings[$identifier]['type']) - ); + $this->getQuery()->setHint(self::IDENTIFIER_TYPE, $property->getType()); $pathExpression = new PathExpression( PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, $rootAlias, - $identifier + $property->getName() ); $pathExpression->type = PathExpression::TYPE_STATE_FIELD; @@ -112,7 +99,7 @@ public function walkSelectStatement(SelectStatement $AST) $AST->selectClause->selectExpressions[] = new SelectExpression( $this->createSelectExpressionItem($item->expression), - '_dctrn_ord' . $this->_aliasCounter++ + '_dctrn_ord' . $this->aliasCounter++ ); } } @@ -131,24 +118,24 @@ private function validate(SelectStatement $AST) // a limit, a fetched to-many join, and an order by condition that // references a column from the fetch joined table. $queryComponents = $this->getQueryComponents(); - $query = $this->_getQuery(); + $query = $this->getQuery(); $from = $AST->fromClause->identificationVariableDeclarations; $fromRoot = reset($from); - if ($query instanceof Query - && $query->getMaxResults() - && $AST->orderByClause - && count($fromRoot->joins)) { + if ($query instanceof Query && $query->getMaxResults() && $AST->orderByClause && count($fromRoot->joins)) { // Check each orderby item. // TODO: check complex orderby items too... foreach ($AST->orderByClause->orderByItems as $orderByItem) { $expression = $orderByItem->expression; - if ($orderByItem->expression instanceof PathExpression - && isset($queryComponents[$expression->identificationVariable])) { + + if ($expression instanceof PathExpression && isset($queryComponents[$expression->identificationVariable])) { $queryComponent = $queryComponents[$expression->identificationVariable]; - if (isset($queryComponent['parent']) - && $queryComponent['relation']['type'] & ClassMetadataInfo::TO_MANY) { - throw new \RuntimeException("Cannot select distinct identifiers from query with LIMIT and ORDER BY on a column from a fetch joined to-many association. Use output walkers."); + + if (isset($queryComponent['parent']) && $queryComponent['relation'] instanceof ToManyAssociationMetadata) { + throw new \RuntimeException( + "Cannot select distinct identifiers from query with LIMIT and ORDER BY on a column from a " + . "fetch joined to-many association. Use output walkers." + ); } } } diff --git a/lib/Doctrine/ORM/Tools/Pagination/Paginator.php b/lib/Doctrine/ORM/Tools/Pagination/Paginator.php index 250df071f92..4f37eed6643 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/Paginator.php +++ b/lib/Doctrine/ORM/Tools/Pagination/Paginator.php @@ -1,29 +1,15 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Pagination; -use Doctrine\ORM\Query\Parser; -use Doctrine\ORM\QueryBuilder; +use Doctrine\DBAL\Types\Type; +use Doctrine\ORM\NoResultException; use Doctrine\ORM\Query; +use Doctrine\ORM\Query\Parser; use Doctrine\ORM\Query\ResultSetMapping; -use Doctrine\ORM\NoResultException; +use Doctrine\ORM\QueryBuilder; /** * The paginator can handle various complex scenarios with DQL. @@ -152,12 +138,14 @@ public function getIterator() $ids = array_map('current', $subQuery->getScalarResult()); $whereInQuery = $this->cloneQuery($this->query); + // don't do this for an empty id array if (count($ids) === 0) { return new \ArrayIterator([]); } $this->appendTreeWalker($whereInQuery, WhereInWalker::class); + $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, count($ids)); $whereInQuery->setFirstResult(null)->setMaxResults(null); $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, $ids); @@ -250,7 +238,8 @@ private function getCountQuery() $platform = $countQuery->getEntityManager()->getConnection()->getDatabasePlatform(); // law of demeter win $rsm = new ResultSetMapping(); - $rsm->addScalarResult($platform->getSQLResultCasing('dctrn_count'), 'count'); + + $rsm->addScalarResult($platform->getSQLResultCasing('dctrn_count'), 'count', Type::getType('integer')); $countQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountOutputWalker::class); $countQuery->setResultSetMapping($rsm); diff --git a/lib/Doctrine/ORM/Tools/Pagination/RowNumberOverFunction.php b/lib/Doctrine/ORM/Tools/Pagination/RowNumberOverFunction.php index a9d3e5d686e..58c35a5ac3b 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/RowNumberOverFunction.php +++ b/lib/Doctrine/ORM/Tools/Pagination/RowNumberOverFunction.php @@ -1,22 +1,7 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Pagination; diff --git a/lib/Doctrine/ORM/Tools/Pagination/WhereInWalker.php b/lib/Doctrine/ORM/Tools/Pagination/WhereInWalker.php index 5fa4e2d94c4..4eacffbc074 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/WhereInWalker.php +++ b/lib/Doctrine/ORM/Tools/Pagination/WhereInWalker.php @@ -1,24 +1,11 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools\Pagination; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; use Doctrine\ORM\Query\AST\ArithmeticExpression; use Doctrine\ORM\Query\AST\SimpleArithmeticExpression; use Doctrine\ORM\Query\TreeWalkerAdapter; @@ -73,7 +60,7 @@ class WhereInWalker extends TreeWalkerAdapter */ public function walkSelectStatement(SelectStatement $AST) { - $queryComponents = $this->_getQueryComponents(); + $queryComponents = $this->getQueryComponents(); // Get the root entity and alias from the AST fromClause $from = $AST->fromClause->identificationVariableDeclarations; @@ -81,20 +68,28 @@ public function walkSelectStatement(SelectStatement $AST) throw new \RuntimeException("Cannot count query which selects two FROM components, cannot make distinction"); } - $fromRoot = reset($from); - $rootAlias = $fromRoot->rangeVariableDeclaration->aliasIdentificationVariable; - $rootClass = $queryComponents[$rootAlias]['metadata']; - $identifierFieldName = $rootClass->getSingleIdentifierFieldName(); + $fromRoot = reset($from); + $rootAlias = $fromRoot->rangeVariableDeclaration->aliasIdentificationVariable; + $rootClass = $queryComponents[$rootAlias]['metadata']; + $property = $rootClass->getProperty($rootClass->getSingleIdentifierFieldName()); + $pathType = PathExpression::TYPE_STATE_FIELD; - $pathType = PathExpression::TYPE_STATE_FIELD; - if (isset($rootClass->associationMappings[$identifierFieldName])) { - $pathType = PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION; + if ($property instanceof AssociationMetadata) { + $pathType = $property instanceof ToOneAssociationMetadata + ? PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION + : PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION + ; } - $pathExpression = new PathExpression(PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, $rootAlias, $identifierFieldName); + $pathExpression = new PathExpression( + PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, + $rootAlias, + $property->getName() + ); + $pathExpression->type = $pathType; - $count = $this->_getQuery()->getHint(self::HINT_PAGINATOR_ID_COUNT); + $count = $this->getQuery()->getHint(self::HINT_PAGINATOR_ID_COUNT); if ($count > 0) { $arithmeticExpression = new ArithmeticExpression(); @@ -111,6 +106,7 @@ public function walkSelectStatement(SelectStatement $AST) $conditionalPrimary = new ConditionalPrimary; $conditionalPrimary->simpleConditionalExpression = $expression; + if ($AST->whereClause) { if ($AST->whereClause->conditionalExpression instanceof ConditionalTerm) { $AST->whereClause->conditionalExpression->conditionalFactors[] = $conditionalPrimary; diff --git a/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php b/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php index 36f1f929bde..09c2a914d4a 100644 --- a/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php +++ b/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php @@ -1,26 +1,12 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools; use Doctrine\ORM\Event\LoadClassMetadataEventArgs; use Doctrine\ORM\Event\OnClassMetadataNotFoundEventArgs; +use Doctrine\ORM\Mapping\AssociationMetadata; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\Common\EventSubscriber; use Doctrine\ORM\Events; @@ -57,14 +43,12 @@ public function getSubscribedEvents() * * @param string $originalEntity * @param string $newEntity - * @param array $mapping * * @return void */ - public function addResolveTargetEntity($originalEntity, $newEntity, array $mapping) + public function addResolveTargetEntity($originalEntity, $newEntity) { - $mapping['targetEntity'] = ltrim($newEntity, "\\"); - $this->resolveTargetEntities[ltrim($originalEntity, "\\")] = $mapping; + $this->resolveTargetEntities[ltrim($originalEntity, "\\")] = ltrim($newEntity, "\\"); } /** @@ -77,11 +61,10 @@ public function addResolveTargetEntity($originalEntity, $newEntity, array $mappi public function onClassMetadataNotFound(OnClassMetadataNotFoundEventArgs $args) { if (array_key_exists($args->getClassName(), $this->resolveTargetEntities)) { - $args->setFoundMetadata( - $args - ->getObjectManager() - ->getClassMetadata($this->resolveTargetEntities[$args->getClassName()]['targetEntity']) - ); + $resolvedClassName = $this->resolveTargetEntities[$args->getClassName()]; + $resolvedMetadata = $args->getObjectManager()->getClassMetadata($resolvedClassName); + + $args->setFoundMetadata($resolvedMetadata); } } @@ -97,48 +80,29 @@ public function onClassMetadataNotFound(OnClassMetadataNotFoundEventArgs $args) public function loadClassMetadata(LoadClassMetadataEventArgs $args) { /* @var $cm \Doctrine\ORM\Mapping\ClassMetadata */ - $cm = $args->getClassMetadata(); + $class = $args->getClassMetadata(); - foreach ($cm->associationMappings as $mapping) { - if (isset($this->resolveTargetEntities[$mapping['targetEntity']])) { - $this->remapAssociation($cm, $mapping); - } - } + foreach ($class->discriminatorMap as $key => $className) { + if (isset($this->resolveTargetEntities[$className])) { + $targetEntity = $this->resolveTargetEntities[$className]; - foreach ($this->resolveTargetEntities as $interface => $data) { - if ($data['targetEntity'] == $cm->getName()) { - $args->getEntityManager()->getMetadataFactory()->setMetadataFor($interface, $cm); + $class->discriminatorMap[$key] = $targetEntity; } } - } - /** - * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $classMetadata - * @param array $mapping - * - * @return void - */ - private function remapAssociation($classMetadata, $mapping) - { - $newMapping = $this->resolveTargetEntities[$mapping['targetEntity']]; - $newMapping = array_replace_recursive($mapping, $newMapping); - $newMapping['fieldName'] = $mapping['fieldName']; + foreach ($class->getDeclaredPropertiesIterator() as $association) { + if ($association instanceof AssociationMetadata && + isset($this->resolveTargetEntities[$association->getTargetEntity()])) { + $targetEntity = $this->resolveTargetEntities[$association->getTargetEntity()]; - unset($classMetadata->associationMappings[$mapping['fieldName']]); + $association->setTargetEntity($targetEntity); + } + } - switch ($mapping['type']) { - case ClassMetadata::MANY_TO_MANY: - $classMetadata->mapManyToMany($newMapping); - break; - case ClassMetadata::MANY_TO_ONE: - $classMetadata->mapManyToOne($newMapping); - break; - case ClassMetadata::ONE_TO_MANY: - $classMetadata->mapOneToMany($newMapping); - break; - case ClassMetadata::ONE_TO_ONE: - $classMetadata->mapOneToOne($newMapping); - break; + foreach ($this->resolveTargetEntities as $interface => $targetEntity) { + if ($targetEntity === $class->getClassName()) { + $args->getEntityManager()->getMetadataFactory()->setMetadataFor($interface, $class); + } } } } diff --git a/lib/Doctrine/ORM/Tools/SchemaTool.php b/lib/Doctrine/ORM/Tools/SchemaTool.php index 007ac85a8b7..5e0ad740489 100644 --- a/lib/Doctrine/ORM/Tools/SchemaTool.php +++ b/lib/Doctrine/ORM/Tools/SchemaTool.php @@ -1,25 +1,10 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools; -use Doctrine\ORM\ORMException; +use Doctrine\DBAL\Schema\Column; use Doctrine\DBAL\Schema\Comparator; use Doctrine\DBAL\Schema\Index; use Doctrine\DBAL\Schema\Schema; @@ -27,9 +12,18 @@ use Doctrine\DBAL\Schema\Visitor\DropSchemaSqlCollector; use Doctrine\DBAL\Schema\Visitor\RemoveNamespacedAssets; use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\AssociationMetadata; use Doctrine\ORM\Mapping\ClassMetadata; -use Doctrine\ORM\Tools\Event\GenerateSchemaTableEventArgs; +use Doctrine\ORM\Mapping\FieldMetadata; +use Doctrine\ORM\Mapping\GeneratorType; +use Doctrine\ORM\Mapping\InheritanceType; +use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata; +use Doctrine\ORM\Mapping\MappingException; +use Doctrine\ORM\Mapping\OneToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; +use Doctrine\ORM\ORMException; use Doctrine\ORM\Tools\Event\GenerateSchemaEventArgs; +use Doctrine\ORM\Tools\Event\GenerateSchemaTableEventArgs; /** * The SchemaTool is a tool to create/drop/update database schemas based on @@ -55,13 +49,6 @@ class SchemaTool */ private $platform; - /** - * The quote strategy. - * - * @var \Doctrine\ORM\Mapping\QuoteStrategy - */ - private $quoteStrategy; - /** * Initializes a new SchemaTool instance that uses the connection of the * provided EntityManager. @@ -70,9 +57,8 @@ class SchemaTool */ public function __construct(EntityManagerInterface $em) { - $this->em = $em; - $this->platform = $em->getConnection()->getDatabasePlatform(); - $this->quoteStrategy = $em->getConfiguration()->getQuoteStrategy(); + $this->em = $em; + $this->platform = $em->getConnection()->getDatabasePlatform(); } /** @@ -124,10 +110,10 @@ public function getCreateSchemaSql(array $classes) private function processingNotRequired($class, array $processedClasses) { return ( - isset($processedClasses[$class->name]) || + isset($processedClasses[$class->getClassName()]) || $class->isMappedSuperclass || $class->isEmbeddedClass || - ($class->isInheritanceTypeSingleTable() && $class->name != $class->rootEntityName) + ($class->inheritanceType === InheritanceType::SINGLE_TABLE && ! $class->isRootEntity()) ); } @@ -160,104 +146,121 @@ public function getSchemaFromMetadata(array $classes) continue; } - $table = $schema->createTable($this->quoteStrategy->getTableName($class, $this->platform)); + $table = $schema->createTable($class->table->getQuotedQualifiedName($this->platform)); - if ($class->isInheritanceTypeSingleTable()) { - $this->gatherColumns($class, $table); - $this->gatherRelationsSql($class, $table, $schema, $addedFks, $blacklistedFks); + switch ($class->inheritanceType) { + case InheritanceType::SINGLE_TABLE: + $this->gatherColumns($class, $table); + $this->gatherRelationsSql($class, $table, $schema, $addedFks, $blacklistedFks); - // Add the discriminator column - $this->addDiscriminatorColumnDefinition($class, $table); + // Add the discriminator column + $this->addDiscriminatorColumnDefinition($class, $table); - // Aggregate all the information from all classes in the hierarchy - foreach ($class->parentClasses as $parentClassName) { - // Parent class information is already contained in this class - $processedClasses[$parentClassName] = true; - } + // Aggregate all the information from all classes in the hierarchy + $parentClass = $class; - foreach ($class->subClasses as $subClassName) { - $subClass = $this->em->getClassMetadata($subClassName); - $this->gatherColumns($subClass, $table); - $this->gatherRelationsSql($subClass, $table, $schema, $addedFks, $blacklistedFks); - $processedClasses[$subClassName] = true; - } - } elseif ($class->isInheritanceTypeJoined()) { - // Add all non-inherited fields as columns - $pkColumns = []; - foreach ($class->fieldMappings as $fieldName => $mapping) { - if ( ! isset($mapping['inherited'])) { - $columnName = $this->quoteStrategy->getColumnName( - $mapping['fieldName'], - $class, - $this->platform - ); - $this->gatherColumn($class, $mapping, $table); + while (($parentClass = $parentClass->getParent()) !== null) { + // Parent class information is already contained in this class + $processedClasses[$parent->getClassName()] = true; + } - if ($class->isIdentifier($fieldName)) { - $pkColumns[] = $columnName; - } + foreach ($class->getSubClasses() as $subClassName) { + $subClass = $this->em->getClassMetadata($subClassName); + + $this->gatherColumns($subClass, $table); + $this->gatherRelationsSql($subClass, $table, $schema, $addedFks, $blacklistedFks); + + $processedClasses[$subClassName] = true; } - } - $this->gatherRelationsSql($class, $table, $schema, $addedFks, $blacklistedFks); + break; - // Add the discriminator column only to the root table - if ($class->name == $class->rootEntityName) { - $this->addDiscriminatorColumnDefinition($class, $table); - } else { - // Add an ID FK column to child tables - $inheritedKeyColumns = []; - foreach ($class->identifier as $identifierField) { - $idMapping = $class->fieldMappings[$identifierField]; - if (isset($idMapping['inherited'])) { - $this->gatherColumn($class, $idMapping, $table); - $columnName = $this->quoteStrategy->getColumnName( - $identifierField, - $class, - $this->platform - ); - // TODO: This seems rather hackish, can we optimize it? - $table->getColumn($columnName)->setAutoincrement(false); - - $pkColumns[] = $columnName; - $inheritedKeyColumns[] = $columnName; + case InheritanceType::JOINED: + // Add all non-inherited fields as columns + $pkColumns = []; + + foreach ($class->getDeclaredPropertiesIterator() as $fieldName => $property) { + if (! ($property instanceof FieldMetadata)) { + continue; + } + + if (! $class->isInheritedProperty($fieldName)) { + $columnName = $this->platform->quoteIdentifier($property->getColumnName()); + + $this->gatherColumn($class, $property, $table); + + if ($class->isIdentifier($fieldName)) { + $pkColumns[] = $columnName; + } } } - if (!empty($inheritedKeyColumns)) { - // Add a FK constraint on the ID column + + $this->gatherRelationsSql($class, $table, $schema, $addedFks, $blacklistedFks); + + // Add the discriminator column only to the root table + if ($class->isRootEntity()) { + $this->addDiscriminatorColumnDefinition($class, $table); + } else { + // Add an ID FK column to child tables + $inheritedKeyColumns = []; + + foreach ($class->identifier as $identifierField) { + $idProperty = $class->getProperty($identifierField); + + if ($class->isInheritedProperty($identifierField)) { + $column = $this->gatherColumn($class, $idProperty, $table); + $columnName = $column->getQuotedName($this->platform); + + // TODO: This seems rather hackish, can we optimize it? + $column->setAutoincrement(false); + + $pkColumns[] = $columnName; + $inheritedKeyColumns[] = $columnName; + } + } + + if ( ! empty($inheritedKeyColumns)) { + // Add a FK constraint on the ID column + $rootClass = $this->em->getClassMetadata($class->getRootClassName()); + $table->addForeignKeyConstraint( - $this->quoteStrategy->getTableName( - $this->em->getClassMetadata($class->rootEntityName), - $this->platform - ), + $rootClass->table->getQuotedQualifiedName($this->platform), $inheritedKeyColumns, $inheritedKeyColumns, ['onDelete' => 'CASCADE'] ); } - } + } - $table->setPrimaryKey($pkColumns); + $table->setPrimaryKey($pkColumns); - } elseif ($class->isInheritanceTypeTablePerClass()) { - throw ORMException::notSupported(); - } else { - $this->gatherColumns($class, $table); - $this->gatherRelationsSql($class, $table, $schema, $addedFks, $blacklistedFks); + break; + + case InheritanceType::TABLE_PER_CLASS: + throw ORMException::notSupported(); + + default: + $this->gatherColumns($class, $table); + $this->gatherRelationsSql($class, $table, $schema, $addedFks, $blacklistedFks); + + break; } $pkColumns = []; foreach ($class->identifier as $identifierField) { - if (isset($class->fieldMappings[$identifierField])) { - $pkColumns[] = $this->quoteStrategy->getColumnName($identifierField, $class, $this->platform); - } elseif (isset($class->associationMappings[$identifierField])) { - /* @var $assoc \Doctrine\ORM\Mapping\OneToOne */ - $assoc = $class->associationMappings[$identifierField]; - - foreach ($assoc['joinColumns'] as $joinColumn) { - $pkColumns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); + $property = $class->getProperty($identifierField); + + if ($property instanceof FieldMetadata) { + $pkColumns[] = $this->platform->quoteIdentifier($property->getColumnName()); + + continue; + } + + if ($property instanceof ToOneAssociationMetadata) { + foreach ($property->getJoinColumns() as $joinColumn) { + $pkColumns[] = $this->platform->quoteIdentifier($joinColumn->getColumnName()); } } } @@ -277,19 +280,31 @@ public function getSchemaFromMetadata(array $classes) } } - if (isset($class->table['indexes'])) { - foreach ($class->table['indexes'] as $indexName => $indexData) { - if ( ! isset($indexData['flags'])) { - $indexData['flags'] = []; + if ($class->table->getIndexes()) { + foreach ($class->table->getIndexes() as $indexName => $indexData) { + $indexName = is_numeric($indexName) ? null : $indexName; + $index = new Index($indexName, $indexData['columns'], $indexData['unique'], $indexData['flags'], $indexData['options']); + + foreach ($table->getIndexes() as $tableIndexName => $tableIndex) { + if ($tableIndex->isFullfilledBy($index)) { + $table->dropIndex($tableIndexName); + break; + } + } + + if ($indexData['unique']) { + $table->addUniqueIndex($indexData['columns'], $indexName, $indexData['options']); + } else { + $table->addIndex($indexData['columns'], $indexName, $indexData['flags'], $indexData['options']); } - $table->addIndex($indexData['columns'], is_numeric($indexName) ? null : $indexName, (array) $indexData['flags'], isset($indexData['options']) ? $indexData['options'] : []); } } - if (isset($class->table['uniqueConstraints'])) { - foreach ($class->table['uniqueConstraints'] as $indexName => $indexData) { - $uniqIndex = new Index($indexName, $indexData['columns'], true, false, [], isset($indexData['options']) ? $indexData['options'] : []); + if ($class->table->getUniqueConstraints()) { + foreach ($class->table->getUniqueConstraints() as $indexName => $indexData) { + $indexName = is_numeric($indexName) ? null : $indexName; + $uniqIndex = new Index($indexName, $indexData['columns'], true, false, $indexData['flags'], $indexData['options']); foreach ($table->getIndexes() as $tableIndexName => $tableIndex) { if ($tableIndex->isFullfilledBy($uniqIndex)) { @@ -298,27 +313,30 @@ public function getSchemaFromMetadata(array $classes) } } - $table->addUniqueIndex($indexData['columns'], is_numeric($indexName) ? null : $indexName, isset($indexData['options']) ? $indexData['options'] : []); + $table->addUniqueConstraint($indexData['columns'], $indexName, $indexData['flags'], $indexData['options']); } } - if (isset($class->table['options'])) { - foreach ($class->table['options'] as $key => $val) { + if ($class->table->getOptions()) { + foreach ($class->table->getOptions() as $key => $val) { $table->addOption($key, $val); } } - $processedClasses[$class->name] = true; + $processedClasses[$class->getClassName()] = true; - if ($class->isIdGeneratorSequence() && $class->name == $class->rootEntityName) { - $seqDef = $class->sequenceGeneratorDefinition; - $quotedName = $this->quoteStrategy->getSequenceName($seqDef, $class, $this->platform); - if ( ! $schema->hasSequence($quotedName)) { - $schema->createSequence( - $quotedName, - $seqDef['allocationSize'], - $seqDef['initialValue'] - ); + foreach ($class->getDeclaredPropertiesIterator() as $property) { + if (! $property instanceof FieldMetadata + || ! $property->hasValueGenerator() + || $property->getValueGenerator()->getType() !== GeneratorType::SEQUENCE + || $class->getClassName() !== $class->getRootClassName()) { + continue; + } + + $quotedName = $this->platform->quoteIdentifier($property->getValueGenerator()->getDefinition()['sequenceName']); + + if (! $schema->hasSequence($quotedName)) { + $schema->createSequence($quotedName, $property->getValueGenerator()->getDefinition()['allocationSize']); } } @@ -355,25 +373,28 @@ public function getSchemaFromMetadata(array $classes) */ private function addDiscriminatorColumnDefinition($class, Table $table) { - $discrColumn = $class->discriminatorColumn; + $discrColumn = $class->discriminatorColumn; + $discrColumnType = $discrColumn->getTypeName(); + $options = [ + 'notnull' => ! $discrColumn->isNullable(), + ]; - if ( ! isset($discrColumn['type']) || - (strtolower($discrColumn['type']) == 'string' && ! isset($discrColumn['length'])) - ) { - $discrColumn['type'] = 'string'; - $discrColumn['length'] = 255; - } + switch ($discrColumnType) { + case 'string': + $options['length'] = $discrColumn->getLength() ?? 255; + break; - $options = [ - 'length' => isset($discrColumn['length']) ? $discrColumn['length'] : null, - 'notnull' => true - ]; + case 'decimal': + $options['scale'] = $discrColumn->getScale(); + $options['precision'] = $discrColumn->getPrecision(); + break; + } - if (isset($discrColumn['columnDefinition'])) { - $options['columnDefinition'] = $discrColumn['columnDefinition']; + if (!empty($discrColumn->getColumnDefinition())) { + $options['columnDefinition'] = $discrColumn->getColumnDefinition(); } - $table->addColumn($discrColumn['name'], $discrColumn['type'], $options); + $table->addColumn($discrColumn->getColumnName(), $discrColumnType, $options); } /** @@ -389,15 +410,19 @@ private function gatherColumns($class, Table $table) { $pkColumns = []; - foreach ($class->fieldMappings as $mapping) { - if ($class->isInheritanceTypeSingleTable() && isset($mapping['inherited'])) { + foreach ($class->getDeclaredPropertiesIterator() as $fieldName => $property) { + if (! ($property instanceof FieldMetadata)) { continue; } - $this->gatherColumn($class, $mapping, $table); + if ($class->inheritanceType === InheritanceType::SINGLE_TABLE && $class->isInheritedProperty($fieldName)) { + continue; + } - if ($class->isIdentifier($mapping['fieldName'])) { - $pkColumns[] = $this->quoteStrategy->getColumnName($mapping['fieldName'], $class, $this->platform); + $this->gatherColumn($class, $property, $table); + + if ($property->isPrimaryKey()) { + $pkColumns[] = $this->platform->quoteIdentifier($property->getColumnName()); } } } @@ -405,79 +430,89 @@ private function gatherColumns($class, Table $table) /** * Creates a column definition as required by the DBAL from an ORM field mapping definition. * - * @param ClassMetadata $class The class that owns the field mapping. - * @param array $mapping The field mapping. + * @param ClassMetadata $classMetadata The class that owns the field mapping. + * @param FieldMetadata $fieldMetadata The field mapping. * @param Table $table * - * @return void + * @return Column The portable column definition as required by the DBAL. */ - private function gatherColumn($class, array $mapping, Table $table) + private function gatherColumn($classMetadata, FieldMetadata $fieldMetadata, Table $table) { - $columnName = $this->quoteStrategy->getColumnName($mapping['fieldName'], $class, $this->platform); - $columnType = $mapping['type']; + $fieldName = $fieldMetadata->getName(); + $columnName = $fieldMetadata->getColumnName(); + $columnType = $fieldMetadata->getTypeName(); - $options = []; - $options['length'] = isset($mapping['length']) ? $mapping['length'] : null; - $options['notnull'] = isset($mapping['nullable']) ? ! $mapping['nullable'] : true; - if ($class->isInheritanceTypeSingleTable() && $class->parentClasses) { + $options = [ + 'length' => $fieldMetadata->getLength(), + 'notnull' => ! $fieldMetadata->isNullable(), + 'platformOptions' => [ + 'version' => ($classMetadata->isVersioned() && $classMetadata->versionProperty->getName() === $fieldName), + ], + ]; + + if ($classMetadata->inheritanceType === InheritanceType::SINGLE_TABLE && $classMetadata->getParent()) { $options['notnull'] = false; } - $options['platformOptions'] = []; - $options['platformOptions']['version'] = $class->isVersioned && $class->versionField === $mapping['fieldName']; - if (strtolower($columnType) === 'string' && null === $options['length']) { $options['length'] = 255; } - if (isset($mapping['precision'])) { - $options['precision'] = $mapping['precision']; + if (is_int($fieldMetadata->getPrecision())) { + $options['precision'] = $fieldMetadata->getPrecision(); } - if (isset($mapping['scale'])) { - $options['scale'] = $mapping['scale']; + if (is_int($fieldMetadata->getScale())) { + $options['scale'] = $fieldMetadata->getScale(); } - if (isset($mapping['default'])) { - $options['default'] = $mapping['default']; + if ($fieldMetadata->getColumnDefinition()) { + $options['columnDefinition'] = $fieldMetadata->getColumnDefinition(); } - if (isset($mapping['columnDefinition'])) { - $options['columnDefinition'] = $mapping['columnDefinition']; - } + $fieldOptions = $fieldMetadata->getOptions(); - if (isset($mapping['options'])) { + if ($fieldOptions) { $knownOptions = ['comment', 'unsigned', 'fixed', 'default']; foreach ($knownOptions as $knownOption) { - if (array_key_exists($knownOption, $mapping['options'])) { - $options[$knownOption] = $mapping['options'][$knownOption]; + if (array_key_exists($knownOption, $fieldOptions)) { + $options[$knownOption] = $fieldOptions[$knownOption]; - unset($mapping['options'][$knownOption]); + unset($fieldOptions[$knownOption]); } } - $options['customSchemaOptions'] = $mapping['options']; + $options['customSchemaOptions'] = $fieldOptions; } - if ($class->isIdGeneratorIdentity() && $class->getIdentifierFieldNames() == [$mapping['fieldName']]) { + if ($fieldMetadata->hasValueGenerator() + && $fieldMetadata->getValueGenerator()->getType() === GeneratorType::IDENTITY + && in_array($fieldName, $classMetadata->getIdentifierFieldNames(), true) + ) { $options['autoincrement'] = true; } - if ($class->isInheritanceTypeJoined() && $class->name !== $class->rootEntityName) { + + if ($classMetadata->inheritanceType === InheritanceType::JOINED && ! $classMetadata->isRootEntity()) { $options['autoincrement'] = false; } - if ($table->hasColumn($columnName)) { + $quotedColumnName = $this->platform->quoteIdentifier($fieldMetadata->getColumnName()); + + if ($table->hasColumn($quotedColumnName)) { // required in some inheritance scenarios - $table->changeColumn($columnName, $options); + $table->changeColumn($quotedColumnName, $options); + + $column = $table->getColumn($quotedColumnName); } else { - $table->addColumn($columnName, $columnType, $options); + $column = $table->addColumn($quotedColumnName, $columnType, $options); } - $isUnique = isset($mapping['unique']) ? $mapping['unique'] : false; - if ($isUnique) { + if ($fieldMetadata->isUnique()) { $table->addUniqueIndex([$columnName]); } + + return $column; } /** @@ -496,61 +531,74 @@ private function gatherColumn($class, array $mapping, Table $table) */ private function gatherRelationsSql($class, $table, $schema, &$addedFks, &$blacklistedFks) { - foreach ($class->associationMappings as $mapping) { - if (isset($mapping['inherited'])) { + foreach ($class->getDeclaredPropertiesIterator() as $fieldName => $property) { + if (! ($property instanceof AssociationMetadata)) { continue; } - $foreignClass = $this->em->getClassMetadata($mapping['targetEntity']); + if ($class->isInheritedProperty($fieldName) && ! $property->getDeclaringClass()->isMappedSuperclass) { + continue; + } - if ($mapping['type'] & ClassMetadata::TO_ONE && $mapping['isOwningSide']) { - $primaryKeyColumns = []; // PK is unnecessary for this relation-type + if (! $property->isOwningSide()) { + continue; + } - $this->gatherRelationJoinColumns( - $mapping['joinColumns'], - $table, - $foreignClass, - $mapping, - $primaryKeyColumns, - $addedFks, - $blacklistedFks - ); - } elseif ($mapping['type'] == ClassMetadata::ONE_TO_MANY && $mapping['isOwningSide']) { - //... create join table, one-many through join table supported later - throw ORMException::notSupported(); - } elseif ($mapping['type'] == ClassMetadata::MANY_TO_MANY && $mapping['isOwningSide']) { - // create join table - $joinTable = $mapping['joinTable']; - - $theJoinTable = $schema->createTable( - $this->quoteStrategy->getJoinTableName($mapping, $foreignClass, $this->platform) - ); + $foreignClass = $this->em->getClassMetadata($property->getTargetEntity()); - $primaryKeyColumns = []; - - // Build first FK constraint (relation table => source table) - $this->gatherRelationJoinColumns( - $joinTable['joinColumns'], - $theJoinTable, - $class, - $mapping, - $primaryKeyColumns, - $addedFks, - $blacklistedFks - ); + switch (true) { + case ($property instanceof ToOneAssociationMetadata): + $primaryKeyColumns = []; // PK is unnecessary for this relation-type - // Build second FK constraint (relation table => target table) - $this->gatherRelationJoinColumns( - $joinTable['inverseJoinColumns'], - $theJoinTable, - $foreignClass, - $mapping, - $primaryKeyColumns, - $addedFks, - $blacklistedFks - ); + $this->gatherRelationJoinColumns( + $property->getJoinColumns(), + $table, + $foreignClass, + $property, + $primaryKeyColumns, + $addedFks, + $blacklistedFks + ); + + break; + + case ($property instanceof OneToManyAssociationMetadata): + //... create join table, one-many through join table supported later + throw ORMException::notSupported(); + + case ($property instanceof ManyToManyAssociationMetadata): + // create join table + $joinTable = $property->getJoinTable(); + $joinTableName = $joinTable->getQuotedQualifiedName($this->platform); + $theJoinTable = $schema->createTable($joinTableName); + + $primaryKeyColumns = []; + + // Build first FK constraint (relation table => source table) + $this->gatherRelationJoinColumns( + $joinTable->getJoinColumns(), + $theJoinTable, + $class, + $property, + $primaryKeyColumns, + $addedFks, + $blacklistedFks + ); - $theJoinTable->setPrimaryKey($primaryKeyColumns); + // Build second FK constraint (relation table => target table) + $this->gatherRelationJoinColumns( + $joinTable->getInverseJoinColumns(), + $theJoinTable, + $foreignClass, + $property, + $primaryKeyColumns, + $addedFks, + $blacklistedFks + ); + + $theJoinTable->setPrimaryKey($primaryKeyColumns); + + break; } } } @@ -571,22 +619,41 @@ private function gatherRelationsSql($class, $table, $schema, &$addedFks, &$black */ private function getDefiningClass($class, $referencedColumnName) { - $referencedFieldName = $class->getFieldName($referencedColumnName); + if (isset($class->fieldNames[$referencedColumnName])) { + $propertyName = $class->fieldNames[$referencedColumnName]; - if ($class->hasField($referencedFieldName)) { - return [$class, $referencedFieldName]; + if ($class->hasField($propertyName)) { + return [$class, $propertyName]; + } } - if (in_array($referencedColumnName, $class->getIdentifierColumnNames())) { - // it seems to be an entity as foreign key - foreach ($class->getIdentifierFieldNames() as $fieldName) { - if ($class->hasAssociation($fieldName) - && $class->getSingleAssociationJoinColumnName($fieldName) == $referencedColumnName) { - return $this->getDefiningClass( - $this->em->getClassMetadata($class->associationMappings[$fieldName]['targetEntity']), - $class->getSingleAssociationReferencedJoinColumnName($fieldName) - ); - } + $idColumns = $class->getIdentifierColumns($this->em); + $idColumnNameList = array_keys($idColumns); + + if (! in_array($referencedColumnName, $idColumnNameList)) { + return null; + } + + // it seems to be an entity as foreign key + foreach ($class->getIdentifierFieldNames() as $fieldName) { + $property = $class->getProperty($fieldName); + + if (! ($property instanceof AssociationMetadata)) { + continue; + } + + $joinColumns = $property->getJoinColumns(); + + if (count($joinColumns) > 1) { + throw MappingException::noSingleAssociationJoinColumnFound($class->getClassName(), $fieldName); + } + + $joinColumn = reset($joinColumns); + + if ($joinColumn->getColumnName() === $referencedColumnName) { + $targetEntity = $this->em->getClassMetadata($property->getTargetEntity()); + + return $this->getDefiningClass($targetEntity, $joinColumn->getReferencedColumnName()); } } @@ -621,74 +688,74 @@ private function gatherRelationJoinColumns( $localColumns = []; $foreignColumns = []; $fkOptions = []; - $foreignTableName = $this->quoteStrategy->getTableName($class, $this->platform); + $foreignTableName = $class->table->getQuotedQualifiedName($this->platform); $uniqueConstraints = []; foreach ($joinColumns as $joinColumn) { - list($definingClass, $referencedFieldName) = $this->getDefiningClass( $class, - $joinColumn['referencedColumnName'] + $joinColumn->getReferencedColumnName() ); if ( ! $definingClass) { - throw new \Doctrine\ORM\ORMException( - "Column name `".$joinColumn['referencedColumnName']."` referenced for relation from ". - $mapping['sourceEntity'] . " towards ". $mapping['targetEntity'] . " does not exist." - ); + throw new \Doctrine\ORM\ORMException(sprintf( + 'Column name "%s" referenced for relation from %s towards %s does not exist.', + $joinColumn->getReferencedColumnName(), + $mapping->getSourceEntity(), + $mapping->getTargetEntity() + )); } - $quotedColumnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); - $quotedRefColumnName = $this->quoteStrategy->getReferencedJoinColumnName( - $joinColumn, - $class, - $this->platform - ); + $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName()); + $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName()); $primaryKeyColumns[] = $quotedColumnName; $localColumns[] = $quotedColumnName; - $foreignColumns[] = $quotedRefColumnName; + $foreignColumns[] = $quotedReferencedColumnName; if ( ! $theJoinTable->hasColumn($quotedColumnName)) { // Only add the column to the table if it does not exist already. // It might exist already if the foreign key is mapped into a regular // property as well. - - $fieldMapping = $definingClass->getFieldMapping($referencedFieldName); - + $property = $definingClass->getProperty($referencedFieldName); $columnDef = null; - if (isset($joinColumn['columnDefinition'])) { - $columnDef = $joinColumn['columnDefinition']; - } elseif (isset($fieldMapping['columnDefinition'])) { - $columnDef = $fieldMapping['columnDefinition']; + + if (!empty($joinColumn->getColumnDefinition())) { + $columnDef = $joinColumn->getColumnDefinition(); + } elseif ($property->getColumnDefinition()) { + $columnDef = $property->getColumnDefinition(); } - $columnOptions = ['notnull' => false, 'columnDefinition' => $columnDef]; + $columnType = $property->getTypeName(); + $columnOptions = [ + 'notnull' => !$joinColumn->isNullable(), + 'columnDefinition' => $columnDef, + ]; - if (isset($joinColumn['nullable'])) { - $columnOptions['notnull'] = !$joinColumn['nullable']; + if ($property->getOptions()) { + $columnOptions['options'] = $property->getOptions(); } - if (isset($fieldMapping['options'])) { - $columnOptions['options'] = $fieldMapping['options']; - } + switch ($columnType) { + case 'string': + $columnOptions['length'] = is_int($property->getLength()) ? $property->getLength() : 255; + break; - if ($fieldMapping['type'] == "string" && isset($fieldMapping['length'])) { - $columnOptions['length'] = $fieldMapping['length']; - } elseif ($fieldMapping['type'] == "decimal") { - $columnOptions['scale'] = $fieldMapping['scale']; - $columnOptions['precision'] = $fieldMapping['precision']; + case 'decimal': + $columnOptions['scale'] = $property->getScale(); + $columnOptions['precision'] = $property->getPrecision(); + break; } - $theJoinTable->addColumn($quotedColumnName, $fieldMapping['type'], $columnOptions); + $theJoinTable->addColumn($quotedColumnName, $columnType, $columnOptions); } - if (isset($joinColumn['unique']) && $joinColumn['unique'] == true) { + if ($joinColumn->isUnique()) { $uniqueConstraints[] = ['columns' => [$quotedColumnName]]; } - if (isset($joinColumn['onDelete'])) { - $fkOptions['onDelete'] = $joinColumn['onDelete']; + if (!empty($joinColumn->getOnDelete())) { + $fkOptions['onDelete'] = $joinColumn->getOnDelete(); } } @@ -699,6 +766,7 @@ private function gatherRelationJoinColumns( } $compositeName = $theJoinTable->getName().'.'.implode('', $localColumns); + if (isset($addedFks[$compositeName]) && ($foreignTableName != $addedFks[$compositeName]['foreignTableName'] || 0 < count(array_diff($foreignColumns, $addedFks[$compositeName]['foreignColumns']))) @@ -712,10 +780,15 @@ private function gatherRelationJoinColumns( break; } } + $blacklistedFks[$compositeName] = true; } elseif (!isset($blacklistedFks[$compositeName])) { - $addedFks[$compositeName] = ['foreignTableName' => $foreignTableName, 'foreignColumns' => $foreignColumns]; - $theJoinTable->addUnnamedForeignKeyConstraint( + $addedFks[$compositeName] = [ + 'foreignTableName' => $foreignTableName, + 'foreignColumns' => $foreignColumns + ]; + + $theJoinTable->addForeignKeyConstraint( $foreignTableName, $localColumns, $foreignColumns, diff --git a/lib/Doctrine/ORM/Tools/SchemaValidator.php b/lib/Doctrine/ORM/Tools/SchemaValidator.php index ee39aed817e..b207dc8d2c1 100644 --- a/lib/Doctrine/ORM/Tools/SchemaValidator.php +++ b/lib/Doctrine/ORM/Tools/SchemaValidator.php @@ -1,27 +1,20 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools; use Doctrine\ORM\EntityManagerInterface; -use Doctrine\ORM\Mapping\ClassMetadataInfo; -use Doctrine\DBAL\Types\Type; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\FieldMetadata; +use Doctrine\ORM\Mapping\JoinColumnMetadata; +use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ManyToOneAssociationMetadata; +use Doctrine\ORM\Mapping\OneToManyAssociationMetadata; +use Doctrine\ORM\Mapping\OneToOneAssociationMetadata; +use Doctrine\ORM\Mapping\ToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; /** * Performs strict validation of the mapping schema @@ -69,7 +62,7 @@ public function validateMapping() foreach ($classes as $class) { if ($ce = $this->validateClass($class)) { - $errors[$class->name] = $ce; + $errors[$class->getClassName()] = $ce; } } @@ -79,178 +72,252 @@ public function validateMapping() /** * Validates a single class of the current. * - * @param ClassMetadataInfo $class + * @param ClassMetadata $class * * @return array */ - public function validateClass(ClassMetadataInfo $class) + public function validateClass(ClassMetadata $class) { $ce = []; - $cmf = $this->em->getMetadataFactory(); - foreach ($class->fieldMappings as $fieldName => $mapping) { - if (!Type::hasType($mapping['type'])) { - $ce[] = "The field '" . $class->name . "#" . $fieldName."' uses a non-existent type '" . $mapping['type'] . "'."; + foreach ($class->getDeclaredPropertiesIterator() as $fieldName => $association) { + if (! ($association instanceof AssociationMetadata)) { + continue; } + + $ce = array_merge($ce, $this->validateAssociation($class, $association)); } - foreach ($class->associationMappings as $fieldName => $assoc) { - if (!class_exists($assoc['targetEntity']) || $cmf->isTransient($assoc['targetEntity'])) { - $ce[] = "The target entity '" . $assoc['targetEntity'] . "' specified on " . $class->name . '#' . $fieldName . ' is unknown or not an entity.'; + foreach ($class->getSubClasses() as $subClass) { + if (!in_array($class->getClassName(), class_parents($subClass))) { + $message = "According to the discriminator map class, '%s' has to be a child of '%s', but these entities are not related through inheritance."; - return $ce; + $ce[] = sprintf($message, $subClass, $class->getClassName()); } + } + + return $ce; + } + + /** + * @param ClassMetadata $class + * @param AssociationMetadata $association + * + * @return array + */ + private function validateAssociation(ClassMetadata $class, AssociationMetadata $association) + { + $metadataFactory = $this->em->getMetadataFactory(); + $fieldName = $association->getName(); + $targetEntity = $association->getTargetEntity(); + + if (!class_exists($targetEntity) || $metadataFactory->isTransient($targetEntity)) { + $message = "The target entity '%s' specified on %s#%s is unknown or not an entity."; + + return [ + sprintf($message, $targetEntity, $class->getClassName(), $fieldName) + ]; + } + + $mappedBy = $association->getMappedBy(); + $inversedBy = $association->getInversedBy(); - if ($assoc['mappedBy'] && $assoc['inversedBy']) { - $ce[] = "The association " . $class . "#" . $fieldName . " cannot be defined as both inverse and owning."; + $ce = []; + + if ($mappedBy && $inversedBy) { + $message = 'The association %s#%s cannot be defined as both inverse and owning.'; + + $ce[] = sprintf($message, $class, $fieldName); + } + + /** @var ClassMetadata $targetMetadata */ + $targetMetadata = $metadataFactory->getMetadataFor($targetEntity); + $containsForeignId = array_filter($targetMetadata->identifier, function ($identifier) use ($targetMetadata) { + $targetProperty = $targetMetadata->getProperty($identifier); + + return $targetProperty instanceof AssociationMetadata; + }); + + if ($association->isPrimaryKey() && count($containsForeignId)) { + $message = "Cannot map association %s#%s as identifier, because the target entity '%s' also maps an association as identifier."; + + $ce[] = sprintf($message, $class->getClassName(), $fieldName, $targetEntity); + } + + if ($mappedBy) { + /** @var AssociationMetadata $targetAssociation */ + $targetAssociation = $targetMetadata->getProperty($mappedBy); + + if (! $targetAssociation) { + $message = "The association %s#%s refers to the owning side property %s#%s which does not exist."; + + $ce[] = sprintf($message, $class->getClassName(), $fieldName, $targetEntity, $mappedBy); + } else if ($targetAssociation instanceof FieldMetadata) { + $message = "The association %s#%s refers to the owning side property %s#%s which is not defined as association, but as field."; + + $ce[] = sprintf($message, $class->getClassName(), $fieldName, $targetEntity, $mappedBy); + } else if ($targetAssociation->getInversedBy() === null) { + $message = "The property %s#%s is on the inverse side of a bi-directional relationship, but the " + . "specified mappedBy association on the target-entity %s#%s does not contain the required 'inversedBy=\"%s\"' attribute."; + + $ce[] = sprintf($message, $class->getClassName(), $fieldName, $targetEntity, $mappedBy, $fieldName); + } else if ($targetAssociation->getInversedBy() !== $fieldName) { + $message = "The mapping between %s#%s and %s#%s are inconsistent with each other."; + + $ce[] = sprintf($message, $class->getClassName(), $fieldName, $targetEntity, $mappedBy); } + } + + if ($inversedBy) { + /** @var AssociationMetadata $targetAssociation */ + $targetAssociation = $targetMetadata->getProperty($inversedBy); + + if (! $targetAssociation) { + $message = "The association %s#%s refers to the inverse side property %s#%s which does not exist."; - $targetMetadata = $cmf->getMetadataFor($assoc['targetEntity']); + $ce[] = sprintf($message, $class->getClassName(), $fieldName, $targetEntity, $inversedBy); + } else if ($targetAssociation instanceof FieldMetadata) { + $message = "The association %s#%s refers to the inverse side property %s#%s which is not defined as association, but as field."; - if (isset($assoc['id']) && $targetMetadata->containsForeignIdentifier) { - $ce[] = "Cannot map association '" . $class->name. "#". $fieldName ." as identifier, because " . - "the target entity '". $targetMetadata->name . "' also maps an association as identifier."; + $ce[] = sprintf($message, $class->getClassName(), $fieldName, $targetEntity, $inversedBy); + } else if ($targetAssociation->getMappedBy() === null) { + $message = "The property %s#%s is on the owning side of a bi-directional relationship, but the " + . "specified mappedBy association on the target-entity %s#%s does not contain the required 'inversedBy=\"%s\"' attribute."; + + $ce[] = sprintf($message, $class->getClassName(), $fieldName, $targetEntity, $mappedBy, $fieldName); + } else if ($targetAssociation->getMappedBy() !== $fieldName) { + $message = "The mapping between %s#%s and %s#%s are inconsistent with each other."; + + $ce[] = sprintf($message, $class->getClassName(), $fieldName, $targetEntity, $inversedBy); } - if ($assoc['mappedBy']) { - if ($targetMetadata->hasField($assoc['mappedBy'])) { - $ce[] = "The association " . $class->name . "#" . $fieldName . " refers to the owning side ". - "field " . $assoc['targetEntity'] . "#" . $assoc['mappedBy'] . " which is not defined as association, but as field."; - } - if (!$targetMetadata->hasAssociation($assoc['mappedBy'])) { - $ce[] = "The association " . $class->name . "#" . $fieldName . " refers to the owning side ". - "field " . $assoc['targetEntity'] . "#" . $assoc['mappedBy'] . " which does not exist."; - } elseif ($targetMetadata->associationMappings[$assoc['mappedBy']]['inversedBy'] == null) { - $ce[] = "The field " . $class->name . "#" . $fieldName . " is on the inverse side of a ". - "bi-directional relationship, but the specified mappedBy association on the target-entity ". - $assoc['targetEntity'] . "#" . $assoc['mappedBy'] . " does not contain the required ". - "'inversedBy=\"" . $fieldName . "\"' attribute."; - } elseif ($targetMetadata->associationMappings[$assoc['mappedBy']]['inversedBy'] != $fieldName) { - $ce[] = "The mappings " . $class->name . "#" . $fieldName . " and " . - $assoc['targetEntity'] . "#" . $assoc['mappedBy'] . " are ". - "inconsistent with each other."; + // Verify inverse side/owning side match each other + if ($targetAssociation) { + if ($association instanceof OneToOneAssociationMetadata && ! $targetAssociation instanceof OneToOneAssociationMetadata) { + $message = "If association %s#%s is one-to-one, then the inversed side %s#%s has to be one-to-one as well."; + + $ce[] = sprintf($message, $class->getClassName(), $fieldName, $targetMetadata->getClassName(), $inversedBy); + } else if ($association instanceof ManyToOneAssociationMetadata && ! $targetAssociation instanceof OneToManyAssociationMetadata) { + $message = "If association %s#%s is many-to-one, then the inversed side %s#%s has to be one-to-many."; + + $ce[] = sprintf($message, $class->getClassName(), $fieldName, $targetMetadata->getClassName(), $inversedBy); + } else if ($association instanceof ManyToManyAssociationMetadata && ! $targetAssociation instanceof ManyToManyAssociationMetadata) { + $message = "If association %s#%s is many-to-many, then the inversed side %s#%s has to be many-to-many as well."; + + $ce[] = sprintf($message, $class->getClassName(), $fieldName, $targetMetadata->getClassName(), $inversedBy); } } + } - if ($assoc['inversedBy']) { - if ($targetMetadata->hasField($assoc['inversedBy'])) { - $ce[] = "The association " . $class->name . "#" . $fieldName . " refers to the inverse side ". - "field " . $assoc['targetEntity'] . "#" . $assoc['inversedBy'] . " which is not defined as association."; - } + if ($association->isOwningSide()) { + if ($association instanceof ManyToManyAssociationMetadata) { + $classIdentifierColumns = array_keys($class->getIdentifierColumns($this->em)); + $targetIdentifierColumns = array_keys($targetMetadata->getIdentifierColumns($this->em)); + $joinTable = $association->getJoinTable(); - if (!$targetMetadata->hasAssociation($assoc['inversedBy'])) { - $ce[] = "The association " . $class->name . "#" . $fieldName . " refers to the inverse side ". - "field " . $assoc['targetEntity'] . "#" . $assoc['inversedBy'] . " which does not exist."; - } elseif ($targetMetadata->associationMappings[$assoc['inversedBy']]['mappedBy'] == null) { - $ce[] = "The field " . $class->name . "#" . $fieldName . " is on the owning side of a ". - "bi-directional relationship, but the specified mappedBy association on the target-entity ". - $assoc['targetEntity'] . "#" . $assoc['mappedBy'] . " does not contain the required ". - "'inversedBy' attribute."; - } elseif ($targetMetadata->associationMappings[$assoc['inversedBy']]['mappedBy'] != $fieldName) { - $ce[] = "The mappings " . $class->name . "#" . $fieldName . " and " . - $assoc['targetEntity'] . "#" . $assoc['inversedBy'] . " are ". - "inconsistent with each other."; - } + foreach ($joinTable->getJoinColumns() as $joinColumn) { + if (! in_array($joinColumn->getReferencedColumnName(), $classIdentifierColumns)) { + $message = "The referenced column name '%s' has to be a primary key column on the target entity class '%s'."; - // Verify inverse side/owning side match each other - if (array_key_exists($assoc['inversedBy'], $targetMetadata->associationMappings)) { - $targetAssoc = $targetMetadata->associationMappings[$assoc['inversedBy']]; - if ($assoc['type'] == ClassMetadataInfo::ONE_TO_ONE && $targetAssoc['type'] !== ClassMetadataInfo::ONE_TO_ONE) { - $ce[] = "If association " . $class->name . "#" . $fieldName . " is one-to-one, then the inversed " . - "side " . $targetMetadata->name . "#" . $assoc['inversedBy'] . " has to be one-to-one as well."; - } elseif ($assoc['type'] == ClassMetadataInfo::MANY_TO_ONE && $targetAssoc['type'] !== ClassMetadataInfo::ONE_TO_MANY) { - $ce[] = "If association " . $class->name . "#" . $fieldName . " is many-to-one, then the inversed " . - "side " . $targetMetadata->name . "#" . $assoc['inversedBy'] . " has to be one-to-many."; - } elseif ($assoc['type'] == ClassMetadataInfo::MANY_TO_MANY && $targetAssoc['type'] !== ClassMetadataInfo::MANY_TO_MANY) { - $ce[] = "If association " . $class->name . "#" . $fieldName . " is many-to-many, then the inversed " . - "side " . $targetMetadata->name . "#" . $assoc['inversedBy'] . " has to be many-to-many as well."; + $ce[] = sprintf($message, $joinColumn->getReferencedColumnName(), $class->getClassName()); + break; } } - } - if ($assoc['isOwningSide']) { - if ($assoc['type'] == ClassMetadataInfo::MANY_TO_MANY) { - $identifierColumns = $class->getIdentifierColumnNames(); - foreach ($assoc['joinTable']['joinColumns'] as $joinColumn) { - if (!in_array($joinColumn['referencedColumnName'], $identifierColumns)) { - $ce[] = "The referenced column name '" . $joinColumn['referencedColumnName'] . "' " . - "has to be a primary key column on the target entity class '".$class->name."'."; - break; - } - } + foreach ($joinTable->getInverseJoinColumns() as $inverseJoinColumn) { + if (! in_array($inverseJoinColumn->getReferencedColumnName(), $targetIdentifierColumns)) { + $message = "The referenced column name '%s' has to be a primary key column on the target entity class '%s'."; - $identifierColumns = $targetMetadata->getIdentifierColumnNames(); - foreach ($assoc['joinTable']['inverseJoinColumns'] as $inverseJoinColumn) { - if (!in_array($inverseJoinColumn['referencedColumnName'], $identifierColumns)) { - $ce[] = "The referenced column name '" . $joinColumn['referencedColumnName'] . "' " . - "has to be a primary key column on the target entity class '".$targetMetadata->name."'."; - break; - } + $ce[] = sprintf($message, $joinColumn->getReferencedColumnName(), $targetMetadata->getClassName()); + break; } + } - if (count($targetMetadata->getIdentifierColumnNames()) != count($assoc['joinTable']['inverseJoinColumns'])) { - $ce[] = "The inverse join columns of the many-to-many table '" . $assoc['joinTable']['name'] . "' " . - "have to contain to ALL identifier columns of the target entity '". $targetMetadata->name . "', " . - "however '" . implode(", ", array_diff($targetMetadata->getIdentifierColumnNames(), array_values($assoc['relationToTargetKeyColumns']))) . - "' are missing."; - } + if (count($targetIdentifierColumns) !== count($joinTable->getInverseJoinColumns())) { + $columnNames = array_map( + function (JoinColumnMetadata $joinColumn) { + return $joinColumn->getReferencedColumnName(); + }, + $joinTable->getInverseJoinColumns() + ); - if (count($class->getIdentifierColumnNames()) != count($assoc['joinTable']['joinColumns'])) { - $ce[] = "The join columns of the many-to-many table '" . $assoc['joinTable']['name'] . "' " . - "have to contain to ALL identifier columns of the source entity '". $class->name . "', " . - "however '" . implode(", ", array_diff($class->getIdentifierColumnNames(), array_values($assoc['relationToSourceKeyColumns']))) . - "' are missing."; - } + $columnString = implode("', '", array_diff($targetIdentifierColumns, $columnNames)); + $message = "The inverse join columns of the many-to-many table '%s' have to contain to ALL " + . "identifier columns of the target entity '%s', however '%s' are missing."; - } elseif ($assoc['type'] & ClassMetadataInfo::TO_ONE) { - $identifierColumns = $targetMetadata->getIdentifierColumnNames(); - foreach ($assoc['joinColumns'] as $joinColumn) { - if (!in_array($joinColumn['referencedColumnName'], $identifierColumns)) { - $ce[] = "The referenced column name '" . $joinColumn['referencedColumnName'] . "' " . - "has to be a primary key column on the target entity class '".$targetMetadata->name."'."; - } - } + $ce[] = sprintf($message, $joinTable->getName(), $targetMetadata->getClassName(), $columnString); + } - if (count($identifierColumns) != count($assoc['joinColumns'])) { - $ids = []; + if (count($classIdentifierColumns) !== count($joinTable->getJoinColumns())) { + $columnNames = array_map( + function (JoinColumnMetadata $joinColumn) { + return $joinColumn->getReferencedColumnName(); + }, + $joinTable->getJoinColumns() + ); - foreach ($assoc['joinColumns'] as $joinColumn) { - $ids[] = $joinColumn['name']; - } + $columnString = implode("', '", array_diff($classIdentifierColumns, $columnNames)); + $message = "The join columns of the many-to-many table '%s' have to contain to ALL " + . "identifier columns of the source entity '%s', however '%s' are missing."; - $ce[] = "The join columns of the association '" . $assoc['fieldName'] . "' " . - "have to match to ALL identifier columns of the target entity '". $targetMetadata->name . "', " . - "however '" . implode(", ", array_diff($targetMetadata->getIdentifierColumnNames(), $ids)) . - "' are missing."; - } + $ce[] = sprintf($message, $joinTable->getName(), $class->getClassName(), $columnString); } - } + } else if ($association instanceof ToOneAssociationMetadata) { + $identifierColumns = array_keys($targetMetadata->getIdentifierColumns($this->em)); + $joinColumns = $association->getJoinColumns(); - if (isset($assoc['orderBy']) && $assoc['orderBy'] !== null) { - foreach ($assoc['orderBy'] as $orderField => $orientation) { - if (!$targetMetadata->hasField($orderField) && !$targetMetadata->hasAssociation($orderField)) { - $ce[] = "The association " . $class->name."#".$fieldName." is ordered by a foreign field " . - $orderField . " that is not a field on the target entity " . $targetMetadata->name . "."; - continue; - } - if ($targetMetadata->isCollectionValuedAssociation($orderField)) { - $ce[] = "The association " . $class->name."#".$fieldName." is ordered by a field " . - $orderField . " on " . $targetMetadata->name . " that is a collection-valued association."; - continue; + foreach ($joinColumns as $joinColumn) { + if (!in_array($joinColumn->getReferencedColumnName(), $identifierColumns)) { + $message = "The referenced column name '%s' has to be a primary key column on the target entity class '%s'."; + + $ce[] = sprintf($message, $joinColumn->getReferencedColumnName(), $targetMetadata->getClassName()); } - if ($targetMetadata->isAssociationInverseSide($orderField)) { - $ce[] = "The association " . $class->name."#".$fieldName." is ordered by a field " . - $orderField . " on " . $targetMetadata->name . " that is the inverse side of an association."; - continue; + } + + if (count($identifierColumns) !== count($joinColumns)) { + $ids = []; + + foreach ($joinColumns as $joinColumn) { + $ids[] = $joinColumn->getColumnName(); } + + $columnString = implode("', '", array_diff($identifierColumns, $ids)); + $message = "The join columns of the association '%s' have to match to ALL " + . "identifier columns of the target entity '%s', however '%s' are missing."; + + $ce[] = sprintf($message, $fieldName, $targetMetadata->getClassName(), $columnString); } } } - foreach ($class->subClasses as $subClass) { - if (!in_array($class->name, class_parents($subClass))) { - $ce[] = "According to the discriminator map class '" . $subClass . "' has to be a child ". - "of '" . $class->name . "' but these entities are not related through inheritance."; + if ($association instanceof ToManyAssociationMetadata && $association->getOrderBy()) { + foreach ($association->getOrderBy() as $orderField => $orientation) { + $targetProperty = $targetMetadata->getProperty($orderField); + + if ($targetProperty instanceof FieldMetadata) { + continue; + } + + if (! ($targetProperty instanceof AssociationMetadata)) { + $message = "The association %s#%s is ordered by a property '%s' that is non-existing field on the target entity '%s'."; + + $ce[] = sprintf($message, $class->getClassName(), $fieldName, $orderField, $targetMetadata->getClassName()); + continue; + } + + if ($targetProperty instanceof ToManyAssociationMetadata) { + $message = "The association %s#%s is ordered by a property '%s' on '%s' that is a collection-valued association."; + + $ce[] = sprintf($message, $class->getClassName(), $fieldName, $orderField, $targetMetadata->getClassName()); + continue; + } + + if ($targetProperty instanceof AssociationMetadata && ! $targetProperty->isOwningSide()) { + $message = "The association %s#%s is ordered by a property '%s' on '%s' that is the inverse side of an association."; + + $ce[] = sprintf($message, $class->getClassName(), $fieldName, $orderField, $targetMetadata->getClassName()); + continue; + } } } @@ -265,7 +332,6 @@ public function validateClass(ClassMetadataInfo $class) public function schemaInSyncWithMetadata() { $schemaTool = new SchemaTool($this->em); - $allMetadata = $this->em->getMetadataFactory()->getAllMetadata(); return count($schemaTool->getUpdateSchemaSql($allMetadata, true)) == 0; diff --git a/lib/Doctrine/ORM/Tools/Setup.php b/lib/Doctrine/ORM/Tools/Setup.php index 666d627a4b4..3322d4dda84 100644 --- a/lib/Doctrine/ORM/Tools/Setup.php +++ b/lib/Doctrine/ORM/Tools/Setup.php @@ -1,31 +1,15 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools; -use Doctrine\Common\ClassLoader; +use Doctrine\Common\Cache\ArrayCache; use Doctrine\Common\Cache\Cache; use Doctrine\Common\Cache\CacheProvider; -use Doctrine\Common\Cache\ArrayCache; +use Doctrine\Common\ClassLoader; use Doctrine\ORM\Configuration; use Doctrine\ORM\Mapping\Driver\XmlDriver; -use Doctrine\ORM\Mapping\Driver\YamlDriver; /** * Convenience class for setting up Doctrine from different installations and configurations. @@ -51,7 +35,7 @@ public static function registerAutoloadDirectory($directory) $loader = new ClassLoader("Doctrine", $directory); $loader->register(); - $loader = new ClassLoader("Symfony\Component", $directory . "/Doctrine"); + $loader = new ClassLoader('Symfony\Component', $directory . "/Doctrine"); $loader->register(); } @@ -62,14 +46,13 @@ public static function registerAutoloadDirectory($directory) * @param boolean $isDevMode * @param string $proxyDir * @param Cache $cache - * @param bool $useSimpleAnnotationReader * * @return Configuration */ - public static function createAnnotationMetadataConfiguration(array $paths, $isDevMode = false, $proxyDir = null, Cache $cache = null, $useSimpleAnnotationReader = true) + public static function createAnnotationMetadataConfiguration(array $paths, $isDevMode = false, $proxyDir = null, Cache $cache = null) { $config = self::createConfiguration($isDevMode, $proxyDir, $cache); - $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver($paths, $useSimpleAnnotationReader)); + $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver($paths)); return $config; } @@ -92,24 +75,6 @@ public static function createXMLMetadataConfiguration(array $paths, $isDevMode = return $config; } - /** - * Creates a configuration with a yaml metadata driver. - * - * @param array $paths - * @param boolean $isDevMode - * @param string $proxyDir - * @param Cache $cache - * - * @return Configuration - */ - public static function createYAMLMetadataConfiguration(array $paths, $isDevMode = false, $proxyDir = null, Cache $cache = null) - { - $config = self::createConfiguration($isDevMode, $proxyDir, $cache); - $config->setMetadataDriverImpl(new YamlDriver($paths)); - - return $config; - } - /** * Creates a configuration without a metadata driver. * diff --git a/lib/Doctrine/ORM/Tools/ToolEvents.php b/lib/Doctrine/ORM/Tools/ToolEvents.php index aebb5d8f37d..8d04b4baedb 100644 --- a/lib/Doctrine/ORM/Tools/ToolEvents.php +++ b/lib/Doctrine/ORM/Tools/ToolEvents.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools; diff --git a/lib/Doctrine/ORM/Tools/ToolsException.php b/lib/Doctrine/ORM/Tools/ToolsException.php index 0a461640491..79397dfdffb 100644 --- a/lib/Doctrine/ORM/Tools/ToolsException.php +++ b/lib/Doctrine/ORM/Tools/ToolsException.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Tools; @@ -36,16 +21,6 @@ class ToolsException extends ORMException */ public static function schemaToolFailure($sql, \Exception $e) { - return new self("Schema-Tool failed with Error '" . $e->getMessage() . "' while executing DDL: " . $sql, "0", $e); - } - - /** - * @param string $type - * - * @return ToolsException - */ - public static function couldNotMapDoctrine1Type($type) - { - return new self("Could not map doctrine 1 type '$type'!"); + return new self("Schema-Tool failed with Error '" . $e->getMessage() . "' while executing DDL: " . $sql, 0, $e); } } diff --git a/lib/Doctrine/ORM/TransactionRequiredException.php b/lib/Doctrine/ORM/TransactionRequiredException.php index c3417b67426..337840e2c9a 100644 --- a/lib/Doctrine/ORM/TransactionRequiredException.php +++ b/lib/Doctrine/ORM/TransactionRequiredException.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; diff --git a/lib/Doctrine/ORM/UnexpectedResultException.php b/lib/Doctrine/ORM/UnexpectedResultException.php index 3cd561f0965..ded3b2ffd51 100644 --- a/lib/Doctrine/ORM/UnexpectedResultException.php +++ b/lib/Doctrine/ORM/UnexpectedResultException.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; diff --git a/lib/Doctrine/ORM/UnitOfWork.php b/lib/Doctrine/ORM/UnitOfWork.php index c0b0dd8c302..1b043fcdabb 100644 --- a/lib/Doctrine/ORM/UnitOfWork.php +++ b/lib/Doctrine/ORM/UnitOfWork.php @@ -1,31 +1,14 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM; -use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\Common\NotifyPropertyChanged; -use Doctrine\Common\Persistence\Mapping\RuntimeReflectionService; -use Doctrine\Common\Persistence\ObjectManagerAware; use Doctrine\Common\PropertyChangedListener; use Doctrine\DBAL\LockMode; +use Doctrine\Instantiator\Instantiator; use Doctrine\ORM\Cache\Persister\CachedPersister; use Doctrine\ORM\Event\LifecycleEventArgs; use Doctrine\ORM\Event\ListenersInvoker; @@ -34,15 +17,27 @@ use Doctrine\ORM\Event\PreFlushEventArgs; use Doctrine\ORM\Event\PreUpdateEventArgs; use Doctrine\ORM\Internal\HydrationCompleteHandler; +use Doctrine\ORM\Mapping\AssociationMetadata; +use Doctrine\ORM\Mapping\ChangeTrackingPolicy; use Doctrine\ORM\Mapping\ClassMetadata; -use Doctrine\ORM\Mapping\Reflection\ReflectionPropertiesGetter; +use Doctrine\ORM\Mapping\FetchMode; +use Doctrine\ORM\Mapping\FieldMetadata; +use Doctrine\ORM\Mapping\GeneratorType; +use Doctrine\ORM\Mapping\InheritanceType; +use Doctrine\ORM\Mapping\JoinColumnMetadata; +use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata; +use Doctrine\ORM\Mapping\OneToManyAssociationMetadata; +use Doctrine\ORM\Mapping\OneToOneAssociationMetadata; +use Doctrine\ORM\Mapping\Property; +use Doctrine\ORM\Mapping\ToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; +use Doctrine\ORM\Mapping\VersionFieldMetadata; use Doctrine\ORM\Persisters\Collection\ManyToManyPersister; use Doctrine\ORM\Persisters\Collection\OneToManyPersister; use Doctrine\ORM\Persisters\Entity\BasicEntityPersister; use Doctrine\ORM\Persisters\Entity\JoinedSubclassPersister; use Doctrine\ORM\Persisters\Entity\SingleTablePersister; use Doctrine\ORM\Proxy\Proxy; -use Doctrine\ORM\Utility\IdentifierFlattener; use Exception; use InvalidArgumentException; use UnexpectedValueException; @@ -106,7 +101,8 @@ class UnitOfWork implements PropertyChangedListener /** * Map of all identifiers of managed entities. - * Keys are object ids (spl_object_hash). + * This is a 2-dimensional data structure (map of maps). Keys are object ids (spl_object_hash). + * Values are maps of entity identifiers, where its key is the column name and the value is the raw value. * * @var array */ @@ -114,12 +110,13 @@ class UnitOfWork implements PropertyChangedListener /** * Map of the original entity data of managed entities. - * Keys are object ids (spl_object_hash). This is used for calculating changesets - * at commit time. + * This is a 2-dimensional data structure (map of maps). Keys are object ids (spl_object_hash). + * Values are maps of entity data, where its key is the field name and the value is the converted + * (convertToPHPValue) value. + * This structure is used for calculating changesets at commit time. * - * Internal note: Note that PHPs "copy-on-write" behavior helps a lot with memory usage. - * A value will only really be copied if the value in the entity is modified - * by the user. + * Internal: Note that PHPs "copy-on-write" behavior helps a lot with memory usage. + * A value will only really be copied if the value in the entity is modified by the user. * * @var array */ @@ -213,7 +210,7 @@ class UnitOfWork implements PropertyChangedListener * * @var array */ - private $persisters = []; + private $entityPersisters = []; /** * The collection persister instances used to persist collections. @@ -227,7 +224,7 @@ class UnitOfWork implements PropertyChangedListener * * @var \Doctrine\Common\EventManager */ - private $evm; + private $eventManager; /** * The ListenersInvoker used for dispatching events. @@ -237,11 +234,9 @@ class UnitOfWork implements PropertyChangedListener private $listenersInvoker; /** - * The IdentifierFlattener used for manipulating identifiers - * - * @var \Doctrine\ORM\Utility\IdentifierFlattener + * @var Instantiator */ - private $identifierFlattener; + private $instantiator; /** * Orphaned entities that are scheduled for removal. @@ -276,11 +271,6 @@ class UnitOfWork implements PropertyChangedListener */ private $hydrationCompleteHandler; - /** - * @var ReflectionPropertiesGetter - */ - private $reflectionPropertiesGetter; - /** * Initializes a new UnitOfWork instance, bound to the given EntityManager. * @@ -288,13 +278,12 @@ class UnitOfWork implements PropertyChangedListener */ public function __construct(EntityManagerInterface $em) { - $this->em = $em; - $this->evm = $em->getEventManager(); - $this->listenersInvoker = new ListenersInvoker($em); - $this->hasCache = $em->getConfiguration()->isSecondLevelCacheEnabled(); - $this->identifierFlattener = new IdentifierFlattener($this, $em->getMetadataFactory()); - $this->hydrationCompleteHandler = new HydrationCompleteHandler($this->listenersInvoker, $em); - $this->reflectionPropertiesGetter = new ReflectionPropertiesGetter(new RuntimeReflectionService()); + $this->em = $em; + $this->eventManager = $em->getEventManager(); + $this->listenersInvoker = new ListenersInvoker($em); + $this->hasCache = $em->getConfiguration()->isSecondLevelCacheEnabled(); + $this->instantiator = new Instantiator(); + $this->hydrationCompleteHandler = new HydrationCompleteHandler($this->listenersInvoker, $em); } /** @@ -310,29 +299,18 @@ public function __construct(EntityManagerInterface $em) * 4) All collection updates * 5) All entity deletions * - * @param null|object|array $entity - * * @return void * * @throws \Exception */ - public function commit($entity = null) + public function commit() { // Raise preFlush - if ($this->evm->hasListeners(Events::preFlush)) { - $this->evm->dispatchEvent(Events::preFlush, new PreFlushEventArgs($this->em)); + if ($this->eventManager->hasListeners(Events::preFlush)) { + $this->eventManager->dispatchEvent(Events::preFlush, new PreFlushEventArgs($this->em)); } - // Compute changes done since last commit. - if ($entity === null) { - $this->computeChangeSets(); - } elseif (is_object($entity)) { - $this->computeSingleEntityChangeSet($entity); - } elseif (is_array($entity)) { - foreach ($entity as $object) { - $this->computeSingleEntityChangeSet($object); - } - } + $this->computeChangeSets(); if ( ! ($this->entityInsertions || $this->entityDeletions || @@ -390,8 +368,12 @@ public function commit($entity = null) // Entity deletions come last and need to be in reverse commit order if ($this->entityDeletions) { - for ($count = count($commitOrder), $i = $count - 1; $i >= 0 && $this->entityDeletions; --$i) { - $this->executeDeletions($commitOrder[$i]); + foreach (array_reverse($commitOrder) as $committedEntityName) { + if (! $this->entityDeletions) { + break; // just a performance optimisation + } + + $this->executeDeletions($committedEntityName); } } @@ -441,54 +423,6 @@ private function computeScheduleInsertsChangeSets() } } - /** - * Only flushes the given entity according to a ruleset that keeps the UoW consistent. - * - * 1. All entities scheduled for insertion, (orphan) removals and changes in collections are processed as well! - * 2. Read Only entities are skipped. - * 3. Proxies are skipped. - * 4. Only if entity is properly managed. - * - * @param object $entity - * - * @return void - * - * @throws \InvalidArgumentException - */ - private function computeSingleEntityChangeSet($entity) - { - $state = $this->getEntityState($entity); - - if ($state !== self::STATE_MANAGED && $state !== self::STATE_REMOVED) { - throw new \InvalidArgumentException("Entity has to be managed or scheduled for removal for single computation " . self::objToStr($entity)); - } - - $class = $this->em->getClassMetadata(get_class($entity)); - - if ($state === self::STATE_MANAGED && $class->isChangeTrackingDeferredImplicit()) { - $this->persist($entity); - } - - // Compute changes for INSERTed entities first. This must always happen even in this case. - $this->computeScheduleInsertsChangeSets(); - - if ($class->isReadOnly) { - return; - } - - // Ignore uninitialized proxy objects - if ($entity instanceof Proxy && ! $entity->__isInitialized__) { - return; - } - - // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here. - $oid = spl_object_hash($entity); - - if ( ! isset($this->entityInsertions[$oid]) && ! isset($this->entityDeletions[$oid]) && isset($this->entityStates[$oid])) { - $this->computeChangeSet($class, $entity); - } - } - /** * Executes any extra updates that have been scheduled. */ @@ -498,6 +432,10 @@ private function executeExtraUpdates() list ($entity, $changeset) = $update; $this->entityChangeSets[$oid] = $changeset; + +// echo 'Extra update: '; +// \Doctrine\Common\Util\Debug::dump($changeset, 3); + $this->getEntityPersister(get_class($entity))->update($entity); } @@ -528,23 +466,23 @@ public function & getEntityChangeSet($entity) * * Modifies/populates the following properties: * - * {@link _originalEntityData} + * {@link originalEntityData} * If the entity is NEW or MANAGED but not yet fully persisted (only has an id) * then it was not fetched from the database and therefore we have no original * entity data yet. All of the current entity data is stored as the original entity data. * - * {@link _entityChangeSets} + * {@link entityChangeSets} * The changes detected on all properties of the entity are stored there. * A change is a tuple array where the first entry is the old value and the second * entry is the new value of the property. Changesets are used by persisters * to INSERT/UPDATE the persistent entity state. * - * {@link _entityUpdates} + * {@link entityUpdates} * If the entity is already fully MANAGED (has been fetched from the database before) * and any changes to its properties are detected, then a reference to the entity is stored * there to mark it for an update. * - * {@link _collectionDeletions} + * {@link collectionDeletions} * If a PersistentCollection has been de-referenced in a fully MANAGED entity, * then this collection is marked for deletion. * @@ -565,7 +503,7 @@ public function computeChangeSet(ClassMetadata $class, $entity) return; } - if ( ! $class->isInheritanceTypeNone()) { + if ($class->inheritanceType !== InheritanceType::NONE) { $class = $this->em->getClassMetadata(get_class($entity)); } @@ -577,40 +515,29 @@ public function computeChangeSet(ClassMetadata $class, $entity) $actualData = []; - foreach ($class->reflFields as $name => $refProp) { - $value = $refProp->getValue($entity); + foreach ($class->getDeclaredPropertiesIterator() as $name => $property) { + $value = $property->getValue($entity); - if ($class->isCollectionValuedAssociation($name) && $value !== null) { - if ($value instanceof PersistentCollection) { - if ($value->getOwner() === $entity) { - continue; - } - - $value = new ArrayCollection($value->getValues()); - } - - // If $value is not a Collection then use an ArrayCollection. - if ( ! $value instanceof Collection) { - $value = new ArrayCollection($value); + if ($property instanceof ToManyAssociationMetadata && $value !== null) { + if ($value instanceof PersistentCollection && $value->getOwner() === $entity) { + continue; } - $assoc = $class->associationMappings[$name]; - - // Inject PersistentCollection - $value = new PersistentCollection( - $this->em, $this->em->getClassMetadata($assoc['targetEntity']), $value - ); - $value->setOwner($entity, $assoc); - $value->setDirty( ! $value->isEmpty()); + $value = $property->wrap($entity, $value, $this->em); - $class->reflFields[$name]->setValue($entity, $value); + $property->setValue($entity, $value); $actualData[$name] = $value; continue; } - if (( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity()) && ($name !== $class->versionField)) { + if ( + ( ! $class->isIdentifier($name) + || ! $class->getProperty($name) instanceof FieldMetadata + || ! $class->getProperty($name)->hasValueGenerator() + || $class->getProperty($name)->getValueGenerator()->getType() !== GeneratorType::IDENTITY + ) && (! $class->isVersioned() || $name !== $class->versionProperty->getName())) { $actualData[$name] = $value; } } @@ -622,15 +549,10 @@ public function computeChangeSet(ClassMetadata $class, $entity) $changeSet = []; foreach ($actualData as $propName => $actualValue) { - if ( ! isset($class->associationMappings[$propName])) { - $changeSet[$propName] = [null, $actualValue]; - - continue; - } + $property = $class->getProperty($propName); - $assoc = $class->associationMappings[$propName]; - - if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) { + if (($property instanceof FieldMetadata) || + ($property instanceof ToOneAssociationMetadata && $property->isOwningSide())) { $changeSet[$propName] = [null, $actualValue]; } } @@ -640,7 +562,7 @@ public function computeChangeSet(ClassMetadata $class, $entity) // Entity is "fully" MANAGED: it was already fully persisted before // and we have a copy of the original data $originalData = $this->originalEntityData[$oid]; - $isChangeTrackingNotify = $class->isChangeTrackingNotify(); + $isChangeTrackingNotify = $class->changeTrackingPolicy === ChangeTrackingPolicy::NOTIFY; $changeSet = ($isChangeTrackingNotify && isset($this->entityChangeSets[$oid])) ? $this->entityChangeSets[$oid] : []; @@ -658,58 +580,67 @@ public function computeChangeSet(ClassMetadata $class, $entity) continue; } - // if regular field - if ( ! isset($class->associationMappings[$propName])) { - if ($isChangeTrackingNotify) { - continue; - } - - $changeSet[$propName] = [$orgValue, $actualValue]; - - continue; - } - - $assoc = $class->associationMappings[$propName]; + $property = $class->getProperty($propName); // Persistent collection was exchanged with the "originally" // created one. This can only mean it was cloned and replaced // on another entity. if ($actualValue instanceof PersistentCollection) { $owner = $actualValue->getOwner(); + if ($owner === null) { // cloned - $actualValue->setOwner($entity, $assoc); + $actualValue->setOwner($entity, $property); } else if ($owner !== $entity) { // no clone, we have to fix - if (!$actualValue->isInitialized()) { + if (! $actualValue->isInitialized()) { $actualValue->initialize(); // we have to do this otherwise the cols share state } + $newValue = clone $actualValue; - $newValue->setOwner($entity, $assoc); - $class->reflFields[$propName]->setValue($entity, $newValue); + + $newValue->setOwner($entity, $property); + + $property->setValue($entity, $newValue); } } - if ($orgValue instanceof PersistentCollection) { - // A PersistentCollection was de-referenced, so delete it. - $coid = spl_object_hash($orgValue); + switch (true) { + case ($property instanceof FieldMetadata): + if ($isChangeTrackingNotify) { + // Continue inside switch behaves as break. + // We are required to use continue 2, since we need to continue to next $actualData item + continue 2; + } - if (isset($this->collectionDeletions[$coid])) { - continue; - } + $changeSet[$propName] = [$orgValue, $actualValue]; + break; - $this->collectionDeletions[$coid] = $orgValue; - $changeSet[$propName] = $orgValue; // Signal changeset, to-many assocs will be ignored. + case ($property instanceof ToOneAssociationMetadata): + if ($property->isOwningSide()) { + $changeSet[$propName] = [$orgValue, $actualValue]; + } - continue; - } + if ($orgValue !== null && $property->isOrphanRemoval()) { + $this->scheduleOrphanRemoval($orgValue); + } - if ($assoc['type'] & ClassMetadata::TO_ONE) { - if ($assoc['isOwningSide']) { - $changeSet[$propName] = [$orgValue, $actualValue]; - } + break; - if ($orgValue !== null && $assoc['orphanRemoval']) { - $this->scheduleOrphanRemoval($orgValue); - } + case ($property instanceof ToManyAssociationMetadata): + // Check if original value exists + if ($orgValue instanceof PersistentCollection) { + // A PersistentCollection was de-referenced, so delete it. + $coid = spl_object_hash($orgValue); + + if (!isset($this->collectionDeletions[$coid])) { + $this->collectionDeletions[$coid] = $orgValue; + $changeSet[$propName] = $orgValue; // Signal changeset, to-many associations will be ignored + } + } + + break; + + default: + // Do nothing } } @@ -721,18 +652,18 @@ public function computeChangeSet(ClassMetadata $class, $entity) } // Look for changes in associations of the entity - foreach ($class->associationMappings as $field => $assoc) { - if (($val = $class->reflFields[$field]->getValue($entity)) === null) { + foreach ($class->getDeclaredPropertiesIterator() as $property) { + if (! ($property instanceof AssociationMetadata) || ($value = $property->getValue($entity)) === null) { continue; } - $this->computeAssociationChanges($assoc, $val); + $this->computeAssociationChanges($property, $value); - if ( ! isset($this->entityChangeSets[$oid]) && - $assoc['isOwningSide'] && - $assoc['type'] == ClassMetadata::MANY_TO_MANY && - $val instanceof PersistentCollection && - $val->isDirty()) { + if ($property instanceof ManyToManyAssociationMetadata && + $value instanceof PersistentCollection && + ! isset($this->entityChangeSets[$oid]) && + $property->isOwningSide() && + $value->isDirty()) { $this->entityChangeSets[$oid] = []; $this->originalEntityData[$oid] = $actualData; @@ -758,14 +689,14 @@ public function computeChangeSets() $class = $this->em->getClassMetadata($className); // Skip class if instances are read-only - if ($class->isReadOnly) { + if ($class->isReadOnly()) { continue; } // If change tracking is explicit or happens through notification, then only compute // changes on entities of that type that are explicitly marked for synchronization. switch (true) { - case ($class->isChangeTrackingDeferredImplicit()): + case ($class->changeTrackingPolicy === ChangeTrackingPolicy::DEFERRED_IMPLICIT): $entitiesToProcess = $entities; break; @@ -780,7 +711,7 @@ public function computeChangeSets() foreach ($entitiesToProcess as $entity) { // Ignore uninitialized proxy objects - if ($entity instanceof Proxy && ! $entity->__isInitialized__) { + if ($entity instanceof Proxy && ! $entity->__isInitialized()) { continue; } @@ -797,17 +728,17 @@ public function computeChangeSets() /** * Computes the changes of an association. * - * @param array $assoc The association mapping. - * @param mixed $value The value of the association. + * @param AssociationMetadata $association The association mapping. + * @param mixed $value The value of the association. * * @throws ORMInvalidArgumentException * @throws ORMException * * @return void */ - private function computeAssociationChanges($assoc, $value) + private function computeAssociationChanges(AssociationMetadata $association, $value) { - if ($value instanceof Proxy && ! $value->__isInitialized__) { + if ($value instanceof Proxy && ! $value->__isInitialized()) { return; } @@ -821,24 +752,30 @@ private function computeAssociationChanges($assoc, $value) // Look through the entities, and in any of their associations, // for transient (new) entities, recursively. ("Persistence by reachability") // Unwrap. Uninitialized collections will simply be empty. - $unwrappedValue = ($assoc['type'] & ClassMetadata::TO_ONE) ? [$value] : $value->unwrap(); - $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); + $unwrappedValue = ($association instanceof ToOneAssociationMetadata) ? [$value] : $value->unwrap(); + $targetEntity = $association->getTargetEntity(); + $targetClass = $this->em->getClassMetadata($targetEntity); foreach ($unwrappedValue as $key => $entry) { - if (! ($entry instanceof $targetClass->name)) { - throw ORMInvalidArgumentException::invalidAssociation($targetClass, $assoc, $entry); + if (! ($entry instanceof $targetEntity)) { + throw ORMInvalidArgumentException::invalidAssociation($targetClass, $association, $entry); } $state = $this->getEntityState($entry, self::STATE_NEW); - if ( ! ($entry instanceof $assoc['targetEntity'])) { - throw ORMException::unexpectedAssociationValue($assoc['sourceEntity'], $assoc['fieldName'], get_class($entry), $assoc['targetEntity']); + if (! ($entry instanceof $targetEntity)) { + throw ORMException::unexpectedAssociationValue( + $association->getSourceEntity(), + $association->getName(), + get_class($entry), + $targetEntity + ); } switch ($state) { case self::STATE_NEW: - if ( ! $assoc['isCascadePersist']) { - throw ORMInvalidArgumentException::newEntityFoundThroughRelationship($assoc, $entry); + if ( ! in_array('persist', $association->getCascade())) { + throw ORMInvalidArgumentException::newEntityFoundThroughRelationship($association, $entry); } $this->persistNew($targetClass, $entry); @@ -848,7 +785,7 @@ private function computeAssociationChanges($assoc, $value) case self::STATE_REMOVED: // Consume the $value as array (it's either an array or an ArrayAccess) // and remove the element from Collection. - if ($assoc['type'] & ClassMetadata::TO_MANY) { + if ($association instanceof ToManyAssociationMetadata) { unset($value[$key]); } break; @@ -856,7 +793,7 @@ private function computeAssociationChanges($assoc, $value) case self::STATE_DETACHED: // Can actually not happen right now as we assume STATE_NEW, // so the exception will be raised from the DBAL layer (constraint violation). - throw ORMInvalidArgumentException::detachedEntityFoundThroughRelationship($assoc, $entry); + throw ORMInvalidArgumentException::detachedEntityFoundThroughRelationship($association, $entry); break; default: @@ -881,18 +818,13 @@ private function persistNew($class, $entity) $this->listenersInvoker->invoke($class, Events::prePersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke); } - $idGen = $class->idGenerator; - - if ( ! $idGen->isPostInsertGenerator()) { - $idValue = $idGen->generate($this->em, $entity); + $generationPlan = $class->getValueGenerationPlan(); + $persister = $this->getEntityPersister($class->getClassName()); + $generationPlan->executeImmediate($this->em, $entity); - if ( ! $idGen instanceof \Doctrine\ORM\Id\AssignedGenerator) { - $idValue = [$class->getSingleIdentifierFieldName() => $this->convertSingleFieldIdentifierToPHPValue($class, $idValue)]; - - $class->setIdentifierValues($entity, $idValue); - } - - $this->entityIdentifiers[$oid] = $idValue; + if (! $generationPlan->containsDeferred()) { + $id = $this->em->getIdentifierFlattener()->flattenIdentifier($class, $persister->getIdentifier($entity)); + $this->entityIdentifiers[$oid] = $id; } $this->entityStates[$oid] = self::STATE_MANAGED; @@ -917,31 +849,45 @@ private function persistNew($class, $entity) * @return void * * @throws ORMInvalidArgumentException If the passed entity is not MANAGED. + * @throws \RuntimeException */ - public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity) + public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity) : void { $oid = spl_object_hash($entity); - if ( ! isset($this->entityStates[$oid]) || $this->entityStates[$oid] != self::STATE_MANAGED) { + if (! isset($this->entityStates[$oid]) || $this->entityStates[$oid] !== self::STATE_MANAGED) { throw ORMInvalidArgumentException::entityNotManaged($entity); } // skip if change tracking is "NOTIFY" - if ($class->isChangeTrackingNotify()) { + if ($class->changeTrackingPolicy === ChangeTrackingPolicy::NOTIFY) { return; } - if ( ! $class->isInheritanceTypeNone()) { + if ($class->inheritanceType !== InheritanceType::NONE) { $class = $this->em->getClassMetadata(get_class($entity)); } $actualData = []; - foreach ($class->reflFields as $name => $refProp) { - if (( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity()) - && ($name !== $class->versionField) - && ! $class->isCollectionValuedAssociation($name)) { - $actualData[$name] = $refProp->getValue($entity); + foreach ($class->getDeclaredPropertiesIterator() as $name => $property) { + switch (true) { + case ($property instanceof VersionFieldMetadata): + // Ignore version field + break; + + case ($property instanceof FieldMetadata): + if (! $property->isPrimaryKey() + || ! $property->getValueGenerator() + || $property->getValueGenerator()->getType() !== GeneratorType::IDENTITY) { + $actualData[$name] = $property->getValue($entity); + } + + break; + + case ($property instanceof ToOneAssociationMetadata): + $actualData[$name] = $property->getValue($entity); + break; } } @@ -974,55 +920,43 @@ public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity) /** * Executes all entity insertions for entities of the specified type. * - * @param \Doctrine\ORM\Mapping\ClassMetadata $class + * @param ClassMetadata $class * * @return void */ - private function executeInserts($class) + private function executeInserts(ClassMetadata $class) : void { - $entities = []; - $className = $class->name; - $persister = $this->getEntityPersister($className); - $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postPersist); + $className = $class->getClassName(); + $persister = $this->getEntityPersister($className); + $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postPersist); + $generationPlan = $class->getValueGenerationPlan(); foreach ($this->entityInsertions as $oid => $entity) { - - if ($this->em->getClassMetadata(get_class($entity))->name !== $className) { + if ($this->em->getClassMetadata(get_class($entity))->getClassName() !== $className) { continue; } - $persister->addInsert($entity); - - unset($this->entityInsertions[$oid]); - - if ($invoke !== ListenersInvoker::INVOKE_NONE) { - $entities[] = $entity; - } - } - - $postInsertIds = $persister->executeInserts(); - - if ($postInsertIds) { - // Persister returned post-insert IDs - foreach ($postInsertIds as $postInsertId) { - $idField = $class->getSingleIdentifierFieldName(); - $idValue = $this->convertSingleFieldIdentifierToPHPValue($class, $postInsertId['generatedId']); - - $entity = $postInsertId['entity']; - $oid = spl_object_hash($entity); + $persister->insert($entity); - $class->reflFields[$idField]->setValue($entity, $idValue); + if ($generationPlan->containsDeferred()) { + // Entity has post-insert IDs + $oid = spl_object_hash($entity); + $id = $this->em->getIdentifierFlattener()->flattenIdentifier($class, $persister->getIdentifier($entity)); - $this->entityIdentifiers[$oid] = [$idField => $idValue]; + $this->entityIdentifiers[$oid] = $id; $this->entityStates[$oid] = self::STATE_MANAGED; - $this->originalEntityData[$oid][$idField] = $idValue; + $this->originalEntityData[$oid] = $id + $this->originalEntityData[$oid]; $this->addToIdentityMap($entity); } - } - foreach ($entities as $entity) { - $this->listenersInvoker->invoke($class, Events::postPersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke); + unset($this->entityInsertions[$oid]); + + if ($invoke !== ListenersInvoker::INVOKE_NONE) { + $eventArgs = new LifecycleEventArgs($entity, $this->em); + + $this->listenersInvoker->invoke($class, Events::postPersist, $entity, $eventArgs, $invoke); + } } } @@ -1035,13 +969,13 @@ private function executeInserts($class) */ private function executeUpdates($class) { - $className = $class->name; + $className = $class->getClassName(); $persister = $this->getEntityPersister($className); $preUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preUpdate); $postUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postUpdate); foreach ($this->entityUpdates as $oid => $entity) { - if ($this->em->getClassMetadata(get_class($entity))->name !== $className) { + if ($this->em->getClassMetadata(get_class($entity))->getClassName() !== $className) { continue; } @@ -1052,6 +986,9 @@ private function executeUpdates($class) } if ( ! empty($this->entityChangeSets[$oid])) { +// echo 'Update: '; +// \Doctrine\Common\Util\Debug::dump($this->entityChangeSets[$oid], 3); + $persister->update($entity); } @@ -1072,12 +1009,12 @@ private function executeUpdates($class) */ private function executeDeletions($class) { - $className = $class->name; + $className = $class->getClassName(); $persister = $this->getEntityPersister($className); $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postRemove); foreach ($this->entityDeletions as $oid => $entity) { - if ($this->em->getClassMetadata(get_class($entity))->name !== $className) { + if ($this->em->getClassMetadata(get_class($entity))->getClassName() !== $className) { continue; } @@ -1093,12 +1030,18 @@ private function executeDeletions($class) // Entity with this $oid after deletion treated as NEW, even if the $oid // is obtained by a new entity because the old one went out of scope. //$this->entityStates[$oid] = self::STATE_NEW; - if ( ! $class->isIdentifierNatural()) { - $class->reflFields[$class->identifier[0]]->setValue($entity, null); + if (! $class->isIdentifierComposite()) { + $property = $class->getProperty($class->getSingleIdentifierFieldName()); + + if ($property instanceof FieldMetadata && $property->hasValueGenerator()) { + $property->setValue($entity, null); + } } if ($invoke !== ListenersInvoker::INVOKE_NONE) { - $this->listenersInvoker->invoke($class, Events::postRemove, $entity, new LifecycleEventArgs($entity, $this->em), $invoke); + $eventArgs = new LifecycleEventArgs($entity, $this->em); + + $this->listenersInvoker->invoke($class, Events::postRemove, $entity, $eventArgs, $invoke); } } } @@ -1106,17 +1049,11 @@ private function executeDeletions($class) /** * Gets the commit order. * - * @param array|null $entityChangeSet - * * @return array */ - private function getCommitOrder(array $entityChangeSet = null) + private function getCommitOrder() { - if ($entityChangeSet === null) { - $entityChangeSet = array_merge($this->entityInsertions, $this->entityUpdates, $this->entityDeletions); - } - - $calc = $this->getCommitOrderCalculator(); + $calc = new Internal\CommitOrderCalculator(); // See if there are any new classes in the changeset, that are not in the // commit order graph yet (don't have a node). @@ -1125,52 +1062,55 @@ private function getCommitOrder(array $entityChangeSet = null) // are not yet available. $newNodes = []; - foreach ($entityChangeSet as $entity) { + foreach (\array_merge($this->entityInsertions, $this->entityUpdates, $this->entityDeletions) as $entity) { $class = $this->em->getClassMetadata(get_class($entity)); - if ($calc->hasNode($class->name)) { + if ($calc->hasNode($class->getClassName())) { continue; } - $calc->addNode($class->name, $class); + $calc->addNode($class->getClassName(), $class); $newNodes[] = $class; } // Calculate dependencies for new nodes while ($class = array_pop($newNodes)) { - foreach ($class->associationMappings as $assoc) { - if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) { + foreach ($class->getDeclaredPropertiesIterator() as $property) { + if (! ($property instanceof ToOneAssociationMetadata && $property->isOwningSide())) { continue; } - $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); + $targetClass = $this->em->getClassMetadata($property->getTargetEntity()); - if ( ! $calc->hasNode($targetClass->name)) { - $calc->addNode($targetClass->name, $targetClass); + if ( ! $calc->hasNode($targetClass->getClassName())) { + $calc->addNode($targetClass->getClassName(), $targetClass); $newNodes[] = $targetClass; } - $joinColumns = reset($assoc['joinColumns']); + $weight = ! array_filter( + $property->getJoinColumns(), + function (JoinColumnMetadata $joinColumn) { return $joinColumn->isNullable(); } + ); - $calc->addDependency($targetClass->name, $class->name, (int)empty($joinColumns['nullable'])); + $calc->addDependency($targetClass->getClassName(), $class->getClassName(), $weight); // If the target class has mapped subclasses, these share the same dependency. - if ( ! $targetClass->subClasses) { + if ( ! $targetClass->getSubClasses()) { continue; } - foreach ($targetClass->subClasses as $subClassName) { + foreach ($targetClass->getSubClasses() as $subClassName) { $targetSubClass = $this->em->getClassMetadata($subClassName); if ( ! $calc->hasNode($subClassName)) { - $calc->addNode($targetSubClass->name, $targetSubClass); + $calc->addNode($targetSubClass->getClassName(), $targetSubClass); $newNodes[] = $targetSubClass; } - $calc->addDependency($targetSubClass->name, $class->name, 1); + $calc->addDependency($targetSubClass->getClassName(), $class->getClassName(), 1); } } } @@ -1240,7 +1180,7 @@ public function isScheduledForInsert($entity) * * @throws ORMInvalidArgumentException */ - public function scheduleForUpdate($entity) + public function scheduleForUpdate($entity) : void { $oid = spl_object_hash($entity); @@ -1271,13 +1211,13 @@ public function scheduleForUpdate($entity) * * @return void */ - public function scheduleExtraUpdate($entity, array $changeset) + public function scheduleExtraUpdate($entity, array $changeset) : void { $oid = spl_object_hash($entity); $extraUpdate = [$entity, $changeset]; if (isset($this->extraUpdates[$oid])) { - list(, $changeset2) = $this->extraUpdates[$oid]; + [$unused, $changeset2] = $this->extraUpdates[$oid]; $extraUpdate = [$entity, $changeset + $changeset2]; } @@ -1294,7 +1234,7 @@ public function scheduleExtraUpdate($entity, array $changeset) * * @return boolean */ - public function isScheduledForUpdate($entity) + public function isScheduledForUpdate($entity) : bool { return isset($this->entityUpdates[spl_object_hash($entity)]); } @@ -1306,9 +1246,9 @@ public function isScheduledForUpdate($entity) * * @return boolean */ - public function isScheduledForDirtyCheck($entity) + public function isScheduledForDirtyCheck($entity) : bool { - $rootEntityName = $this->em->getClassMetadata(get_class($entity))->rootEntityName; + $rootEntityName = $this->em->getClassMetadata(get_class($entity))->getRootClassName(); return isset($this->scheduledForSynchronization[$rootEntityName][spl_object_hash($entity)]); } @@ -1399,11 +1339,11 @@ public function addToIdentityMap($entity) $identifier = $this->entityIdentifiers[spl_object_hash($entity)]; if (empty($identifier) || in_array(null, $identifier, true)) { - throw ORMInvalidArgumentException::entityWithoutIdentity($classMetadata->name, $entity); + throw ORMInvalidArgumentException::entityWithoutIdentity($classMetadata->getClassName(), $entity); } $idHash = implode(' ', $identifier); - $className = $classMetadata->rootEntityName; + $className = $classMetadata->getRootClassName(); if (isset($this->identityMap[$className][$idHash])) { return false; @@ -1441,58 +1381,61 @@ public function getEntityState($entity, $assume = null) // Note that you can not remember the NEW or DETACHED state in _entityStates since // the UoW does not hold references to such objects and the object hash can be reused. // More generally because the state may "change" between NEW/DETACHED without the UoW being aware of it. - $class = $this->em->getClassMetadata(get_class($entity)); - $id = $class->getIdentifierValues($entity); + $class = $this->em->getClassMetadata(get_class($entity)); + $persister = $this->getEntityPersister($class->getClassName()); + $id = $persister->getIdentifier($entity); - if ( ! $id) { + if (! $id) { return self::STATE_NEW; } - if ($class->containsForeignIdentifier) { - $id = $this->identifierFlattener->flattenIdentifier($class, $id); - } - - switch (true) { - case ($class->isIdentifierNatural()): - // Check for a version field, if available, to avoid a db lookup. - if ($class->isVersioned) { - return ($class->getFieldValue($entity, $class->versionField)) - ? self::STATE_DETACHED - : self::STATE_NEW; - } - - // Last try before db lookup: check the identity map. - if ($this->tryGetById($id, $class->rootEntityName)) { - return self::STATE_DETACHED; - } + $flatId = $this->em->getIdentifierFlattener()->flattenIdentifier($class, $id); - // db lookup - if ($this->getEntityPersister($class->name)->exists($entity)) { - return self::STATE_DETACHED; - } + if ($class->isIdentifierComposite() + || ! $class->getProperty($class->getSingleIdentifierFieldName()) instanceof FieldMetadata + || ! $class->getProperty($class->getSingleIdentifierFieldName())->hasValueGenerator() + ) { + // Check for a version field, if available, to avoid a db lookup. + if ($class->isVersioned()) { + return $class->versionProperty->getValue($entity) + ? self::STATE_DETACHED + : self::STATE_NEW; + } - return self::STATE_NEW; + // Last try before db lookup: check the identity map. + if ($this->tryGetById($flatId, $class->getRootClassName())) { + return self::STATE_DETACHED; + } - case ( ! $class->idGenerator->isPostInsertGenerator()): - // if we have a pre insert generator we can't be sure that having an id - // really means that the entity exists. We have to verify this through - // the last resort: a db lookup + // db lookup + if ($this->getEntityPersister($class->getClassName())->exists($entity)) { + return self::STATE_DETACHED; + } - // Last try before db lookup: check the identity map. - if ($this->tryGetById($id, $class->rootEntityName)) { - return self::STATE_DETACHED; - } + return self::STATE_NEW; + } - // db lookup - if ($this->getEntityPersister($class->name)->exists($entity)) { - return self::STATE_DETACHED; - } + if ($class->isIdentifierComposite() + || ! $class->getProperty($class->getSingleIdentifierFieldName()) instanceof FieldMetadata + || ! $class->getValueGenerationPlan()->containsDeferred()) { + // if we have a pre insert generator we can't be sure that having an id + // really means that the entity exists. We have to verify this through + // the last resort: a db lookup - return self::STATE_NEW; + // Last try before db lookup: check the identity map. + if ($this->tryGetById($flatId, $class->getRootClassName())) { + return self::STATE_DETACHED; + } - default: + // db lookup + if ($this->getEntityPersister($class->getClassName())->exists($entity)) { return self::STATE_DETACHED; + } + + return self::STATE_NEW; } + + return self::STATE_DETACHED; } /** @@ -1518,7 +1461,7 @@ public function removeFromIdentityMap($entity) throw ORMInvalidArgumentException::entityHasNoIdentity($entity, "remove from identity map"); } - $className = $classMetadata->rootEntityName; + $className = $classMetadata->getRootClassName(); if (isset($this->identityMap[$className][$idHash])) { unset($this->identityMap[$className][$idHash]); @@ -1587,7 +1530,7 @@ public function isInIdentityMap($entity) $classMetadata = $this->em->getClassMetadata(get_class($entity)); $idHash = implode(' ', $this->entityIdentifiers[$oid]); - return isset($this->identityMap[$classMetadata->rootEntityName][$idHash]); + return isset($this->identityMap[$classMetadata->getRootClassName()][$idHash]); } /** @@ -1655,8 +1598,8 @@ private function doPersist($entity, array &$visited) switch ($entityState) { case self::STATE_MANAGED: // Nothing to do, except if policy is "deferred explicit" - if ($class->isChangeTrackingDeferredExplicit()) { - $this->scheduleForDirtyCheck($entity); + if ($class->changeTrackingPolicy === ChangeTrackingPolicy::DEFERRED_EXPLICIT) { + $this->scheduleForSynchronization($entity); } break; @@ -1753,327 +1696,118 @@ private function doRemove($entity, array &$visited) } /** - * Merges the state of the given detached entity into this UnitOfWork. - * - * @param object $entity + * Refreshes the state of the given entity from the database, overwriting + * any local, unpersisted changes. * - * @return object The managed copy of the entity. + * @param object $entity The entity to refresh. * - * @throws OptimisticLockException If the entity uses optimistic locking through a version - * attribute and the version check against the managed copy fails. + * @return void * - * @todo Require active transaction!? OptimisticLockException may result in undefined state!? + * @throws InvalidArgumentException If the entity is not MANAGED. */ - public function merge($entity) + public function refresh($entity) { $visited = []; - return $this->doMerge($entity, $visited); + $this->doRefresh($entity, $visited); } /** - * Executes a merge operation on an entity. + * Executes a refresh operation on an entity. * - * @param object $entity - * @param array $visited - * @param object|null $prevManagedCopy - * @param array|null $assoc + * @param object $entity The entity to refresh. + * @param array $visited The already visited entities during cascades. * - * @return object The managed copy of the entity. + * @return void * - * @throws OptimisticLockException If the entity uses optimistic locking through a version - * attribute and the version check against the managed copy fails. - * @throws ORMInvalidArgumentException If the entity instance is NEW. - * @throws EntityNotFoundException if an assigned identifier is used in the entity, but none is provided + * @throws ORMInvalidArgumentException If the entity is not MANAGED. */ - private function doMerge($entity, array &$visited, $prevManagedCopy = null, array $assoc = []) + private function doRefresh($entity, array &$visited) { $oid = spl_object_hash($entity); if (isset($visited[$oid])) { - $managedCopy = $visited[$oid]; - - if ($prevManagedCopy !== null) { - $this->updateAssociationWithMergedEntity($entity, $assoc, $prevManagedCopy, $managedCopy); - } - - return $managedCopy; + return; // Prevent infinite recursion } - $class = $this->em->getClassMetadata(get_class($entity)); - - // First we assume DETACHED, although it can still be NEW but we can avoid - // an extra db-roundtrip this way. If it is not MANAGED but has an identity, - // we need to fetch it from the db anyway in order to merge. - // MANAGED entities are ignored by the merge operation. - $managedCopy = $entity; - - if ($this->getEntityState($entity, self::STATE_DETACHED) !== self::STATE_MANAGED) { - // Try to look the entity up in the identity map. - $id = $class->getIdentifierValues($entity); - - // If there is no ID, it is actually NEW. - if ( ! $id) { - $managedCopy = $this->newInstance($class); - - $this->mergeEntityStateIntoManagedCopy($entity, $managedCopy); - $this->persistNew($class, $managedCopy); - } else { - $flatId = ($class->containsForeignIdentifier) - ? $this->identifierFlattener->flattenIdentifier($class, $id) - : $id; - - $managedCopy = $this->tryGetById($flatId, $class->rootEntityName); - - if ($managedCopy) { - // We have the entity in-memory already, just make sure its not removed. - if ($this->getEntityState($managedCopy) == self::STATE_REMOVED) { - throw ORMInvalidArgumentException::entityIsRemoved($managedCopy, "merge"); - } - } else { - // We need to fetch the managed copy in order to merge. - $managedCopy = $this->em->find($class->name, $flatId); - } - - if ($managedCopy === null) { - // If the identifier is ASSIGNED, it is NEW, otherwise an error - // since the managed entity was not found. - if ( ! $class->isIdentifierNatural()) { - throw EntityNotFoundException::fromClassNameAndIdentifier( - $class->getName(), - $this->identifierFlattener->flattenIdentifier($class, $id) - ); - } - - $managedCopy = $this->newInstance($class); - $class->setIdentifierValues($managedCopy, $id); - - $this->mergeEntityStateIntoManagedCopy($entity, $managedCopy); - $this->persistNew($class, $managedCopy); - } else { - $this->ensureVersionMatch($class, $entity, $managedCopy); - $this->mergeEntityStateIntoManagedCopy($entity, $managedCopy); - } - } - - $visited[$oid] = $managedCopy; // mark visited + $visited[$oid] = $entity; // mark visited - if ($class->isChangeTrackingDeferredExplicit()) { - $this->scheduleForDirtyCheck($entity); - } - } + $class = $this->em->getClassMetadata(get_class($entity)); - if ($prevManagedCopy !== null) { - $this->updateAssociationWithMergedEntity($entity, $assoc, $prevManagedCopy, $managedCopy); + if ($this->getEntityState($entity) !== self::STATE_MANAGED) { + throw ORMInvalidArgumentException::entityNotManaged($entity); } - // Mark the managed copy visited as well - $visited[spl_object_hash($managedCopy)] = $managedCopy; - - $this->cascadeMerge($entity, $managedCopy, $visited); + $this->getEntityPersister($class->getClassName())->refresh( + array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]), + $entity + ); - return $managedCopy; + $this->cascadeRefresh($entity, $visited); } /** - * @param ClassMetadata $class - * @param object $entity - * @param object $managedCopy + * Cascades a refresh operation to associated entities. * - * @return void + * @param object $entity + * @param array $visited * - * @throws OptimisticLockException + * @return void */ - private function ensureVersionMatch(ClassMetadata $class, $entity, $managedCopy) + private function cascadeRefresh($entity, array &$visited) { - if (! ($class->isVersioned && $this->isLoaded($managedCopy) && $this->isLoaded($entity))) { - return; - } + $class = $this->em->getClassMetadata(get_class($entity)); - $reflField = $class->reflFields[$class->versionField]; - $managedCopyVersion = $reflField->getValue($managedCopy); - $entityVersion = $reflField->getValue($entity); + foreach ($class->getDeclaredPropertiesIterator() as $association) { + if (! ($association instanceof AssociationMetadata && in_array('refresh', $association->getCascade()))) { + continue; + } - // Throw exception if versions don't match. - if ($managedCopyVersion == $entityVersion) { - return; - } + $relatedEntities = $association->getValue($entity); - throw OptimisticLockException::lockFailedVersionMismatch($entity, $entityVersion, $managedCopyVersion); - } + switch (true) { + case ($relatedEntities instanceof PersistentCollection): + // Unwrap so that foreach() does not initialize + $relatedEntities = $relatedEntities->unwrap(); + // break; is commented intentionally! - /** - * Tests if an entity is loaded - must either be a loaded proxy or not a proxy - * - * @param object $entity - * - * @return bool - */ - private function isLoaded($entity) - { - return !($entity instanceof Proxy) || $entity->__isInitialized(); + case ($relatedEntities instanceof Collection): + case (is_array($relatedEntities)): + foreach ($relatedEntities as $relatedEntity) { + $this->doRefresh($relatedEntity, $visited); + } + break; + + case ($relatedEntities !== null): + $this->doRefresh($relatedEntities, $visited); + break; + + default: + // Do nothing + } + } } /** - * Sets/adds associated managed copies into the previous entity's association field + * Cascades the save operation to associated entities. * * @param object $entity - * @param array $association - * @param object $previousManagedCopy - * @param object $managedCopy + * @param array $visited * * @return void */ - private function updateAssociationWithMergedEntity($entity, array $association, $previousManagedCopy, $managedCopy) + private function cascadePersist($entity, array &$visited) { - $assocField = $association['fieldName']; - $prevClass = $this->em->getClassMetadata(get_class($previousManagedCopy)); - - if ($association['type'] & ClassMetadata::TO_ONE) { - $prevClass->reflFields[$assocField]->setValue($previousManagedCopy, $managedCopy); + $class = $this->em->getClassMetadata(get_class($entity)); - return; - } + foreach ($class->getDeclaredPropertiesIterator() as $association) { + if (! ($association instanceof AssociationMetadata && in_array('persist', $association->getCascade()))) { + continue; + } - $value = $prevClass->reflFields[$assocField]->getValue($previousManagedCopy); - $value[] = $managedCopy; - - if ($association['type'] == ClassMetadata::ONE_TO_MANY) { - $class = $this->em->getClassMetadata(get_class($entity)); - - $class->reflFields[$association['mappedBy']]->setValue($managedCopy, $previousManagedCopy); - } - } - - /** - * Detaches an entity from the persistence management. It's persistence will - * no longer be managed by Doctrine. - * - * @param object $entity The entity to detach. - * - * @return void - */ - public function detach($entity) - { - $visited = []; - - $this->doDetach($entity, $visited); - } - - /** - * Executes a detach operation on the given entity. - * - * @param object $entity - * @param array $visited - * @param boolean $noCascade if true, don't cascade detach operation. - * - * @return void - */ - private function doDetach($entity, array &$visited, $noCascade = false) - { - $oid = spl_object_hash($entity); - - if (isset($visited[$oid])) { - return; // Prevent infinite recursion - } - - $visited[$oid] = $entity; // mark visited - - switch ($this->getEntityState($entity, self::STATE_DETACHED)) { - case self::STATE_MANAGED: - if ($this->isInIdentityMap($entity)) { - $this->removeFromIdentityMap($entity); - } - - unset( - $this->entityInsertions[$oid], - $this->entityUpdates[$oid], - $this->entityDeletions[$oid], - $this->entityIdentifiers[$oid], - $this->entityStates[$oid], - $this->originalEntityData[$oid] - ); - break; - case self::STATE_NEW: - case self::STATE_DETACHED: - return; - } - - if ( ! $noCascade) { - $this->cascadeDetach($entity, $visited); - } - } - - /** - * Refreshes the state of the given entity from the database, overwriting - * any local, unpersisted changes. - * - * @param object $entity The entity to refresh. - * - * @return void - * - * @throws InvalidArgumentException If the entity is not MANAGED. - */ - public function refresh($entity) - { - $visited = []; - - $this->doRefresh($entity, $visited); - } - - /** - * Executes a refresh operation on an entity. - * - * @param object $entity The entity to refresh. - * @param array $visited The already visited entities during cascades. - * - * @return void - * - * @throws ORMInvalidArgumentException If the entity is not MANAGED. - */ - private function doRefresh($entity, array &$visited) - { - $oid = spl_object_hash($entity); - - if (isset($visited[$oid])) { - return; // Prevent infinite recursion - } - - $visited[$oid] = $entity; // mark visited - - $class = $this->em->getClassMetadata(get_class($entity)); - - if ($this->getEntityState($entity) !== self::STATE_MANAGED) { - throw ORMInvalidArgumentException::entityNotManaged($entity); - } - - $this->getEntityPersister($class->name)->refresh( - array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]), - $entity - ); - - $this->cascadeRefresh($entity, $visited); - } - - /** - * Cascades a refresh operation to associated entities. - * - * @param object $entity - * @param array $visited - * - * @return void - */ - private function cascadeRefresh($entity, array &$visited) - { - $class = $this->em->getClassMetadata(get_class($entity)); - - $associationMappings = array_filter( - $class->associationMappings, - function ($assoc) { return $assoc['isCascadeRefresh']; } - ); - - foreach ($associationMappings as $assoc) { - $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity); + /** @var AssociationMetadata $association */ + $relatedEntities = $association->getValue($entity); + $targetEntity = $association->getTargetEntity(); switch (true) { case ($relatedEntities instanceof PersistentCollection): @@ -2083,136 +1817,10 @@ function ($assoc) { return $assoc['isCascadeRefresh']; } case ($relatedEntities instanceof Collection): case (is_array($relatedEntities)): - foreach ($relatedEntities as $relatedEntity) { - $this->doRefresh($relatedEntity, $visited); - } - break; - - case ($relatedEntities !== null): - $this->doRefresh($relatedEntities, $visited); - break; - - default: - // Do nothing - } - } - } - - /** - * Cascades a detach operation to associated entities. - * - * @param object $entity - * @param array $visited - * - * @return void - */ - private function cascadeDetach($entity, array &$visited) - { - $class = $this->em->getClassMetadata(get_class($entity)); - - $associationMappings = array_filter( - $class->associationMappings, - function ($assoc) { return $assoc['isCascadeDetach']; } - ); - - foreach ($associationMappings as $assoc) { - $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity); - - switch (true) { - case ($relatedEntities instanceof PersistentCollection): - // Unwrap so that foreach() does not initialize - $relatedEntities = $relatedEntities->unwrap(); - // break; is commented intentionally! - - case ($relatedEntities instanceof Collection): - case (is_array($relatedEntities)): - foreach ($relatedEntities as $relatedEntity) { - $this->doDetach($relatedEntity, $visited); - } - break; - - case ($relatedEntities !== null): - $this->doDetach($relatedEntities, $visited); - break; - - default: - // Do nothing - } - } - } - - /** - * Cascades a merge operation to associated entities. - * - * @param object $entity - * @param object $managedCopy - * @param array $visited - * - * @return void - */ - private function cascadeMerge($entity, $managedCopy, array &$visited) - { - $class = $this->em->getClassMetadata(get_class($entity)); - - $associationMappings = array_filter( - $class->associationMappings, - function ($assoc) { return $assoc['isCascadeMerge']; } - ); - - foreach ($associationMappings as $assoc) { - $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity); - - if ($relatedEntities instanceof Collection) { - if ($relatedEntities === $class->reflFields[$assoc['fieldName']]->getValue($managedCopy)) { - continue; - } - - if ($relatedEntities instanceof PersistentCollection) { - // Unwrap so that foreach() does not initialize - $relatedEntities = $relatedEntities->unwrap(); - } - - foreach ($relatedEntities as $relatedEntity) { - $this->doMerge($relatedEntity, $visited, $managedCopy, $assoc); - } - } else if ($relatedEntities !== null) { - $this->doMerge($relatedEntities, $visited, $managedCopy, $assoc); - } - } - } - - /** - * Cascades the save operation to associated entities. - * - * @param object $entity - * @param array $visited - * - * @return void - */ - private function cascadePersist($entity, array &$visited) - { - $class = $this->em->getClassMetadata(get_class($entity)); - - $associationMappings = array_filter( - $class->associationMappings, - function ($assoc) { return $assoc['isCascadePersist']; } - ); - - foreach ($associationMappings as $assoc) { - $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity); - - switch (true) { - case ($relatedEntities instanceof PersistentCollection): - // Unwrap so that foreach() does not initialize - $relatedEntities = $relatedEntities->unwrap(); - // break; is commented intentionally! - - case ($relatedEntities instanceof Collection): - case (is_array($relatedEntities)): - if (($assoc['type'] & ClassMetadata::TO_MANY) <= 0) { + if (! ($association instanceof ToManyAssociationMetadata)) { throw ORMInvalidArgumentException::invalidAssociation( - $this->em->getClassMetadata($assoc['targetEntity']), - $assoc, + $this->em->getClassMetadata($targetEntity), + $association, $relatedEntities ); } @@ -2224,10 +1832,10 @@ function ($assoc) { return $assoc['isCascadePersist']; } break; case ($relatedEntities !== null): - if (! $relatedEntities instanceof $assoc['targetEntity']) { + if (! $relatedEntities instanceof $targetEntity) { throw ORMInvalidArgumentException::invalidAssociation( - $this->em->getClassMetadata($assoc['targetEntity']), - $assoc, + $this->em->getClassMetadata($targetEntity), + $association, $relatedEntities ); } @@ -2251,21 +1859,19 @@ function ($assoc) { return $assoc['isCascadePersist']; } */ private function cascadeRemove($entity, array &$visited) { - $class = $this->em->getClassMetadata(get_class($entity)); - - $associationMappings = array_filter( - $class->associationMappings, - function ($assoc) { return $assoc['isCascadeRemove']; } - ); - $entitiesToCascade = []; + $class = $this->em->getClassMetadata(get_class($entity)); + + foreach ($class->getDeclaredPropertiesIterator() as $association) { + if (! ($association instanceof AssociationMetadata && in_array('remove', $association->getCascade()))) { + continue; + } - foreach ($associationMappings as $assoc) { - if ($entity instanceof Proxy && !$entity->__isInitialized__) { + if ($entity instanceof Proxy && ! $entity->__isInitialized()) { $entity->__load(); } - $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity); + $relatedEntities = $association->getValue($entity); switch (true) { case ($relatedEntities instanceof Collection): @@ -2317,19 +1923,19 @@ public function lock($entity, $lockMode, $lockVersion = null) switch (true) { case LockMode::OPTIMISTIC === $lockMode: - if ( ! $class->isVersioned) { - throw OptimisticLockException::notVersioned($class->name); + if ( ! $class->isVersioned()) { + throw OptimisticLockException::notVersioned($class->getClassName()); } if ($lockVersion === null) { return; } - if ($entity instanceof Proxy && !$entity->__isInitialized__) { + if ($entity instanceof Proxy && ! $entity->__isInitialized()) { $entity->__load(); } - $entityVersion = $class->reflFields[$class->versionField]->getValue($entity); + $entityVersion = $class->versionProperty->getValue($entity); if ($entityVersion != $lockVersion) { throw OptimisticLockException::lockFailedVersionMismatch($entity, $lockVersion, $entityVersion); @@ -2346,7 +1952,7 @@ public function lock($entity, $lockMode, $lockVersion = null) $oid = spl_object_hash($entity); - $this->getEntityPersister($class->name)->lock( + $this->getEntityPersister($class->getClassName())->lock( array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]), $lockMode ); @@ -2357,50 +1963,34 @@ public function lock($entity, $lockMode, $lockVersion = null) } } - /** - * Gets the CommitOrderCalculator used by the UnitOfWork to order commits. - * - * @return \Doctrine\ORM\Internal\CommitOrderCalculator - */ - public function getCommitOrderCalculator() - { - return new Internal\CommitOrderCalculator(); - } - /** * Clears the UnitOfWork. * - * @param string|null $entityName if given, only entities of this type will get detached. - * * @return void - * - * @throws ORMInvalidArgumentException if an invalid entity name is given - */ - public function clear($entityName = null) - { - if ($entityName === null) { - $this->identityMap = - $this->entityIdentifiers = - $this->originalEntityData = - $this->entityChangeSets = - $this->entityStates = - $this->scheduledForSynchronization = - $this->entityInsertions = - $this->entityUpdates = - $this->entityDeletions = - $this->collectionDeletions = - $this->collectionUpdates = - $this->extraUpdates = - $this->readOnlyObjects = - $this->visitedCollections = - $this->orphanRemovals = []; - } else { - $this->clearIdentityMapForEntityName($entityName); - $this->clearEntityInsertionsForEntityName($entityName); - } + */ + public function clear() + { + $this->entityPersisters = + $this->collectionPersisters = + $this->eagerLoadingEntities = + $this->identityMap = + $this->entityIdentifiers = + $this->originalEntityData = + $this->entityChangeSets = + $this->entityStates = + $this->scheduledForSynchronization = + $this->entityInsertions = + $this->entityUpdates = + $this->entityDeletions = + $this->collectionDeletions = + $this->collectionUpdates = + $this->extraUpdates = + $this->readOnlyObjects = + $this->visitedCollections = + $this->orphanRemovals = []; - if ($this->evm->hasListeners(Events::onClear)) { - $this->evm->dispatchEvent(Events::onClear, new Event\OnClearEventArgs($this->em, $entityName)); + if ($this->eventManager->hasListeners(Events::onClear)) { + $this->eventManager->dispatchEvent(Events::onClear, new Event\OnClearEventArgs($this->em)); } } @@ -2466,16 +2056,22 @@ public function isCollectionScheduledForDeletion(PersistentCollection $coll) } /** + * INTERNAL: + * Creates a new instance of the mapped class, without invoking the constructor. + * This is only meant to be used internally, and should not be consumed by end users. + * + * @ignore + * * @param ClassMetadata $class * - * @return \Doctrine\Common\Persistence\ObjectManagerAware|object + * @return EntityManagerAware|object */ - private function newInstance($class) + public function newInstance(ClassMetadata $class) { - $entity = $class->newInstance(); + $entity = $this->instantiator->instantiate($class->getClassName()); - if ($entity instanceof \Doctrine\Common\Persistence\ObjectManagerAware) { - $entity->injectObjectManager($this->em, $class); + if ($entity instanceof EntityManagerAware) { + $entity->injectEntityManager($this->em, $class); } return $entity; @@ -2499,14 +2095,13 @@ private function newInstance($class) */ public function createEntity($className, array $data, &$hints = []) { - $class = $this->em->getClassMetadata($className); - //$isReadOnly = isset($hints[Query::HINT_READ_ONLY]); - - $id = $this->identifierFlattener->flattenIdentifier($class, $data); + $class = $this->em->getClassMetadata($className); + $id = $this->em->getIdentifierFlattener()->flattenIdentifier($class, $data); $idHash = implode(' ', $id); + //$isReadOnly = isset($hints[Query::HINT_READ_ONLY]); - if (isset($this->identityMap[$class->rootEntityName][$idHash])) { - $entity = $this->identityMap[$class->rootEntityName][$idHash]; + if (isset($this->identityMap[$class->getRootClassName()][$idHash])) { + $entity = $this->identityMap[$class->getRootClassName()][$idHash]; $oid = spl_object_hash($entity); if ( @@ -2519,9 +2114,10 @@ public function createEntity($className, array $data, &$hints = []) // DDC-1238 - we have a managed instance, but it isn't the provided one. // Therefore we clear its identifier. Also, we must re-fetch metadata since the // refreshed object may be anything - foreach ($class->identifier as $fieldName) { - $class->reflFields[$fieldName]->setValue($unmanagedProxy, null); + $property = $class->getProperty($fieldName); + + $property->setValue($unmanagedProxy, null); } return $unmanagedProxy; @@ -2545,9 +2141,9 @@ public function createEntity($className, array $data, &$hints = []) } if ($overrideLocalValues) { - // inject ObjectManager upon refresh. - if ($entity instanceof ObjectManagerAware) { - $entity->injectObjectManager($this->em, $class); + // inject EntityManager upon refresh. + if ($entity instanceof EntityManagerAware) { + $entity->injectEntityManager($this->em, $class); } $this->originalEntityData[$oid] = $data; @@ -2560,7 +2156,7 @@ public function createEntity($className, array $data, &$hints = []) $this->entityStates[$oid] = self::STATE_MANAGED; $this->originalEntityData[$oid] = $data; - $this->identityMap[$class->rootEntityName][$idHash] = $entity; + $this->identityMap[$class->getRootClassName()][$idHash] = $entity; if ($entity instanceof NotifyPropertyChanged) { $entity->addPropertyChangedListener($this); @@ -2574,16 +2170,18 @@ public function createEntity($className, array $data, &$hints = []) } foreach ($data as $field => $value) { - if (isset($class->fieldMappings[$field])) { - $class->reflFields[$field]->setValue($entity, $value); + $property = $class->getProperty($field); + + if ($property instanceof FieldMetadata) { + $property->setValue($entity, $value); } } // Loading the entity right here, if its in the eager loading map get rid of it there. - unset($this->eagerLoadingEntities[$class->rootEntityName][$idHash]); + unset($this->eagerLoadingEntities[$class->getRootClassName()][$idHash]); - if (isset($this->eagerLoadingEntities[$class->rootEntityName]) && ! $this->eagerLoadingEntities[$class->rootEntityName]) { - unset($this->eagerLoadingEntities[$class->rootEntityName]); + if (isset($this->eagerLoadingEntities[$class->getRootClassName()]) && ! $this->eagerLoadingEntities[$class->getRootClassName()]) { + unset($this->eagerLoadingEntities[$class->getRootClassName()]); } // Properly initialize any unfetched associations, if partial objects are not allowed. @@ -2591,186 +2189,190 @@ public function createEntity($className, array $data, &$hints = []) return $entity; } - foreach ($class->associationMappings as $field => $assoc) { + foreach ($class->getDeclaredPropertiesIterator() as $field => $association) { + if (! ($association instanceof AssociationMetadata)) { + continue; + } + // Check if the association is not among the fetch-joined associations already. if (isset($hints['fetchAlias']) && isset($hints['fetched'][$hints['fetchAlias']][$field])) { continue; } - $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); + $targetEntity = $association->getTargetEntity(); + $targetClass = $this->em->getClassMetadata($targetEntity); - switch (true) { - case ($assoc['type'] & ClassMetadata::TO_ONE): - if ( ! $assoc['isOwningSide']) { + if ($association instanceof ToManyAssociationMetadata) { + // Ignore if its a cached collection + if (isset($hints[Query::HINT_CACHE_ENABLED]) && + $association->getValue($entity) instanceof PersistentCollection) { + continue; + } - // use the given entity association - if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_hash($data[$field])])) { + $hasDataField = isset($data[$field]); - $this->originalEntityData[$oid][$field] = $data[$field]; + // use the given collection + if ($hasDataField && $data[$field] instanceof PersistentCollection) { + $data[$field]->setOwner($entity, $association); - $class->reflFields[$field]->setValue($entity, $data[$field]); - $targetClass->reflFields[$assoc['mappedBy']]->setValue($data[$field], $entity); + $association->setValue($entity, $data[$field]); - continue 2; - } + $this->originalEntityData[$oid][$field] = $data[$field]; - // Inverse side of x-to-one can never be lazy - $class->reflFields[$field]->setValue($entity, $this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc, $entity)); + continue; + } - continue 2; - } + // Inject collection + $pColl = $association->wrap($entity, $hasDataField ? $data[$field] : [], $this->em); - // use the entity association - if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_hash($data[$field])])) { - $class->reflFields[$field]->setValue($entity, $data[$field]); - $this->originalEntityData[$oid][$field] = $data[$field]; + $pColl->setInitialized($hasDataField); - continue; - } + $association->setValue($entity, $pColl); - $associatedId = []; + if ($association->getFetchMode() === FetchMode::EAGER) { + $this->loadCollection($pColl); + $pColl->takeSnapshot(); + } - // TODO: Is this even computed right in all cases of composite keys? - foreach ($assoc['targetToSourceKeyColumns'] as $targetColumn => $srcColumn) { - $joinColumnValue = isset($data[$srcColumn]) ? $data[$srcColumn] : null; + $this->originalEntityData[$oid][$field] = $pColl; - if ($joinColumnValue !== null) { - if ($targetClass->containsForeignIdentifier) { - $associatedId[$targetClass->getFieldForColumn($targetColumn)] = $joinColumnValue; - } else { - $associatedId[$targetClass->fieldNames[$targetColumn]] = $joinColumnValue; - } - } elseif ($targetClass->containsForeignIdentifier - && in_array($targetClass->getFieldForColumn($targetColumn), $targetClass->identifier, true) - ) { - // the missing key is part of target's entity primary key - $associatedId = []; - break; - } - } + continue; + } - if ( ! $associatedId) { - // Foreign key is NULL - $class->reflFields[$field]->setValue($entity, null); - $this->originalEntityData[$oid][$field] = null; + if (! $association->isOwningSide()) { + // use the given entity association + if (isset($data[$field]) && is_object($data[$field]) && + isset($this->entityStates[spl_object_hash($data[$field])])) { + $inverseAssociation = $targetClass->getProperty($association->getMappedBy()); - continue; - } + $association->setValue($entity, $data[$field]); + $inverseAssociation->setValue($data[$field], $entity); - if ( ! isset($hints['fetchMode'][$class->name][$field])) { - $hints['fetchMode'][$class->name][$field] = $assoc['fetch']; - } + $this->originalEntityData[$oid][$field] = $data[$field]; - // Foreign key is set - // Check identity map first - // FIXME: Can break easily with composite keys if join column values are in - // wrong order. The correct order is the one in ClassMetadata#identifier. - $relatedIdHash = implode(' ', $associatedId); + continue; + } - switch (true) { - case (isset($this->identityMap[$targetClass->rootEntityName][$relatedIdHash])): - $newValue = $this->identityMap[$targetClass->rootEntityName][$relatedIdHash]; - - // If this is an uninitialized proxy, we are deferring eager loads, - // this association is marked as eager fetch, and its an uninitialized proxy (wtf!) - // then we can append this entity for eager loading! - if ($hints['fetchMode'][$class->name][$field] == ClassMetadata::FETCH_EAGER && - isset($hints[self::HINT_DEFEREAGERLOAD]) && - !$targetClass->isIdentifierComposite && - $newValue instanceof Proxy && - $newValue->__isInitialized__ === false) { - - $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId); - } + // Inverse side of x-to-one can never be lazy + $persister = $this->getEntityPersister($targetEntity); - break; + $association->setValue($entity, $persister->loadToOneEntity($association, $entity)); - case ($targetClass->subClasses): - // If it might be a subtype, it can not be lazy. There isn't even - // a way to solve this with deferred eager loading, which means putting - // an entity with subclasses at a *-to-one location is really bad! (performance-wise) - $newValue = $this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc, $entity, $associatedId); - break; + continue; + } - default: - switch (true) { - // We are negating the condition here. Other cases will assume it is valid! - case ($hints['fetchMode'][$class->name][$field] !== ClassMetadata::FETCH_EAGER): - $newValue = $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId); - break; - - // Deferred eager load only works for single identifier classes - case (isset($hints[self::HINT_DEFEREAGERLOAD]) && ! $targetClass->isIdentifierComposite): - // TODO: Is there a faster approach? - $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId); - - $newValue = $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId); - break; - - default: - // TODO: This is very imperformant, ignore it? - $newValue = $this->em->find($assoc['targetEntity'], $associatedId); - break; - } + // use the entity association + if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_hash($data[$field])])) { + $association->setValue($entity, $data[$field]); - // PERF: Inlined & optimized code from UnitOfWork#registerManaged() - $newValueOid = spl_object_hash($newValue); - $this->entityIdentifiers[$newValueOid] = $associatedId; - $this->identityMap[$targetClass->rootEntityName][$relatedIdHash] = $newValue; + $this->originalEntityData[$oid][$field] = $data[$field]; - if ( - $newValue instanceof NotifyPropertyChanged && - ( ! $newValue instanceof Proxy || $newValue->__isInitialized()) - ) { - $newValue->addPropertyChangedListener($this); - } - $this->entityStates[$newValueOid] = self::STATE_MANAGED; - // make sure that when an proxy is then finally loaded, $this->originalEntityData is set also! - break; - } + continue; + } + + $associatedId = []; + + // TODO: Is this even computed right in all cases of composite keys? + foreach ($association->getJoinColumns() as $joinColumn) { + /** @var JoinColumnMetadata $joinColumn */ + $joinColumnName = $joinColumn->getColumnName(); + $joinColumnValue = isset($data[$joinColumnName]) ? $data[$joinColumnName] : null; + $targetField = $targetClass->fieldNames[$joinColumn->getReferencedColumnName()]; + + if ($joinColumnValue === null && in_array($targetField, $targetClass->identifier, true)) { + // the missing key is part of target's entity primary key + $associatedId = []; - $this->originalEntityData[$oid][$field] = $newValue; - $class->reflFields[$field]->setValue($entity, $newValue); + continue; + } + + $associatedId[$targetField] = $joinColumnValue; + } + + if (! $associatedId) { + // Foreign key is NULL + $association->setValue($entity, null); + $this->originalEntityData[$oid][$field] = null; + + continue; + } + + // @todo guilhermeblanco Can we remove the need of this somehow? + if (!isset($hints['fetchMode'][$class->getClassName()][$field])) { + $hints['fetchMode'][$class->getClassName()][$field] = $association->getFetchMode(); + } + + // Foreign key is set + // Check identity map first + // FIXME: Can break easily with composite keys if join column values are in + // wrong order. The correct order is the one in ClassMetadata#identifier. + $relatedIdHash = implode(' ', $associatedId); - if ($assoc['inversedBy'] && $assoc['type'] & ClassMetadata::ONE_TO_ONE) { - $inverseAssoc = $targetClass->associationMappings[$assoc['inversedBy']]; - $targetClass->reflFields[$inverseAssoc['fieldName']]->setValue($newValue, $entity); + switch (true) { + case (isset($this->identityMap[$targetClass->getRootClassName()][$relatedIdHash])): + $newValue = $this->identityMap[$targetClass->getRootClassName()][$relatedIdHash]; + + // If this is an uninitialized proxy, we are deferring eager loads, + // this association is marked as eager fetch, and its an uninitialized proxy (wtf!) + // then we can append this entity for eager loading! + if (!$targetClass->isIdentifierComposite() && + $newValue instanceof Proxy && + isset($hints[self::HINT_DEFEREAGERLOAD]) && + $hints['fetchMode'][$class->getClassName()][$field] === FetchMode::EAGER && + ! $newValue->__isInitialized() + ) { + + $this->eagerLoadingEntities[$targetClass->getRootClassName()][$relatedIdHash] = current($associatedId); } break; + case ($targetClass->getSubClasses()): + // If it might be a subtype, it can not be lazy. There isn't even + // a way to solve this with deferred eager loading, which means putting + // an entity with subclasses at a *-to-one location is really bad! (performance-wise) + $persister = $this->getEntityPersister($targetEntity); + $newValue = $persister->loadToOneEntity($association, $entity, $associatedId); + break; + default: - // Ignore if its a cached collection - if (isset($hints[Query::HINT_CACHE_ENABLED]) && $class->getFieldValue($entity, $field) instanceof PersistentCollection) { - break; - } + // Proxies do not carry any kind of original entity data until they're fully loaded/initialized + $managedData = []; - // use the given collection - if (isset($data[$field]) && $data[$field] instanceof PersistentCollection) { + switch (true) { + // We are negating the condition here. Other cases will assume it is valid! + case ($hints['fetchMode'][$class->getClassName()][$field] !== FetchMode::EAGER): + $newValue = $this->em->getProxyFactory()->getProxy($targetEntity, $associatedId); + break; - $data[$field]->setOwner($entity, $assoc); + // Deferred eager load only works for single identifier classes + case (isset($hints[self::HINT_DEFEREAGERLOAD]) && !$targetClass->isIdentifierComposite()): + // TODO: Is there a faster approach? + $this->eagerLoadingEntities[$targetClass->getRootClassName()][$relatedIdHash] = current($associatedId); - $class->reflFields[$field]->setValue($entity, $data[$field]); - $this->originalEntityData[$oid][$field] = $data[$field]; + $newValue = $this->em->getProxyFactory()->getProxy($targetEntity, $associatedId); + break; - break; + default: + // TODO: This is very imperformant, ignore it? + $newValue = $this->em->find($targetEntity, $associatedId); + // Needed to re-assign original entity data for freshly loaded entity + $managedData = $this->originalEntityData[spl_object_hash($newValue)]; + break; } - // Inject collection - $pColl = new PersistentCollection($this->em, $targetClass, new ArrayCollection); - $pColl->setOwner($entity, $assoc); - $pColl->setInitialized(false); + $this->registerManaged($newValue, $associatedId, $managedData); - $reflField = $class->reflFields[$field]; - $reflField->setValue($entity, $pColl); + break; + } - if ($assoc['fetch'] == ClassMetadata::FETCH_EAGER) { - $this->loadCollection($pColl); - $pColl->takeSnapshot(); - } + $this->originalEntityData[$oid][$field] = $newValue; + $association->setValue($entity, $newValue); - $this->originalEntityData[$oid][$field] = $pColl; - break; + if ($association->getInversedBy() && $association instanceof OneToOneAssociationMetadata) { + $inverseAssociation = $targetClass->getProperty($association->getInversedBy()); + + $inverseAssociation->setValue($newValue, $entity); } } @@ -2819,17 +2421,13 @@ public function triggerEagerLoads() */ public function loadCollection(PersistentCollection $collection) { - $assoc = $collection->getMapping(); - $persister = $this->getEntityPersister($assoc['targetEntity']); - - switch ($assoc['type']) { - case ClassMetadata::ONE_TO_MANY: - $persister->loadOneToManyCollection($assoc, $collection->getOwner(), $collection); - break; + $association = $collection->getMapping(); + $persister = $this->getEntityPersister($association->getTargetEntity()); - case ClassMetadata::MANY_TO_MANY: - $persister->loadManyToManyCollection($assoc, $collection->getOwner(), $collection); - break; + if ($association instanceof OneToManyAssociationMetadata) { + $persister->loadOneToManyCollection($association, $collection->getOwner(), $collection); + } else { + $persister->loadManyToManyCollection($association, $collection->getOwner(), $collection); } $collection->setInitialized(true); @@ -2918,15 +2516,16 @@ public function getEntityIdentifier($entity) */ public function getSingleIdentifierValue($entity) { - $class = $this->em->getClassMetadata(get_class($entity)); + $class = $this->em->getClassMetadata(get_class($entity)); + $persister = $this->getEntityPersister($class->getClassName()); - if ($class->isIdentifierComposite) { + if ($class->isIdentifierComposite()) { throw ORMInvalidArgumentException::invalidCompositeIdentifier(); } $values = $this->isInIdentityMap($entity) ? $this->getEntityIdentifier($entity) - : $class->getIdentifierValues($entity); + : $persister->getIdentifier($entity); return isset($values[$class->identifier[0]]) ? $values[$class->identifier[0]] : null; } @@ -2956,12 +2555,10 @@ public function tryGetById($id, $rootClassName) * @param object $entity The entity to schedule for dirty-checking. * * @return void - * - * @todo Rename: scheduleForSynchronization */ - public function scheduleForDirtyCheck($entity) + public function scheduleForSynchronization($entity) { - $rootClassName = $this->em->getClassMetadata(get_class($entity))->rootEntityName; + $rootClassName = $this->em->getClassMetadata(get_class($entity))->getRootClassName(); $this->scheduledForSynchronization[$rootClassName][spl_object_hash($entity)] = $entity; } @@ -2984,9 +2581,7 @@ public function hasPendingInsertions() */ public function size() { - $countArray = array_map('count', $this->identityMap); - - return array_sum($countArray); + return \array_sum(\array_map('count', $this->identityMap)); } /** @@ -2998,22 +2593,22 @@ public function size() */ public function getEntityPersister($entityName) { - if (isset($this->persisters[$entityName])) { - return $this->persisters[$entityName]; + if (isset($this->entityPersisters[$entityName])) { + return $this->entityPersisters[$entityName]; } $class = $this->em->getClassMetadata($entityName); switch (true) { - case ($class->isInheritanceTypeNone()): + case ($class->inheritanceType === InheritanceType::NONE): $persister = new BasicEntityPersister($this->em, $class); break; - case ($class->isInheritanceTypeSingleTable()): + case ($class->inheritanceType === InheritanceType::SINGLE_TABLE): $persister = new SingleTablePersister($this->em, $class); break; - case ($class->isInheritanceTypeJoined()): + case ($class->inheritanceType === InheritanceType::JOINED): $persister = new JoinedSubclassPersister($this->em, $class); break; @@ -3021,40 +2616,40 @@ public function getEntityPersister($entityName) throw new \RuntimeException('No persister found for entity.'); } - if ($this->hasCache && $class->cache !== null) { + if ($this->hasCache && $class->getCache()) { $persister = $this->em->getConfiguration() ->getSecondLevelCacheConfiguration() ->getCacheFactory() ->buildCachedEntityPersister($this->em, $persister, $class); } - $this->persisters[$entityName] = $persister; + $this->entityPersisters[$entityName] = $persister; - return $this->persisters[$entityName]; + return $this->entityPersisters[$entityName]; } /** * Gets a collection persister for a collection-valued association. * - * @param array $association + * @param ToManyAssociationMetadata $association * * @return \Doctrine\ORM\Persisters\Collection\CollectionPersister */ - public function getCollectionPersister(array $association) + public function getCollectionPersister(ToManyAssociationMetadata $association) { - $role = isset($association['cache']) - ? $association['sourceEntity'] . '::' . $association['fieldName'] - : $association['type']; + $role = $association->getCache() + ? sprintf('%s::%s', $association->getSourceEntity(), $association->getName()) + : get_class($association); if (isset($this->collectionPersisters[$role])) { return $this->collectionPersisters[$role]; } - $persister = ClassMetadata::ONE_TO_MANY === $association['type'] + $persister = $association instanceof OneToManyAssociationMetadata ? new OneToManyPersister($this->em) : new ManyToManyPersister($this->em); - if ($this->hasCache && isset($association['cache'])) { + if ($this->hasCache && $association->getCache()) { $persister = $this->em->getConfiguration() ->getSecondLevelCacheConfiguration() ->getCacheFactory() @@ -3071,14 +2666,15 @@ public function getCollectionPersister(array $association) * Registers an entity as managed. * * @param object $entity The entity. - * @param array $id The identifier values. + * @param array $id Map containing identifier field names as key and its associated values. * @param array $data The original entity data. * * @return void */ public function registerManaged($entity, array $id, array $data) { - $oid = spl_object_hash($entity); + $isProxy = $entity instanceof Proxy && ! $entity->__isInitialized(); + $oid = spl_object_hash($entity); $this->entityIdentifiers[$oid] = $id; $this->entityStates[$oid] = self::STATE_MANAGED; @@ -3086,7 +2682,7 @@ public function registerManaged($entity, array $id, array $data) $this->addToIdentityMap($entity); - if ($entity instanceof NotifyPropertyChanged && ( ! $entity instanceof Proxy || $entity->__isInitialized())) { + if ($entity instanceof NotifyPropertyChanged && ! $isProxy) { $entity->addPropertyChangedListener($this); } } @@ -3118,20 +2714,19 @@ public function clearEntityChangeSet($oid) */ public function propertyChanged($entity, $propertyName, $oldValue, $newValue) { - $oid = spl_object_hash($entity); $class = $this->em->getClassMetadata(get_class($entity)); - $isAssocField = isset($class->associationMappings[$propertyName]); - - if ( ! $isAssocField && ! isset($class->fieldMappings[$propertyName])) { + if (! $class->getProperty($propertyName)) { return; // ignore non-persistent fields } + $oid = spl_object_hash($entity); + // Update changeset and mark entity for synchronization $this->entityChangeSets[$oid][$propertyName] = [$oldValue, $newValue]; - if ( ! isset($this->scheduledForSynchronization[$class->rootEntityName][$oid])) { - $this->scheduleForDirtyCheck($entity); + if ( ! isset($this->scheduledForSynchronization[$class->getRootClassName()][$oid])) { + $this->scheduleForSynchronization($entity); } } @@ -3287,7 +2882,7 @@ private function performCallbackOnCachedPersister(callable $callback) return; } - foreach (array_merge($this->persisters, $this->collectionPersisters) as $persister) { + foreach (array_merge($this->entityPersisters, $this->collectionPersisters) as $persister) { if ($persister instanceof CachedPersister) { $callback($persister); } @@ -3296,15 +2891,15 @@ private function performCallbackOnCachedPersister(callable $callback) private function dispatchOnFlushEvent() { - if ($this->evm->hasListeners(Events::onFlush)) { - $this->evm->dispatchEvent(Events::onFlush, new OnFlushEventArgs($this->em)); + if ($this->eventManager->hasListeners(Events::onFlush)) { + $this->eventManager->dispatchEvent(Events::onFlush, new OnFlushEventArgs($this->em)); } } private function dispatchPostFlushEvent() { - if ($this->evm->hasListeners(Events::postFlush)) { - $this->evm->dispatchEvent(Events::postFlush, new PostFlushEventArgs($this->em)); + if ($this->eventManager->hasListeners(Events::postFlush)) { + $this->eventManager->dispatchEvent(Events::postFlush, new PostFlushEventArgs($this->em)); } } @@ -3322,133 +2917,28 @@ private function isIdentifierEquals($entity1, $entity2) return true; } - $class = $this->em->getClassMetadata(get_class($entity1)); + $class = $this->em->getClassMetadata(get_class($entity1)); + $persister = $this->getEntityPersister($class->getClassName()); if ($class !== $this->em->getClassMetadata(get_class($entity2))) { return false; } + $identifierFlattener = $this->em->getIdentifierFlattener(); + $oid1 = spl_object_hash($entity1); $oid2 = spl_object_hash($entity2); $id1 = isset($this->entityIdentifiers[$oid1]) ? $this->entityIdentifiers[$oid1] - : $this->identifierFlattener->flattenIdentifier($class, $class->getIdentifierValues($entity1)); + : $identifierFlattener->flattenIdentifier($class, $persister->getIdentifier($entity1)); $id2 = isset($this->entityIdentifiers[$oid2]) ? $this->entityIdentifiers[$oid2] - : $this->identifierFlattener->flattenIdentifier($class, $class->getIdentifierValues($entity2)); + : $identifierFlattener->flattenIdentifier($class, $persister->getIdentifier($entity2)); return $id1 === $id2 || implode(' ', $id1) === implode(' ', $id2); } - /** - * @param object $entity - * @param object $managedCopy - * - * @throws ORMException - * @throws OptimisticLockException - * @throws TransactionRequiredException - */ - private function mergeEntityStateIntoManagedCopy($entity, $managedCopy) - { - if (! $this->isLoaded($entity)) { - return; - } - - if (! $this->isLoaded($managedCopy)) { - $managedCopy->__load(); - } - - $class = $this->em->getClassMetadata(get_class($entity)); - - foreach ($this->reflectionPropertiesGetter->getProperties($class->name) as $prop) { - $name = $prop->name; - - $prop->setAccessible(true); - - if ( ! isset($class->associationMappings[$name])) { - if ( ! $class->isIdentifier($name)) { - $prop->setValue($managedCopy, $prop->getValue($entity)); - } - } else { - $assoc2 = $class->associationMappings[$name]; - - if ($assoc2['type'] & ClassMetadata::TO_ONE) { - $other = $prop->getValue($entity); - if ($other === null) { - $prop->setValue($managedCopy, null); - } else { - if ($other instanceof Proxy && !$other->__isInitialized()) { - // do not merge fields marked lazy that have not been fetched. - continue; - } - - if ( ! $assoc2['isCascadeMerge']) { - if ($this->getEntityState($other) === self::STATE_DETACHED) { - $targetClass = $this->em->getClassMetadata($assoc2['targetEntity']); - $relatedId = $targetClass->getIdentifierValues($other); - - if ($targetClass->subClasses) { - $other = $this->em->find($targetClass->name, $relatedId); - } else { - $other = $this->em->getProxyFactory()->getProxy( - $assoc2['targetEntity'], - $relatedId - ); - $this->registerManaged($other, $relatedId, []); - } - } - - $prop->setValue($managedCopy, $other); - } - } - } else { - $mergeCol = $prop->getValue($entity); - - if ($mergeCol instanceof PersistentCollection && ! $mergeCol->isInitialized()) { - // do not merge fields marked lazy that have not been fetched. - // keep the lazy persistent collection of the managed copy. - continue; - } - - $managedCol = $prop->getValue($managedCopy); - - if ( ! $managedCol) { - $managedCol = new PersistentCollection( - $this->em, - $this->em->getClassMetadata($assoc2['targetEntity']), - new ArrayCollection - ); - $managedCol->setOwner($managedCopy, $assoc2); - $prop->setValue($managedCopy, $managedCol); - } - - if ($assoc2['isCascadeMerge']) { - $managedCol->initialize(); - - // clear and set dirty a managed collection if its not also the same collection to merge from. - if ( ! $managedCol->isEmpty() && $managedCol !== $mergeCol) { - $managedCol->unwrap()->clear(); - $managedCol->setDirty(true); - - if ($assoc2['isOwningSide'] - && $assoc2['type'] == ClassMetadata::MANY_TO_MANY - && $class->isChangeTrackingNotify() - ) { - $this->scheduleForDirtyCheck($managedCopy); - } - } - } - } - } - - if ($class->isChangeTrackingNotify()) { - // Just treat all properties as changed, there is no other choice. - $this->propertyChanged($managedCopy, $name, null, $prop->getValue($managedCopy)); - } - } - } - /** * This method called by hydrators, and indicates that hydrator totally completed current hydration cycle. * Unit of work able to fire deferred events, related to loading events here. @@ -3459,49 +2949,4 @@ public function hydrationComplete() { $this->hydrationCompleteHandler->hydrationComplete(); } - - /** - * @param string $entityName - */ - private function clearIdentityMapForEntityName($entityName) - { - if (! isset($this->identityMap[$entityName])) { - return; - } - - $visited = []; - - foreach ($this->identityMap[$entityName] as $entity) { - $this->doDetach($entity, $visited, false); - } - } - - /** - * @param string $entityName - */ - private function clearEntityInsertionsForEntityName($entityName) - { - foreach ($this->entityInsertions as $hash => $entity) { - // note: performance optimization - `instanceof` is much faster than a function call - if ($entity instanceof $entityName && get_class($entity) === $entityName) { - unset($this->entityInsertions[$hash]); - } - } - } - - /** - * @param ClassMetadata $class - * @param mixed $identifierValue - * - * @return mixed the identifier after type conversion - * - * @throws \Doctrine\ORM\Mapping\MappingException if the entity has more than a single identifier - */ - private function convertSingleFieldIdentifierToPHPValue(ClassMetadata $class, $identifierValue) - { - return $this->em->getConnection()->convertToPHPValue( - $identifierValue, - $class->getTypeOfField($class->getSingleIdentifierFieldName()) - ); - } } diff --git a/lib/Doctrine/ORM/Utility/IdentifierFlattener.php b/lib/Doctrine/ORM/Utility/IdentifierFlattener.php index a283a683492..f659b82a27a 100644 --- a/lib/Doctrine/ORM/Utility/IdentifierFlattener.php +++ b/lib/Doctrine/ORM/Utility/IdentifierFlattener.php @@ -1,24 +1,10 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Utility; +use Doctrine\ORM\Mapping\FieldMetadata; use Doctrine\ORM\UnitOfWork; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\Common\Persistence\Mapping\ClassMetadataFactory; @@ -71,30 +57,39 @@ public function flattenIdentifier(ClassMetadata $class, array $id) $flatId = []; foreach ($class->identifier as $field) { - if (isset($class->associationMappings[$field]) && isset($id[$field]) && is_object($id[$field])) { + $property = $class->getProperty($field); + + if ($property instanceof FieldMetadata) { + $flatId[$field] = $id[$field]; + + continue; + } + + if (isset($id[$field]) && is_object($id[$field])) { /* @var $targetClassMetadata ClassMetadata */ - $targetClassMetadata = $this->metadataFactory->getMetadataFor( - $class->associationMappings[$field]['targetEntity'] - ); + $targetClassMetadata = $this->metadataFactory->getMetadataFor($property->getTargetEntity()); + $targetClassPersister = $this->unitOfWork->getEntityPersister($property->getTargetEntity()); + // @todo guilhermeblanco Bring this back: + // $identifiers = $this->unitOfWork->isInIdentityMap($id[$field]) + // ? $this->unitOfWork->getEntityIdentifier($id[$field]) + // : $targetClassPersister->getIdentifier($id[$field]) + // ; + $identifiers = $targetClassPersister->getIdentifier($id[$field]); - if ($this->unitOfWork->isInIdentityMap($id[$field])) { - $associatedId = $this->flattenIdentifier($targetClassMetadata, $this->unitOfWork->getEntityIdentifier($id[$field])); - } else { - $associatedId = $this->flattenIdentifier($targetClassMetadata, $targetClassMetadata->getIdentifierValues($id[$field])); - } + $associatedId = $this->flattenIdentifier($targetClassMetadata, $identifiers); $flatId[$field] = implode(' ', $associatedId); - } elseif (isset($class->associationMappings[$field])) { - $associatedId = []; - foreach ($class->associationMappings[$field]['joinColumns'] as $joinColumn) { - $associatedId[] = $id[$joinColumn['name']]; - } + continue; + } - $flatId[$field] = implode(' ', $associatedId); - } else { - $flatId[$field] = $id[$field]; + $associatedId = []; + + foreach ($property->getJoinColumns() as $joinColumn) { + $associatedId[] = $id[$joinColumn->getColumnName()]; } + + $flatId[$field] = implode(' ', $associatedId); } return $flatId; diff --git a/lib/Doctrine/ORM/Utility/PersisterHelper.php b/lib/Doctrine/ORM/Utility/PersisterHelper.php index d72dc3e19c0..12fb60043ea 100644 --- a/lib/Doctrine/ORM/Utility/PersisterHelper.php +++ b/lib/Doctrine/ORM/Utility/PersisterHelper.php @@ -1,27 +1,17 @@ . - */ + +declare(strict_types=1); namespace Doctrine\ORM\Utility; +use Doctrine\DBAL\Types\Type; use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\AssociationMetadata; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\FieldMetadata; +use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata; +use Doctrine\ORM\Mapping\ToOneAssociationMetadata; use Doctrine\ORM\Query\QueryException; /** @@ -34,53 +24,12 @@ */ class PersisterHelper { - /** - * @param string $fieldName - * @param ClassMetadata $class - * @param EntityManagerInterface $em - * - * @return array - * - * @throws QueryException - */ - public static function getTypeOfField($fieldName, ClassMetadata $class, EntityManagerInterface $em) - { - if (isset($class->fieldMappings[$fieldName])) { - return [$class->fieldMappings[$fieldName]['type']]; - } - - if ( ! isset($class->associationMappings[$fieldName])) { - return []; - } - - $assoc = $class->associationMappings[$fieldName]; - - if (! $assoc['isOwningSide']) { - return self::getTypeOfField($assoc['mappedBy'], $em->getClassMetadata($assoc['targetEntity']), $em); - } - - if ($assoc['type'] & ClassMetadata::MANY_TO_MANY) { - $joinData = $assoc['joinTable']; - } else { - $joinData = $assoc; - } - - $types = []; - $targetClass = $em->getClassMetadata($assoc['targetEntity']); - - foreach ($joinData['joinColumns'] as $joinColumn) { - $types[] = self::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $em); - } - - return $types; - } - /** * @param string $columnName * @param ClassMetadata $class * @param EntityManagerInterface $em * - * @return string + * @return Type * * @throws \RuntimeException */ @@ -88,48 +37,61 @@ public static function getTypeOfColumn($columnName, ClassMetadata $class, Entity { if (isset($class->fieldNames[$columnName])) { $fieldName = $class->fieldNames[$columnName]; + $property = $class->getProperty($fieldName); - if (isset($class->fieldMappings[$fieldName])) { - return $class->fieldMappings[$fieldName]['type']; - } - } + switch (true) { + case ($property instanceof FieldMetadata): + return $property->getType(); - // iterate over to-one association mappings - foreach ($class->associationMappings as $assoc) { - if ( ! isset($assoc['joinColumns'])) { - continue; - } + // Optimization: Do not loop through all properties later since we can recognize to-one owning scenario + case ($property instanceof ToOneAssociationMetadata): + // We know this is the owning side of a to-one because we found columns in the class (join columns) + foreach ($property->getJoinColumns() as $joinColumn) { + if ($joinColumn->getColumnName() !== $columnName) { + continue; + } - foreach ($assoc['joinColumns'] as $joinColumn) { - if ($joinColumn['name'] == $columnName) { - $targetColumnName = $joinColumn['referencedColumnName']; - $targetClass = $em->getClassMetadata($assoc['targetEntity']); + $targetClass = $em->getClassMetadata($property->getTargetEntity()); - return self::getTypeOfColumn($targetColumnName, $targetClass, $em); - } + return self::getTypeOfColumn($joinColumn->getReferencedColumnName(), $targetClass, $em); + } + + break; } } - // iterate over to-many association mappings - foreach ($class->associationMappings as $assoc) { - if ( ! (isset($assoc['joinTable']) && isset($assoc['joinTable']['joinColumns']))) { + // iterate over association mappings + foreach ($class->getDeclaredPropertiesIterator() as $association) { + if (! ($association instanceof AssociationMetadata)) { continue; } - foreach ($assoc['joinTable']['joinColumns'] as $joinColumn) { - if ($joinColumn['name'] == $columnName) { - $targetColumnName = $joinColumn['referencedColumnName']; - $targetClass = $em->getClassMetadata($assoc['targetEntity']); + // resolve join columns over to-one or to-many + $targetClass = $em->getClassMetadata($association->getTargetEntity()); - return self::getTypeOfColumn($targetColumnName, $targetClass, $em); + if (! $association->isOwningSide()) { + $association = $targetClass->getProperty($association->getMappedBy()); + $targetClass = $em->getClassMetadata($association->getTargetEntity()); + } + + $joinColumns = $association instanceof ManyToManyAssociationMetadata + ? $association->getJoinTable()->getInverseJoinColumns() + : $association->getJoinColumns() + ; + + foreach ($joinColumns as $joinColumn) { + if ($joinColumn->getColumnName() !== $columnName) { + continue; } + + return self::getTypeOfColumn($joinColumn->getReferencedColumnName(), $targetClass, $em); } } throw new \RuntimeException(sprintf( 'Could not resolve type of column "%s" of class "%s"', $columnName, - $class->getName() + $class->getClassName() )); } } diff --git a/lib/Doctrine/ORM/Version.php b/lib/Doctrine/ORM/Version.php deleted file mode 100644 index fee5b82c0a1..00000000000 --- a/lib/Doctrine/ORM/Version.php +++ /dev/null @@ -1,56 +0,0 @@ -. - */ - -namespace Doctrine\ORM; - -/** - * Class to store and retrieve the version of Doctrine - * - * - * @link www.doctrine-project.org - * @since 2.0 - * @version $Revision$ - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - */ -class Version -{ - /** - * Current Doctrine Version - */ - const VERSION = '2.6.0-DEV'; - - /** - * Compares a Doctrine version with the current one. - * - * @param string $version Doctrine version to compare. - * - * @return int Returns -1 if older, 0 if it is the same, 1 if version - * passed as argument is newer. - */ - public static function compare($version) - { - $currentVersion = str_replace(' ', '', strtolower(self::VERSION)); - $version = str_replace(' ', '', $version); - - return version_compare($version, $currentVersion); - } -} diff --git a/phpunit.xml.dist b/phpunit.xml.dist index e6fc543159c..3b3ad1c7673 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -11,16 +11,22 @@ tests/ folder: phpunit -c ... Example: phpunit -c mysqlconf.xml AllTests --> - @@ -31,6 +37,7 @@ + embedded performance locking_functional diff --git a/tests/Doctrine/Performance/ChangeSet/UnitOfWorkComputeChangesBench.php b/tests/Doctrine/Performance/ChangeSet/UnitOfWorkComputeChangesBench.php index 25cc2fffdbb..7643f8e33b9 100644 --- a/tests/Doctrine/Performance/ChangeSet/UnitOfWorkComputeChangesBench.php +++ b/tests/Doctrine/Performance/ChangeSet/UnitOfWorkComputeChangesBench.php @@ -1,5 +1,7 @@ setProxyDir(__DIR__ . '/../Tests/Proxies'); $config->setProxyNamespace('Doctrine\Tests\Proxies'); - $config->setAutoGenerateProxyClasses(ProxyFactory::AUTOGENERATE_EVAL); - $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver([ - realpath(__DIR__ . '/Models/Cache'), - realpath(__DIR__ . '/Models/GeoNames') - ], true)); + $config->setAutoGenerateProxyClasses(StaticProxyFactory::AUTOGENERATE_EVAL); + $config->setMetadataDriverImpl( + $config->newDefaultAnnotationDriver([ + realpath(__DIR__ . '/Models/Cache'), + realpath(__DIR__ . '/Models/GeoNames') + ]) + ); $entityManager = EntityManager::create( [ diff --git a/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinArrayHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinArrayHydrationPerformanceBench.php index bbda1f23dd8..10207e4ddd3 100644 --- a/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinArrayHydrationPerformanceBench.php +++ b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinArrayHydrationPerformanceBench.php @@ -1,7 +1,10 @@ rsm->addFieldResult('u', 'u__status', 'status'); $this->rsm->addFieldResult('u', 'u__username', 'username'); $this->rsm->addFieldResult('u', 'u__name', 'name'); - $this->rsm->addScalarResult('sclr0', 'nameUpper'); + $this->rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); $this->rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); } diff --git a/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinFullObjectHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinFullObjectHydrationPerformanceBench.php index c70ca77cb10..159e4491759 100644 --- a/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinFullObjectHydrationPerformanceBench.php +++ b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinFullObjectHydrationPerformanceBench.php @@ -1,7 +1,10 @@ rsm->addFieldResult('u', 'u__status', 'status'); $this->rsm->addFieldResult('u', 'u__username', 'username'); $this->rsm->addFieldResult('u', 'u__name', 'name'); - $this->rsm->addScalarResult('sclr0', 'nameUpper'); + $this->rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); $this->rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); $this->rsm->addJoinedEntityResult(CmsAddress::class, 'a', 'u', 'address'); $this->rsm->addFieldResult('a', 'a__id', 'id'); diff --git a/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinPartialObjectHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinPartialObjectHydrationPerformanceBench.php index f2e33f76dbd..01e31543cee 100644 --- a/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinPartialObjectHydrationPerformanceBench.php +++ b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinPartialObjectHydrationPerformanceBench.php @@ -1,7 +1,10 @@ rsm->addFieldResult('u', 'u__status', 'status'); $this->rsm->addFieldResult('u', 'u__username', 'username'); $this->rsm->addFieldResult('u', 'u__name', 'name'); - $this->rsm->addScalarResult('sclr0', 'nameUpper'); + $this->rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); $this->rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); } diff --git a/tests/Doctrine/Performance/Hydration/SimpleHydrationBench.php b/tests/Doctrine/Performance/Hydration/SimpleHydrationBench.php index a3fd637d67e..c8303b4630f 100644 --- a/tests/Doctrine/Performance/Hydration/SimpleHydrationBench.php +++ b/tests/Doctrine/Performance/Hydration/SimpleHydrationBench.php @@ -1,5 +1,7 @@ realEntityManager->getConfiguration(); - return new ProxyFactory( - $this, - $config->getProxyDir(), - $config->getProxyNamespace(), - $config->getAutoGenerateProxyClasses() - ); + $proxyConfiguration = new ProxyConfiguration(); + + $proxyConfiguration->setResolver(new DefaultProxyResolver($config->getProxyNamespace(), $config->getProxyDir())); + $proxyConfiguration->setDirectory($config->getProxyDir()); + $proxyConfiguration->setNamespace($config->getProxyNamespace()); + $proxyConfiguration->setAutoGenerate($config->getAutoGenerateProxyClasses()); + + return new StaticProxyFactory($this, $proxyConfiguration); } /** @@ -49,7 +55,7 @@ public function getMetadataFactory() /** * {@inheritDoc} */ - public function getClassMetadata($className) + public function getClassMetadata($className) : ClassMetadata { return $this->realEntityManager->getClassMetadata($className); } @@ -97,7 +103,7 @@ public function beginTransaction() /** * {@inheritDoc} */ - public function transactional($func) + public function transactional(callable $func) { return $this->realEntityManager->transactional($func); } @@ -289,25 +295,29 @@ public function remove($object) /** * {@inheritDoc} */ - public function merge($object) + public function clear($objectName = null) { - return $this->realEntityManager->merge($object); + $this->realEntityManager->clear($objectName); } /** * {@inheritDoc} + * + * @deprecated */ - public function clear($objectName = null) + public function merge($object) { - $this->realEntityManager->clear($objectName); + throw new \BadMethodCallException('@TODO method disabled - will be removed in 3.0 with a release of doctrine/common'); } /** * {@inheritDoc} + * + * @deprecated */ public function detach($object) { - $this->realEntityManager->detach($object); + throw new \BadMethodCallException('@TODO method disabled - will be removed in 3.0 with a release of doctrine/common'); } /** @@ -349,4 +359,12 @@ public function contains($object) { return $this->realEntityManager->contains($object); } -} \ No newline at end of file + + /** + * {@inheritDoc} + */ + public function getIdentifierFlattener() + { + return $this->realEntityManager->getIdentifierFlattener(); + } +} diff --git a/tests/Doctrine/Performance/Mock/NonProxyLoadingUnitOfWork.php b/tests/Doctrine/Performance/Mock/NonProxyLoadingUnitOfWork.php index dd9139ae778..dadffa1324e 100644 --- a/tests/Doctrine/Performance/Mock/NonProxyLoadingUnitOfWork.php +++ b/tests/Doctrine/Performance/Mock/NonProxyLoadingUnitOfWork.php @@ -1,8 +1,10 @@ sharedFixture['conn'] = null; - self::$_sharedConn = null; + + self::$sharedConn = null; } /** @@ -31,12 +34,15 @@ protected function resetSharedConn() protected function setUp() { if (isset($this->sharedFixture['conn'])) { - $this->_conn = $this->sharedFixture['conn']; - } else { - if ( ! isset(self::$_sharedConn)) { - self::$_sharedConn = TestUtil::getConnection(); - } - $this->_conn = self::$_sharedConn; + $this->conn = $this->sharedFixture['conn']; + + return; + } + + if (! isset(self::$sharedConn)) { + self::$sharedConn = TestUtil::getConnection(); } + + $this->conn = self::$sharedConn; } } diff --git a/tests/Doctrine/Tests/DbalTestCase.php b/tests/Doctrine/Tests/DbalTestCase.php index 35ef8bc86d0..a7270774d1c 100644 --- a/tests/Doctrine/Tests/DbalTestCase.php +++ b/tests/Doctrine/Tests/DbalTestCase.php @@ -1,5 +1,7 @@ getObjectManager(); /** @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */ - if (strstr($metadata->name, 'Doctrine\Tests\Models\Cache')) { + if (strstr($metadata->getClassName(), 'Doctrine\Tests\Models\Cache')) { return; } @@ -42,7 +45,7 @@ public function loadClassMetadata(LoadClassMetadataEventArgs $event) */ private function isVisited(ClassMetadata $metadata) { - return isset($this->enabledItems[$metadata->getName()]); + return isset($this->enabledItems[$metadata->getClassName()]); } /** @@ -50,39 +53,43 @@ private function isVisited(ClassMetadata $metadata) */ private function recordVisit(ClassMetadata $metadata) { - $this->enabledItems[$metadata->getName()] = true; + $this->enabledItems[$metadata->getClassName()] = true; } /** - * @param ClassMetadata $metadata - * @param EntityManager $em + * @param ClassMetadata $metadata + * @param EntityManagerInterface $em */ - protected function enableCaching(ClassMetadata $metadata, EntityManager $em) + protected function enableCaching(ClassMetadata $metadata, EntityManagerInterface $em) { if ($this->isVisited($metadata)) { return; // Already handled in the past } - $cache = [ - 'usage' => ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE - ]; - - if ($metadata->isVersioned) { + if ($metadata->isVersioned()) { return; } - $metadata->enableCache($cache); + $region = strtolower(str_replace('\\', '_', $metadata->getRootClassName())); + + $metadata->setCache(new CacheMetadata(CacheUsage::NONSTRICT_READ_WRITE, $region)); $this->recordVisit($metadata); // only enable association-caching when the target has already been // given caching settings - foreach ($metadata->associationMappings as $mapping) { - $targetMeta = $em->getClassMetadata($mapping['targetEntity']); + foreach ($metadata->associationMappings as $association) { + $targetMeta = $em->getClassMetadata($association->getTargetEntity()); + $this->enableCaching($targetMeta, $em); if ($this->isVisited($targetMeta)) { - $metadata->enableAssociationCache($mapping['fieldName'], $cache); + $association->setCache( + new CacheMetadata( + CacheUsage::NONSTRICT_READ_WRITE, + sprintf('%s__%s', $region, $association->getName()) + ) + ); } } } diff --git a/tests/Doctrine/Tests/Mocks/CacheEntryMock.php b/tests/Doctrine/Tests/Mocks/CacheEntryMock.php index 7053df563ba..12ceafe0efd 100644 --- a/tests/Doctrine/Tests/Mocks/CacheEntryMock.php +++ b/tests/Doctrine/Tests/Mocks/CacheEntryMock.php @@ -1,5 +1,7 @@ _generatorType = $type; - } } diff --git a/tests/Doctrine/Tests/Mocks/ConcurrentRegionMock.php b/tests/Doctrine/Tests/Mocks/ConcurrentRegionMock.php index 0f939999d70..24f345216b7 100644 --- a/tests/Doctrine/Tests/Mocks/ConcurrentRegionMock.php +++ b/tests/Doctrine/Tests/Mocks/ConcurrentRegionMock.php @@ -1,5 +1,7 @@ _platformMock = new DatabasePlatformMock(); + $this->platformMock = new DatabasePlatformMock(); parent::__construct($params, $driver, $config, $eventManager); // Override possible assignment of platform to database platform mock - $this->_platform = $this->_platformMock; + $this->platform = $this->platformMock; } /** @@ -66,7 +68,7 @@ public function __construct(array $params, $driver, $config = null, $eventManage */ public function getDatabasePlatform() { - return $this->_platformMock; + return $this->platformMock; } /** @@ -74,7 +76,7 @@ public function getDatabasePlatform() */ public function insert($tableName, array $data, array $types = []) { - $this->_inserts[$tableName][] = $data; + $this->inserts[$tableName][] = $data; } /** @@ -82,7 +84,7 @@ public function insert($tableName, array $data, array $types = []) */ public function executeUpdate($query, array $params = [], array $types = []) { - $this->_executeUpdates[] = ['query' => $query, 'params' => $params, 'types' => $types]; + $this->executeUpdates[] = ['query' => $query, 'params' => $params, 'types' => $types]; } /** @@ -90,7 +92,7 @@ public function executeUpdate($query, array $params = [], array $types = []) */ public function lastInsertId($seqName = null) { - return $this->_lastInsertId; + return $this->lastInsertId; } /** @@ -98,11 +100,11 @@ public function lastInsertId($seqName = null) */ public function fetchColumn($statement, array $params = [], $colnum = 0, array $types = []) { - if (null !== $this->_fetchOneException) { - throw $this->_fetchOneException; + if (null !== $this->fetchOneException) { + throw $this->fetchOneException; } - return $this->_fetchOneResult; + return $this->fetchOneResult; } /** @@ -110,7 +112,7 @@ public function fetchColumn($statement, array $params = [], $colnum = 0, array $ */ public function query() : Statement { - return $this->_queryResult; + return $this->queryResult; } /** @@ -133,7 +135,7 @@ public function quote($input, $type = null) */ public function setFetchOneResult($fetchOneResult) { - $this->_fetchOneResult = $fetchOneResult; + $this->fetchOneResult = $fetchOneResult; } /** @@ -143,7 +145,7 @@ public function setFetchOneResult($fetchOneResult) */ public function setFetchOneException(\Exception $exception = null) { - $this->_fetchOneException = $exception; + $this->fetchOneException = $exception; } /** @@ -153,7 +155,7 @@ public function setFetchOneException(\Exception $exception = null) */ public function setDatabasePlatform($platform) { - $this->_platformMock = $platform; + $this->platformMock = $platform; } /** @@ -163,7 +165,7 @@ public function setDatabasePlatform($platform) */ public function setLastInsertId($id) { - $this->_lastInsertId = $id; + $this->lastInsertId = $id; } /** @@ -171,7 +173,7 @@ public function setLastInsertId($id) */ public function setQueryResult(Statement $result) { - $this->_queryResult = $result; + $this->queryResult = $result; } /** @@ -179,7 +181,7 @@ public function setQueryResult(Statement $result) */ public function getInserts() { - return $this->_inserts; + return $this->inserts; } /** @@ -187,7 +189,7 @@ public function getInserts() */ public function getExecuteUpdates() { - return $this->_executeUpdates; + return $this->executeUpdates; } /** @@ -195,7 +197,7 @@ public function getExecuteUpdates() */ public function reset() { - $this->_inserts = []; - $this->_lastInsertId = 0; + $this->inserts = []; + $this->lastInsertId = 0; } } diff --git a/tests/Doctrine/Tests/Mocks/DatabasePlatformMock.php b/tests/Doctrine/Tests/Mocks/DatabasePlatformMock.php index 60807af5ba4..8cb230581e1 100644 --- a/tests/Doctrine/Tests/Mocks/DatabasePlatformMock.php +++ b/tests/Doctrine/Tests/Mocks/DatabasePlatformMock.php @@ -1,5 +1,7 @@ _prefersIdentityColumns; + return $this->prefersIdentityColumns; } /** @@ -37,7 +39,7 @@ public function prefersIdentityColumns() */ public function prefersSequences() { - return $this->_prefersSequences; + return $this->prefersSequences; } /** @@ -45,7 +47,7 @@ public function prefersSequences() */ public function getSequenceNextValSQL($sequenceName) { - return $this->_sequenceNextValSql; + return $this->sequenceNextValSql; } /** @@ -106,7 +108,7 @@ public function getClobTypeDeclarationSQL(array $field) */ public function setPrefersIdentityColumns($bool) { - $this->_prefersIdentityColumns = $bool; + $this->prefersIdentityColumns = $bool; } /** @@ -116,7 +118,7 @@ public function setPrefersIdentityColumns($bool) */ public function setPrefersSequences($bool) { - $this->_prefersSequences = $bool; + $this->prefersSequences = $bool; } /** @@ -126,7 +128,7 @@ public function setPrefersSequences($bool) */ public function setSequenceNextValSql($sql) { - $this->_sequenceNextValSql = $sql; + $this->sequenceNextValSql = $sql; } /** diff --git a/tests/Doctrine/Tests/Mocks/DriverConnectionMock.php b/tests/Doctrine/Tests/Mocks/DriverConnectionMock.php index af1a4977f49..1168fb12c1c 100644 --- a/tests/Doctrine/Tests/Mocks/DriverConnectionMock.php +++ b/tests/Doctrine/Tests/Mocks/DriverConnectionMock.php @@ -1,5 +1,7 @@ _platformMock) { - $this->_platformMock = new DatabasePlatformMock; + if ( ! $this->platformMock) { + $this->platformMock = new DatabasePlatformMock; } - return $this->_platformMock; + return $this->platformMock; } /** @@ -46,10 +48,10 @@ public function getDatabasePlatform() */ public function getSchemaManager(Connection $conn) { - if ($this->_schemaManagerMock == null) { + if ($this->schemaManagerMock == null) { return new SchemaManagerMock($conn); } else { - return $this->_schemaManagerMock; + return $this->schemaManagerMock; } } @@ -62,7 +64,7 @@ public function getSchemaManager(Connection $conn) */ public function setDatabasePlatform(AbstractPlatform $platform) { - $this->_platformMock = $platform; + $this->platformMock = $platform; } /** @@ -72,7 +74,7 @@ public function setDatabasePlatform(AbstractPlatform $platform) */ public function setSchemaManager(AbstractSchemaManager $sm) { - $this->_schemaManagerMock = $sm; + $this->schemaManagerMock = $sm; } /** diff --git a/tests/Doctrine/Tests/Mocks/EntityManagerMock.php b/tests/Doctrine/Tests/Mocks/EntityManagerMock.php index f7af70227dd..33f570e12a5 100644 --- a/tests/Doctrine/Tests/Mocks/EntityManagerMock.php +++ b/tests/Doctrine/Tests/Mocks/EntityManagerMock.php @@ -1,36 +1,46 @@ wrapped; + } /** * {@inheritdoc} */ public function getUnitOfWork() { - return isset($this->_uowMock) ? $this->_uowMock : parent::getUnitOfWork(); + return $this->uowMock ?? $this->wrapped->getUnitOfWork(); } - /* Mock API */ - /** * Sets a (mock) UnitOfWork that will be returned when getUnitOfWork() is called. * @@ -40,25 +50,25 @@ public function getUnitOfWork() */ public function setUnitOfWork($uow) { - $this->_uowMock = $uow; + $this->uowMock = $uow; } /** - * @param \Doctrine\ORM\Proxy\ProxyFactory $proxyFactory + * @param \Doctrine\ORM\Proxy\Factory\ProxyFactory $proxyFactory * * @return void */ public function setProxyFactory($proxyFactory) { - $this->_proxyFactoryMock = $proxyFactory; + $this->proxyFactoryMock = $proxyFactory; } /** - * @return \Doctrine\ORM\Proxy\ProxyFactory + * @return \Doctrine\ORM\Proxy\Factory\ProxyFactory */ public function getProxyFactory() { - return isset($this->_proxyFactoryMock) ? $this->_proxyFactoryMock : parent::getProxyFactory(); + return $this->proxyFactoryMock ?? $this->wrapped->getProxyFactory(); } /** @@ -70,14 +80,18 @@ public static function create($conn, Configuration $config = null, EventManager { if (null === $config) { $config = new Configuration(); + $config->setProxyDir(__DIR__ . '/../Proxies'); $config->setProxyNamespace('Doctrine\Tests\Proxies'); - $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver([], true)); + $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver()); } + if (null === $eventManager) { - $eventManager = new EventManager(); + $eventManager = $conn->getEventManager(); } - return new EntityManagerMock($conn, $config, $eventManager); + $em = EntityManager::create($conn, $config, $eventManager); + + return new EntityManagerMock($em); } } diff --git a/tests/Doctrine/Tests/Mocks/EntityPersisterMock.php b/tests/Doctrine/Tests/Mocks/EntityPersisterMock.php index 63be3397e68..03ce8e9ac97 100644 --- a/tests/Doctrine/Tests/Mocks/EntityPersisterMock.php +++ b/tests/Doctrine/Tests/Mocks/EntityPersisterMock.php @@ -1,9 +1,12 @@ inserts[] = $entity; - if ( ! is_null($this->mockIdGeneratorType) && $this->mockIdGeneratorType == ClassMetadata::GENERATOR_TYPE_IDENTITY - || $this->class->isIdGeneratorIdentity()) { - $id = $this->identityColumnValueCounter++; - $this->postInsertIds[] = [ - 'generatedId' => $id, - 'entity' => $entity, - ]; - return $id; - } - return null; + $this->mockIdGeneratorType = $genType; } /** - * @return array + * {@inheritdoc} */ - public function executeInserts() + public function insert($entity) { - return $this->postInsertIds; - } + $this->inserts[] = $entity; - /** - * @param int $genType - * - * @return void - */ - public function setMockIdGeneratorType($genType) - { - $this->mockIdGeneratorType = $genType; + if ($this->class->getValueGenerationPlan()->containsDeferred()) { + $this->class->getValueGenerationPlan()->executeDeferred($this->em, $entity); + } } /** @@ -138,7 +115,6 @@ public function getDeletes() public function reset() { $this->existsCalled = false; - $this->identityColumnValueCounter = 0; $this->inserts = []; $this->updates = []; $this->deletes = []; diff --git a/tests/Doctrine/Tests/Mocks/HydratorMockStatement.php b/tests/Doctrine/Tests/Mocks/HydratorMockStatement.php index 4f6df40e59d..8f2476c7405 100644 --- a/tests/Doctrine/Tests/Mocks/HydratorMockStatement.php +++ b/tests/Doctrine/Tests/Mocks/HydratorMockStatement.php @@ -1,5 +1,7 @@ _resultSet = $resultSet; + $this->resultSet = $resultSet; } /** @@ -37,7 +39,7 @@ public function __construct(array $resultSet) */ public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null) { - return $this->_resultSet; + return $this->resultSet; } /** @@ -45,7 +47,7 @@ public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = n */ public function fetchColumn($columnNumber = 0) { - $row = current($this->_resultSet); + $row = current($this->resultSet); if ( ! is_array($row)) return false; $val = array_shift($row); return $val !== null ? $val : false; @@ -56,8 +58,8 @@ public function fetchColumn($columnNumber = 0) */ public function fetch($fetchStyle = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { - $current = current($this->_resultSet); - next($this->_resultSet); + $current = current($this->resultSet); + next($this->resultSet); return $current; } @@ -123,7 +125,7 @@ public function rowCount() */ public function getIterator() { - return $this->_resultSet; + return $this->resultSet; } /** diff --git a/tests/Doctrine/Tests/Mocks/MetadataDriverMock.php b/tests/Doctrine/Tests/Mocks/MetadataDriverMock.php index f14c256b19e..e9a229a5078 100644 --- a/tests/Doctrine/Tests/Mocks/MetadataDriverMock.php +++ b/tests/Doctrine/Tests/Mocks/MetadataDriverMock.php @@ -1,9 +1,12 @@ _sequenceNumber++; + return $this->sequenceNumber++; } /* Mock API */ @@ -30,6 +32,6 @@ public function generate(EntityManager $em, $entity) */ public function reset() { - $this->_sequenceNumber = 0; + $this->sequenceNumber = 0; } } diff --git a/tests/Doctrine/Tests/Mocks/StatementArrayMock.php b/tests/Doctrine/Tests/Mocks/StatementArrayMock.php index ed6ea4fdf6c..8db6e30220e 100644 --- a/tests/Doctrine/Tests/Mocks/StatementArrayMock.php +++ b/tests/Doctrine/Tests/Mocks/StatementArrayMock.php @@ -1,5 +1,7 @@ _result = $result; + $this->result = $result; } public function getIterator() { - return new \ArrayIterator($this->_result); + return new \ArrayIterator($this->result); } public function columnCount() { - $row = reset($this->_result); + $row = reset($this->result); if ($row) { return count($row); } else { @@ -36,22 +38,22 @@ public function columnCount() public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null) { - return $this->_result; + return $this->result; } public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { - $current = current($this->_result); - next($this->_result); + $current = current($this->result); + next($this->result); return $current; } public function fetchColumn($columnIndex = 0) { - $current = current($this->_result); + $current = current($this->result); if ($current) { - next($this->_result); + next($this->result); return reset($current); } else { return false; @@ -60,6 +62,6 @@ public function fetchColumn($columnIndex = 0) public function rowCount() { - return count($this->_result); + return count($this->result); } } diff --git a/tests/Doctrine/Tests/Mocks/StatementMock.php b/tests/Doctrine/Tests/Mocks/StatementMock.php index efba7d841b4..8fb373b4de7 100644 --- a/tests/Doctrine/Tests/Mocks/StatementMock.php +++ b/tests/Doctrine/Tests/Mocks/StatementMock.php @@ -1,5 +1,7 @@ - */ -class TaskMock extends \Doctrine\Common\Cli\Tasks\AbstractTask -{ - /** - * Since instances of this class can be created elsewhere all instances - * register themselves in this array for later inspection. - * - * @var array (TaskMock) - */ - static public $instances = []; - - /** - * @var int - */ - private $runCounter = 0; - - /** - * Constructor of Task Mock Object. - * Makes sure the object can be inspected later. - * - * @param AbstractNamespace $namespace CLI Namespace, passed to parent constructor. - */ - function __construct(AbstractNamespace $namespace) - { - self::$instances[] = $this; - - parent::__construct($namespace); - } - - /** - * Returns the number of times run() was called on this object. - * - * @return int - */ - public function getRunCounter() - { - return $this->runCounter; - } - - /* Mock API */ - - /** - * Method invoked by CLI to run task. - * - * @return void - */ - public function run() - { - $this->runCounter++; - } - - /** - * Method supposed to generate the CLI Task Documentation. - * - * @return void - */ - public function buildDocumentation() - { - } -} diff --git a/tests/Doctrine/Tests/Mocks/TimestampRegionMock.php b/tests/Doctrine/Tests/Mocks/TimestampRegionMock.php index 3f088a4e492..8e3faf3666c 100644 --- a/tests/Doctrine/Tests/Mocks/TimestampRegionMock.php +++ b/tests/Doctrine/Tests/Mocks/TimestampRegionMock.php @@ -1,5 +1,7 @@ _persisterMock[$entityName]) - ? $this->_persisterMock[$entityName] + return isset($this->persisterMock[$entityName]) + ? $this->persisterMock[$entityName] : parent::getEntityPersister($entityName); } @@ -36,8 +38,8 @@ public function & getEntityChangeSet($entity) { $oid = spl_object_hash($entity); - if (isset($this->_mockDataChangeSets[$oid])) { - return $this->_mockDataChangeSets[$oid]; + if (isset($this->mockDataChangeSets[$oid])) { + return $this->mockDataChangeSets[$oid]; } $data = parent::getEntityChangeSet($entity); @@ -58,14 +60,6 @@ public function & getEntityChangeSet($entity) */ public function setEntityPersister($entityName, $persister) { - $this->_persisterMock[$entityName] = $persister; - } - - /** - * {@inheritdoc} - */ - public function setOriginalEntityData($entity, array $originalData) - { - $this->_originalEntityData[spl_object_hash($entity)] = $originalData; + $this->persisterMock[$entityName] = $persister; } } diff --git a/tests/Doctrine/Tests/Models/CMS/CmsAddress.php b/tests/Doctrine/Tests/Models/CMS/CmsAddress.php index f5c0b9af766..b10acd7bc7a 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsAddress.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsAddress.php @@ -1,86 +1,94 @@ setAddress($this); } } - - public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) - { - $metadata->setPrimaryTable( - [ - 'name' => 'company_person', - ] - ); - - $metadata->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - ] - ); - - $metadata->mapField( - [ - 'fieldName' => 'zip', - 'length' => 50, - ] - ); - - $metadata->mapField( - [ - 'fieldName' => 'city', - 'length' => 50, - ] - ); - - $metadata->mapOneToOne( - [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser', - 'joinColumns' => [['referencedColumnName' => 'id']] - ] - ); - - $metadata->addNamedNativeQuery( - [ - 'name' => 'find-all', - 'query' => 'SELECT id, country, city FROM cms_addresses', - 'resultSetMapping' => 'mapping-find-all', - ] - ); - - $metadata->addNamedNativeQuery( - [ - 'name' => 'find-by-id', - 'query' => 'SELECT * FROM cms_addresses WHERE id = ?', - 'resultClass' => CmsAddress::class, - ] - ); - - $metadata->addNamedNativeQuery( - [ - 'name' => 'count', - 'query' => 'SELECT COUNT(*) AS count FROM cms_addresses', - 'resultSetMapping' => 'mapping-count', - ] - ); - - $metadata->addSqlResultSetMapping( - [ - 'name' => 'mapping-find-all', - 'columns' => [], - 'entities' => [ - [ - 'fields' => [ - [ - 'name' => 'id', - 'column' => 'id', - ], - [ - 'name' => 'city', - 'column' => 'city', - ], - [ - 'name' => 'country', - 'column' => 'country', - ], - ], - 'entityClass' => CmsAddress::class, - ], - ], - ] - ); - - $metadata->addSqlResultSetMapping( - [ - 'name' => 'mapping-without-fields', - 'columns' => [], - 'entities' => [ - [ - 'entityClass' => CmsAddress::class, - 'fields' => [] - ] - ] - ] - ); - - $metadata->addSqlResultSetMapping( - [ - 'name' => 'mapping-count', - 'columns' => [ - [ - 'name' => 'count', - ], - ] - ] - ); - - $metadata->addEntityListener(\Doctrine\ORM\Events::postPersist, 'CmsAddressListener', 'postPersist'); - $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CmsAddressListener', 'prePersist'); - - $metadata->addEntityListener(\Doctrine\ORM\Events::postUpdate, 'CmsAddressListener', 'postUpdate'); - $metadata->addEntityListener(\Doctrine\ORM\Events::preUpdate, 'CmsAddressListener', 'preUpdate'); - - $metadata->addEntityListener(\Doctrine\ORM\Events::postRemove, 'CmsAddressListener', 'postRemove'); - $metadata->addEntityListener(\Doctrine\ORM\Events::preRemove, 'CmsAddressListener', 'preRemove'); - - $metadata->addEntityListener(\Doctrine\ORM\Events::preFlush, 'CmsAddressListener', 'preFlush'); - $metadata->addEntityListener(\Doctrine\ORM\Events::postLoad, 'CmsAddressListener', 'postLoad'); - } } diff --git a/tests/Doctrine/Tests/Models/CMS/CmsAddressDTO.php b/tests/Doctrine/Tests/Models/CMS/CmsAddressDTO.php index 2a4f220f8c8..7f6bf51d51e 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsAddressDTO.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsAddressDTO.php @@ -1,5 +1,7 @@ city = $city; $this->zip = $zip; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/CMS/CmsAddressListener.php b/tests/Doctrine/Tests/Models/CMS/CmsAddressListener.php index 9c9db89eb14..f8ffe931fc3 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsAddressListener.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsAddressListener.php @@ -1,5 +1,7 @@ user = $user; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/CMS/CmsEmployee.php b/tests/Doctrine/Tests/Models/CMS/CmsEmployee.php index c1697150fc4..a06190afcdd 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsEmployee.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsEmployee.php @@ -1,31 +1,36 @@ setPrimaryTable( - [ - 'name' => 'cms_users', - ] - ); - - $metadata->addNamedNativeQuery( - [ - 'name' => 'fetchIdAndUsernameWithResultClass', - 'query' => 'SELECT id, username FROM cms_users WHERE username = ?', - 'resultClass' => CmsUser::class, - ] - ); - - $metadata->addNamedNativeQuery( - [ - 'name' => 'fetchAllColumns', - 'query' => 'SELECT * FROM cms_users WHERE username = ?', - 'resultClass' => CmsUser::class, - ] - ); - - $metadata->addNamedNativeQuery( - [ - 'name' => 'fetchJoinedAddress', - 'query' => 'SELECT u.id, u.name, u.status, a.id AS a_id, a.country, a.zip, a.city FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id WHERE u.username = ?', - 'resultSetMapping' => 'mappingJoinedAddress', - ] - ); - - $metadata->addNamedNativeQuery( - [ - 'name' => 'fetchJoinedPhonenumber', - 'query' => 'SELECT id, name, status, phonenumber AS number FROM cms_users INNER JOIN cms_phonenumbers ON id = user_id WHERE username = ?', - 'resultSetMapping' => 'mappingJoinedPhonenumber', - ] - ); - - $metadata->addNamedNativeQuery( - [ - 'name' => 'fetchUserPhonenumberCount', - 'query' => 'SELECT id, name, status, COUNT(phonenumber) AS numphones FROM cms_users INNER JOIN cms_phonenumbers ON id = user_id WHERE username IN (?) GROUP BY id, name, status, username ORDER BY username', - 'resultSetMapping' => 'mappingUserPhonenumberCount', - ] - ); - - $metadata->addNamedNativeQuery( - [ - "name" => "fetchMultipleJoinsEntityResults", - "resultSetMapping" => "mappingMultipleJoinsEntityResults", - "query" => "SELECT u.id AS u_id, u.name AS u_name, u.status AS u_status, a.id AS a_id, a.zip AS a_zip, a.country AS a_country, COUNT(p.phonenumber) AS numphones FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id INNER JOIN cms_phonenumbers p ON u.id = p.user_id GROUP BY u.id, u.name, u.status, u.username, a.id, a.zip, a.country ORDER BY u.username" - ] - ); - - $metadata->addSqlResultSetMapping( - [ - 'name' => 'mappingJoinedAddress', - 'columns' => [], - 'entities' => [ - [ - 'fields'=> [ - [ - 'name' => 'id', - 'column' => 'id', - ], - [ - 'name' => 'name', - 'column' => 'name', - ], - [ - 'name' => 'status', - 'column' => 'status', - ], - [ - 'name' => 'address.zip', - 'column' => 'zip', - ], - [ - 'name' => 'address.city', - 'column' => 'city', - ], - [ - 'name' => 'address.country', - 'column' => 'country', - ], - [ - 'name' => 'address.id', - 'column' => 'a_id', - ], - ], - 'entityClass' => CmsUser::class, - 'discriminatorColumn' => null - ], - ], - ] - ); - - $metadata->addSqlResultSetMapping( - [ - 'name' => 'mappingJoinedPhonenumber', - 'columns' => [], - 'entities' => [ - [ - 'fields'=> [ - [ - 'name' => 'id', - 'column' => 'id', - ], - [ - 'name' => 'name', - 'column' => 'name', - ], - [ - 'name' => 'status', - 'column' => 'status', - ], - [ - 'name' => 'phonenumbers.phonenumber', - 'column' => 'number', - ], - ], - 'entityClass' => CmsUser::class, - 'discriminatorColumn' => null - ], - ], - ] - ); - - $metadata->addSqlResultSetMapping( - [ - 'name' => 'mappingUserPhonenumberCount', - 'columns' => [], - 'entities' => [ - [ - 'fields' => [ - [ - 'name' => 'id', - 'column' => 'id', - ], - [ - 'name' => 'name', - 'column' => 'name', - ], - [ - 'name' => 'status', - 'column' => 'status', - ] - ], - 'entityClass' => CmsUser::class, - 'discriminatorColumn' => null - ] - ], - 'columns' => [ - [ - 'name' => 'numphones', - ] - ] - ] - ); - - $metadata->addSqlResultSetMapping( - [ - 'name' => 'mappingMultipleJoinsEntityResults', - 'entities' => [ - [ - 'fields' => [ - [ - 'name' => 'id', - 'column' => 'u_id', - ], - [ - 'name' => 'name', - 'column' => 'u_name', - ], - [ - 'name' => 'status', - 'column' => 'u_status', - ] - ], - 'entityClass' => CmsUser::class, - 'discriminatorColumn' => null, - ], - [ - 'fields' => [ - [ - 'name' => 'id', - 'column' => 'a_id', - ], - [ - 'name' => 'zip', - 'column' => 'a_zip', - ], - [ - 'name' => 'country', - 'column' => 'a_country', - ], - ], - 'entityClass' => CmsAddress::class, - 'discriminatorColumn' => null, - ], - ], - 'columns' => [ - [ - 'name' => 'numphones', - ] - ] - ] - ); - - } } diff --git a/tests/Doctrine/Tests/Models/CMS/CmsUserDTO.php b/tests/Doctrine/Tests/Models/CMS/CmsUserDTO.php index 0a07d26c16d..9a1fde4bf45 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsUserDTO.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsUserDTO.php @@ -1,5 +1,7 @@ address = $address; $this->phonenumbers = $phonenumbers; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Cache/Action.php b/tests/Doctrine/Tests/Models/Cache/Action.php index 72bbba4c173..b62155d1008 100644 --- a/tests/Doctrine/Tests/Models/Cache/Action.php +++ b/tests/Doctrine/Tests/Models/Cache/Action.php @@ -1,24 +1,27 @@ attractions; } - - public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) - { - include __DIR__ . '/../../ORM/Mapping/php/Doctrine.Tests.Models.Cache.City.php'; - } } diff --git a/tests/Doctrine/Tests/Models/Cache/Client.php b/tests/Doctrine/Tests/Models/Cache/Client.php index dfbc60e30cf..67dc15d3c5b 100644 --- a/tests/Doctrine/Tests/Models/Cache/Client.php +++ b/tests/Doctrine/Tests/Models/Cache/Client.php @@ -1,22 +1,26 @@ title; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Company/CompanyContract.php b/tests/Doctrine/Tests/Models/Company/CompanyContract.php index 15e691ba087..605da9c6e4b 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyContract.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyContract.php @@ -1,55 +1,62 @@ setInheritanceType(\Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_JOINED); - $metadata->setTableName( 'company_contracts'); - $metadata->setDiscriminatorColumn( - [ - 'name' => 'discr', - 'type' => 'string', - ] - ); - - $metadata->mapField( - [ - 'id' => true, - 'name' => 'id', - 'fieldName' => 'id', - ] - ); - - $metadata->mapField( - [ - 'type' => 'boolean', - 'name' => 'completed', - 'fieldName' => 'completed', - ] - ); - - $metadata->setDiscriminatorMap( - [ - "fix" => "CompanyFixContract", - "flexible" => "CompanyFlexContract", - "flexultra" => "CompanyFlexUltraContract" - ] - ); - - $metadata->addEntityListener(\Doctrine\ORM\Events::postPersist, 'CompanyContractListener', 'postPersistHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); - - $metadata->addEntityListener(\Doctrine\ORM\Events::postUpdate, 'CompanyContractListener', 'postUpdateHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::preUpdate, 'CompanyContractListener', 'preUpdateHandler'); - - $metadata->addEntityListener(\Doctrine\ORM\Events::postRemove, 'CompanyContractListener', 'postRemoveHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::preRemove, 'CompanyContractListener', 'preRemoveHandler'); - - $metadata->addEntityListener(\Doctrine\ORM\Events::preFlush, 'CompanyContractListener', 'preFlushHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::postLoad, 'CompanyContractListener', 'postLoadHandler'); - } } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyContractListener.php b/tests/Doctrine/Tests/Models/Company/CompanyContractListener.php index 23714f32983..77c98461e77 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyContractListener.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyContractListener.php @@ -1,7 +1,11 @@ organization = $org; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Company/CompanyFixContract.php b/tests/Doctrine/Tests/Models/Company/CompanyFixContract.php index 8fe94e2584d..b51444a79d5 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyFixContract.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyFixContract.php @@ -1,14 +1,20 @@ fixPrice = $fixPrice; } - - static public function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) - { - $metadata->mapField( - [ - 'type' => 'integer', - 'name' => 'fixPrice', - 'fieldName' => 'fixPrice', - ] - ); - } } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyFlexContract.php b/tests/Doctrine/Tests/Models/Company/CompanyFlexContract.php index 978e8d5e6cd..6b43ebdfd47 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyFlexContract.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyFlexContract.php @@ -1,45 +1,52 @@ managers->removeElement($manager); } - - static public function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) - { - $metadata->mapField( - [ - 'type' => 'integer', - 'name' => 'hoursWorked', - 'fieldName' => 'hoursWorked', - ] - ); - - $metadata->mapField( - [ - 'type' => 'integer', - 'name' => 'pricePerHour', - 'fieldName' => 'pricePerHour', - ] - ); - } } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContract.php b/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContract.php index 47313d032e7..84228d10237 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContract.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContract.php @@ -1,16 +1,23 @@ maxPrice = $maxPrice; } - - static public function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) - { - $metadata->mapField( - [ - 'type' => 'integer', - 'name' => 'maxPrice', - 'fieldName' => 'maxPrice', - ] - ); - $metadata->addEntityListener(\Doctrine\ORM\Events::postPersist, 'CompanyContractListener', 'postPersistHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); - - $metadata->addEntityListener(\Doctrine\ORM\Events::postUpdate, 'CompanyContractListener', 'postUpdateHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::preUpdate, 'CompanyContractListener', 'preUpdateHandler'); - - $metadata->addEntityListener(\Doctrine\ORM\Events::postRemove, 'CompanyContractListener', 'postRemoveHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::preRemove, 'CompanyContractListener', 'preRemoveHandler'); - - $metadata->addEntityListener(\Doctrine\ORM\Events::preFlush, 'CompanyContractListener', 'preFlushHandler'); - $metadata->addEntityListener(\Doctrine\ORM\Events::postLoad, 'CompanyContractListener', 'postLoadHandler'); - - $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyFlexUltraContractListener', 'prePersistHandler1'); - $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyFlexUltraContractListener', 'prePersistHandler2'); - } } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContractListener.php b/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContractListener.php index 2f028e35f0f..ec083dfe90e 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContractListener.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContractListener.php @@ -1,7 +1,10 @@ spouse->setSpouse($this); } } - - public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) - { - - $metadata->setPrimaryTable( - [ - 'name' => 'company_person', - ] - ); - - $metadata->addNamedNativeQuery( - [ - 'name' => 'fetchAllWithResultClass', - 'query' => 'SELECT id, name, discr FROM company_persons ORDER BY name', - 'resultClass' => CompanyPerson::class, - ] - ); - - $metadata->addNamedNativeQuery( - [ - 'name' => 'fetchAllWithSqlResultSetMapping', - 'query' => 'SELECT id, name, discr AS discriminator FROM company_persons ORDER BY name', - 'resultSetMapping' => 'mappingFetchAll', - ] - ); - - $metadata->addSqlResultSetMapping( - [ - 'name' => 'mappingFetchAll', - 'columns' => [], - 'entities' => [ - [ - 'fields' => [ - [ - 'name' => 'id', - 'column' => 'id', - ], - [ - 'name' => 'name', - 'column' => 'name', - ], - ], - 'entityClass' => CompanyPerson::class, - 'discriminatorColumn' => 'discriminator', - ], - ], - ] - ); - } } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyRaffle.php b/tests/Doctrine/Tests/Models/Company/CompanyRaffle.php index 733190d5845..cbe43466a5b 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyRaffle.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyRaffle.php @@ -1,10 +1,18 @@ data; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/CompositeKeyInheritance/JoinedChildClass.php b/tests/Doctrine/Tests/Models/CompositeKeyInheritance/JoinedChildClass.php index ba59736470d..b9daa233131 100644 --- a/tests/Doctrine/Tests/Models/CompositeKeyInheritance/JoinedChildClass.php +++ b/tests/Doctrine/Tests/Models/CompositeKeyInheritance/JoinedChildClass.php @@ -1,21 +1,26 @@ translation; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC117/DDC117Article.php b/tests/Doctrine/Tests/Models/DDC117/DDC117Article.php index 9d57b56523a..f834d8c5035 100644 --- a/tests/Doctrine/Tests/Models/DDC117/DDC117Article.php +++ b/tests/Doctrine/Tests/Models/DDC117/DDC117Article.php @@ -1,35 +1,39 @@ text; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC117/DDC117Editor.php b/tests/Doctrine/Tests/Models/DDC117/DDC117Editor.php index a323bb3045e..155f3131b52 100644 --- a/tests/Doctrine/Tests/Models/DDC117/DDC117Editor.php +++ b/tests/Doctrine/Tests/Models/DDC117/DDC117Editor.php @@ -1,41 +1,45 @@ lastTranslation = $t; $t->lastTranslatedBy[] = $this; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC117/DDC117Link.php b/tests/Doctrine/Tests/Models/DDC117/DDC117Link.php index 7e0084a67d7..8e483d5550c 100644 --- a/tests/Doctrine/Tests/Models/DDC117/DDC117Link.php +++ b/tests/Doctrine/Tests/Models/DDC117/DDC117Link.php @@ -1,25 +1,29 @@ name = $name; } - - public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) - { - $metadata->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - ] - ); - $metadata->mapField( - [ - 'fieldName' => 'name', - ] - ); - - $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_NONE); - } - } diff --git a/tests/Doctrine/Tests/Models/DDC1590/DDC1590Entity.php b/tests/Doctrine/Tests/Models/DDC1590/DDC1590Entity.php index 2bb75f2e0e8..2f94d68c7ee 100644 --- a/tests/Doctrine/Tests/Models/DDC1590/DDC1590Entity.php +++ b/tests/Doctrine/Tests/Models/DDC1590/DDC1590Entity.php @@ -1,22 +1,26 @@ setAddress($this); } } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC2372/DDC2372Admin.php b/tests/Doctrine/Tests/Models/DDC2372/DDC2372Admin.php index 604e919f75b..fbb08b5c45d 100644 --- a/tests/Doctrine/Tests/Models/DDC2372/DDC2372Admin.php +++ b/tests/Doctrine/Tests/Models/DDC2372/DDC2372Admin.php @@ -1,8 +1,12 @@ name = $name; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC2372/Traits/DDC2372AddressTrait.php b/tests/Doctrine/Tests/Models/DDC2372/Traits/DDC2372AddressTrait.php index 66ca1744611..c3266747936 100644 --- a/tests/Doctrine/Tests/Models/DDC2372/Traits/DDC2372AddressTrait.php +++ b/tests/Doctrine/Tests/Models/DDC2372/Traits/DDC2372AddressTrait.php @@ -1,12 +1,16 @@ setUser($this); } } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC2504/DDC2504ChildClass.php b/tests/Doctrine/Tests/Models/DDC2504/DDC2504ChildClass.php index a43de5bbfe7..f41b4f4b0f3 100644 --- a/tests/Doctrine/Tests/Models/DDC2504/DDC2504ChildClass.php +++ b/tests/Doctrine/Tests/Models/DDC2504/DDC2504ChildClass.php @@ -1,9 +1,13 @@ setAssociationOverride('groups', [ - 'inversedBy' => 'admins' - ] - ); - } } diff --git a/tests/Doctrine/Tests/Models/DDC3579/DDC3579Group.php b/tests/Doctrine/Tests/Models/DDC3579/DDC3579Group.php index 821c06b57ce..40b3970659a 100644 --- a/tests/Doctrine/Tests/Models/DDC3579/DDC3579Group.php +++ b/tests/Doctrine/Tests/Models/DDC3579/DDC3579Group.php @@ -1,30 +1,30 @@ groups; } - - public static function loadMetadata($metadata) - { - $metadata->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'user_id', - 'length' => 150, - ] - ); - - $metadata->mapField( - [ - 'fieldName' => 'name', - 'type' => 'string', - 'columnName'=> 'user_name', - 'nullable' => true, - 'unique' => false, - 'length' => 250, - ] - ); - - $metadata->mapManyToMany( - [ - 'fieldName' => 'groups', - 'targetEntity' => 'DDC3579Group' - ] - ); - - $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_AUTO); - } } diff --git a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Image.php b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Image.php index 5d1acfeb6ad..51d800e9b5a 100644 --- a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Image.php +++ b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Image.php @@ -1,27 +1,30 @@ - * @Entity + * @ORM\Entity */ -class DDC3597Image extends DDC3597Media { - +class DDC3597Image extends DDC3597Media +{ /** * @var DDC3597Dimension - * @Embedded(class = "Doctrine\Tests\Models\DDC3597\Embeddable\DDC3597Dimension", columnPrefix = false) + * @ORM\Embedded(class = "Doctrine\Tests\Models\DDC3597\Embeddable\DDC3597Dimension", columnPrefix = false) */ private $dimension; /** * @param string $distributionHash */ - function __construct($distributionHash) { + public function __construct($distributionHash) { parent::__construct($distributionHash); $this->dimension = new DDC3597Dimension(); } diff --git a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Media.php b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Media.php index c285b3c40e6..df528f983e2 100644 --- a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Media.php +++ b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Media.php @@ -1,36 +1,40 @@ - * @Entity + * @ORM\Entity */ -abstract class DDC3597Media extends DDC3597Root { - +abstract class DDC3597Media extends DDC3597Root +{ /** * @var string * - * @Column + * @ORM\Column */ private $distributionHash; /** * @var integer * - * @Column + * @ORM\Column */ private $size = 0; /** * @var string - * @Column + * @ORM\Column */ private $format; - function __construct($distributionHash) { + public function __construct($distributionHash) { $this->distributionHash = $distributionHash; } @@ -68,7 +72,4 @@ public function getFormat() { public function setFormat($format) { $this->format = $format; } - - - } diff --git a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Root.php b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Root.php index 3bdb67f13d7..a2e14f8ddfa 100644 --- a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Root.php +++ b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Root.php @@ -1,56 +1,59 @@ updatedAt = $this->createdAt = new \DateTime(); } /** * Set updatedAt * - * @PreUpdate + * @ORM\PreUpdate */ - public function _preUpdate() { + public function preUpdate() { $this->updatedAt = new \DateTime(); } diff --git a/tests/Doctrine/Tests/Models/DDC3597/Embeddable/DDC3597Dimension.php b/tests/Doctrine/Tests/Models/DDC3597/Embeddable/DDC3597Dimension.php index cd5dc70a232..e29b406c836 100644 --- a/tests/Doctrine/Tests/Models/DDC3597/Embeddable/DDC3597Dimension.php +++ b/tests/Doctrine/Tests/Models/DDC3597/Embeddable/DDC3597Dimension.php @@ -1,27 +1,31 @@ setWidth($width); $this->setHeight($height); } @@ -53,4 +57,4 @@ public function getHeight() { public function setHeight($height) { $this->height = (int)$height; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC3699/DDC3699Child.php b/tests/Doctrine/Tests/Models/DDC3699/DDC3699Child.php index dc2ccfddde1..fb87213ec8a 100644 --- a/tests/Doctrine/Tests/Models/DDC3699/DDC3699Child.php +++ b/tests/Doctrine/Tests/Models/DDC3699/DDC3699Child.php @@ -1,19 +1,23 @@ members = new ArrayCollection(); } - - public static function loadMetadata(ClassMetadata $metadata) - { - $metadata->mapField([ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'id', - ]); - - $metadata->mapManyToMany([ - 'fieldName' => 'members', - 'targetEntity' => 'DDC5934Member', - ]); - - $metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_AUTO); - } } diff --git a/tests/Doctrine/Tests/Models/DDC5934/DDC5934Contract.php b/tests/Doctrine/Tests/Models/DDC5934/DDC5934Contract.php index e26c4d66501..ef10fbaddbb 100644 --- a/tests/Doctrine/Tests/Models/DDC5934/DDC5934Contract.php +++ b/tests/Doctrine/Tests/Models/DDC5934/DDC5934Contract.php @@ -1,24 +1,19 @@ setAssociationOverride('members', [ - 'fetch' => ClassMetadata::FETCH_EXTRA_LAZY, - ]); - } } diff --git a/tests/Doctrine/Tests/Models/DDC5934/DDC5934Member.php b/tests/Doctrine/Tests/Models/DDC5934/DDC5934Member.php index ff85d6c6613..a0aad3fe6aa 100644 --- a/tests/Doctrine/Tests/Models/DDC5934/DDC5934Member.php +++ b/tests/Doctrine/Tests/Models/DDC5934/DDC5934Member.php @@ -1,5 +1,7 @@ mapField( - [ - 'fieldName' => 'serialNumber', - 'type' => 'string', - ] - ); - } - } diff --git a/tests/Doctrine/Tests/Models/DDC869/DDC869CreditCardPayment.php b/tests/Doctrine/Tests/Models/DDC869/DDC869CreditCardPayment.php index 6f314e31889..ed72555803d 100644 --- a/tests/Doctrine/Tests/Models/DDC869/DDC869CreditCardPayment.php +++ b/tests/Doctrine/Tests/Models/DDC869/DDC869CreditCardPayment.php @@ -1,24 +1,18 @@ mapField( - [ - 'fieldName' => 'creditCardNumber', - 'type' => 'string', - ] - ); - } - } diff --git a/tests/Doctrine/Tests/Models/DDC869/DDC869Payment.php b/tests/Doctrine/Tests/Models/DDC869/DDC869Payment.php index 992c53ae27a..f0fbcdd111b 100644 --- a/tests/Doctrine/Tests/Models/DDC869/DDC869Payment.php +++ b/tests/Doctrine/Tests/Models/DDC869/DDC869Payment.php @@ -1,43 +1,25 @@ mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'id', - ] - ); - $metadata->mapField( - [ - 'fieldName' => 'value', - 'type' => 'float', - ] - ); - $metadata->isMappedSuperclass = true; - $metadata->setCustomRepositoryClass(DDC869PaymentRepository::class); - $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_AUTO); - } - } diff --git a/tests/Doctrine/Tests/Models/DDC869/DDC869PaymentRepository.php b/tests/Doctrine/Tests/Models/DDC869/DDC869PaymentRepository.php index 3c11b154bce..5b6b52e0dc1 100644 --- a/tests/Doctrine/Tests/Models/DDC869/DDC869PaymentRepository.php +++ b/tests/Doctrine/Tests/Models/DDC869/DDC869PaymentRepository.php @@ -1,12 +1,13 @@ mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'id', - ] - ); - - $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_AUTO); - } - } diff --git a/tests/Doctrine/Tests/Models/DDC889/DDC889Entity.php b/tests/Doctrine/Tests/Models/DDC889/DDC889Entity.php index 43884435fa7..f951e271bc1 100644 --- a/tests/Doctrine/Tests/Models/DDC889/DDC889Entity.php +++ b/tests/Doctrine/Tests/Models/DDC889/DDC889Entity.php @@ -1,15 +1,15 @@ mapField( - [ - 'fieldName' => 'name', - ] - ); - - $metadata->isMappedSuperclass = true; - $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_NONE); - } } diff --git a/tests/Doctrine/Tests/Models/DDC964/DDC964Address.php b/tests/Doctrine/Tests/Models/DDC964/DDC964Address.php index a549dc98cec..1761ff3d9ec 100644 --- a/tests/Doctrine/Tests/Models/DDC964/DDC964Address.php +++ b/tests/Doctrine/Tests/Models/DDC964/DDC964Address.php @@ -1,36 +1,39 @@ street = $street; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC964/DDC964Admin.php b/tests/Doctrine/Tests/Models/DDC964/DDC964Admin.php index 29ea4dd4e14..6bd0adc1e67 100644 --- a/tests/Doctrine/Tests/Models/DDC964/DDC964Admin.php +++ b/tests/Doctrine/Tests/Models/DDC964/DDC964Admin.php @@ -1,19 +1,26 @@ setAssociationOverride('address', - [ - 'joinColumns'=> [ - [ - 'name' => 'adminaddress_id', - 'referencedColumnName' => 'id', - ] - ] - ] - ); - - $metadata->setAssociationOverride('groups', - [ - 'joinTable' => [ - 'name' => 'ddc964_users_admingroups', - 'joinColumns' => [ - [ - 'name' => 'adminuser_id', - ] - ], - 'inverseJoinColumns' => [[ - 'name' => 'admingroup_id', - ]] - ] - ] - ); - } } diff --git a/tests/Doctrine/Tests/Models/DDC964/DDC964Group.php b/tests/Doctrine/Tests/Models/DDC964/DDC964Group.php index 52604099764..efe415861f5 100644 --- a/tests/Doctrine/Tests/Models/DDC964/DDC964Group.php +++ b/tests/Doctrine/Tests/Models/DDC964/DDC964Group.php @@ -1,30 +1,30 @@ setAttributeOverride('id', [ - 'columnName' => 'guest_id', - 'type' => 'integer', - 'length' => 140, - ] - ); - - $metadata->setAttributeOverride('name', - [ - 'columnName' => 'guest_name', - 'nullable' => false, - 'unique' => true, - 'length' => 240, - ] - ); - } } diff --git a/tests/Doctrine/Tests/Models/DDC964/DDC964User.php b/tests/Doctrine/Tests/Models/DDC964/DDC964User.php index a9f15c8c948..0d4965d76eb 100644 --- a/tests/Doctrine/Tests/Models/DDC964/DDC964User.php +++ b/tests/Doctrine/Tests/Models/DDC964/DDC964User.php @@ -1,34 +1,38 @@ address = $address; } - public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) + public static function loadMetadata(Mapping\ClassMetadata $metadata) { - $metadata->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'user_id', - 'length' => 150, - ] - ); - $metadata->mapField( - [ - 'fieldName' => 'name', - 'type' => 'string', - 'columnName'=> 'user_name', - 'nullable' => true, - 'unique' => false, - 'length' => 250, - ] - ); - - $metadata->mapManyToOne( - [ - 'fieldName' => 'address', - 'targetEntity' => 'DDC964Address', - 'cascade' => ['persist','merge'], - 'joinColumn' => ['name'=>'address_id', 'referencedColumnMame'=>'id'], - ] - ); - - $metadata->mapManyToMany( - [ - 'fieldName' => 'groups', - 'targetEntity' => 'DDC964Group', - 'inversedBy' => 'users', - 'cascade' => ['persist','merge','detach'], - 'joinTable' => [ - 'name' => 'ddc964_users_groups', - 'joinColumns' => [ - [ - 'name'=>'user_id', - 'referencedColumnName'=>'id', - ] - ], - 'inverseJoinColumns'=> [ - [ - 'name'=>'group_id', - 'referencedColumnName'=>'id', - ] - ] - ] - ] - ); - - $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_AUTO); + $fieldMetadata = new Mapping\FieldMetadata('id'); + $fieldMetadata->setType(Type::getType('integer')); + $fieldMetadata->setColumnName('user_id'); + $fieldMetadata->setPrimaryKey(true); + + $metadata->addProperty($fieldMetadata); + + $fieldMetadata = new Mapping\FieldMetadata('name'); + $fieldMetadata->setType(Type::getType('string')); + $fieldMetadata->setLength(250); + $fieldMetadata->setColumnName('user_name'); + $fieldMetadata->setNullable(true); + $fieldMetadata->setUnique(false); + + $metadata->addProperty($fieldMetadata); + + $joinColumns = []; + + $joinColumn = new Mapping\JoinColumnMetadata(); + + $joinColumn->setColumnName('address_id'); + $joinColumn->setReferencedColumnName('id'); + + $joinColumns[] = $joinColumn; + + $association = new Mapping\ManyToOneAssociationMetadata('address'); + + $association->setJoinColumns($joinColumns); + $association->setTargetEntity('DDC964Address'); + $association->setCascade(['persist']); + + $metadata->addProperty($association); + + $joinTable = new Mapping\JoinTableMetadata(); + $joinTable->setName('ddc964_users_groups'); + + $joinColumn = new Mapping\JoinColumnMetadata(); + + $joinColumn->setColumnName('user_id'); + $joinColumn->setReferencedColumnName('id'); + + $joinTable->addJoinColumn($joinColumn); + + $joinColumn = new Mapping\JoinColumnMetadata(); + + $joinColumn->setColumnName('group_id'); + $joinColumn->setReferencedColumnName('id'); + + $joinTable->addInverseJoinColumn($joinColumn); + + $association = new Mapping\ManyToManyAssociationMetadata('groups'); + + $association->setJoinTable($joinTable); + $association->setTargetEntity('DDC964Group'); + $association->setInversedBy('users'); + $association->setCascade(['persist']); + + $metadata->addProperty($association); + + $metadata->setIdGeneratorType(Mapping\GeneratorType::AUTO); } } diff --git a/tests/Doctrine/Tests/Models/DirectoryTree/AbstractContentItem.php b/tests/Doctrine/Tests/Models/DirectoryTree/AbstractContentItem.php index 41798724b20..0925bb8e962 100644 --- a/tests/Doctrine/Tests/Models/DirectoryTree/AbstractContentItem.php +++ b/tests/Doctrine/Tests/Models/DirectoryTree/AbstractContentItem.php @@ -1,23 +1,27 @@ extension; diff --git a/tests/Doctrine/Tests/Models/ECommerce/ECommerceCart.php b/tests/Doctrine/Tests/Models/ECommerce/ECommerceCart.php index 3d9f6798f1c..1f04136e86c 100644 --- a/tests/Doctrine/Tests/Models/ECommerce/ECommerceCart.php +++ b/tests/Doctrine/Tests/Models/ECommerce/ECommerceCart.php @@ -1,42 +1,45 @@ value = $value; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Generic/SerializationModel.php b/tests/Doctrine/Tests/Models/Generic/SerializationModel.php index 4f07d427aad..b899f87b579 100644 --- a/tests/Doctrine/Tests/Models/Generic/SerializationModel.php +++ b/tests/Doctrine/Tests/Models/Generic/SerializationModel.php @@ -1,25 +1,29 @@ id = $id; diff --git a/tests/Doctrine/Tests/Models/GeoNames/City.php b/tests/Doctrine/Tests/Models/GeoNames/City.php index 411f4db9126..ef86a3c70e8 100644 --- a/tests/Doctrine/Tests/Models/GeoNames/City.php +++ b/tests/Doctrine/Tests/Models/GeoNames/City.php @@ -1,44 +1,47 @@ id = $id; diff --git a/tests/Doctrine/Tests/Models/GeoNames/Country.php b/tests/Doctrine/Tests/Models/GeoNames/Country.php index ebde305f805..77b3e691799 100644 --- a/tests/Doctrine/Tests/Models/GeoNames/Country.php +++ b/tests/Doctrine/Tests/Models/GeoNames/Country.php @@ -1,23 +1,27 @@ _user = $author; + public $user; + + public function setAuthor(LegacyUser $author) + { + $this->user = $author; } } diff --git a/tests/Doctrine/Tests/Models/Legacy/LegacyCar.php b/tests/Doctrine/Tests/Models/Legacy/LegacyCar.php index 4b955be914b..3def1c9b520 100644 --- a/tests/Doctrine/Tests/Models/Legacy/LegacyCar.php +++ b/tests/Doctrine/Tests/Models/Legacy/LegacyCar.php @@ -1,39 +1,44 @@ _description; + return $this->description; } public function addUser(LegacyUser $user) { - $this->_users[] = $user; + $this->users[] = $user; } public function getUsers() { - return $this->_users; + return $this->users; } } diff --git a/tests/Doctrine/Tests/Models/Legacy/LegacyUser.php b/tests/Doctrine/Tests/Models/Legacy/LegacyUser.php index 3e3deedb153..e7fb75756d9 100644 --- a/tests/Doctrine/Tests/Models/Legacy/LegacyUser.php +++ b/tests/Doctrine/Tests/Models/Legacy/LegacyUser.php @@ -1,80 +1,90 @@ _articles = new ArrayCollection; - $this->_references = new ArrayCollection; - $this->_cars = new ArrayCollection; + public $cars; + + public function __construct() + { + $this->articles = new ArrayCollection; + $this->references = new ArrayCollection; + $this->cars = new ArrayCollection; } public function getId() { - return $this->_id; + return $this->id; } public function getUsername() { - return $this->_username; + return $this->username; } public function addArticle(LegacyArticle $article) { - $this->_articles[] = $article; + $this->articles[] = $article; $article->setAuthor($this); } public function addReference($reference) { - $this->_references[] = $reference; + $this->references[] = $reference; } public function references() { - return $this->_references; + return $this->references; } public function addCar(LegacyCar $car) { - $this->_cars[] = $car; + $this->cars[] = $car; $car->addUser($this); } public function getCars() { - return $this->_cars; + return $this->cars; } } diff --git a/tests/Doctrine/Tests/Models/Legacy/LegacyUserReference.php b/tests/Doctrine/Tests/Models/Legacy/LegacyUserReference.php index 8dc20db2323..eb2c76bfe8d 100644 --- a/tests/Doctrine/Tests/Models/Legacy/LegacyUserReference.php +++ b/tests/Doctrine/Tests/Models/Legacy/LegacyUserReference.php @@ -1,65 +1,69 @@ addReference($this); $target->addReference($this); - $this->_source = $source; - $this->_target = $target; - $this->_description = $description; - $this->_created = new \DateTime("now"); + $this->source = $source; + $this->target = $target; + $this->description = $description; + $this->created = new \DateTime("now"); } public function source() { - return $this->_source; + return $this->source; } public function target() { - return $this->_target; + return $this->target; } public function setDescription($desc) { - $this->_description = $desc; + $this->description = $desc; } public function getDescription() { - return $this->_description; + return $this->description; } } diff --git a/tests/Doctrine/Tests/Models/MixedToOneIdentity/CompositeToOneKeyState.php b/tests/Doctrine/Tests/Models/MixedToOneIdentity/CompositeToOneKeyState.php index 09bab229ef6..01a7c981a13 100644 --- a/tests/Doctrine/Tests/Models/MixedToOneIdentity/CompositeToOneKeyState.php +++ b/tests/Doctrine/Tests/Models/MixedToOneIdentity/CompositeToOneKeyState.php @@ -1,21 +1,25 @@ name = $name; } @@ -36,4 +40,4 @@ public function getId() { public function getName() { return $this->name; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Navigation/NavPhotos.php b/tests/Doctrine/Tests/Models/Navigation/NavPhotos.php index 25858d0b3eb..67fee573b5f 100644 --- a/tests/Doctrine/Tests/Models/Navigation/NavPhotos.php +++ b/tests/Doctrine/Tests/Models/Navigation/NavPhotos.php @@ -1,35 +1,39 @@ poi = $poi; $this->file = $file; } @@ -45,4 +49,4 @@ public function getPointOfInterest() { public function getFile() { return $this->file; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Navigation/NavPointOfInterest.php b/tests/Doctrine/Tests/Models/Navigation/NavPointOfInterest.php index 33d0f70bdb2..186f0425bf3 100644 --- a/tests/Doctrine/Tests/Models/Navigation/NavPointOfInterest.php +++ b/tests/Doctrine/Tests/Models/Navigation/NavPointOfInterest.php @@ -1,42 +1,46 @@ id; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Navigation/NavUser.php b/tests/Doctrine/Tests/Models/Navigation/NavUser.php index 42117e46b89..8f50158b07d 100644 --- a/tests/Doctrine/Tests/Models/Navigation/NavUser.php +++ b/tests/Doctrine/Tests/Models/Navigation/NavUser.php @@ -1,22 +1,26 @@ user !== $user) { $this->user = $user; @@ -38,7 +40,6 @@ public function setUser(User $user) { } } - public function getId() { return $this->id; @@ -53,5 +54,4 @@ public function getUser() { return $this->user; } - } diff --git a/tests/Doctrine/Tests/Models/Quote/City.php b/tests/Doctrine/Tests/Models/Quote/City.php index 74503ea0858..a91d06af2fd 100644 --- a/tests/Doctrine/Tests/Models/Quote/City.php +++ b/tests/Doctrine/Tests/Models/Quote/City.php @@ -1,22 +1,26 @@ value = $value; } - -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Quote/Phone.php b/tests/Doctrine/Tests/Models/Quote/Phone.php index 3d4475372c1..c2a05fbbc1b 100644 --- a/tests/Doctrine/Tests/Models/Quote/Phone.php +++ b/tests/Doctrine/Tests/Models/Quote/Phone.php @@ -1,24 +1,26 @@ name; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Routing/RoutingRoute.php b/tests/Doctrine/Tests/Models/Routing/RoutingRoute.php index 7354e56ca25..f507869e9df 100644 --- a/tests/Doctrine/Tests/Models/Routing/RoutingRoute.php +++ b/tests/Doctrine/Tests/Models/Routing/RoutingRoute.php @@ -1,34 +1,37 @@ passengerName; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/StockExchange/Bond.php b/tests/Doctrine/Tests/Models/StockExchange/Bond.php index a0d37bfe858..e57d3375aaf 100644 --- a/tests/Doctrine/Tests/Models/StockExchange/Bond.php +++ b/tests/Doctrine/Tests/Models/StockExchange/Bond.php @@ -1,31 +1,35 @@ stocks[$stock->getSymbol()] = $stock; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/StockExchange/Market.php b/tests/Doctrine/Tests/Models/StockExchange/Market.php index 87e12cab654..a1d27218a8c 100644 --- a/tests/Doctrine/Tests/Models/StockExchange/Market.php +++ b/tests/Doctrine/Tests/Models/StockExchange/Market.php @@ -1,29 +1,32 @@ stocks[$symbol]; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/StockExchange/Stock.php b/tests/Doctrine/Tests/Models/StockExchange/Stock.php index 00e14e12ea8..73d71ac5e4d 100644 --- a/tests/Doctrine/Tests/Models/StockExchange/Stock.php +++ b/tests/Doctrine/Tests/Models/StockExchange/Stock.php @@ -1,15 +1,19 @@ symbol; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Taxi/Car.php b/tests/Doctrine/Tests/Models/Taxi/Car.php index 03cc74c96b8..1bda2a020b9 100644 --- a/tests/Doctrine/Tests/Models/Taxi/Car.php +++ b/tests/Doctrine/Tests/Models/Taxi/Car.php @@ -1,32 +1,36 @@ target = new AssociationIdentifierTarget(); + } + + public function getTarget() : AssociationIdentifierTarget + { + return $this->target; + } + + public function getId() : ?string + { + return $this->id; + } + + public function getRegular() : ?string + { + return $this->regular; + } +} diff --git a/tests/Doctrine/Tests/Models/ValueGenerators/AssociationIdentifierTarget.php b/tests/Doctrine/Tests/Models/ValueGenerators/AssociationIdentifierTarget.php new file mode 100644 index 00000000000..c85083c73b0 --- /dev/null +++ b/tests/Doctrine/Tests/Models/ValueGenerators/AssociationIdentifierTarget.php @@ -0,0 +1,28 @@ +id; + } +} diff --git a/tests/Doctrine/Tests/Models/ValueGenerators/BarGenerator.php b/tests/Doctrine/Tests/Models/ValueGenerators/BarGenerator.php new file mode 100644 index 00000000000..098472bc5d3 --- /dev/null +++ b/tests/Doctrine/Tests/Models/ValueGenerators/BarGenerator.php @@ -0,0 +1,23 @@ +a; + } + + public function getB() : ?string + { + return $this->b; + } +} diff --git a/tests/Doctrine/Tests/Models/ValueGenerators/DummyWithThreeProperties.php b/tests/Doctrine/Tests/Models/ValueGenerators/DummyWithThreeProperties.php new file mode 100644 index 00000000000..151f753a176 --- /dev/null +++ b/tests/Doctrine/Tests/Models/ValueGenerators/DummyWithThreeProperties.php @@ -0,0 +1,19 @@ +a; + } +} diff --git a/tests/Doctrine/Tests/Models/ValueGenerators/InheritanceGeneratorsChildB.php b/tests/Doctrine/Tests/Models/ValueGenerators/InheritanceGeneratorsChildB.php new file mode 100644 index 00000000000..8ad1d3a3815 --- /dev/null +++ b/tests/Doctrine/Tests/Models/ValueGenerators/InheritanceGeneratorsChildB.php @@ -0,0 +1,26 @@ +b; + } +} diff --git a/tests/Doctrine/Tests/Models/ValueGenerators/InheritanceGeneratorsRoot.php b/tests/Doctrine/Tests/Models/ValueGenerators/InheritanceGeneratorsRoot.php new file mode 100644 index 00000000000..9358cbc229b --- /dev/null +++ b/tests/Doctrine/Tests/Models/ValueGenerators/InheritanceGeneratorsRoot.php @@ -0,0 +1,34 @@ +id; + } +} diff --git a/tests/Doctrine/Tests/Models/ValueGenerators/NonIdentifierGenerators.php b/tests/Doctrine/Tests/Models/ValueGenerators/NonIdentifierGenerators.php new file mode 100644 index 00000000000..17fb0a80532 --- /dev/null +++ b/tests/Doctrine/Tests/Models/ValueGenerators/NonIdentifierGenerators.php @@ -0,0 +1,53 @@ +id; + } + + public function getFoo() : ?string + { + return $this->foo; + } + + public function getBar() : ?string + { + return $this->bar; + } +} diff --git a/tests/Doctrine/Tests/Models/ValueObjects/Name.php b/tests/Doctrine/Tests/Models/ValueObjects/Name.php index 1c836032417..9698e78e7c4 100644 --- a/tests/Doctrine/Tests/Models/ValueObjects/Name.php +++ b/tests/Doctrine/Tests/Models/ValueObjects/Name.php @@ -1,5 +1,7 @@ * - * @Entity - * @Table(name="first_entity") + * @ORM\Entity + * @ORM\Table(name="first_entity") */ class FirstRelatedEntity { /** - * @Id - * @OneToOne(targetEntity="SecondRelatedEntity", fetch="EAGER") - * @JoinColumn(name="second_entity_id", referencedColumnName="id") + * @ORM\Id + * @ORM\OneToOne(targetEntity="SecondRelatedEntity", fetch="EAGER") + * @ORM\JoinColumn(name="second_entity_id", referencedColumnName="id") */ public $secondEntity; /** - * @Column(name="name") + * @ORM\Column(name="name") */ public $name; /** * Version column * - * @Column(type="integer", name="version") - * @Version + * @ORM\Column(type="integer", name="version") + * @ORM\Version */ public $version; } diff --git a/tests/Doctrine/Tests/Models/VersionedOneToOne/SecondRelatedEntity.php b/tests/Doctrine/Tests/Models/VersionedOneToOne/SecondRelatedEntity.php index cb5dcf66c67..57e65772f50 100644 --- a/tests/Doctrine/Tests/Models/VersionedOneToOne/SecondRelatedEntity.php +++ b/tests/Doctrine/Tests/Models/VersionedOneToOne/SecondRelatedEntity.php @@ -1,32 +1,36 @@ * - * @Entity - * @Table(name="second_entity") + * @ORM\Entity + * @ORM\Table(name="second_entity") */ class SecondRelatedEntity { /** - * @Id - * @Column(name="id", type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @Column(name="name") + * @ORM\Column(name="name") */ public $name; /** * Version column * - * @Column(type="integer", name="version") - * @Version + * @ORM\Column(type="integer", name="version") + * @ORM\Version */ public $version; } diff --git a/tests/Doctrine/Tests/ORM/Cache/AbstractRegionTest.php b/tests/Doctrine/Tests/ORM/Cache/AbstractRegionTest.php index 665978f01d3..f2a8e51cfba 100644 --- a/tests/Doctrine/Tests/ORM/Cache/AbstractRegionTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/AbstractRegionTest.php @@ -1,5 +1,7 @@ assertFalse($this->region->contains($key)); + self::assertFalse($this->region->contains($key)); $this->region->put($key, $value); - $this->assertTrue($this->region->contains($key)); + self::assertTrue($this->region->contains($key)); $actual = $this->region->get($key); - $this->assertEquals($value, $actual); + self::assertEquals($value, $actual); $this->region->evict($key); - $this->assertFalse($this->region->contains($key)); + self::assertFalse($this->region->contains($key)); } public function testEvictAll() @@ -68,18 +70,18 @@ public function testEvictAll() $key1 = new CacheKeyMock('key.1'); $key2 = new CacheKeyMock('key.2'); - $this->assertFalse($this->region->contains($key1)); - $this->assertFalse($this->region->contains($key2)); + self::assertFalse($this->region->contains($key1)); + self::assertFalse($this->region->contains($key2)); $this->region->put($key1, new CacheEntryMock(['value' => 'foo'])); $this->region->put($key2, new CacheEntryMock(['value' => 'bar'])); - $this->assertTrue($this->region->contains($key1)); - $this->assertTrue($this->region->contains($key2)); + self::assertTrue($this->region->contains($key1)); + self::assertTrue($this->region->contains($key2)); $this->region->evictAll(); - $this->assertFalse($this->region->contains($key1)); - $this->assertFalse($this->region->contains($key2)); + self::assertFalse($this->region->contains($key1)); + self::assertFalse($this->region->contains($key2)); } } diff --git a/tests/Doctrine/Tests/ORM/Cache/CacheConfigTest.php b/tests/Doctrine/Tests/ORM/Cache/CacheConfigTest.php index 4c016df1fc7..079e6008a42 100644 --- a/tests/Doctrine/Tests/ORM/Cache/CacheConfigTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/CacheConfigTest.php @@ -1,5 +1,7 @@ setDefaultLifetime(111); - $this->assertEquals($config->getDefaultLifetime(), $config->getLifetime('foo_region')); + self::assertEquals($config->getDefaultLifetime(), $config->getLifetime('foo_region')); $config->setLifetime('foo_region', 222); - $this->assertEquals(222, $config->getLifetime('foo_region')); + self::assertEquals(222, $config->getLifetime('foo_region')); } public function testSetGetCacheLogger() { $logger = $this->createMock(CacheLogger::class); - $this->assertNull($this->config->getCacheLogger()); + self::assertNull($this->config->getCacheLogger()); $this->config->setCacheLogger($logger); - $this->assertEquals($logger, $this->config->getCacheLogger()); + self::assertEquals($logger, $this->config->getCacheLogger()); } public function testSetGetCacheFactory() { $factory = $this->createMock(CacheFactory::class); - $this->assertNull($this->config->getCacheFactory()); + self::assertNull($this->config->getCacheFactory()); $this->config->setCacheFactory($factory); - $this->assertEquals($factory, $this->config->getCacheFactory()); + self::assertEquals($factory, $this->config->getCacheFactory()); } public function testSetGetQueryValidator() @@ -76,10 +78,10 @@ public function testSetGetQueryValidator() $validator = $this->createMock(QueryCacheValidator::class); - $this->assertInstanceOf(TimestampQueryCacheValidator::class, $this->config->getQueryValidator()); + self::assertInstanceOf(TimestampQueryCacheValidator::class, $this->config->getQueryValidator()); $this->config->setQueryValidator($validator); - $this->assertEquals($validator, $this->config->getQueryValidator()); + self::assertEquals($validator, $this->config->getQueryValidator()); } } diff --git a/tests/Doctrine/Tests/ORM/Cache/CacheKeyTest.php b/tests/Doctrine/Tests/ORM/Cache/CacheKeyTest.php index 63c86d7f1af..c42b1cfb3aa 100644 --- a/tests/Doctrine/Tests/ORM/Cache/CacheKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/CacheKeyTest.php @@ -1,5 +1,7 @@ 1]); $key2 = new EntityCacheKey('Bar', ['id'=>1]); - $this->assertNotEquals($key1->hash, $key2->hash); + self::assertNotEquals($key1->hash, $key2->hash); } public function testEntityCacheKeyIdentifierType() @@ -24,7 +26,7 @@ public function testEntityCacheKeyIdentifierType() $key1 = new EntityCacheKey('Foo', ['id'=>1]); $key2 = new EntityCacheKey('Foo', ['id'=>'1']); - $this->assertEquals($key1->hash, $key2->hash); + self::assertEquals($key1->hash, $key2->hash); } public function testEntityCacheKeyIdentifierOrder() @@ -32,7 +34,7 @@ public function testEntityCacheKeyIdentifierOrder() $key1 = new EntityCacheKey('Foo', ['foo_bar'=>1, 'bar_foo'=> 2]); $key2 = new EntityCacheKey('Foo', ['bar_foo'=>2, 'foo_bar'=> 1]); - $this->assertEquals($key1->hash, $key2->hash); + self::assertEquals($key1->hash, $key2->hash); } public function testCollectionCacheKeyIdentifierType() @@ -40,7 +42,7 @@ public function testCollectionCacheKeyIdentifierType() $key1 = new CollectionCacheKey('Foo', 'assoc', ['id'=>1]); $key2 = new CollectionCacheKey('Foo', 'assoc', ['id'=>'1']); - $this->assertEquals($key1->hash, $key2->hash); + self::assertEquals($key1->hash, $key2->hash); } public function testCollectionCacheKeyIdentifierOrder() @@ -48,7 +50,7 @@ public function testCollectionCacheKeyIdentifierOrder() $key1 = new CollectionCacheKey('Foo', 'assoc', ['foo_bar'=>1, 'bar_foo'=> 2]); $key2 = new CollectionCacheKey('Foo', 'assoc', ['bar_foo'=>2, 'foo_bar'=> 1]); - $this->assertEquals($key1->hash, $key2->hash); + self::assertEquals($key1->hash, $key2->hash); } public function testCollectionCacheKeyIdentifierCollision() @@ -56,7 +58,7 @@ public function testCollectionCacheKeyIdentifierCollision() $key1 = new CollectionCacheKey('Foo', 'assoc', ['id'=>1]); $key2 = new CollectionCacheKey('Bar', 'assoc', ['id'=>1]); - $this->assertNotEquals($key1->hash, $key2->hash); + self::assertNotEquals($key1->hash, $key2->hash); } public function testCollectionCacheKeyAssociationCollision() @@ -64,6 +66,6 @@ public function testCollectionCacheKeyAssociationCollision() $key1 = new CollectionCacheKey('Foo', 'assoc1', ['id'=>1]); $key2 = new CollectionCacheKey('Foo', 'assoc2', ['id'=>1]); - $this->assertNotEquals($key1->hash, $key2->hash); + self::assertNotEquals($key1->hash, $key2->hash); } } diff --git a/tests/Doctrine/Tests/ORM/Cache/CacheLoggerChainTest.php b/tests/Doctrine/Tests/ORM/Cache/CacheLoggerChainTest.php index a070237a200..559978997d9 100644 --- a/tests/Doctrine/Tests/ORM/Cache/CacheLoggerChainTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/CacheLoggerChainTest.php @@ -1,5 +1,7 @@ assertEmpty($this->logger->getLoggers()); + self::assertEmpty($this->logger->getLoggers()); - $this->assertNull($this->logger->getLogger('mock')); + self::assertNull($this->logger->getLogger('mock')); $this->logger->setLogger('mock', $this->mock); - $this->assertSame($this->mock, $this->logger->getLogger('mock')); - $this->assertEquals(['mock' => $this->mock], $this->logger->getLoggers()); + self::assertSame($this->mock, $this->logger->getLogger('mock')); + self::assertEquals(['mock' => $this->mock], $this->logger->getLoggers()); } public function testEntityCacheChain() diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultCacheFactoryTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultCacheFactoryTest.php index 1ca213b20e0..63c0cd4419d 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultCacheFactoryTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultCacheFactoryTest.php @@ -1,5 +1,7 @@ enableSecondLevelCache(); + parent::setUp(); - $this->em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); $this->regionsConfig = new RegionsConfiguration; - $arguments = [$this->regionsConfig, $this->getSharedSecondLevelCacheDriverImpl()]; - $this->factory = $this->getMockBuilder(DefaultCacheFactory::class) - ->setMethods(['getRegion']) - ->setConstructorArgs($arguments) - ->getMock(); + + $arguments = [ + $this->regionsConfig, + $this->getSharedSecondLevelCacheDriverImpl() + ]; + + $this->factory = $this->getMockBuilder(DefaultCacheFactory::class) + ->setMethods(['getRegion']) + ->setConstructorArgs($arguments) + ->getMock() + ; } public function testImplementsCacheFactory() { - $this->assertInstanceOf(CacheFactory::class, $this->factory); + self::assertInstanceOf(CacheFactory::class, $this->factory); } public function testBuildCachedEntityPersisterReadOnly() { - $em = $this->em; - $metadata = clone $em->getClassMetadata(State::class); - $persister = new BasicEntityPersister($em, $metadata); - $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); + $em = $this->em; + $metadata = clone $em->getClassMetadata(State::class); + $persister = new BasicEntityPersister($em, $metadata); + $region = new ConcurrentRegionMock( + new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl()) + ); - $metadata->cache['usage'] = ClassMetadata::CACHE_USAGE_READ_ONLY; + $metadata->setCache( + new CacheMetadata(CacheUsage::READ_ONLY, 'doctrine_tests_models_cache_state') + ); $this->factory->expects($this->once()) ->method('getRegion') - ->with($this->equalTo($metadata->cache)) + ->with($this->equalTo($metadata->getCache())) ->will($this->returnValue($region)); $cachedPersister = $this->factory->buildCachedEntityPersister($em, $persister, $metadata); - $this->assertInstanceOf(CachedEntityPersister::class, $cachedPersister); - $this->assertInstanceOf(ReadOnlyCachedEntityPersister::class, $cachedPersister); + self::assertInstanceOf(CachedEntityPersister::class, $cachedPersister); + self::assertInstanceOf(ReadOnlyCachedEntityPersister::class, $cachedPersister); } public function testBuildCachedEntityPersisterReadWrite() @@ -91,103 +105,123 @@ public function testBuildCachedEntityPersisterReadWrite() $em = $this->em; $metadata = clone $em->getClassMetadata(State::class); $persister = new BasicEntityPersister($em, $metadata); - $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); + $region = new ConcurrentRegionMock( + new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl()) + ); - $metadata->cache['usage'] = ClassMetadata::CACHE_USAGE_READ_WRITE; + $metadata->setCache( + new CacheMetadata(CacheUsage::READ_WRITE, 'doctrine_tests_models_cache_state') + ); $this->factory->expects($this->once()) ->method('getRegion') - ->with($this->equalTo($metadata->cache)) + ->with($this->equalTo($metadata->getCache())) ->will($this->returnValue($region)); $cachedPersister = $this->factory->buildCachedEntityPersister($em, $persister, $metadata); - $this->assertInstanceOf(CachedEntityPersister::class, $cachedPersister); - $this->assertInstanceOf(ReadWriteCachedEntityPersister::class, $cachedPersister); + self::assertInstanceOf(CachedEntityPersister::class, $cachedPersister); + self::assertInstanceOf(ReadWriteCachedEntityPersister::class, $cachedPersister); } public function testBuildCachedEntityPersisterNonStrictReadWrite() { - $em = $this->em; - $metadata = clone $em->getClassMetadata(State::class); - $persister = new BasicEntityPersister($em, $metadata); - $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); + $em = $this->em; + $metadata = clone $em->getClassMetadata(State::class); + $persister = new BasicEntityPersister($em, $metadata); + $region = new ConcurrentRegionMock( + new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl()) + ); - $metadata->cache['usage'] = ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE; + $metadata->setCache( + new CacheMetadata(CacheUsage::NONSTRICT_READ_WRITE, 'doctrine_tests_models_cache_state') + ); $this->factory->expects($this->once()) ->method('getRegion') - ->with($this->equalTo($metadata->cache)) + ->with($this->equalTo($metadata->getCache())) ->will($this->returnValue($region)); $cachedPersister = $this->factory->buildCachedEntityPersister($em, $persister, $metadata); - $this->assertInstanceOf(CachedEntityPersister::class, $cachedPersister); - $this->assertInstanceOf(NonStrictReadWriteCachedEntityPersister::class, $cachedPersister); + self::assertInstanceOf(CachedEntityPersister::class, $cachedPersister); + self::assertInstanceOf(NonStrictReadWriteCachedEntityPersister::class, $cachedPersister); } public function testBuildCachedCollectionPersisterReadOnly() { - $em = $this->em; - $metadata = $em->getClassMetadata(State::class); - $mapping = $metadata->associationMappings['cities']; - $persister = new OneToManyPersister($em); - $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); + $em = $this->em; + $metadata = clone $em->getClassMetadata(State::class); + $association = $metadata->getProperty('cities'); + $persister = new OneToManyPersister($em); + $region = new ConcurrentRegionMock( + new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl()) + ); - $mapping['cache']['usage'] = ClassMetadata::CACHE_USAGE_READ_ONLY; + $association->setCache( + new CacheMetadata(CacheUsage::READ_ONLY, 'doctrine_tests_models_cache_state__cities') + ); $this->factory->expects($this->once()) ->method('getRegion') - ->with($this->equalTo($mapping['cache'])) + ->with($this->equalTo($association->getCache())) ->will($this->returnValue($region)); - $cachedPersister = $this->factory->buildCachedCollectionPersister($em, $persister, $mapping); + $cachedPersister = $this->factory->buildCachedCollectionPersister($em, $persister, $association); - $this->assertInstanceOf(CachedCollectionPersister::class, $cachedPersister); - $this->assertInstanceOf(ReadOnlyCachedCollectionPersister::class, $cachedPersister); + self::assertInstanceOf(CachedCollectionPersister::class, $cachedPersister); + self::assertInstanceOf(ReadOnlyCachedCollectionPersister::class, $cachedPersister); } public function testBuildCachedCollectionPersisterReadWrite() { - $em = $this->em; - $metadata = $em->getClassMetadata(State::class); - $mapping = $metadata->associationMappings['cities']; - $persister = new OneToManyPersister($em); - $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); + $em = $this->em; + $metadata = clone $em->getClassMetadata(State::class); + $association = $metadata->getProperty('cities'); + $persister = new OneToManyPersister($em); + $region = new ConcurrentRegionMock( + new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl()) + ); - $mapping['cache']['usage'] = ClassMetadata::CACHE_USAGE_READ_WRITE; + $association->setCache( + new CacheMetadata(CacheUsage::READ_WRITE, 'doctrine_tests_models_cache_state__cities') + ); $this->factory->expects($this->once()) ->method('getRegion') - ->with($this->equalTo($mapping['cache'])) + ->with($this->equalTo($association->getCache())) ->will($this->returnValue($region)); - $cachedPersister = $this->factory->buildCachedCollectionPersister($em, $persister, $mapping); + $cachedPersister = $this->factory->buildCachedCollectionPersister($em, $persister, $association); - $this->assertInstanceOf(CachedCollectionPersister::class, $cachedPersister); - $this->assertInstanceOf(ReadWriteCachedCollectionPersister::class, $cachedPersister); + self::assertInstanceOf(CachedCollectionPersister::class, $cachedPersister); + self::assertInstanceOf(ReadWriteCachedCollectionPersister::class, $cachedPersister); } public function testBuildCachedCollectionPersisterNonStrictReadWrite() { - $em = $this->em; - $metadata = $em->getClassMetadata(State::class); - $mapping = $metadata->associationMappings['cities']; - $persister = new OneToManyPersister($em); - $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); + $em = $this->em; + $metadata = clone $em->getClassMetadata(State::class); + $association = $metadata->getProperty('cities'); + $persister = new OneToManyPersister($em); + $region = new ConcurrentRegionMock( + new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl()) + ); - $mapping['cache']['usage'] = ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE; + $association->setCache( + new CacheMetadata(CacheUsage::NONSTRICT_READ_WRITE, 'doctrine_tests_models_cache_state__cities') + ); $this->factory->expects($this->once()) ->method('getRegion') - ->with($this->equalTo($mapping['cache'])) + ->with($this->equalTo($association->getCache())) ->will($this->returnValue($region)); - $cachedPersister = $this->factory->buildCachedCollectionPersister($em, $persister, $mapping); + $cachedPersister = $this->factory->buildCachedCollectionPersister($em, $persister, $association); - $this->assertInstanceOf(CachedCollectionPersister::class, $cachedPersister); - $this->assertInstanceOf(NonStrictReadWriteCachedCollectionPersister::class, $cachedPersister); + self::assertInstanceOf(CachedCollectionPersister::class, $cachedPersister); + self::assertInstanceOf(NonStrictReadWriteCachedCollectionPersister::class, $cachedPersister); } public function testInheritedEntityCacheRegion() @@ -202,11 +236,11 @@ public function testInheritedEntityCacheRegion() $cachedPersister1 = $factory->buildCachedEntityPersister($em, $persister1, $metadata1); $cachedPersister2 = $factory->buildCachedEntityPersister($em, $persister2, $metadata2); - $this->assertInstanceOf(CachedEntityPersister::class, $cachedPersister1); - $this->assertInstanceOf(CachedEntityPersister::class, $cachedPersister2); + self::assertInstanceOf(CachedEntityPersister::class, $cachedPersister1); + self::assertInstanceOf(CachedEntityPersister::class, $cachedPersister2); - $this->assertNotSame($cachedPersister1, $cachedPersister2); - $this->assertSame($cachedPersister1->getCacheRegion(), $cachedPersister2->getCacheRegion()); + self::assertNotSame($cachedPersister1, $cachedPersister2); + self::assertSame($cachedPersister1->getCacheRegion(), $cachedPersister2->getCacheRegion()); } public function testCreateNewCacheDriver() @@ -221,79 +255,73 @@ public function testCreateNewCacheDriver() $cachedPersister1 = $factory->buildCachedEntityPersister($em, $persister1, $metadata1); $cachedPersister2 = $factory->buildCachedEntityPersister($em, $persister2, $metadata2); - $this->assertInstanceOf(CachedEntityPersister::class, $cachedPersister1); - $this->assertInstanceOf(CachedEntityPersister::class, $cachedPersister2); + self::assertInstanceOf(CachedEntityPersister::class, $cachedPersister1); + self::assertInstanceOf(CachedEntityPersister::class, $cachedPersister2); - $this->assertNotSame($cachedPersister1, $cachedPersister2); - $this->assertNotSame($cachedPersister1->getCacheRegion(), $cachedPersister2->getCacheRegion()); + self::assertNotSame($cachedPersister1, $cachedPersister2); + self::assertNotSame($cachedPersister1->getCacheRegion(), $cachedPersister2->getCacheRegion()); } /** - * @expectedException InvalidArgumentException + * @expectedException \InvalidArgumentException * @expectedExceptionMessage Unrecognized access strategy type [-1] */ public function testBuildCachedEntityPersisterNonStrictException() { - $em = $this->em; - $metadata = clone $em->getClassMetadata(State::class); - $persister = new BasicEntityPersister($em, $metadata); + $em = $this->em; + $metadata = clone $em->getClassMetadata(State::class); + $persister = new BasicEntityPersister($em, $metadata); - $metadata->cache['usage'] = -1; + $metadata->setCache( + new CacheMetadata('-1', 'doctrine_tests_models_cache_state') + ); $this->factory->buildCachedEntityPersister($em, $persister, $metadata); } /** - * @expectedException InvalidArgumentException + * @expectedException \InvalidArgumentException * @expectedExceptionMessage Unrecognized access strategy type [-1] */ public function testBuildCachedCollectionPersisterException() { - $em = $this->em; - $metadata = $em->getClassMetadata(State::class); - $mapping = $metadata->associationMappings['cities']; - $persister = new OneToManyPersister($em); + $em = $this->em; + $metadata = clone $em->getClassMetadata(State::class); + $association = $metadata->getProperty('cities'); + $persister = new OneToManyPersister($em); - $mapping['cache']['usage'] = -1; + $association->setCache( + new CacheMetadata('-1', 'doctrine_tests_models_cache_state__cities') + ); - $this->factory->buildCachedCollectionPersister($em, $persister, $mapping); + $this->factory->buildCachedCollectionPersister($em, $persister, $association); } /** - * @expectedException LogicException + * @expectedException \LogicException * @expectedExceptionMessage If you want to use a "READ_WRITE" cache an implementation of "Doctrine\ORM\Cache\ConcurrentRegion" is required, The default implementation provided by doctrine is "Doctrine\ORM\Cache\Region\FileLockRegion" if you want to use it please provide a valid directory */ public function testInvalidFileLockRegionDirectoryException() { $factory = new DefaultCacheFactory($this->regionsConfig, $this->getSharedSecondLevelCacheDriverImpl()); - $factory->getRegion( - [ - 'usage' => ClassMetadata::CACHE_USAGE_READ_WRITE, - 'region' => 'foo' - ] - ); + $fooCache = new CacheMetadata(CacheUsage::READ_WRITE, 'foo'); + + $factory->getRegion($fooCache); } public function testBuildsNewNamespacedCacheInstancePerRegionInstance() { $factory = new DefaultCacheFactory($this->regionsConfig, $this->getSharedSecondLevelCacheDriverImpl()); - $fooRegion = $factory->getRegion( - [ - 'region' => 'foo', - 'usage' => ClassMetadata::CACHE_USAGE_READ_ONLY, - ] - ); - $barRegion = $factory->getRegion( - [ - 'region' => 'bar', - 'usage' => ClassMetadata::CACHE_USAGE_READ_ONLY, - ] - ); + $fooCache = new CacheMetadata(CacheUsage::READ_ONLY, 'foo'); + $fooRegion = $factory->getRegion($fooCache); + + $barCache = new CacheMetadata(CacheUsage::READ_ONLY, 'bar'); + $barRegion = $factory->getRegion($barCache); - $this->assertSame('foo', $fooRegion->getCache()->getNamespace()); - $this->assertSame('bar', $barRegion->getCache()->getNamespace()); + self::assertSame('foo', $fooRegion->getCache()->getNamespace()); + self::assertSame('bar', $barRegion->getCache()->getNamespace()); } public function testAppendsNamespacedCacheInstancePerRegionInstanceWhenItsAlreadySet() @@ -303,57 +331,38 @@ public function testAppendsNamespacedCacheInstancePerRegionInstanceWhenItsAlread $factory = new DefaultCacheFactory($this->regionsConfig, $cache); - $fooRegion = $factory->getRegion( - [ - 'region' => 'foo', - 'usage' => ClassMetadata::CACHE_USAGE_READ_ONLY, - ] - ); - $barRegion = $factory->getRegion( - [ - 'region' => 'bar', - 'usage' => ClassMetadata::CACHE_USAGE_READ_ONLY, - ] - ); + $fooCache = new CacheMetadata(CacheUsage::READ_ONLY, 'foo'); + $fooRegion = $factory->getRegion($fooCache); + + $barCache = new CacheMetadata(CacheUsage::READ_ONLY, 'bar'); + $barRegion = $factory->getRegion($barCache); - $this->assertSame('testing:foo', $fooRegion->getCache()->getNamespace()); - $this->assertSame('testing:bar', $barRegion->getCache()->getNamespace()); + self::assertSame('testing:foo', $fooRegion->getCache()->getNamespace()); + self::assertSame('testing:bar', $barRegion->getCache()->getNamespace()); } public function testBuildsDefaultCacheRegionFromGenericCacheRegion() { /* @var $cache \Doctrine\Common\Cache\Cache */ - $cache = $this->createMock(Cache::class); - + $cache = $this->createMock(Cache::class); $factory = new DefaultCacheFactory($this->regionsConfig, $cache); - $this->assertInstanceOf( - DefaultRegion::class, - $factory->getRegion( - [ - 'region' => 'bar', - 'usage' => ClassMetadata::CACHE_USAGE_READ_ONLY, - ] - ) - ); + $barCache = new CacheMetadata(CacheUsage::READ_ONLY, 'bar'); + $barRegion = $factory->getRegion($barCache); + + self::assertInstanceOf(DefaultRegion::class, $barRegion); } public function testBuildsMultiGetCacheRegionFromGenericCacheRegion() { /* @var $cache \Doctrine\Common\Cache\CacheProvider */ - $cache = $this->getMockForAbstractClass(CacheProvider::class); - + $cache = $this->getMockForAbstractClass(CacheProvider::class); $factory = new DefaultCacheFactory($this->regionsConfig, $cache); - $this->assertInstanceOf( - DefaultMultiGetRegion::class, - $factory->getRegion( - [ - 'region' => 'bar', - 'usage' => ClassMetadata::CACHE_USAGE_READ_ONLY, - ] - ) - ); + $barCache = new CacheMetadata(CacheUsage::READ_ONLY, 'bar'); + $barRegion = $factory->getRegion($barCache); + + self::assertInstanceOf(DefaultMultiGetRegion::class, $barRegion); } } diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultCacheTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultCacheTest.php index cbc9d8e8b73..6175288f728 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultCacheTest.php @@ -1,5 +1,7 @@ enableSecondLevelCache(); + parent::setUp(); - $this->em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); $this->cache = new DefaultCache($this->em); } @@ -45,9 +48,9 @@ protected function setUp() private function putEntityCacheEntry($className, array $identifier, array $data) { $metadata = $this->em->getClassMetadata($className); - $cacheKey = new EntityCacheKey($metadata->name, $identifier); - $cacheEntry = new EntityCacheEntry($metadata->name, $data); - $persister = $this->em->getUnitOfWork()->getEntityPersister($metadata->rootEntityName); + $cacheKey = new EntityCacheKey($metadata->getClassName(), $identifier); + $cacheEntry = new EntityCacheEntry($metadata->getClassName(), $data); + $persister = $this->em->getUnitOfWork()->getEntityPersister($metadata->getRootClassName()); $persister->getCacheRegion()->put($cacheKey, $cacheEntry); } @@ -61,188 +64,180 @@ private function putEntityCacheEntry($className, array $identifier, array $data) private function putCollectionCacheEntry($className, $association, array $ownerIdentifier, array $data) { $metadata = $this->em->getClassMetadata($className); - $cacheKey = new CollectionCacheKey($metadata->name, $association, $ownerIdentifier); + $cacheKey = new CollectionCacheKey($metadata->getClassName(), $association, $ownerIdentifier); $cacheEntry = new CollectionCacheEntry($data); - $persister = $this->em->getUnitOfWork()->getCollectionPersister($metadata->getAssociationMapping($association)); + $persister = $this->em->getUnitOfWork()->getCollectionPersister($metadata->getProperty($association)); $persister->getCacheRegion()->put($cacheKey, $cacheEntry); } public function testImplementsCache() { - $this->assertInstanceOf(Cache::class, $this->cache); + self::assertInstanceOf(Cache::class, $this->cache); } public function testGetEntityCacheRegionAccess() { - $this->assertInstanceOf(Cache\Region::class, $this->cache->getEntityCacheRegion(State::class)); - $this->assertNull($this->cache->getEntityCacheRegion(CmsUser::class)); + self::assertInstanceOf(Cache\Region::class, $this->cache->getEntityCacheRegion(State::class)); + self::assertNull($this->cache->getEntityCacheRegion(CmsUser::class)); } public function testGetCollectionCacheRegionAccess() { - $this->assertInstanceOf(Cache\Region::class, $this->cache->getCollectionCacheRegion(State::class, 'cities')); - $this->assertNull($this->cache->getCollectionCacheRegion(CmsUser::class, 'phonenumbers')); + self::assertInstanceOf(Cache\Region::class, $this->cache->getCollectionCacheRegion(State::class, 'cities')); + self::assertNull($this->cache->getCollectionCacheRegion(CmsUser::class, 'phonenumbers')); } public function testContainsEntity() { - $identifier = ['id'=>1]; - $className = Country::class; + $identifier = ['id' => 1]; $cacheEntry = array_merge($identifier, ['name' => 'Brazil']); - $this->assertFalse($this->cache->containsEntity(Country::class, 1)); + self::assertFalse($this->cache->containsEntity(Country::class, 1)); - $this->putEntityCacheEntry($className, $identifier, $cacheEntry); + $this->putEntityCacheEntry(Country::class, $identifier, $cacheEntry); - $this->assertTrue($this->cache->containsEntity(Country::class, 1)); - $this->assertFalse($this->cache->containsEntity(CmsUser::class, 1)); + self::assertTrue($this->cache->containsEntity(Country::class, 1)); + self::assertFalse($this->cache->containsEntity(CmsUser::class, 1)); } public function testEvictEntity() { - $identifier = ['id'=>1]; - $className = Country::class; + $identifier = ['id' => 1]; $cacheEntry = array_merge($identifier, ['name' => 'Brazil']); - $this->putEntityCacheEntry($className, $identifier, $cacheEntry); + $this->putEntityCacheEntry(Country::class, $identifier, $cacheEntry); - $this->assertTrue($this->cache->containsEntity(Country::class, 1)); + self::assertTrue($this->cache->containsEntity(Country::class, 1)); $this->cache->evictEntity(Country::class, 1); $this->cache->evictEntity(CmsUser::class, 1); - $this->assertFalse($this->cache->containsEntity(Country::class, 1)); + self::assertFalse($this->cache->containsEntity(Country::class, 1)); } public function testEvictEntityRegion() { - $identifier = ['id'=>1]; - $className = Country::class; + $identifier = ['id' => 1]; $cacheEntry = array_merge($identifier, ['name' => 'Brazil']); - $this->putEntityCacheEntry($className, $identifier, $cacheEntry); + $this->putEntityCacheEntry(Country::class, $identifier, $cacheEntry); - $this->assertTrue($this->cache->containsEntity(Country::class, 1)); + self::assertTrue($this->cache->containsEntity(Country::class, 1)); $this->cache->evictEntityRegion(Country::class); $this->cache->evictEntityRegion(CmsUser::class); - $this->assertFalse($this->cache->containsEntity(Country::class, 1)); + self::assertFalse($this->cache->containsEntity(Country::class, 1)); } public function testEvictEntityRegions() { - $identifier = ['id'=>1]; - $className = Country::class; + $identifier = ['id' => 1]; $cacheEntry = array_merge($identifier, ['name' => 'Brazil']); - $this->putEntityCacheEntry($className, $identifier, $cacheEntry); + $this->putEntityCacheEntry(Country::class, $identifier, $cacheEntry); - $this->assertTrue($this->cache->containsEntity(Country::class, 1)); + self::assertTrue($this->cache->containsEntity(Country::class, 1)); $this->cache->evictEntityRegions(); - $this->assertFalse($this->cache->containsEntity(Country::class, 1)); + self::assertFalse($this->cache->containsEntity(Country::class, 1)); } public function testContainsCollection() { - $ownerId = ['id'=>1]; - $className = State::class; - $association = 'cities'; - $cacheEntry = [ + $ownerId = ['id' => 1]; + $association = 'cities'; + $cacheEntry = [ ['id' => 11], ['id' => 12], ]; - $this->assertFalse($this->cache->containsCollection(State::class, $association, 1)); + self::assertFalse($this->cache->containsCollection(State::class, $association, 1)); - $this->putCollectionCacheEntry($className, $association, $ownerId, $cacheEntry); + $this->putCollectionCacheEntry(State::class, $association, $ownerId, $cacheEntry); - $this->assertTrue($this->cache->containsCollection(State::class, $association, 1)); - $this->assertFalse($this->cache->containsCollection(CmsUser::class, 'phonenumbers', 1)); + self::assertTrue($this->cache->containsCollection(State::class, $association, 1)); + self::assertFalse($this->cache->containsCollection(CmsUser::class, 'phonenumbers', 1)); } public function testEvictCollection() { - $ownerId = ['id'=>1]; - $className = State::class; - $association = 'cities'; - $cacheEntry = [ + $ownerId = ['id' => 1]; + $association = 'cities'; + $cacheEntry = [ ['id' => 11], ['id' => 12], ]; - $this->putCollectionCacheEntry($className, $association, $ownerId, $cacheEntry); + $this->putCollectionCacheEntry(State::class, $association, $ownerId, $cacheEntry); - $this->assertTrue($this->cache->containsCollection(State::class, $association, 1)); + self::assertTrue($this->cache->containsCollection(State::class, $association, 1)); - $this->cache->evictCollection($className, $association, $ownerId); + $this->cache->evictCollection(State::class, $association, $ownerId); $this->cache->evictCollection(CmsUser::class, 'phonenumbers', 1); - $this->assertFalse($this->cache->containsCollection(State::class, $association, 1)); + self::assertFalse($this->cache->containsCollection(State::class, $association, 1)); } public function testEvictCollectionRegion() { - $ownerId = ['id'=>1]; - $className = State::class; - $association = 'cities'; - $cacheEntry = [ + $ownerId = ['id' => 1]; + $association = 'cities'; + $cacheEntry = [ ['id' => 11], ['id' => 12], ]; - $this->putCollectionCacheEntry($className, $association, $ownerId, $cacheEntry); + $this->putCollectionCacheEntry(State::class, $association, $ownerId, $cacheEntry); - $this->assertTrue($this->cache->containsCollection(State::class, $association, 1)); + self::assertTrue($this->cache->containsCollection(State::class, $association, 1)); - $this->cache->evictCollectionRegion($className, $association); + $this->cache->evictCollectionRegion(State::class, $association); $this->cache->evictCollectionRegion(CmsUser::class, 'phonenumbers'); - $this->assertFalse($this->cache->containsCollection(State::class, $association, 1)); + self::assertFalse($this->cache->containsCollection(State::class, $association, 1)); } public function testEvictCollectionRegions() { - $ownerId = ['id'=>1]; - $className = State::class; - $association = 'cities'; - $cacheEntry = [ + $ownerId = ['id' => 1]; + $association = 'cities'; + $cacheEntry = [ ['id' => 11], ['id' => 12], ]; - $this->putCollectionCacheEntry($className, $association, $ownerId, $cacheEntry); + $this->putCollectionCacheEntry(State::class, $association, $ownerId, $cacheEntry); - $this->assertTrue($this->cache->containsCollection(State::class, $association, 1)); + self::assertTrue($this->cache->containsCollection(State::class, $association, 1)); $this->cache->evictCollectionRegions(); - $this->assertFalse($this->cache->containsCollection(State::class, $association, 1)); + self::assertFalse($this->cache->containsCollection(State::class, $association, 1)); } public function testQueryCache() { - $this->assertFalse($this->cache->containsQuery('foo')); + self::assertFalse($this->cache->containsQuery('foo')); $defaultQueryCache = $this->cache->getQueryCache(); $fooQueryCache = $this->cache->getQueryCache('foo'); - $this->assertInstanceOf(Cache\QueryCache::class, $defaultQueryCache); - $this->assertInstanceOf(Cache\QueryCache::class, $fooQueryCache); - $this->assertSame($defaultQueryCache, $this->cache->getQueryCache()); - $this->assertSame($fooQueryCache, $this->cache->getQueryCache('foo')); + self::assertInstanceOf(Cache\QueryCache::class, $defaultQueryCache); + self::assertInstanceOf(Cache\QueryCache::class, $fooQueryCache); + self::assertSame($defaultQueryCache, $this->cache->getQueryCache()); + self::assertSame($fooQueryCache, $this->cache->getQueryCache('foo')); $this->cache->evictQueryRegion(); $this->cache->evictQueryRegion('foo'); $this->cache->evictQueryRegions(); - $this->assertTrue($this->cache->containsQuery('foo')); + self::assertTrue($this->cache->containsQuery('foo')); - $this->assertSame($defaultQueryCache, $this->cache->getQueryCache()); - $this->assertSame($fooQueryCache, $this->cache->getQueryCache('foo')); + self::assertSame($defaultQueryCache, $this->cache->getQueryCache()); + self::assertSame($fooQueryCache, $this->cache->getQueryCache('foo')); } public function testToIdentifierArrayShouldLookupForEntityIdentifier() @@ -257,7 +252,7 @@ public function testToIdentifierArrayShouldLookupForEntityIdentifier() $method->setAccessible(true); $property->setValue($entity, $identifier); - $this->assertEquals(['id'=>$identifier], $method->invoke($this->cache, $metadata, $identifier)); + self::assertEquals(['id'=>$identifier], $method->invoke($this->cache, $metadata, $identifier)); } } diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultCollectionHydratorTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultCollectionHydratorTest.php index f2a35b16a95..682af0ffb0e 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultCollectionHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultCollectionHydratorTest.php @@ -1,5 +1,7 @@ enableSecondLevelCache(); parent::setUp(); - $targetPersister = $this->_em->getUnitOfWork()->getEntityPersister(City::class); - $this->structure = new DefaultCollectionHydrator($this->_em, $targetPersister); + $targetPersister = $this->em->getUnitOfWork()->getEntityPersister(City::class); + $this->structure = new DefaultCollectionHydrator($this->em, $targetPersister); } public function testImplementsCollectionEntryStructure() { - $this->assertInstanceOf(DefaultCollectionHydrator::class, $this->structure); + self::assertInstanceOf(DefaultCollectionHydrator::class, $this->structure); } public function testLoadCacheCollection() { - $targetRegion = $this->_em->getCache()->getEntityCacheRegion(City::class); + $targetRegion = $this->em->getCache()->getEntityCacheRegion(City::class); $entry = new CollectionCacheEntry( [ new EntityCacheKey(City::class, ['id'=>31]), @@ -53,30 +55,30 @@ public function testLoadCacheCollection() $targetRegion->put(new EntityCacheKey(City::class, ['id'=>32]), new EntityCacheEntry(City::class, ['id'=>32, 'name'=>'Bar'] )); - $sourceClass = $this->_em->getClassMetadata(State::class); - $targetClass = $this->_em->getClassMetadata(City::class); - $key = new CollectionCacheKey($sourceClass->name, 'cities', ['id'=>21]); - $collection = new PersistentCollection($this->_em, $targetClass, new ArrayCollection()); + $sourceClass = $this->em->getClassMetadata(State::class); + $targetClass = $this->em->getClassMetadata(City::class); + $key = new CollectionCacheKey($sourceClass->getClassName(), 'cities', ['id'=>21]); + $collection = new PersistentCollection($this->em, $targetClass, new ArrayCollection()); $list = $this->structure->loadCacheEntry($sourceClass, $key, $entry, $collection); - $this->assertNotNull($list); - $this->assertCount(2, $list); - $this->assertCount(2, $collection); + self::assertNotNull($list); + self::assertCount(2, $list); + self::assertCount(2, $collection); - $this->assertInstanceOf($targetClass->name, $list[0]); - $this->assertInstanceOf($targetClass->name, $list[1]); - $this->assertInstanceOf($targetClass->name, $collection[0]); - $this->assertInstanceOf($targetClass->name, $collection[1]); + self::assertInstanceOf($targetClass->getClassName(), $list[0]); + self::assertInstanceOf($targetClass->getClassName(), $list[1]); + self::assertInstanceOf($targetClass->getClassName(), $collection[0]); + self::assertInstanceOf($targetClass->getClassName(), $collection[1]); - $this->assertSame($list[0], $collection[0]); - $this->assertSame($list[1], $collection[1]); + self::assertSame($list[0], $collection[0]); + self::assertSame($list[1], $collection[1]); - $this->assertEquals(31, $list[0]->getId()); - $this->assertEquals(32, $list[1]->getId()); - $this->assertEquals($list[0]->getId(), $collection[0]->getId()); - $this->assertEquals($list[1]->getId(), $collection[1]->getId()); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($collection[0])); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($collection[1])); + self::assertEquals(31, $list[0]->getId()); + self::assertEquals(32, $list[1]->getId()); + self::assertEquals($list[0]->getId(), $collection[0]->getId()); + self::assertEquals($list[1]->getId(), $collection[1]->getId()); + self::assertEquals(UnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($collection[0])); + self::assertEquals(UnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($collection[1])); } } diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultEntityHydratorTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultEntityHydratorTest.php index d58ab8a0527..e5e96415295 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultEntityHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultEntityHydratorTest.php @@ -1,5 +1,7 @@ em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); $this->structure = new DefaultEntityHydrator($this->em); } public function testImplementsEntityEntryStructure() { - $this->assertInstanceOf('\Doctrine\ORM\Cache\EntityHydrator', $this->structure); + self::assertInstanceOf('Doctrine\ORM\Cache\EntityHydrator', $this->structure); } public function testCreateEntity() { $metadata = $this->em->getClassMetadata(Country::class); - $key = new EntityCacheKey($metadata->name, ['id'=>1]); - $entry = new EntityCacheEntry($metadata->name, ['id'=>1, 'name'=>'Foo']); + $key = new EntityCacheKey($metadata->getClassName(), ['id'=>1]); + $entry = new EntityCacheEntry($metadata->getClassName(), ['id'=>1, 'name'=>'Foo']); $entity = $this->structure->loadCacheEntry($metadata, $key, $entry); - $this->assertInstanceOf($metadata->name, $entity); + self::assertInstanceOf($metadata->getClassName(), $entity); - $this->assertEquals(1, $entity->getId()); - $this->assertEquals('Foo', $entity->getName()); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($entity)); + self::assertEquals(1, $entity->getId()); + self::assertEquals('Foo', $entity->getName()); + self::assertEquals(UnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($entity)); } public function testLoadProxy() { $metadata = $this->em->getClassMetadata(Country::class); - $key = new EntityCacheKey($metadata->name, ['id'=>1]); - $entry = new EntityCacheEntry($metadata->name, ['id'=>1, 'name'=>'Foo']); - $proxy = $this->em->getReference($metadata->name, $key->identifier); + $key = new EntityCacheKey($metadata->getClassName(), ['id'=>1]); + $entry = new EntityCacheEntry($metadata->getClassName(), ['id'=>1, 'name'=>'Foo']); + $proxy = $this->em->getReference($metadata->getClassName(), $key->identifier); $entity = $this->structure->loadCacheEntry($metadata, $key, $entry, $proxy); - $this->assertInstanceOf($metadata->name, $entity); - $this->assertSame($proxy, $entity); + self::assertInstanceOf($metadata->getClassName(), $entity); + self::assertSame($proxy, $entity); - $this->assertEquals(1, $entity->getId()); - $this->assertEquals('Foo', $entity->getName()); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($proxy)); + self::assertEquals(1, $entity->getId()); + self::assertEquals('Foo', $entity->getName()); + self::assertEquals(UnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($proxy)); } public function testBuildCacheEntry() @@ -76,23 +78,25 @@ public function testBuildCacheEntry() $uow = $this->em->getUnitOfWork(); $data = ['id'=>1, 'name'=>'Foo']; $metadata = $this->em->getClassMetadata(Country::class); - $key = new EntityCacheKey($metadata->name, ['id'=>1]); + $key = new EntityCacheKey($metadata->getClassName(), ['id'=>1]); $entity->setId(1); $uow->registerManaged($entity, $key->identifier, $data); $cache = $this->structure->buildCacheEntry($metadata, $key, $entity); - $this->assertInstanceOf(CacheEntry::class, $cache); - $this->assertInstanceOf(EntityCacheEntry::class, $cache); + self::assertInstanceOf(CacheEntry::class, $cache); + self::assertInstanceOf(EntityCacheEntry::class, $cache); - $this->assertArrayHasKey('id', $cache->data); - $this->assertArrayHasKey('name', $cache->data); - $this->assertEquals( + self::assertArrayHasKey('id', $cache->data); + self::assertArrayHasKey('name', $cache->data); + self::assertEquals( [ - 'id' => 1, - 'name' => 'Foo', - ], $cache->data); + 'id' => 1, + 'name' => 'Foo', + ], + $cache->data + ); } public function testBuildCacheEntryAssociation() @@ -103,7 +107,7 @@ public function testBuildCacheEntryAssociation() $countryData = ['id'=>11, 'name'=>'Foo']; $stateData = ['id'=>12, 'name'=>'Bar', 'country' => $country]; $metadata = $this->em->getClassMetadata(State::class); - $key = new EntityCacheKey($metadata->name, ['id'=>11]); + $key = new EntityCacheKey($metadata->getClassName(), ['id'=>11]); $country->setId(11); $state->setId(12); @@ -113,18 +117,20 @@ public function testBuildCacheEntryAssociation() $cache = $this->structure->buildCacheEntry($metadata, $key, $state); - $this->assertInstanceOf(CacheEntry::class, $cache); - $this->assertInstanceOf(EntityCacheEntry::class, $cache); + self::assertInstanceOf(CacheEntry::class, $cache); + self::assertInstanceOf(EntityCacheEntry::class, $cache); - $this->assertArrayHasKey('id', $cache->data); - $this->assertArrayHasKey('name', $cache->data); - $this->assertArrayHasKey('country', $cache->data); - $this->assertEquals( + self::assertArrayHasKey('id', $cache->data); + self::assertArrayHasKey('name', $cache->data); + self::assertArrayHasKey('country', $cache->data); + self::assertEquals( [ - 'id' => 12, - 'name' => 'Bar', - 'country' => new AssociationCacheEntry(Country::class, ['id' => 11]), - ], $cache->data); + 'id' => 12, + 'name' => 'Bar', + 'country' => new AssociationCacheEntry(Country::class, ['id' => 11]), + ], + $cache->data + ); } public function testBuildCacheEntryNonInitializedAssocProxy() @@ -134,7 +140,7 @@ public function testBuildCacheEntryNonInitializedAssocProxy() $uow = $this->em->getUnitOfWork(); $entityData = ['id'=>12, 'name'=>'Bar', 'country' => $proxy]; $metadata = $this->em->getClassMetadata(State::class); - $key = new EntityCacheKey($metadata->name, ['id'=>11]); + $key = new EntityCacheKey($metadata->getClassName(), ['id'=>11]); $entity->setId(12); @@ -142,18 +148,20 @@ public function testBuildCacheEntryNonInitializedAssocProxy() $cache = $this->structure->buildCacheEntry($metadata, $key, $entity); - $this->assertInstanceOf(CacheEntry::class, $cache); - $this->assertInstanceOf(EntityCacheEntry::class, $cache); + self::assertInstanceOf(CacheEntry::class, $cache); + self::assertInstanceOf(EntityCacheEntry::class, $cache); - $this->assertArrayHasKey('id', $cache->data); - $this->assertArrayHasKey('name', $cache->data); - $this->assertArrayHasKey('country', $cache->data); - $this->assertEquals( + self::assertArrayHasKey('id', $cache->data); + self::assertArrayHasKey('name', $cache->data); + self::assertArrayHasKey('country', $cache->data); + self::assertEquals( [ - 'id' => 12, - 'name' => 'Bar', - 'country' => new AssociationCacheEntry(Country::class, ['id' => 11]), - ], $cache->data); + 'id' => 12, + 'name' => 'Bar', + 'country' => new AssociationCacheEntry(Country::class, ['id' => 11]), + ], + $cache->data + ); } public function testCacheEntryWithWrongIdentifierType() @@ -163,7 +171,7 @@ public function testCacheEntryWithWrongIdentifierType() $uow = $this->em->getUnitOfWork(); $entityData = ['id'=> 12, 'name'=>'Bar', 'country' => $proxy]; $metadata = $this->em->getClassMetadata(State::class); - $key = new EntityCacheKey($metadata->name, ['id'=>'12']); + $key = new EntityCacheKey($metadata->getClassName(), ['id'=>'12']); $entity->setId(12); @@ -171,19 +179,21 @@ public function testCacheEntryWithWrongIdentifierType() $cache = $this->structure->buildCacheEntry($metadata, $key, $entity); - $this->assertInstanceOf(CacheEntry::class, $cache); - $this->assertInstanceOf(EntityCacheEntry::class, $cache); + self::assertInstanceOf(CacheEntry::class, $cache); + self::assertInstanceOf(EntityCacheEntry::class, $cache); - $this->assertArrayHasKey('id', $cache->data); - $this->assertArrayHasKey('name', $cache->data); - $this->assertArrayHasKey('country', $cache->data); - $this->assertSame($entity->getId(), $cache->data['id']); - $this->assertEquals( + self::assertArrayHasKey('id', $cache->data); + self::assertArrayHasKey('name', $cache->data); + self::assertArrayHasKey('country', $cache->data); + self::assertSame($entity->getId(), $cache->data['id']); + self::assertEquals( [ - 'id' => 12, - 'name' => 'Bar', - 'country' => new AssociationCacheEntry(Country::class, ['id' => 11]), - ], $cache->data); + 'id' => 12, + 'name' => 'Bar', + 'country' => new AssociationCacheEntry(Country::class, ['id' => 11]), + ], + $cache->data + ); } } diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultQueryCacheTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultQueryCacheTest.php index 58eddd37509..b2f9d4cc528 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultQueryCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultQueryCacheTest.php @@ -1,25 +1,29 @@ enableSecondLevelCache(); - $this->em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); $this->region = new CacheRegionMock(); $this->queryCache = new DefaultQueryCache($this->em, $this->region); $this->cacheFactory = new CacheFactoryDefaultQueryCacheTest($this->queryCache, $this->region); @@ -64,188 +68,181 @@ protected function setUp() public function testImplementQueryCache() { - $this->assertInstanceOf(QueryCache::class, $this->queryCache); + self::assertInstanceOf(QueryCache::class, $this->queryCache); } public function testGetRegion() { - $this->assertSame($this->region, $this->queryCache->getRegion()); + self::assertSame($this->region, $this->queryCache->getRegion()); } public function testClearShouldEvictRegion() { $this->queryCache->clear(); - $this->assertArrayHasKey('evictAll', $this->region->calls); - $this->assertCount(1, $this->region->calls['evictAll']); + self::assertArrayHasKey('evictAll', $this->region->calls); + self::assertCount(1, $this->region->calls['evictAll']); } public function testPutBasicQueryResult() { - $result = []; - $key = new QueryCacheKey('query.key1', 0); - $rsm = new ResultSetMappingBuilder($this->em); - $metadata = $this->em->getClassMetadata(Country::class); + $result = []; + $uow = $this->em->getUnitOfWork(); + $key = new QueryCacheKey('query.key1', 0); + $rsm = new ResultSetMappingBuilder($this->em); $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); for ($i = 0; $i < 4; $i++) { - $name = "Country $i"; - $entity = new Country($name); - $result[] = $entity; + $name = "Country $i"; + $entity = new Country($name); + + $entity->setId($i); - $metadata->setFieldValue($entity, 'id', $i); - $this->em->getUnitOfWork()->registerManaged($entity, ['id' => $i], ['name' => $name]); + $result[] = $entity; + + $uow->registerManaged($entity, ['id' => $entity->getId()], ['name' => $entity->getName()]); } - $this->assertTrue($this->queryCache->put($key, $rsm, $result)); - $this->assertArrayHasKey('put', $this->region->calls); - $this->assertCount(5, $this->region->calls['put']); - - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][0]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][1]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][2]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][3]['key']); - $this->assertInstanceOf(QueryCacheKey::class, $this->region->calls['put'][4]['key']); - - $this->assertInstanceOf(EntityCacheEntry::class, $this->region->calls['put'][0]['entry']); - $this->assertInstanceOf(EntityCacheEntry::class, $this->region->calls['put'][1]['entry']); - $this->assertInstanceOf(EntityCacheEntry::class, $this->region->calls['put'][2]['entry']); - $this->assertInstanceOf(EntityCacheEntry::class, $this->region->calls['put'][3]['entry']); - $this->assertInstanceOf(QueryCacheEntry::class, $this->region->calls['put'][4]['entry']); + self::assertTrue($this->queryCache->put($key, $rsm, $result)); + self::assertArrayHasKey('put', $this->region->calls); + self::assertCount(5, $this->region->calls['put']); + + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][0]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][1]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][2]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][3]['key']); + self::assertInstanceOf(QueryCacheKey::class, $this->region->calls['put'][4]['key']); + + self::assertInstanceOf(EntityCacheEntry::class, $this->region->calls['put'][0]['entry']); + self::assertInstanceOf(EntityCacheEntry::class, $this->region->calls['put'][1]['entry']); + self::assertInstanceOf(EntityCacheEntry::class, $this->region->calls['put'][2]['entry']); + self::assertInstanceOf(EntityCacheEntry::class, $this->region->calls['put'][3]['entry']); + self::assertInstanceOf(QueryCacheEntry::class, $this->region->calls['put'][4]['entry']); } public function testPutToOneAssociationQueryResult() { - $result = []; - $uow = $this->em->getUnitOfWork(); - $key = new QueryCacheKey('query.key1', 0); - $rsm = new ResultSetMappingBuilder($this->em); - $cityClass = $this->em->getClassMetadata(City::class); - $stateClass = $this->em->getClassMetadata(State::class); + $result = []; + $uow = $this->em->getUnitOfWork(); + $key = new QueryCacheKey('query.key1', 0); + $rsm = new ResultSetMappingBuilder($this->em); $rsm->addRootEntityFromClassMetadata(City::class, 'c'); $rsm->addJoinedEntityFromClassMetadata(State::class, 's', 'c', 'state', ['id'=>'state_id', 'name'=>'state_name']); for ($i = 0; $i < 4; $i++) { - $state = new State("State $i"); - $city = new City("City $i", $state); - $result[] = $city; + $state = new State("State $i"); + $city = new City("City $i", $state); + + $city->setId($i); + $state->setId($i * 2); - $cityClass->setFieldValue($city, 'id', $i); - $stateClass->setFieldValue($state, 'id', $i*2); + $result[] = $city; $uow->registerManaged($state, ['id' => $state->getId()], ['name' => $city->getName()]); $uow->registerManaged($city, ['id' => $city->getId()], ['name' => $city->getName(), 'state' => $state]); } - $this->assertTrue($this->queryCache->put($key, $rsm, $result)); - $this->assertArrayHasKey('put', $this->region->calls); - $this->assertCount(9, $this->region->calls['put']); - - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][0]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][1]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][2]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][3]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][4]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][5]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][6]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][7]['key']); - $this->assertInstanceOf(QueryCacheKey::class, $this->region->calls['put'][8]['key']); + self::assertTrue($this->queryCache->put($key, $rsm, $result)); + self::assertArrayHasKey('put', $this->region->calls); + self::assertCount(9, $this->region->calls['put']); + + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][0]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][1]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][2]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][3]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][4]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][5]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][6]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][7]['key']); + self::assertInstanceOf(QueryCacheKey::class, $this->region->calls['put'][8]['key']); } public function testPutToOneAssociation2LevelsQueryResult() { - $result = []; - $uow = $this->em->getUnitOfWork(); - $key = new QueryCacheKey('query.key1', 0); - $rsm = new ResultSetMappingBuilder($this->em); - $cityClass = $this->em->getClassMetadata(City::class); - $stateClass = $this->em->getClassMetadata(State::class); - $countryClass = $this->em->getClassMetadata(Country::class); + $result = []; + $uow = $this->em->getUnitOfWork(); + $key = new QueryCacheKey('query.key1', 0); + $rsm = new ResultSetMappingBuilder($this->em); $rsm->addRootEntityFromClassMetadata(City::class, 'c'); - $rsm->addJoinedEntityFromClassMetadata(State::class, 's', 'c', 'state', ['id'=>'state_id', 'name'=>'state_name'] - ); - $rsm->addJoinedEntityFromClassMetadata(Country::class, 'co', 's', 'country', ['id'=>'country_id', 'name'=>'country_name'] - ); + $rsm->addJoinedEntityFromClassMetadata(State::class, 's', 'c', 'state', ['id'=>'state_id', 'name'=>'state_name']); + $rsm->addJoinedEntityFromClassMetadata(Country::class, 'co', 's', 'country', ['id'=>'country_id', 'name'=>'country_name']); for ($i = 0; $i < 4; $i++) { $country = new Country("Country $i"); $state = new State("State $i", $country); $city = new City("City $i", $state); - $result[] = $city; + $city->setId($i); + $state->setId($i * 2); + $country->setId($i * 3); - $cityClass->setFieldValue($city, 'id', $i); - $stateClass->setFieldValue($state, 'id', $i*2); - $countryClass->setFieldValue($country, 'id', $i*3); + $result[] = $city; $uow->registerManaged($country, ['id' => $country->getId()], ['name' => $country->getName()]); - $uow->registerManaged($state, ['id' => $state->getId()], ['name' => $state->getName(), 'country' => $country] - ); + $uow->registerManaged($state, ['id' => $state->getId()], ['name' => $state->getName(), 'country' => $country]); $uow->registerManaged($city, ['id' => $city->getId()], ['name' => $city->getName(), 'state' => $state]); } - $this->assertTrue($this->queryCache->put($key, $rsm, $result)); - $this->assertArrayHasKey('put', $this->region->calls); - $this->assertCount(13, $this->region->calls['put']); - - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][0]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][1]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][2]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][3]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][4]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][5]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][6]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][7]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][8]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][9]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][10]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][11]['key']); - $this->assertInstanceOf(QueryCacheKey::class, $this->region->calls['put'][12]['key']); + self::assertTrue($this->queryCache->put($key, $rsm, $result)); + self::assertArrayHasKey('put', $this->region->calls); + self::assertCount(13, $this->region->calls['put']); + + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][0]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][1]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][2]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][3]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][4]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][5]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][6]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][7]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][8]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][9]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][10]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][11]['key']); + self::assertInstanceOf(QueryCacheKey::class, $this->region->calls['put'][12]['key']); } public function testPutToOneAssociationNullQueryResult() { - $result = []; - $uow = $this->em->getUnitOfWork(); - $key = new QueryCacheKey('query.key1', 0); - $rsm = new ResultSetMappingBuilder($this->em); - $cityClass = $this->em->getClassMetadata(City::class); + $result = []; + $uow = $this->em->getUnitOfWork(); + $key = new QueryCacheKey('query.key1', 0); + $rsm = new ResultSetMappingBuilder($this->em); $rsm->addRootEntityFromClassMetadata(City::class, 'c'); $rsm->addJoinedEntityFromClassMetadata(State::class, 's', 'c', 'state', ['id'=>'state_id', 'name'=>'state_name'] ); for ($i = 0; $i < 4; $i++) { - $city = new City("City $i", null); - $result[] = $city; + $city = new City("City $i", null); + + $city->setId($i); - $cityClass->setFieldValue($city, 'id', $i); + $result[] = $city; $uow->registerManaged($city, ['id' => $city->getId()], ['name' => $city->getName(), 'state' => null]); } - $this->assertTrue($this->queryCache->put($key, $rsm, $result)); - $this->assertArrayHasKey('put', $this->region->calls); - $this->assertCount(5, $this->region->calls['put']); + self::assertTrue($this->queryCache->put($key, $rsm, $result)); + self::assertArrayHasKey('put', $this->region->calls); + self::assertCount(5, $this->region->calls['put']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][0]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][1]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][2]['key']); - $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][3]['key']); - $this->assertInstanceOf(QueryCacheKey::class, $this->region->calls['put'][4]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][0]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][1]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][2]['key']); + self::assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][3]['key']); + self::assertInstanceOf(QueryCacheKey::class, $this->region->calls['put'][4]['key']); } public function testPutToManyAssociationQueryResult() { - $result = []; - $uow = $this->em->getUnitOfWork(); - $key = new QueryCacheKey('query.key1', 0); - $rsm = new ResultSetMappingBuilder($this->em); - $cityClass = $this->em->getClassMetadata(City::class); - $stateClass = $this->em->getClassMetadata(State::class); + $result = []; + $uow = $this->em->getUnitOfWork(); + $key = new QueryCacheKey('query.key1', 0); + $rsm = new ResultSetMappingBuilder($this->em); $rsm->addRootEntityFromClassMetadata(State::class, 's'); $rsm->addJoinedEntityFromClassMetadata(City::class, 'c', 's', 'cities', ['id'=>'c_id', 'name'=>'c_name']); @@ -254,26 +251,24 @@ public function testPutToManyAssociationQueryResult() $state = new State("State $i"); $city1 = new City("City 1", $state); $city2 = new City("City 2", $state); - $result[] = $state; - $cityClass->setFieldValue($city1, 'id', $i + 11); - $cityClass->setFieldValue($city2, 'id', $i + 22); - $stateClass->setFieldValue($state, 'id', $i); + $state->setId($i); + $city1->setId($i + 11); + $city2->setId($i + 22); + + $result[] = $state; $state->addCity($city1); $state->addCity($city2); - $uow->registerManaged($city1, ['id' => $city1->getId()], ['name' => $city1->getName(), 'state' => $state] - ); - $uow->registerManaged($city2, ['id' => $city2->getId()], ['name' => $city2->getName(), 'state' => $state] - ); - $uow->registerManaged($state, ['id' => $state->getId()], ['name' => $state->getName(), 'cities' => $state->getCities()] - ); + $uow->registerManaged($city1, ['id' => $city1->getId()], ['name' => $city1->getName(), 'state' => $state]); + $uow->registerManaged($city2, ['id' => $city2->getId()], ['name' => $city2->getName(), 'state' => $state]); + $uow->registerManaged($state, ['id' => $state->getId()], ['name' => $state->getName(), 'cities' => $state->getCities()]); } - $this->assertTrue($this->queryCache->put($key, $rsm, $result)); - $this->assertArrayHasKey('put', $this->region->calls); - $this->assertCount(13, $this->region->calls['put']); + self::assertTrue($this->queryCache->put($key, $rsm, $result)); + self::assertArrayHasKey('put', $this->region->calls); + self::assertCount(13, $this->region->calls['put']); } public function testGetBasicQueryResult() @@ -306,13 +301,13 @@ public function testGetBasicQueryResult() $result = $this->queryCache->get($key, $rsm); - $this->assertCount(2, $result); - $this->assertInstanceOf(Country::class, $result[0]); - $this->assertInstanceOf(Country::class, $result[1]); - $this->assertEquals(1, $result[0]->getId()); - $this->assertEquals(2, $result[1]->getId()); - $this->assertEquals('Foo', $result[0]->getName()); - $this->assertEquals('Bar', $result[1]->getName()); + self::assertCount(2, $result); + self::assertInstanceOf(Country::class, $result[0]); + self::assertInstanceOf(Country::class, $result[1]); + self::assertEquals(1, $result[0]->getId()); + self::assertEquals(2, $result[1]->getId()); + self::assertEquals('Foo', $result[0]->getName()); + self::assertEquals('Bar', $result[1]->getName()); } public function testGetWithAssociation() @@ -345,59 +340,59 @@ public function testGetWithAssociation() $result = $this->queryCache->get($key, $rsm); - $this->assertCount(2, $result); - $this->assertInstanceOf(Country::class, $result[0]); - $this->assertInstanceOf(Country::class, $result[1]); - $this->assertEquals(1, $result[0]->getId()); - $this->assertEquals(2, $result[1]->getId()); - $this->assertEquals('Foo', $result[0]->getName()); - $this->assertEquals('Bar', $result[1]->getName()); + self::assertCount(2, $result); + self::assertInstanceOf(Country::class, $result[0]); + self::assertInstanceOf(Country::class, $result[1]); + self::assertEquals(1, $result[0]->getId()); + self::assertEquals(2, $result[1]->getId()); + self::assertEquals('Foo', $result[0]->getName()); + self::assertEquals('Bar', $result[1]->getName()); } public function testCancelPutResultIfEntityPutFails() { - $result = []; - $key = new QueryCacheKey('query.key1', 0); - $rsm = new ResultSetMappingBuilder($this->em); - $metadata = $this->em->getClassMetadata(Country::class); + $result = []; + $uow = $this->em->getUnitOfWork(); + $key = new QueryCacheKey('query.key1', 0); + $rsm = new ResultSetMappingBuilder($this->em); $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); for ($i = 0; $i < 4; $i++) { - $name = "Country $i"; - $entity = new Country($name); - $result[] = $entity; + $name = "Country $i"; + $entity = new Country($name); + + $entity->setId($i); + + $result[] = $entity; - $metadata->setFieldValue($entity, 'id', $i); - $this->em->getUnitOfWork()->registerManaged($entity, ['id' => $i], ['name' => $name]); + $uow->registerManaged($entity, ['id' => $entity->getId()], ['name' => $entity->getName()]); } $this->region->addReturn('put', false); - $this->assertFalse($this->queryCache->put($key, $rsm, $result)); - $this->assertArrayHasKey('put', $this->region->calls); - $this->assertCount(1, $this->region->calls['put']); + self::assertFalse($this->queryCache->put($key, $rsm, $result)); + self::assertArrayHasKey('put', $this->region->calls); + self::assertCount(1, $this->region->calls['put']); } public function testCancelPutResultIfAssociationEntityPutFails() { - $result = []; - $uow = $this->em->getUnitOfWork(); - $key = new QueryCacheKey('query.key1', 0); - $rsm = new ResultSetMappingBuilder($this->em); - $cityClass = $this->em->getClassMetadata(City::class); - $stateClass = $this->em->getClassMetadata(State::class); + $result = []; + $uow = $this->em->getUnitOfWork(); + $key = new QueryCacheKey('query.key1', 0); + $rsm = new ResultSetMappingBuilder($this->em); $rsm->addRootEntityFromClassMetadata(City::class, 'c'); - $rsm->addJoinedEntityFromClassMetadata(State::class, 's', 'c', 'state', ['id'=>'state_id', 'name'=>'state_name'] - ); + $rsm->addJoinedEntityFromClassMetadata(State::class, 's', 'c', 'state', ['id'=>'state_id', 'name'=>'state_name']); - $state = new State("State 1"); - $city = new City("City 2", $state); - $result[] = $city; + $state = new State("State 1"); + $city = new City("City 2", $state); + + $state->setId(1); + $city->setId(11); - $cityClass->setFieldValue($city, 'id', 1); - $stateClass->setFieldValue($state, 'id', 11); + $result[] = $city; $uow->registerManaged($state, ['id' => $state->getId()], ['name' => $city->getName()]); $uow->registerManaged($city, ['id' => $city->getId()], ['name' => $city->getName(), 'state' => $state]); @@ -405,44 +400,42 @@ public function testCancelPutResultIfAssociationEntityPutFails() $this->region->addReturn('put', true); // put root entity $this->region->addReturn('put', false); // association fails - $this->assertFalse($this->queryCache->put($key, $rsm, $result)); + self::assertFalse($this->queryCache->put($key, $rsm, $result)); } public function testCancelPutToManyAssociationQueryResult() { - $result = []; - $uow = $this->em->getUnitOfWork(); - $key = new QueryCacheKey('query.key1', 0); - $rsm = new ResultSetMappingBuilder($this->em); - $cityClass = $this->em->getClassMetadata(City::class); - $stateClass = $this->em->getClassMetadata(State::class); + $result = []; + $uow = $this->em->getUnitOfWork(); + $key = new QueryCacheKey('query.key1', 0); + $rsm = new ResultSetMappingBuilder($this->em); $rsm->addRootEntityFromClassMetadata(State::class, 's'); $rsm->addJoinedEntityFromClassMetadata(City::class, 'c', 's', 'cities', ['id'=>'c_id', 'name'=>'c_name']); - $state = new State("State"); - $city1 = new City("City 1", $state); - $city2 = new City("City 2", $state); - $result[] = $state; + $state = new State("State"); + $city1 = new City("City 1", $state); + $city2 = new City("City 2", $state); + + $state->setId(1); + $city1->setId(11); + $city2->setId(22); - $stateClass->setFieldValue($state, 'id', 1); - $cityClass->setFieldValue($city1, 'id', 11); - $cityClass->setFieldValue($city2, 'id', 22); + $result[] = $state; $state->addCity($city1); $state->addCity($city2); $uow->registerManaged($city1, ['id' => $city1->getId()], ['name' => $city1->getName(), 'state' => $state]); $uow->registerManaged($city2, ['id' => $city2->getId()], ['name' => $city2->getName(), 'state' => $state]); - $uow->registerManaged($state, ['id' => $state->getId()], ['name' => $state->getName(), 'cities' => $state->getCities()] - ); + $uow->registerManaged($state, ['id' => $state->getId()], ['name' => $state->getName(), 'cities' => $state->getCities()]); $this->region->addReturn('put', true); // put root entity $this->region->addReturn('put', false); // collection association fails - $this->assertFalse($this->queryCache->put($key, $rsm, $result)); - $this->assertArrayHasKey('put', $this->region->calls); - $this->assertCount(2, $this->region->calls['put']); + self::assertFalse($this->queryCache->put($key, $rsm, $result)); + self::assertArrayHasKey('put', $this->region->calls); + self::assertCount(2, $this->region->calls['put']); } public function testIgnoreCacheNonGetMode() @@ -451,8 +444,8 @@ public function testIgnoreCacheNonGetMode() $key = new QueryCacheKey('query.key1', 0, Cache::MODE_PUT); $entry = new QueryCacheEntry( [ - ['identifier' => ['id' => 1]], - ['identifier' => ['id' => 2]] + ['identifier' => ['id' => 1]], + ['identifier' => ['id' => 2]] ] ); @@ -460,28 +453,30 @@ public function testIgnoreCacheNonGetMode() $this->region->addReturn('get', $entry); - $this->assertNull($this->queryCache->get($key, $rsm)); + self::assertNull($this->queryCache->get($key, $rsm)); } public function testIgnoreCacheNonPutMode() { - $result = []; - $rsm = new ResultSetMappingBuilder($this->em); - $metadata = $this->em->getClassMetadata(Country::class); - $key = new QueryCacheKey('query.key1', 0, Cache::MODE_GET); + $result = []; + $uow = $this->em->getUnitOfWork(); + $key = new QueryCacheKey('query.key1', 0, Cache::MODE_GET); + $rsm = new ResultSetMappingBuilder($this->em); $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); for ($i = 0; $i < 4; $i++) { - $name = "Country $i"; - $entity = new Country($name); - $result[] = $entity; + $name = "Country $i"; + $entity = new Country($name); + + $entity->setId($i); + + $result[] = $entity; - $metadata->setFieldValue($entity, 'id', $i); - $this->em->getUnitOfWork()->registerManaged($entity, ['id' => $i], ['name' => $name]); + $uow->registerManaged($entity, ['id' => $entity->getId()], ['name' => $entity->getName()]); } - $this->assertFalse($this->queryCache->put($key, $rsm, $result)); + self::assertFalse($this->queryCache->put($key, $rsm, $result)); } public function testGetShouldIgnoreOldQueryCacheEntryResult() @@ -490,11 +485,12 @@ public function testGetShouldIgnoreOldQueryCacheEntryResult() $key = new QueryCacheKey('query.key1', 50); $entry = new QueryCacheEntry( [ - ['identifier' => ['id' => 1]], - ['identifier' => ['id' => 2]] + ['identifier' => ['id' => 1]], + ['identifier' => ['id' => 2]] ] ); - $entities = [ + + $data = [ ['id'=>1, 'name' => 'Foo'], ['id'=>2, 'name' => 'Bar'] ]; @@ -506,14 +502,14 @@ public function testGetShouldIgnoreOldQueryCacheEntryResult() $this->region->addReturn( 'getMultiple', [ - new EntityCacheEntry(Country::class, $entities[0]), - new EntityCacheEntry(Country::class, $entities[1]) + new EntityCacheEntry(Country::class, $data[0]), + new EntityCacheEntry(Country::class, $data[1]) ] ); $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); - $this->assertNull($this->queryCache->get($key, $rsm)); + self::assertNull($this->queryCache->get($key, $rsm)); } public function testGetShouldIgnoreNonQueryCacheEntryResult() @@ -522,8 +518,8 @@ public function testGetShouldIgnoreNonQueryCacheEntryResult() $key = new QueryCacheKey('query.key1', 0); $entry = new \ArrayObject( [ - ['identifier' => ['id' => 1]], - ['identifier' => ['id' => 2]] + ['identifier' => ['id' => 1]], + ['identifier' => ['id' => 2]] ] ); @@ -544,7 +540,7 @@ public function testGetShouldIgnoreNonQueryCacheEntryResult() $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); - $this->assertNull($this->queryCache->get($key, $rsm)); + self::assertNull($this->queryCache->get($key, $rsm)); } public function testGetShouldIgnoreMissingEntityQueryCacheEntry() @@ -553,8 +549,8 @@ public function testGetShouldIgnoreMissingEntityQueryCacheEntry() $key = new QueryCacheKey('query.key1', 0); $entry = new QueryCacheEntry( [ - ['identifier' => ['id' => 1]], - ['identifier' => ['id' => 2]] + ['identifier' => ['id' => 1]], + ['identifier' => ['id' => 2]] ] ); @@ -563,7 +559,7 @@ public function testGetShouldIgnoreMissingEntityQueryCacheEntry() $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); - $this->assertNull($this->queryCache->get($key, $rsm)); + self::assertNull($this->queryCache->get($key, $rsm)); } public function testGetAssociationValue() @@ -601,15 +597,15 @@ public function testGetAssociationValue() $cities = $reflection->invoke($this->queryCache, $rsm, 'c', $bavaria); $attractions = $reflection->invoke($this->queryCache, $rsm, 'a', $bavaria); - $this->assertCount(2, $cities); - $this->assertCount(2, $attractions); + self::assertCount(2, $cities); + self::assertCount(2, $attractions); - $this->assertInstanceOf(Collection::class, $cities); - $this->assertInstanceOf(Collection::class, $attractions[0]); - $this->assertInstanceOf(Collection::class, $attractions[1]); + self::assertInstanceOf(Collection::class, $cities); + self::assertInstanceOf(Collection::class, $attractions[0]); + self::assertInstanceOf(Collection::class, $attractions[1]); - $this->assertCount(2, $attractions[0]); - $this->assertCount(1, $attractions[1]); + self::assertCount(2, $attractions[0]); + self::assertCount(1, $attractions[1]); } /** @@ -622,7 +618,7 @@ public function testScalarResultException() $key = new QueryCacheKey('query.key1', 0); $rsm = new ResultSetMappingBuilder($this->em); - $rsm->addScalarResult('id', 'u', 'integer'); + $rsm->addScalarResult('id', 'u', Type::getType('integer')); $this->queryCache->put($key, $rsm, $result); } @@ -665,7 +661,7 @@ public function testNotCacheableEntityException() $this->em->getUnitOfWork()->registerManaged($entity, ['id' => $i], ['booleanField' => $boolean]); } - $this->assertFalse($this->queryCache->put($key, $rsm, $result)); + self::assertFalse($this->queryCache->put($key, $rsm, $result)); } } @@ -686,7 +682,7 @@ public function buildQueryCache(EntityManagerInterface $em, $regionName = null) return $this->queryCache; } - public function getRegion(array $cache) + public function getRegion(CacheMetadata $cache) { return $this->region; } diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php index 97365dfcf28..06c157aa46f 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php @@ -1,5 +1,7 @@ assertEquals('default.region.test', $this->region->getName()); - $this->assertSame($this->cache, $this->region->getCache()); + self::assertEquals('default.region.test', $this->region->getName()); + self::assertSame($this->cache, $this->region->getCache()); } public function testSharedRegion() @@ -34,19 +36,19 @@ public function testSharedRegion() $region1 = new DefaultRegion('region1', $cache->createChild()); $region2 = new DefaultRegion('region2', $cache->createChild()); - $this->assertFalse($region1->contains($key)); - $this->assertFalse($region2->contains($key)); + self::assertFalse($region1->contains($key)); + self::assertFalse($region2->contains($key)); $region1->put($key, $entry); $region2->put($key, $entry); - $this->assertTrue($region1->contains($key)); - $this->assertTrue($region2->contains($key)); + self::assertTrue($region1->contains($key)); + self::assertTrue($region2->contains($key)); $region1->evictAll(); - $this->assertFalse($region1->contains($key)); - $this->assertTrue($region2->contains($key)); + self::assertFalse($region1->contains($key)); + self::assertTrue($region2->contains($key)); } public function testDoesNotModifyCacheNamespace() @@ -58,7 +60,7 @@ public function testDoesNotModifyCacheNamespace() new DefaultRegion('bar', $cache); new DefaultRegion('baz', $cache); - $this->assertSame('foo', $cache->getNamespace()); + self::assertSame('foo', $cache->getNamespace()); } public function testEvictAllWithGenericCacheThrowsUnsupportedException() @@ -81,19 +83,19 @@ public function testGetMulti() $key2 = new CacheKeyMock('key.2'); $value2 = new CacheEntryMock(['id' => 2, 'name' => 'bar']); - $this->assertFalse($this->region->contains($key1)); - $this->assertFalse($this->region->contains($key2)); + self::assertFalse($this->region->contains($key1)); + self::assertFalse($this->region->contains($key2)); $this->region->put($key1, $value1); $this->region->put($key2, $value2); - $this->assertTrue($this->region->contains($key1)); - $this->assertTrue($this->region->contains($key2)); + self::assertTrue($this->region->contains($key1)); + self::assertTrue($this->region->contains($key2)); $actual = $this->region->getMultiple(new CollectionCacheEntry([$key1, $key2])); - $this->assertEquals($value1, $actual[0]); - $this->assertEquals($value2, $actual[1]); + self::assertEquals($value1, $actual[0]); + self::assertEquals($value2, $actual[1]); } } diff --git a/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php b/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php index 1162f3c6aa6..e17b5fda32a 100644 --- a/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php @@ -1,5 +1,7 @@ assertEquals('concurren_region_test', $this->region->getName()); + self::assertEquals('concurren_region_test', $this->region->getName()); } public function testLockAndUnlock() @@ -70,22 +72,22 @@ public function testLockAndUnlock() $entry = new CacheEntryMock(['foo' => 'bar']); $file = $this->getFileName($this->region, $key); - $this->assertFalse($this->region->contains($key)); - $this->assertTrue($this->region->put($key, $entry)); - $this->assertTrue($this->region->contains($key)); + self::assertFalse($this->region->contains($key)); + self::assertTrue($this->region->put($key, $entry)); + self::assertTrue($this->region->contains($key)); $lock = $this->region->lock($key); - $this->assertFileExists($file); - $this->assertInstanceOf(Lock::class, $lock); - $this->assertEquals($lock->value, file_get_contents($file)); + self::assertFileExists($file); + self::assertInstanceOf(Lock::class, $lock); + self::assertEquals($lock->value, file_get_contents($file)); // should be not available after lock - $this->assertFalse($this->region->contains($key)); - $this->assertNull($this->region->get($key)); + self::assertFalse($this->region->contains($key)); + self::assertNull($this->region->get($key)); - $this->assertTrue($this->region->unlock($key, $lock)); - $this->assertFileNotExists($file); + self::assertTrue($this->region->unlock($key, $lock)); + self::assertFileNotExists($file); } public function testLockWithExistingLock() @@ -94,21 +96,21 @@ public function testLockWithExistingLock() $entry = new CacheEntryMock(['foo' => 'bar']); $file = $this->getFileName($this->region, $key); - $this->assertFalse($this->region->contains($key)); - $this->assertTrue($this->region->put($key, $entry)); - $this->assertTrue($this->region->contains($key)); + self::assertFalse($this->region->contains($key)); + self::assertTrue($this->region->put($key, $entry)); + self::assertTrue($this->region->contains($key)); file_put_contents($file, 'foo'); - $this->assertFileExists($file); - $this->assertEquals('foo' , file_get_contents($file)); + self::assertFileExists($file); + self::assertEquals('foo' , file_get_contents($file)); - $this->assertNull($this->region->lock($key)); - $this->assertEquals('foo' , file_get_contents($file)); - $this->assertFileExists($file); + self::assertNull($this->region->lock($key)); + self::assertEquals('foo' , file_get_contents($file)); + self::assertFileExists($file); // should be not available - $this->assertFalse($this->region->contains($key)); - $this->assertNull($this->region->get($key)); + self::assertFalse($this->region->contains($key)); + self::assertNull($this->region->get($key)); } public function testUnlockWithExistingLock() @@ -117,27 +119,27 @@ public function testUnlockWithExistingLock() $entry = new CacheEntryMock(['foo' => 'bar']); $file = $this->getFileName($this->region, $key); - $this->assertFalse($this->region->contains($key)); - $this->assertTrue($this->region->put($key, $entry)); - $this->assertTrue($this->region->contains($key)); + self::assertFalse($this->region->contains($key)); + self::assertTrue($this->region->put($key, $entry)); + self::assertTrue($this->region->contains($key)); - $this->assertInstanceOf(Lock::class, $lock = $this->region->lock($key)); - $this->assertEquals($lock->value, file_get_contents($file)); - $this->assertFileExists($file); + self::assertInstanceOf(Lock::class, $lock = $this->region->lock($key)); + self::assertEquals($lock->value, file_get_contents($file)); + self::assertFileExists($file); // change the lock file_put_contents($file, 'foo'); - $this->assertFileExists($file); - $this->assertEquals('foo' , file_get_contents($file)); + self::assertFileExists($file); + self::assertEquals('foo' , file_get_contents($file)); //try to unlock - $this->assertFalse($this->region->unlock($key, $lock)); - $this->assertEquals('foo' , file_get_contents($file)); - $this->assertFileExists($file); + self::assertFalse($this->region->unlock($key, $lock)); + self::assertEquals('foo' , file_get_contents($file)); + self::assertFileExists($file); // should be not available - $this->assertFalse($this->region->contains($key)); - $this->assertNull($this->region->get($key)); + self::assertFalse($this->region->contains($key)); + self::assertNull($this->region->get($key)); } public function testPutWithExistingLock() @@ -146,21 +148,21 @@ public function testPutWithExistingLock() $entry = new CacheEntryMock(['foo' => 'bar']); $file = $this->getFileName($this->region, $key); - $this->assertFalse($this->region->contains($key)); - $this->assertTrue($this->region->put($key, $entry)); - $this->assertTrue($this->region->contains($key)); + self::assertFalse($this->region->contains($key)); + self::assertTrue($this->region->put($key, $entry)); + self::assertTrue($this->region->contains($key)); // create lock file_put_contents($file, 'foo'); - $this->assertFileExists($file); - $this->assertEquals('foo' , file_get_contents($file)); + self::assertFileExists($file); + self::assertEquals('foo' , file_get_contents($file)); - $this->assertFalse($this->region->contains($key)); - $this->assertFalse($this->region->put($key, $entry)); - $this->assertFalse($this->region->contains($key)); + self::assertFalse($this->region->contains($key)); + self::assertFalse($this->region->put($key, $entry)); + self::assertFalse($this->region->contains($key)); - $this->assertFileExists($file); - $this->assertEquals('foo' , file_get_contents($file)); + self::assertFileExists($file); + self::assertEquals('foo' , file_get_contents($file)); } public function testLockedEvict() @@ -169,18 +171,18 @@ public function testLockedEvict() $entry = new CacheEntryMock(['foo' => 'bar']); $file = $this->getFileName($this->region, $key); - $this->assertFalse($this->region->contains($key)); - $this->assertTrue($this->region->put($key, $entry)); - $this->assertTrue($this->region->contains($key)); + self::assertFalse($this->region->contains($key)); + self::assertTrue($this->region->put($key, $entry)); + self::assertTrue($this->region->contains($key)); - $this->assertInstanceOf(Lock::class, $lock = $this->region->lock($key)); - $this->assertEquals($lock->value, file_get_contents($file)); - $this->assertFileExists($file); + self::assertInstanceOf(Lock::class, $lock = $this->region->lock($key)); + self::assertEquals($lock->value, file_get_contents($file)); + self::assertFileExists($file); - $this->assertFalse($this->region->contains($key)); - $this->assertTrue($this->region->evict($key)); - $this->assertFalse($this->region->contains($key)); - $this->assertFileNotExists($file); + self::assertFalse($this->region->contains($key)); + self::assertTrue($this->region->evict($key)); + self::assertFalse($this->region->contains($key)); + self::assertFileNotExists($file); } public function testLockedEvictAll() @@ -193,30 +195,30 @@ public function testLockedEvictAll() $entry2 = new CacheEntryMock(['foo2' => 'bar2']); $file2 = $this->getFileName($this->region, $key2); - $this->assertFalse($this->region->contains($key1)); - $this->assertTrue($this->region->put($key1, $entry1)); - $this->assertTrue($this->region->contains($key1)); + self::assertFalse($this->region->contains($key1)); + self::assertTrue($this->region->put($key1, $entry1)); + self::assertTrue($this->region->contains($key1)); - $this->assertFalse($this->region->contains($key2)); - $this->assertTrue($this->region->put($key2, $entry2)); - $this->assertTrue($this->region->contains($key2)); + self::assertFalse($this->region->contains($key2)); + self::assertTrue($this->region->put($key2, $entry2)); + self::assertTrue($this->region->contains($key2)); - $this->assertInstanceOf(Lock::class, $lock1 = $this->region->lock($key1)); - $this->assertInstanceOf(Lock::class, $lock2 = $this->region->lock($key2)); + self::assertInstanceOf(Lock::class, $lock1 = $this->region->lock($key1)); + self::assertInstanceOf(Lock::class, $lock2 = $this->region->lock($key2)); - $this->assertEquals($lock2->value, file_get_contents($file2)); - $this->assertEquals($lock1->value, file_get_contents($file1)); + self::assertEquals($lock2->value, file_get_contents($file2)); + self::assertEquals($lock1->value, file_get_contents($file1)); - $this->assertFileExists($file1); - $this->assertFileExists($file2); + self::assertFileExists($file1); + self::assertFileExists($file2); - $this->assertTrue($this->region->evictAll()); + self::assertTrue($this->region->evictAll()); - $this->assertFileNotExists($file1); - $this->assertFileNotExists($file2); + self::assertFileNotExists($file1); + self::assertFileNotExists($file2); - $this->assertFalse($this->region->contains($key1)); - $this->assertFalse($this->region->contains($key2)); + self::assertFalse($this->region->contains($key1)); + self::assertFalse($this->region->contains($key2)); } public function testLockLifetime() @@ -229,18 +231,18 @@ public function testLockLifetime() $property->setAccessible(true); $property->setValue($this->region, -10); - $this->assertFalse($this->region->contains($key)); - $this->assertTrue($this->region->put($key, $entry)); - $this->assertTrue($this->region->contains($key)); + self::assertFalse($this->region->contains($key)); + self::assertTrue($this->region->put($key, $entry)); + self::assertTrue($this->region->contains($key)); - $this->assertInstanceOf(Lock::class, $lock = $this->region->lock($key)); - $this->assertEquals($lock->value, file_get_contents($file)); - $this->assertFileExists($file); + self::assertInstanceOf(Lock::class, $lock = $this->region->lock($key)); + self::assertEquals($lock->value, file_get_contents($file)); + self::assertFileExists($file); // outdated lock should be removed - $this->assertTrue($this->region->contains($key)); - $this->assertNotNull($this->region->get($key)); - $this->assertFileNotExists($file); + self::assertTrue($this->region->contains($key)); + self::assertNotNull($this->region->get($key)); + self::assertFileNotExists($file); } /** @@ -256,7 +258,7 @@ public function testHandlesScanErrorsGracefullyOnEvictAll() $reflectionDirectory->setValue($region, str_repeat('a', 10000)); set_error_handler(function () {}, E_WARNING); - $this->assertTrue($region->evictAll()); + self::assertTrue($region->evictAll()); restore_error_handler(); } @@ -279,7 +281,7 @@ private function cleanTestDirectory($path) foreach ($directoryIterator as $file) { if ($file->isFile()) { @unlink($file->getRealPath()); - } else { + } elseif ($file->getRealPath() !== false) { @rmdir($file->getRealPath()); } } diff --git a/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php b/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php index 0d98665d0d0..2b8453f82c6 100644 --- a/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php @@ -1,5 +1,7 @@ 2, 'name' => 'bar']); - $this->assertFalse($this->region->contains($key1)); - $this->assertFalse($this->region->contains($key2)); + self::assertFalse($this->region->contains($key1)); + self::assertFalse($this->region->contains($key2)); $this->region->put($key1, $value1); $this->region->put($key2, $value2); - $this->assertTrue($this->region->contains($key1)); - $this->assertTrue($this->region->contains($key2)); + self::assertTrue($this->region->contains($key1)); + self::assertTrue($this->region->contains($key2)); $actual = $this->region->getMultiple(new CollectionCacheEntry([$key1, $key2])); - $this->assertEquals($value1, $actual[0]); - $this->assertEquals($value2, $actual[1]); + self::assertEquals($value1, $actual[0]); + self::assertEquals($value2, $actual[1]); } } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/AbstractCollectionPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/AbstractCollectionPersisterTest.php index c950cea70df..0d0ab0623fa 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/AbstractCollectionPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/AbstractCollectionPersisterTest.php @@ -1,18 +1,20 @@ enableSecondLevelCache(); parent::setUp(); - $this->em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); $this->region = $this->createRegion(); $this->collectionPersister = $this->getMockBuilder(CollectionPersister::class) ->setMethods($this->collectionPersisterMockMethods) @@ -104,7 +111,7 @@ protected function createCollection($owner, $assoc = null, $class = null, $eleme { $em = $this->em; $class = $class ?: $this->em->getClassMetadata(State::class); - $assoc = $assoc ?: $class->associationMappings['cities']; + $assoc = $assoc ?: $class->getProperty('cities'); $coll = new PersistentCollection($em, $class, $elements ?: new ArrayCollection); $coll->setOwner($owner, $assoc); @@ -115,7 +122,7 @@ protected function createCollection($owner, $assoc = null, $class = null, $eleme protected function createPersisterDefault() { - $assoc = $this->em->getClassMetadata(State::class)->associationMappings['cities']; + $assoc = $this->em->getClassMetadata(State::class)->getProperty('cities'); return $this->createPersister($this->em, $this->collectionPersister, $this->region, $assoc); } @@ -124,9 +131,9 @@ public function testImplementsEntityPersister() { $persister = $this->createPersisterDefault(); - $this->assertInstanceOf(CollectionPersister::class, $persister); - $this->assertInstanceOf(CachedPersister::class, $persister); - $this->assertInstanceOf(CachedCollectionPersister::class, $persister); + self::assertInstanceOf(CollectionPersister::class, $persister); + self::assertInstanceOf(CachedPersister::class, $persister); + self::assertInstanceOf(CachedCollectionPersister::class, $persister); } public function testInvokeDelete() @@ -141,7 +148,7 @@ public function testInvokeDelete() ->method('delete') ->with($this->equalTo($collection)); - $this->assertNull($persister->delete($collection)); + self::assertNull($persister->delete($collection)); } public function testInvokeUpdate() @@ -158,7 +165,7 @@ public function testInvokeUpdate() ->method('update') ->with($this->equalTo($collection)); - $this->assertNull($persister->update($collection)); + self::assertNull($persister->update($collection)); } public function testInvokeCount() @@ -174,7 +181,7 @@ public function testInvokeCount() ->with($this->equalTo($collection)) ->will($this->returnValue(0)); - $this->assertEquals(0, $persister->count($collection)); + self::assertEquals(0, $persister->count($collection)); } public function testInvokeSlice() @@ -191,7 +198,7 @@ public function testInvokeSlice() ->with($this->equalTo($collection), $this->equalTo(1), $this->equalTo(2)) ->will($this->returnValue($slice)); - $this->assertEquals($slice, $persister->slice($collection, 1 , 2)); + self::assertEquals($slice, $persister->slice($collection, 1 , 2)); } public function testInvokeContains() @@ -208,7 +215,7 @@ public function testInvokeContains() ->with($this->equalTo($collection), $this->equalTo($element)) ->will($this->returnValue(false)); - $this->assertFalse($persister->contains($collection,$element)); + self::assertFalse($persister->contains($collection,$element)); } public function testInvokeContainsKey() @@ -224,7 +231,7 @@ public function testInvokeContainsKey() ->with($this->equalTo($collection), $this->equalTo(0)) ->will($this->returnValue(false)); - $this->assertFalse($persister->containsKey($collection, 0)); + self::assertFalse($persister->containsKey($collection, 0)); } public function testInvokeRemoveElement() @@ -241,7 +248,7 @@ public function testInvokeRemoveElement() ->with($this->equalTo($collection), $this->equalTo($element)) ->will($this->returnValue(false)); - $this->assertFalse($persister->removeElement($collection, $element)); + self::assertFalse($persister->removeElement($collection, $element)); } public function testInvokeGet() @@ -258,6 +265,6 @@ public function testInvokeGet() ->with($this->equalTo($collection), $this->equalTo(0)) ->will($this->returnValue($element)); - $this->assertEquals($element, $persister->get($collection, 0)); + self::assertEquals($element, $persister->get($collection, 0)); } } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersisterTest.php index bd65c20777f..11df2ee4842 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersisterTest.php @@ -1,9 +1,12 @@ delete($collection); - $this->assertCount(1, $property->getValue($persister)); + self::assertCount(1, $property->getValue($persister)); $persister->afterTransactionRolledBack(); - $this->assertCount(0, $property->getValue($persister)); + self::assertCount(0, $property->getValue($persister)); } public function testTransactionRollBackUpdateShouldClearQueue() @@ -184,11 +192,11 @@ public function testTransactionRollBackUpdateShouldClearQueue() $persister->update($collection); - $this->assertCount(1, $property->getValue($persister)); + self::assertCount(1, $property->getValue($persister)); $persister->afterTransactionRolledBack(); - $this->assertCount(0, $property->getValue($persister)); + self::assertCount(0, $property->getValue($persister)); } public function testTransactionRollCommitDeleteShouldClearQueue() @@ -215,11 +223,11 @@ public function testTransactionRollCommitDeleteShouldClearQueue() $persister->delete($collection); - $this->assertCount(1, $property->getValue($persister)); + self::assertCount(1, $property->getValue($persister)); $persister->afterTransactionComplete(); - $this->assertCount(0, $property->getValue($persister)); + self::assertCount(0, $property->getValue($persister)); } public function testTransactionRollCommitUpdateShouldClearQueue() @@ -246,11 +254,11 @@ public function testTransactionRollCommitUpdateShouldClearQueue() $persister->update($collection); - $this->assertCount(1, $property->getValue($persister)); + self::assertCount(1, $property->getValue($persister)); $persister->afterTransactionComplete(); - $this->assertCount(0, $property->getValue($persister)); + self::assertCount(0, $property->getValue($persister)); } public function testDeleteLockFailureShouldIgnoreQueue() @@ -275,7 +283,7 @@ public function testDeleteLockFailureShouldIgnoreQueue() $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->delete($collection); - $this->assertCount(0, $property->getValue($persister)); + self::assertCount(0, $property->getValue($persister)); } public function testUpdateLockFailureShouldIgnoreQueue() @@ -300,6 +308,6 @@ public function testUpdateLockFailureShouldIgnoreQueue() $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->update($collection); - $this->assertCount(0, $property->getValue($persister)); + self::assertCount(0, $property->getValue($persister)); } } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php index 09c7221f522..8d472a7f4a3 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php @@ -1,5 +1,7 @@ getSharedSecondLevelCacheDriverImpl()->flushAll(); $this->enableSecondLevelCache(); + parent::setUp(); - $this->em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); $this->region = $this->createRegion(); $this->entityPersister = $this->getMockBuilder(EntityPersister::class) ->setMethods($this->entityPersisterMockMethods) @@ -115,7 +122,7 @@ protected function createRegion() } /** - * @return \Doctrine\ORM\Cache\Persister\AbstractEntityPersister + * @return \Doctrine\ORM\Cache\Persister\Entity\AbstractEntityPersister */ protected function createPersisterDefault() { @@ -126,49 +133,24 @@ public function testImplementsEntityPersister() { $persister = $this->createPersisterDefault(); - $this->assertInstanceOf(EntityPersister::class, $persister); - $this->assertInstanceOf(CachedPersister::class, $persister); - $this->assertInstanceOf(CachedEntityPersister::class, $persister); - } - - public function testInvokeAddInsert() - { - $persister = $this->createPersisterDefault(); - $entity = new Country("Foo"); - - $this->entityPersister->expects($this->once()) - ->method('addInsert') - ->with($this->equalTo($entity)); - - $this->assertNull($persister->addInsert($entity)); - } - - public function testInvokeGetInserts() - { - $persister = $this->createPersisterDefault(); - $entity = new Country("Foo"); - - $this->entityPersister->expects($this->once()) - ->method('getInserts') - ->will($this->returnValue([$entity])); - - $this->assertEquals([$entity], $persister->getInserts()); + self::assertInstanceOf(EntityPersister::class, $persister); + self::assertInstanceOf(CachedPersister::class, $persister); + self::assertInstanceOf(CachedEntityPersister::class, $persister); } public function testInvokeGetSelectSQL() { $persister = $this->createPersisterDefault(); + $assoc = new OneToManyAssociationMetadata('name'); $this->entityPersister->expects($this->once()) ->method('getSelectSQL') - ->with($this->equalTo(['name'=>'Foo']), $this->equalTo([0]), $this->equalTo(1), $this->equalTo(2), $this->equalTo(3), $this->equalTo( + ->with($this->equalTo(['name'=>'Foo']), $this->equalTo($assoc), $this->equalTo(1), $this->equalTo(2), $this->equalTo(3), $this->equalTo( [4] )) ->will($this->returnValue('SELECT * FROM foo WERE name = ?')); - $this->assertEquals('SELECT * FROM foo WERE name = ?', $persister->getSelectSQL( - ['name'=>'Foo'], [0], 1, 2, 3, [4] - )); + self::assertEquals('SELECT * FROM foo WERE name = ?', $persister->getSelectSQL(['name'=>'Foo'], $assoc, 1, 2, 3, [4])); } public function testInvokeGetInsertSQL() @@ -179,7 +161,7 @@ public function testInvokeGetInsertSQL() ->method('getInsertSQL') ->will($this->returnValue('INSERT INTO foo (?)')); - $this->assertEquals('INSERT INTO foo (?)', $persister->getInsertSQL()); + self::assertEquals('INSERT INTO foo (?)', $persister->getInsertSQL()); } public function testInvokeExpandParameters() @@ -191,7 +173,7 @@ public function testInvokeExpandParameters() ->with($this->equalTo(['name'=>'Foo'])) ->will($this->returnValue(['name'=>'Foo'])); - $this->assertEquals(['name'=>'Foo'], $persister->expandParameters(['name'=>'Foo'])); + self::assertEquals(['name'=>'Foo'], $persister->expandParameters(['name'=>'Foo'])); } public function testInvokeExpandCriteriaParameters() @@ -204,30 +186,32 @@ public function testInvokeExpandCriteriaParameters() ->with($this->equalTo($criteria)) ->will($this->returnValue(['name'=>'Foo'])); - $this->assertEquals(['name'=>'Foo'], $persister->expandCriteriaParameters($criteria)); + self::assertEquals(['name'=>'Foo'], $persister->expandCriteriaParameters($criteria)); } public function testInvokeSelectConditionStatementSQL() { $persister = $this->createPersisterDefault(); + $assoc = new OneToOneAssociationMetadata('id'); $this->entityPersister->expects($this->once()) ->method('getSelectConditionStatementSQL') - ->with($this->equalTo('id'), $this->equalTo(1), $this->equalTo([]), $this->equalTo('=')) + ->with($this->equalTo('id'), $this->equalTo(1), $this->equalTo($assoc), $this->equalTo('=')) ->will($this->returnValue('name = 1')); - $this->assertEquals('name = 1', $persister->getSelectConditionStatementSQL('id', 1, [], '=')); + self::assertEquals('name = 1', $persister->getSelectConditionStatementSQL('id', 1, $assoc, '=')); } - public function testInvokeExecuteInserts() + public function testInvokeInsert() { $persister = $this->createPersisterDefault(); + $entity = new Country("Foo"); $this->entityPersister->expects($this->once()) - ->method('executeInserts') - ->will($this->returnValue(['id' => 1])); + ->method('insert') + ->with($this->equalTo($entity)); - $this->assertEquals(['id' => 1], $persister->executeInserts()); + self::assertNull($persister->insert($entity)); } public function testInvokeUpdate() @@ -241,7 +225,7 @@ public function testInvokeUpdate() $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); - $this->assertNull($persister->update($entity)); + self::assertNull($persister->update($entity)); } public function testInvokeDelete() @@ -255,7 +239,7 @@ public function testInvokeDelete() $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); - $this->assertNull($persister->delete($entity)); + self::assertNull($persister->delete($entity)); } public function testInvokeGetOwningTable() @@ -267,24 +251,29 @@ public function testInvokeGetOwningTable() ->with($this->equalTo('name')) ->will($this->returnValue('t')); - $this->assertEquals('t', $persister->getOwningTable('name')); + self::assertEquals('t', $persister->getOwningTable('name')); } public function testInvokeLoad() { $persister = $this->createPersisterDefault(); + $assoc = new OneToOneAssociationMetadata('id'); $entity = new Country("Foo"); $this->entityPersister->expects($this->once()) ->method('load') - ->with($this->equalTo(['id' => 1]), $this->equalTo($entity), $this->equalTo([0]), $this->equalTo( - [1] - ), $this->equalTo(2), $this->equalTo(3), $this->equalTo( - [4] - )) + ->with( + $this->equalTo(['id' => 1]), + $this->equalTo($entity), + $this->equalTo($assoc), + $this->equalTo([1]), + $this->equalTo(2), + $this->equalTo(3), + $this->equalTo([4]) + ) ->will($this->returnValue($entity)); - $this->assertEquals($entity, $persister->load(['id' => 1], $entity, [0], [1], 2, 3, [4])); + self::assertEquals($entity, $persister->load(['id' => 1], $entity, $assoc, [1], 2, 3, [4])); } public function testInvokeLoadAll() @@ -306,7 +295,7 @@ public function testInvokeLoadAll() ->method('getResultSetMapping') ->will($this->returnValue($rsm)); - $this->assertEquals([$entity], $persister->loadAll(['id' => 1], [0], 1, 2)); + self::assertEquals([$entity], $persister->loadAll(['id' => 1], [0], 1, 2)); } public function testInvokeLoadById() @@ -319,20 +308,21 @@ public function testInvokeLoadById() ->with($this->equalTo(['id' => 1]), $this->equalTo($entity)) ->will($this->returnValue($entity)); - $this->assertEquals($entity, $persister->loadById(['id' => 1], $entity)); + self::assertEquals($entity, $persister->loadById(['id' => 1], $entity)); } - public function testInvokeLoadOneToOneEntity() + public function testInvokeLoadToOneEntity() { $persister = $this->createPersisterDefault(); + $assoc = new OneToOneAssociationMetadata('name'); $entity = new Country("Foo"); $this->entityPersister->expects($this->once()) - ->method('loadOneToOneEntity') - ->with($this->equalTo([]), $this->equalTo('foo'), $this->equalTo(['id' => 11])) + ->method('loadToOneEntity') + ->with($this->equalTo($assoc), $this->equalTo('foo'), $this->equalTo(['id' => 11])) ->will($this->returnValue($entity)); - $this->assertEquals($entity, $persister->loadOneToOneEntity([], 'foo', ['id' => 11])); + self::assertEquals($entity, $persister->loadToOneEntity($assoc, 'foo', ['id' => 11])); } public function testInvokeRefresh() @@ -345,7 +335,7 @@ public function testInvokeRefresh() ->with($this->equalTo(['id' => 1]), $this->equalTo($entity), $this->equalTo(0)) ->will($this->returnValue($entity)); - $this->assertNull($persister->refresh(['id' => 1], $entity), 0); + self::assertNull($persister->refresh(['id' => 1], $entity), 0); } public function testInvokeLoadCriteria() @@ -367,39 +357,41 @@ public function testInvokeLoadCriteria() ->with($this->equalTo($criteria)) ->will($this->returnValue([$entity])); - $this->assertEquals([$entity], $persister->loadCriteria($criteria)); + self::assertEquals([$entity], $persister->loadCriteria($criteria)); } public function testInvokeGetManyToManyCollection() { $persister = $this->createPersisterDefault(); + $assoc = new ManyToManyAssociationMetadata('name'); $entity = new Country("Foo"); $this->entityPersister->expects($this->once()) ->method('getManyToManyCollection') - ->with($this->equalTo([]), $this->equalTo('Foo'), $this->equalTo(1), $this->equalTo(2)) + ->with($this->equalTo($assoc), $this->equalTo('Foo'), $this->equalTo(1), $this->equalTo(2)) ->will($this->returnValue([$entity])); - $this->assertEquals([$entity], $persister->getManyToManyCollection([], 'Foo', 1 ,2)); + self::assertEquals([$entity], $persister->getManyToManyCollection($assoc, 'Foo', 1 ,2)); } public function testInvokeGetOneToManyCollection() { $persister = $this->createPersisterDefault(); + $assoc = new OneToManyAssociationMetadata('name'); $entity = new Country("Foo"); $this->entityPersister->expects($this->once()) ->method('getOneToManyCollection') - ->with($this->equalTo([]), $this->equalTo('Foo'), $this->equalTo(1), $this->equalTo(2)) + ->with($this->equalTo($assoc), $this->equalTo('Foo'), $this->equalTo(1), $this->equalTo(2)) ->will($this->returnValue([$entity])); - $this->assertEquals([$entity], $persister->getOneToManyCollection([], 'Foo', 1 ,2)); + self::assertEquals([$entity], $persister->getOneToManyCollection($assoc, 'Foo', 1 ,2)); } public function testInvokeLoadManyToManyCollection() { $mapping = $this->em->getClassMetadata(Country::class); - $assoc = ['type' => 1]; + $assoc = new ManyToManyAssociationMetadata('name'); $coll = new PersistentCollection($this->em, $mapping, new ArrayCollection()); $persister = $this->createPersisterDefault(); $entity = new Country("Foo"); @@ -409,13 +401,13 @@ public function testInvokeLoadManyToManyCollection() ->with($this->equalTo($assoc), $this->equalTo('Foo'), $coll) ->will($this->returnValue([$entity])); - $this->assertEquals([$entity], $persister->loadManyToManyCollection($assoc, 'Foo', $coll)); + self::assertEquals([$entity], $persister->loadManyToManyCollection($assoc, 'Foo', $coll)); } public function testInvokeLoadOneToManyCollection() { $mapping = $this->em->getClassMetadata(Country::class); - $assoc = ['type' => 1]; + $assoc = new OneToManyAssociationMetadata('name'); $coll = new PersistentCollection($this->em, $mapping, new ArrayCollection()); $persister = $this->createPersisterDefault(); $entity = new Country("Foo"); @@ -425,7 +417,7 @@ public function testInvokeLoadOneToManyCollection() ->with($this->equalTo($assoc), $this->equalTo('Foo'), $coll) ->will($this->returnValue([$entity])); - $this->assertEquals([$entity], $persister->loadOneToManyCollection($assoc, 'Foo', $coll)); + self::assertEquals([$entity], $persister->loadOneToManyCollection($assoc, 'Foo', $coll)); } public function testInvokeLock() @@ -437,7 +429,7 @@ public function testInvokeLock() ->method('lock') ->with($this->equalTo($identifier), $this->equalTo(1)); - $this->assertNull($persister->lock($identifier, 1)); + self::assertNull($persister->lock($identifier, 1)); } public function testInvokeExists() @@ -449,6 +441,6 @@ public function testInvokeExists() ->method('exists') ->with($this->equalTo($entity), $this->equalTo(null)); - $this->assertNull($persister->exists($entity)); + self::assertNull($persister->exists($entity)); } } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php index 0f1e67b0f63..b86d802c963 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php @@ -1,12 +1,14 @@ update($entity); $persister->delete($entity); - $this->assertCount(2, $property->getValue($persister)); + self::assertCount(2, $property->getValue($persister)); $persister->afterTransactionRolledBack(); - $this->assertCount(0, $property->getValue($persister)); + self::assertCount(0, $property->getValue($persister)); } public function testInsertTransactionCommitShouldPutCache() @@ -59,26 +61,18 @@ public function testInsertTransactionCommitShouldPutCache() ->with($this->equalTo($key), $this->equalTo($entry)); $this->entityPersister->expects($this->once()) - ->method('addInsert') + ->method('insert') ->with($this->equalTo($entity)); - $this->entityPersister->expects($this->once()) - ->method('getInserts') - ->will($this->returnValue([$entity])); - - $this->entityPersister->expects($this->once()) - ->method('executeInserts'); - $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); - $persister->addInsert($entity); - $persister->executeInserts(); + $persister->insert($entity); - $this->assertCount(1, $property->getValue($persister)); + self::assertCount(1, $property->getValue($persister)); $persister->afterTransactionComplete(); - $this->assertCount(0, $property->getValue($persister)); + self::assertCount(0, $property->getValue($persister)); } public function testUpdateTransactionCommitShouldPutCache() @@ -103,11 +97,11 @@ public function testUpdateTransactionCommitShouldPutCache() $persister->update($entity); - $this->assertCount(1, $property->getValue($persister)); + self::assertCount(1, $property->getValue($persister)); $persister->afterTransactionComplete(); - $this->assertCount(0, $property->getValue($persister)); + self::assertCount(0, $property->getValue($persister)); } public function testDeleteTransactionCommitShouldEvictCache() @@ -131,10 +125,10 @@ public function testDeleteTransactionCommitShouldEvictCache() $persister->delete($entity); - $this->assertCount(1, $property->getValue($persister)); + self::assertCount(1, $property->getValue($persister)); $persister->afterTransactionComplete(); - $this->assertCount(0, $property->getValue($persister)); + self::assertCount(0, $property->getValue($persister)); } } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersisterTest.php index 716ea15cbdd..f1fbc0541b4 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadOnlyCachedEntityPersisterTest.php @@ -1,9 +1,11 @@ update($entity); $persister->delete($entity); - $this->assertCount(2, $property->getValue($persister)); + self::assertCount(2, $property->getValue($persister)); $persister->afterTransactionRolledBack(); - $this->assertCount(0, $property->getValue($persister)); + self::assertCount(0, $property->getValue($persister)); } public function testTransactionCommitShouldClearQueue() @@ -181,11 +183,11 @@ public function testTransactionCommitShouldClearQueue() $persister->update($entity); $persister->delete($entity); - $this->assertCount(2, $property->getValue($persister)); + self::assertCount(2, $property->getValue($persister)); $persister->afterTransactionComplete(); - $this->assertCount(0, $property->getValue($persister)); + self::assertCount(0, $property->getValue($persister)); } public function testDeleteLockFailureShouldIgnoreQueue() @@ -209,7 +211,7 @@ public function testDeleteLockFailureShouldIgnoreQueue() $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->delete($entity); - $this->assertCount(0, $property->getValue($persister)); + self::assertCount(0, $property->getValue($persister)); } public function testUpdateLockFailureShouldIgnoreQueue() @@ -233,6 +235,6 @@ public function testUpdateLockFailureShouldIgnoreQueue() $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->update($entity); - $this->assertCount(0, $property->getValue($persister)); + self::assertCount(0, $property->getValue($persister)); } } diff --git a/tests/Doctrine/Tests/ORM/Cache/StatisticsCacheLoggerTest.php b/tests/Doctrine/Tests/ORM/Cache/StatisticsCacheLoggerTest.php index e9f04f350ed..d4abf8ec546 100644 --- a/tests/Doctrine/Tests/ORM/Cache/StatisticsCacheLoggerTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/StatisticsCacheLoggerTest.php @@ -1,5 +1,7 @@ logger->entityCachePut($name, $key); $this->logger->entityCacheMiss($name, $key); - $this->assertEquals(1, $this->logger->getHitCount()); - $this->assertEquals(1, $this->logger->getPutCount()); - $this->assertEquals(1, $this->logger->getMissCount()); - $this->assertEquals(1, $this->logger->getRegionHitCount($name)); - $this->assertEquals(1, $this->logger->getRegionPutCount($name)); - $this->assertEquals(1, $this->logger->getRegionMissCount($name)); + self::assertEquals(1, $this->logger->getHitCount()); + self::assertEquals(1, $this->logger->getPutCount()); + self::assertEquals(1, $this->logger->getMissCount()); + self::assertEquals(1, $this->logger->getRegionHitCount($name)); + self::assertEquals(1, $this->logger->getRegionPutCount($name)); + self::assertEquals(1, $this->logger->getRegionMissCount($name)); } public function testCollectionCache() @@ -52,12 +54,12 @@ public function testCollectionCache() $this->logger->collectionCachePut($name, $key); $this->logger->collectionCacheMiss($name, $key); - $this->assertEquals(1, $this->logger->getHitCount()); - $this->assertEquals(1, $this->logger->getPutCount()); - $this->assertEquals(1, $this->logger->getMissCount()); - $this->assertEquals(1, $this->logger->getRegionHitCount($name)); - $this->assertEquals(1, $this->logger->getRegionPutCount($name)); - $this->assertEquals(1, $this->logger->getRegionMissCount($name)); + self::assertEquals(1, $this->logger->getHitCount()); + self::assertEquals(1, $this->logger->getPutCount()); + self::assertEquals(1, $this->logger->getMissCount()); + self::assertEquals(1, $this->logger->getRegionHitCount($name)); + self::assertEquals(1, $this->logger->getRegionPutCount($name)); + self::assertEquals(1, $this->logger->getRegionMissCount($name)); } public function testQueryCache() @@ -69,12 +71,12 @@ public function testQueryCache() $this->logger->queryCachePut($name, $key); $this->logger->queryCacheMiss($name, $key); - $this->assertEquals(1, $this->logger->getHitCount()); - $this->assertEquals(1, $this->logger->getPutCount()); - $this->assertEquals(1, $this->logger->getMissCount()); - $this->assertEquals(1, $this->logger->getRegionHitCount($name)); - $this->assertEquals(1, $this->logger->getRegionPutCount($name)); - $this->assertEquals(1, $this->logger->getRegionMissCount($name)); + self::assertEquals(1, $this->logger->getHitCount()); + self::assertEquals(1, $this->logger->getPutCount()); + self::assertEquals(1, $this->logger->getMissCount()); + self::assertEquals(1, $this->logger->getRegionHitCount($name)); + self::assertEquals(1, $this->logger->getRegionPutCount($name)); + self::assertEquals(1, $this->logger->getRegionMissCount($name)); } public function testMultipleCaches() @@ -99,36 +101,36 @@ public function testMultipleCaches() $this->logger->collectionCachePut($coolRegion, $coolKey); $this->logger->collectionCacheMiss($coolRegion, $coolKey); - $this->assertEquals(3, $this->logger->getHitCount()); - $this->assertEquals(3, $this->logger->getPutCount()); - $this->assertEquals(3, $this->logger->getMissCount()); + self::assertEquals(3, $this->logger->getHitCount()); + self::assertEquals(3, $this->logger->getPutCount()); + self::assertEquals(3, $this->logger->getMissCount()); - $this->assertEquals(1, $this->logger->getRegionHitCount($queryRegion)); - $this->assertEquals(1, $this->logger->getRegionPutCount($queryRegion)); - $this->assertEquals(1, $this->logger->getRegionMissCount($queryRegion)); + self::assertEquals(1, $this->logger->getRegionHitCount($queryRegion)); + self::assertEquals(1, $this->logger->getRegionPutCount($queryRegion)); + self::assertEquals(1, $this->logger->getRegionMissCount($queryRegion)); - $this->assertEquals(1, $this->logger->getRegionHitCount($coolRegion)); - $this->assertEquals(1, $this->logger->getRegionPutCount($coolRegion)); - $this->assertEquals(1, $this->logger->getRegionMissCount($coolRegion)); + self::assertEquals(1, $this->logger->getRegionHitCount($coolRegion)); + self::assertEquals(1, $this->logger->getRegionPutCount($coolRegion)); + self::assertEquals(1, $this->logger->getRegionMissCount($coolRegion)); - $this->assertEquals(1, $this->logger->getRegionHitCount($entityRegion)); - $this->assertEquals(1, $this->logger->getRegionPutCount($entityRegion)); - $this->assertEquals(1, $this->logger->getRegionMissCount($entityRegion)); + self::assertEquals(1, $this->logger->getRegionHitCount($entityRegion)); + self::assertEquals(1, $this->logger->getRegionPutCount($entityRegion)); + self::assertEquals(1, $this->logger->getRegionMissCount($entityRegion)); $miss = $this->logger->getRegionsMiss(); $hit = $this->logger->getRegionsHit(); $put = $this->logger->getRegionsPut(); - $this->assertArrayHasKey($coolRegion, $miss); - $this->assertArrayHasKey($queryRegion, $miss); - $this->assertArrayHasKey($entityRegion, $miss); + self::assertArrayHasKey($coolRegion, $miss); + self::assertArrayHasKey($queryRegion, $miss); + self::assertArrayHasKey($entityRegion, $miss); - $this->assertArrayHasKey($coolRegion, $put); - $this->assertArrayHasKey($queryRegion, $put); - $this->assertArrayHasKey($entityRegion, $put); + self::assertArrayHasKey($coolRegion, $put); + self::assertArrayHasKey($queryRegion, $put); + self::assertArrayHasKey($entityRegion, $put); - $this->assertArrayHasKey($coolRegion, $hit); - $this->assertArrayHasKey($queryRegion, $hit); - $this->assertArrayHasKey($entityRegion, $hit); + self::assertArrayHasKey($coolRegion, $hit); + self::assertArrayHasKey($queryRegion, $hit); + self::assertArrayHasKey($entityRegion, $hit); } } diff --git a/tests/Doctrine/Tests/ORM/CommitOrderCalculatorTest.php b/tests/Doctrine/Tests/ORM/CommitOrderCalculatorTest.php index 8c9ec26c44d..141b01d8b7e 100644 --- a/tests/Doctrine/Tests/ORM/CommitOrderCalculatorTest.php +++ b/tests/Doctrine/Tests/ORM/CommitOrderCalculatorTest.php @@ -1,9 +1,14 @@ _calc = new CommitOrderCalculator(); + $this->calc = new CommitOrderCalculator(); + $this->metadataBuildingContext = new ClassMetadataBuildingContext( + $this->createMock(ClassMetadataFactory::class), + new RuntimeReflectionService() + ); } public function testCommitOrdering1() { - $class1 = new ClassMetadata(NodeClass1::class); - $class2 = new ClassMetadata(NodeClass2::class); - $class3 = new ClassMetadata(NodeClass3::class); - $class4 = new ClassMetadata(NodeClass4::class); - $class5 = new ClassMetadata(NodeClass5::class); + $class1 = new ClassMetadata(NodeClass1::class, $this->metadataBuildingContext); + $class2 = new ClassMetadata(NodeClass2::class, $this->metadataBuildingContext); + $class3 = new ClassMetadata(NodeClass3::class, $this->metadataBuildingContext); + $class4 = new ClassMetadata(NodeClass4::class, $this->metadataBuildingContext); + $class5 = new ClassMetadata(NodeClass5::class, $this->metadataBuildingContext); - $this->_calc->addNode($class1->name, $class1); - $this->_calc->addNode($class2->name, $class2); - $this->_calc->addNode($class3->name, $class3); - $this->_calc->addNode($class4->name, $class4); - $this->_calc->addNode($class5->name, $class5); + $this->calc->addNode($class1->getClassName(), $class1); + $this->calc->addNode($class2->getClassName(), $class2); + $this->calc->addNode($class3->getClassName(), $class3); + $this->calc->addNode($class4->getClassName(), $class4); + $this->calc->addNode($class5->getClassName(), $class5); - $this->_calc->addDependency($class1->name, $class2->name, 1); - $this->_calc->addDependency($class2->name, $class3->name, 1); - $this->_calc->addDependency($class3->name, $class4->name, 1); - $this->_calc->addDependency($class5->name, $class1->name, 1); + $this->calc->addDependency($class1->getClassName(), $class2->getClassName(), 1); + $this->calc->addDependency($class2->getClassName(), $class3->getClassName(), 1); + $this->calc->addDependency($class3->getClassName(), $class4->getClassName(), 1); + $this->calc->addDependency($class5->getClassName(), $class1->getClassName(), 1); - $sorted = $this->_calc->sort(); + $sorted = $this->calc->sort(); // There is only 1 valid ordering for this constellation $correctOrder = [$class5, $class1, $class2, $class3, $class4]; - $this->assertSame($correctOrder, $sorted); + self::assertSame($correctOrder, $sorted); } public function testCommitOrdering2() { - $class1 = new ClassMetadata(NodeClass1::class); - $class2 = new ClassMetadata(NodeClass2::class); + $class1 = new ClassMetadata(NodeClass1::class, $this->metadataBuildingContext); + $class2 = new ClassMetadata(NodeClass2::class, $this->metadataBuildingContext); - $this->_calc->addNode($class1->name, $class1); - $this->_calc->addNode($class2->name, $class2); + $this->calc->addNode($class1->getClassName(), $class1); + $this->calc->addNode($class2->getClassName(), $class2); - $this->_calc->addDependency($class1->name, $class2->name, 0); - $this->_calc->addDependency($class2->name, $class1->name, 1); + $this->calc->addDependency($class1->getClassName(), $class2->getClassName(), 0); + $this->calc->addDependency($class2->getClassName(), $class1->getClassName(), 1); - $sorted = $this->_calc->sort(); + $sorted = $this->calc->sort(); // There is only 1 valid ordering for this constellation $correctOrder = [$class2, $class1]; - $this->assertSame($correctOrder, $sorted); + self::assertSame($correctOrder, $sorted); } } diff --git a/tests/Doctrine/Tests/ORM/ConfigurationTest.php b/tests/Doctrine/Tests/ORM/ConfigurationTest.php index 92a2eeaea70..cc4953568d4 100644 --- a/tests/Doctrine/Tests/ORM/ConfigurationTest.php +++ b/tests/Doctrine/Tests/ORM/ConfigurationTest.php @@ -1,29 +1,32 @@ */ -class ConfigurationTest extends TestCase +class ConfigurationTest extends DoctrineTestCase { /** * @var Configuration @@ -38,41 +41,41 @@ protected function setUp() public function testSetGetProxyDir() { - $this->assertSame(null, $this->configuration->getProxyDir()); // defaults + self::assertSame(null, $this->configuration->getProxyDir()); // defaults $this->configuration->setProxyDir(__DIR__); - $this->assertSame(__DIR__, $this->configuration->getProxyDir()); + self::assertSame(__DIR__, $this->configuration->getProxyDir()); } public function testSetGetAutoGenerateProxyClasses() { - $this->assertSame(AbstractProxyFactory::AUTOGENERATE_ALWAYS, $this->configuration->getAutoGenerateProxyClasses()); // defaults + self::assertSame(AbstractProxyFactory::AUTOGENERATE_ALWAYS, $this->configuration->getAutoGenerateProxyClasses()); // defaults $this->configuration->setAutoGenerateProxyClasses(false); - $this->assertSame(AbstractProxyFactory::AUTOGENERATE_NEVER, $this->configuration->getAutoGenerateProxyClasses()); + self::assertSame(AbstractProxyFactory::AUTOGENERATE_NEVER, $this->configuration->getAutoGenerateProxyClasses()); $this->configuration->setAutoGenerateProxyClasses(true); - $this->assertSame(AbstractProxyFactory::AUTOGENERATE_ALWAYS, $this->configuration->getAutoGenerateProxyClasses()); + self::assertSame(AbstractProxyFactory::AUTOGENERATE_ALWAYS, $this->configuration->getAutoGenerateProxyClasses()); $this->configuration->setAutoGenerateProxyClasses(AbstractProxyFactory::AUTOGENERATE_FILE_NOT_EXISTS); - $this->assertSame(AbstractProxyFactory::AUTOGENERATE_FILE_NOT_EXISTS, $this->configuration->getAutoGenerateProxyClasses()); + self::assertSame(AbstractProxyFactory::AUTOGENERATE_FILE_NOT_EXISTS, $this->configuration->getAutoGenerateProxyClasses()); } public function testSetGetProxyNamespace() { - $this->assertSame(null, $this->configuration->getProxyNamespace()); // defaults + self::assertSame(null, $this->configuration->getProxyNamespace()); // defaults $this->configuration->setProxyNamespace(__NAMESPACE__); - $this->assertSame(__NAMESPACE__, $this->configuration->getProxyNamespace()); + self::assertSame(__NAMESPACE__, $this->configuration->getProxyNamespace()); } public function testSetGetMetadataDriverImpl() { - $this->assertSame(null, $this->configuration->getMetadataDriverImpl()); // defaults + self::assertSame(null, $this->configuration->getMetadataDriverImpl()); // defaults $metadataDriver = $this->createMock(MappingDriver::class); $this->configuration->setMetadataDriverImpl($metadataDriver); - $this->assertSame($metadataDriver, $this->configuration->getMetadataDriverImpl()); + self::assertSame($metadataDriver, $this->configuration->getMetadataDriverImpl()); } public function testNewDefaultAnnotationDriver() @@ -80,63 +83,56 @@ public function testNewDefaultAnnotationDriver() $paths = [__DIR__]; $reflectionClass = new ReflectionClass(ConfigurationTestAnnotationReaderChecker::class); - $annotationDriver = $this->configuration->newDefaultAnnotationDriver($paths, false); - $reader = $annotationDriver->getReader(); - $annotation = $reader->getMethodAnnotation( - $reflectionClass->getMethod('namespacedAnnotationMethod'), - AnnotationNamespace\PrePersist::class - ); - $this->assertInstanceOf(AnnotationNamespace\PrePersist::class, $annotation); - $annotationDriver = $this->configuration->newDefaultAnnotationDriver($paths); $reader = $annotationDriver->getReader(); $annotation = $reader->getMethodAnnotation( - $reflectionClass->getMethod('simpleAnnotationMethod'), + $reflectionClass->getMethod('annotatedMethod'), AnnotationNamespace\PrePersist::class ); - $this->assertInstanceOf(AnnotationNamespace\PrePersist::class, $annotation); + + self::assertInstanceOf(AnnotationNamespace\PrePersist::class, $annotation); } public function testSetGetEntityNamespace() { $this->configuration->addEntityNamespace('TestNamespace', __NAMESPACE__); - $this->assertSame(__NAMESPACE__, $this->configuration->getEntityNamespace('TestNamespace')); + self::assertSame(__NAMESPACE__, $this->configuration->getEntityNamespace('TestNamespace')); $namespaces = ['OtherNamespace' => __NAMESPACE__]; $this->configuration->setEntityNamespaces($namespaces); - $this->assertSame($namespaces, $this->configuration->getEntityNamespaces()); + self::assertSame($namespaces, $this->configuration->getEntityNamespaces()); $this->expectException(ORMException::class); $this->configuration->getEntityNamespace('NonExistingNamespace'); } public function testSetGetQueryCacheImpl() { - $this->assertSame(null, $this->configuration->getQueryCacheImpl()); // defaults + self::assertSame(null, $this->configuration->getQueryCacheImpl()); // defaults $queryCacheImpl = $this->createMock(Cache::class); $this->configuration->setQueryCacheImpl($queryCacheImpl); - $this->assertSame($queryCacheImpl, $this->configuration->getQueryCacheImpl()); + self::assertSame($queryCacheImpl, $this->configuration->getQueryCacheImpl()); } public function testSetGetHydrationCacheImpl() { - $this->assertSame(null, $this->configuration->getHydrationCacheImpl()); // defaults + self::assertSame(null, $this->configuration->getHydrationCacheImpl()); // defaults $queryCacheImpl = $this->createMock(Cache::class); $this->configuration->setHydrationCacheImpl($queryCacheImpl); - $this->assertSame($queryCacheImpl, $this->configuration->getHydrationCacheImpl()); + self::assertSame($queryCacheImpl, $this->configuration->getHydrationCacheImpl()); } public function testSetGetMetadataCacheImpl() { - $this->assertSame(null, $this->configuration->getMetadataCacheImpl()); // defaults + self::assertSame(null, $this->configuration->getMetadataCacheImpl()); // defaults $queryCacheImpl = $this->createMock(Cache::class); $this->configuration->setMetadataCacheImpl($queryCacheImpl); - $this->assertSame($queryCacheImpl, $this->configuration->getMetadataCacheImpl()); + self::assertSame($queryCacheImpl, $this->configuration->getMetadataCacheImpl()); } public function testAddGetNamedQuery() { $dql = 'SELECT u FROM User u'; $this->configuration->addNamedQuery('QueryName', $dql); - $this->assertSame($dql, $this->configuration->getNamedQuery('QueryName')); + self::assertSame($dql, $this->configuration->getNamedQuery('QueryName')); $this->expectException(ORMException::class); $this->expectExceptionMessage('a named query'); $this->configuration->getNamedQuery('NonExistingQuery'); @@ -148,8 +144,8 @@ public function testAddGetNamedNativeQuery() $rsm = $this->createMock(ResultSetMapping::class); $this->configuration->addNamedNativeQuery('QueryName', $sql, $rsm); $fetched = $this->configuration->getNamedNativeQuery('QueryName'); - $this->assertSame($sql, $fetched[0]); - $this->assertSame($rsm, $fetched[1]); + self::assertSame($sql, $fetched[0]); + self::assertSame($rsm, $fetched[1]); $this->expectException(ORMException::class); $this->expectExceptionMessage('a named native query'); $this->configuration->getNamedNativeQuery('NonExistingQuery'); @@ -180,7 +176,7 @@ public function testEnsureProductionSettings() $this->setProductionSettings(); $this->configuration->ensureProductionSettings(); - $this->addToAssertionCount(1); + self::addToAssertionCount(1); } public function testEnsureProductionSettingsQueryCache() @@ -261,41 +257,53 @@ public function testEnsureProductionSettingsAutoGenerateProxyClassesEval() public function testAddGetCustomStringFunction() { $this->configuration->addCustomStringFunction('FunctionName', __CLASS__); - $this->assertSame(__CLASS__, $this->configuration->getCustomStringFunction('FunctionName')); - $this->assertSame(null, $this->configuration->getCustomStringFunction('NonExistingFunction')); + + self::assertSame(__CLASS__, $this->configuration->getCustomStringFunction('FunctionName')); + self::assertSame(null, $this->configuration->getCustomStringFunction('NonExistingFunction')); + $this->configuration->setCustomStringFunctions(['OtherFunctionName' => __CLASS__]); - $this->assertSame(__CLASS__, $this->configuration->getCustomStringFunction('OtherFunctionName')); + + self::assertSame(__CLASS__, $this->configuration->getCustomStringFunction('OtherFunctionName')); } public function testAddGetCustomNumericFunction() { $this->configuration->addCustomNumericFunction('FunctionName', __CLASS__); - $this->assertSame(__CLASS__, $this->configuration->getCustomNumericFunction('FunctionName')); - $this->assertSame(null, $this->configuration->getCustomNumericFunction('NonExistingFunction')); + + self::assertSame(__CLASS__, $this->configuration->getCustomNumericFunction('FunctionName')); + self::assertSame(null, $this->configuration->getCustomNumericFunction('NonExistingFunction')); + $this->configuration->setCustomNumericFunctions(['OtherFunctionName' => __CLASS__]); - $this->assertSame(__CLASS__, $this->configuration->getCustomNumericFunction('OtherFunctionName')); + + self::assertSame(__CLASS__, $this->configuration->getCustomNumericFunction('OtherFunctionName')); } public function testAddGetCustomDatetimeFunction() { $this->configuration->addCustomDatetimeFunction('FunctionName', __CLASS__); - $this->assertSame(__CLASS__, $this->configuration->getCustomDatetimeFunction('FunctionName')); - $this->assertSame(null, $this->configuration->getCustomDatetimeFunction('NonExistingFunction')); + + self::assertSame(__CLASS__, $this->configuration->getCustomDatetimeFunction('FunctionName')); + self::assertSame(null, $this->configuration->getCustomDatetimeFunction('NonExistingFunction')); + $this->configuration->setCustomDatetimeFunctions(['OtherFunctionName' => __CLASS__]); - $this->assertSame(__CLASS__, $this->configuration->getCustomDatetimeFunction('OtherFunctionName')); + + self::assertSame(__CLASS__, $this->configuration->getCustomDatetimeFunction('OtherFunctionName')); } public function testAddGetCustomHydrationMode() { - $this->assertSame(null, $this->configuration->getCustomHydrationMode('NonExisting')); + self::assertSame(null, $this->configuration->getCustomHydrationMode('NonExisting')); + $this->configuration->addCustomHydrationMode('HydrationModeName', __CLASS__); - $this->assertSame(__CLASS__, $this->configuration->getCustomHydrationMode('HydrationModeName')); + + self::assertSame(__CLASS__, $this->configuration->getCustomHydrationMode('HydrationModeName')); } public function testSetCustomHydrationModes() { $this->configuration->addCustomHydrationMode('HydrationModeName', __CLASS__); - $this->assertSame(__CLASS__, $this->configuration->getCustomHydrationMode('HydrationModeName')); + + self::assertSame(__CLASS__, $this->configuration->getCustomHydrationMode('HydrationModeName')); $this->configuration->setCustomHydrationModes( [ @@ -303,47 +311,49 @@ public function testSetCustomHydrationModes() ] ); - $this->assertNull($this->configuration->getCustomHydrationMode('HydrationModeName')); - $this->assertSame(__CLASS__, $this->configuration->getCustomHydrationMode('AnotherHydrationModeName')); + self::assertNull($this->configuration->getCustomHydrationMode('HydrationModeName')); + self::assertSame(__CLASS__, $this->configuration->getCustomHydrationMode('AnotherHydrationModeName')); } public function testSetGetClassMetadataFactoryName() { - $this->assertSame(AnnotationNamespace\ClassMetadataFactory::class, $this->configuration->getClassMetadataFactoryName()); + self::assertSame(ClassMetadataFactory::class, $this->configuration->getClassMetadataFactoryName()); + $this->configuration->setClassMetadataFactoryName(__CLASS__); - $this->assertSame(__CLASS__, $this->configuration->getClassMetadataFactoryName()); + + self::assertSame(__CLASS__, $this->configuration->getClassMetadataFactoryName()); } public function testAddGetFilters() { - $this->assertSame(null, $this->configuration->getFilterClassName('NonExistingFilter')); + self::assertSame(null, $this->configuration->getFilterClassName('NonExistingFilter')); + $this->configuration->addFilter('FilterName', __CLASS__); - $this->assertSame(__CLASS__, $this->configuration->getFilterClassName('FilterName')); + + self::assertSame(__CLASS__, $this->configuration->getFilterClassName('FilterName')); } public function setDefaultRepositoryClassName() { - $this->assertSame(EntityRepository::class, $this->configuration->getDefaultRepositoryClassName()); + self::assertSame(EntityRepository::class, $this->configuration->getDefaultRepositoryClassName()); + $this->configuration->setDefaultRepositoryClassName(DDC753CustomRepository::class); - $this->assertSame(DDC753CustomRepository::class, $this->configuration->getDefaultRepositoryClassName()); + + self::assertSame(DDC753CustomRepository::class, $this->configuration->getDefaultRepositoryClassName()); + $this->expectException(ORMException::class); $this->configuration->setDefaultRepositoryClassName(__CLASS__); } public function testSetGetNamingStrategy() { - $this->assertInstanceOf(NamingStrategy::class, $this->configuration->getNamingStrategy()); + self::assertInstanceOf(NamingStrategy::class, $this->configuration->getNamingStrategy()); + $namingStrategy = $this->createMock(NamingStrategy::class); + $this->configuration->setNamingStrategy($namingStrategy); - $this->assertSame($namingStrategy, $this->configuration->getNamingStrategy()); - } - public function testSetGetQuoteStrategy() - { - $this->assertInstanceOf(QuoteStrategy::class, $this->configuration->getQuoteStrategy()); - $quoteStrategy = $this->createMock(QuoteStrategy::class); - $this->configuration->setQuoteStrategy($quoteStrategy); - $this->assertSame($quoteStrategy, $this->configuration->getQuoteStrategy()); + self::assertSame($namingStrategy, $this->configuration->getNamingStrategy()); } /** @@ -351,11 +361,14 @@ public function testSetGetQuoteStrategy() */ public function testSetGetEntityListenerResolver() { - $this->assertInstanceOf(EntityListenerResolver::class, $this->configuration->getEntityListenerResolver()); - $this->assertInstanceOf(AnnotationNamespace\DefaultEntityListenerResolver::class, $this->configuration->getEntityListenerResolver()); + self::assertInstanceOf(EntityListenerResolver::class, $this->configuration->getEntityListenerResolver()); + self::assertInstanceOf(DefaultEntityListenerResolver::class, $this->configuration->getEntityListenerResolver()); + $resolver = $this->createMock(EntityListenerResolver::class); + $this->configuration->setEntityListenerResolver($resolver); - $this->assertSame($resolver, $this->configuration->getEntityListenerResolver()); + + self::assertSame($resolver, $this->configuration->getEntityListenerResolver()); } /** @@ -365,21 +378,16 @@ public function testSetGetSecondLevelCacheConfig() { $mockClass = $this->createMock(CacheConfiguration::class); - $this->assertNull($this->configuration->getSecondLevelCacheConfiguration()); + self::assertNull($this->configuration->getSecondLevelCacheConfiguration()); $this->configuration->setSecondLevelCacheConfiguration($mockClass); - $this->assertEquals($mockClass, $this->configuration->getSecondLevelCacheConfiguration()); + self::assertEquals($mockClass, $this->configuration->getSecondLevelCacheConfiguration()); } } class ConfigurationTestAnnotationReaderChecker { - /** @PrePersist */ - public function simpleAnnotationMethod() - { - } - /** @AnnotationNamespace\PrePersist */ - public function namespacedAnnotationMethod() + public function annotatedMethod() { } } diff --git a/tests/Doctrine/Tests/ORM/Decorator/EntityManagerDecoratorTest.php b/tests/Doctrine/Tests/ORM/Decorator/EntityManagerDecoratorTest.php index b8688d871db..50b76406f0e 100644 --- a/tests/Doctrine/Tests/ORM/Decorator/EntityManagerDecoratorTest.php +++ b/tests/Doctrine/Tests/ORM/Decorator/EntityManagerDecoratorTest.php @@ -1,32 +1,30 @@ wrapped = $this->createMock(EntityManagerInterface::class); + $this->decorator = new class($this->wrapped) extends EntityManagerDecorator {}; } public function getMethodParameters() @@ -52,6 +50,11 @@ private function getParameters(\ReflectionMethod $method) return [$method->getName(), ['name', new ResultSetMapping()]]; } + /** Special case EntityManager::transactional() */ + if ($method->getName() === 'transactional') { + return [$method->getName(), [function () {}]]; + } + if ($method->getNumberOfRequiredParameters() === 0) { return [$method->getName(), []]; } @@ -60,7 +63,7 @@ private function getParameters(\ReflectionMethod $method) return [$method->getName(), array_fill(0, $method->getNumberOfRequiredParameters(), 'req') ?: []]; } - if ($method->getNumberOfParameters() != $method->getNumberOfRequiredParameters()) { + if ($method->getNumberOfParameters() !== $method->getNumberOfRequiredParameters()) { return [$method->getName(), array_fill(0, $method->getNumberOfParameters(), 'all') ?: []]; } @@ -72,16 +75,12 @@ private function getParameters(\ReflectionMethod $method) */ public function testAllMethodCallsAreDelegatedToTheWrappedInstance($method, array $parameters) { - $return = !in_array($method, self::VOID_METHODS) ? 'INNER VALUE FROM ' . $method : null; - - $this->wrapped->expects($this->once()) + $stub = $this->wrapped + ->expects(self::once()) ->method($method) - ->with(...$parameters) - ->willReturn($return); - - $decorator = new class ($this->wrapped) extends EntityManagerDecorator { - }; + ; - $this->assertSame($return, $decorator->$method(...$parameters)); + call_user_func_array([$stub, 'with'], $parameters); + call_user_func_array([$this->decorator, $method], $parameters); } } diff --git a/tests/Doctrine/Tests/ORM/Entity/ConstructorTest.php b/tests/Doctrine/Tests/ORM/Entity/ConstructorTest.php index 117525eca32..3df24aa1e1c 100644 --- a/tests/Doctrine/Tests/ORM/Entity/ConstructorTest.php +++ b/tests/Doctrine/Tests/ORM/Entity/ConstructorTest.php @@ -1,5 +1,7 @@ assertEquals("romanb", $entity->username); + self::assertEquals("romanb", $entity->username); } } diff --git a/tests/Doctrine/Tests/ORM/EntityManagerTest.php b/tests/Doctrine/Tests/ORM/EntityManagerTest.php index 7f36bb285b1..b20917dde27 100644 --- a/tests/Doctrine/Tests/ORM/EntityManagerTest.php +++ b/tests/Doctrine/Tests/ORM/EntityManagerTest.php @@ -1,18 +1,19 @@ _em = $this->_getTestEntityManager(); + + $this->em = $this->getTestEntityManager(); } /** @@ -39,47 +41,47 @@ function setUp() */ public function testIsOpen() { - $this->assertTrue($this->_em->isOpen()); - $this->_em->close(); - $this->assertFalse($this->_em->isOpen()); + self::assertTrue($this->em->isOpen()); + $this->em->close(); + self::assertFalse($this->em->isOpen()); } public function testGetConnection() { - $this->assertInstanceOf(Connection::class, $this->_em->getConnection()); + self::assertInstanceOf(Connection::class, $this->em->getConnection()); } public function testGetMetadataFactory() { - $this->assertInstanceOf(ClassMetadataFactory::class, $this->_em->getMetadataFactory()); + self::assertInstanceOf(ClassMetadataFactory::class, $this->em->getMetadataFactory()); } public function testGetConfiguration() { - $this->assertInstanceOf(Configuration::class, $this->_em->getConfiguration()); + self::assertInstanceOf(Configuration::class, $this->em->getConfiguration()); } public function testGetUnitOfWork() { - $this->assertInstanceOf(UnitOfWork::class, $this->_em->getUnitOfWork()); + self::assertInstanceOf(UnitOfWork::class, $this->em->getUnitOfWork()); } public function testGetProxyFactory() { - $this->assertInstanceOf(ProxyFactory::class, $this->_em->getProxyFactory()); + self::assertInstanceOf(ProxyFactory::class, $this->em->getProxyFactory()); } public function testGetEventManager() { - $this->assertInstanceOf(EventManager::class, $this->_em->getEventManager()); + self::assertInstanceOf(EventManager::class, $this->em->getEventManager()); } public function testCreateNativeQuery() { $rsm = new ResultSetMapping(); - $query = $this->_em->createNativeQuery('SELECT foo', $rsm); + $query = $this->em->createNativeQuery('SELECT foo', $rsm); - $this->assertSame('SELECT foo', $query->getSql()); + self::assertSame('SELECT foo', $query->getSql()); } /** @@ -88,50 +90,50 @@ public function testCreateNativeQuery() public function testCreateNamedNativeQuery() { $rsm = new ResultSetMapping(); - $this->_em->getConfiguration()->addNamedNativeQuery('foo', 'SELECT foo', $rsm); + $this->em->getConfiguration()->addNamedNativeQuery('foo', 'SELECT foo', $rsm); - $query = $this->_em->createNamedNativeQuery('foo'); + $query = $this->em->createNamedNativeQuery('foo'); - $this->assertInstanceOf(NativeQuery::class, $query); + self::assertInstanceOf(NativeQuery::class, $query); } public function testCreateQueryBuilder() { - $this->assertInstanceOf(QueryBuilder::class, $this->_em->createQueryBuilder()); + self::assertInstanceOf(QueryBuilder::class, $this->em->createQueryBuilder()); } public function testCreateQueryBuilderAliasValid() { - $q = $this->_em->createQueryBuilder() + $q = $this->em->createQueryBuilder() ->select('u')->from(CmsUser::class, 'u'); $q2 = clone $q; - $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $q->getQuery()->getDql()); - $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $q2->getQuery()->getDql()); + self::assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $q->getQuery()->getDql()); + self::assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $q2->getQuery()->getDql()); $q3 = clone $q; - $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $q3->getQuery()->getDql()); + self::assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $q3->getQuery()->getDql()); } public function testCreateQuery_DqlIsOptional() { - $this->assertInstanceOf(Query::class, $this->_em->createQuery()); + self::assertInstanceOf(Query::class, $this->em->createQuery()); } public function testGetPartialReference() { - $user = $this->_em->getPartialReference(CmsUser::class, 42); - $this->assertTrue($this->_em->contains($user)); - $this->assertEquals(42, $user->id); - $this->assertNull($user->getName()); + $user = $this->em->getPartialReference(CmsUser::class, 42); + self::assertTrue($this->em->contains($user)); + self::assertEquals(42, $user->id); + self::assertNull($user->getName()); } public function testCreateQuery() { - $q = $this->_em->createQuery('SELECT 1'); - $this->assertInstanceOf(Query::class, $q); - $this->assertEquals('SELECT 1', $q->getDql()); + $q = $this->em->createQuery('SELECT 1'); + self::assertInstanceOf(Query::class, $q); + self::assertEquals('SELECT 1', $q->getDql()); } /** @@ -139,11 +141,11 @@ public function testCreateQuery() */ public function testCreateNamedQuery() { - $this->_em->getConfiguration()->addNamedQuery('foo', 'SELECT 1'); + $this->em->getConfiguration()->addNamedQuery('foo', 'SELECT 1'); - $query = $this->_em->createNamedQuery('foo'); - $this->assertInstanceOf(Query::class, $query); - $this->assertEquals('SELECT 1', $query->getDql()); + $query = $this->em->createNamedQuery('foo'); + self::assertInstanceOf(Query::class, $query); + self::assertEquals('SELECT 1', $query->getDql()); } static public function dataMethodsAffectedByNoObjectArguments() @@ -151,9 +153,7 @@ static public function dataMethodsAffectedByNoObjectArguments() return [ ['persist'], ['remove'], - ['merge'], ['refresh'], - ['detach'] ]; } @@ -164,7 +164,7 @@ public function testThrowsExceptionOnNonObjectValues($methodName) { $this->expectException(ORMInvalidArgumentException::class); $this->expectExceptionMessage('EntityManager#' . $methodName . '() expects parameter 1 to be an entity object, NULL given.'); - $this->_em->$methodName(null); + $this->em->$methodName(null); } static public function dataAffectedByErrorIfClosedException() @@ -173,7 +173,6 @@ static public function dataAffectedByErrorIfClosedException() ['flush'], ['persist'], ['remove'], - ['merge'], ['refresh'], ]; } @@ -187,38 +186,40 @@ public function testAffectedByErrorIfClosedException($methodName) $this->expectException(ORMException::class); $this->expectExceptionMessage('closed'); - $this->_em->close(); - $this->_em->$methodName(new \stdClass()); + $this->em->close(); + $this->em->$methodName(new \stdClass()); + } + + public function dataToBeReturnedByTransactional() + { + return [ + [null], + [false], + ['foo'], + ]; } /** - * @group DDC-1125 + * @dataProvider dataToBeReturnedByTransactional */ - public function testTransactionalAcceptsReturn() + public function testTransactionalAcceptsReturn($value) { - $return = $this->_em->transactional(function ($em) { - return 'foo'; - }); - - $this->assertEquals('foo', $return); + self::assertSame( + $value, + $this->em->transactional(function ($em) use ($value) { + return $value; + }) + ); } public function testTransactionalAcceptsVariousCallables() { - $this->assertSame('callback', $this->_em->transactional([$this, 'transactionalCallback'])); - } - - public function testTransactionalThrowsInvalidArgumentExceptionIfNonCallablePassed() - { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('Expected argument of type "callable", got "object"'); - - $this->_em->transactional($this); + self::assertSame('callback', $this->em->transactional([$this, 'transactionalCallback'])); } public function transactionalCallback($em) { - $this->assertSame($this->_em, $em); + self::assertSame($this->em, $em); return 'callback'; } @@ -235,56 +236,16 @@ public function testCreateInvalidConnection() /** * @group 6017 */ - public function testClearManagerWithObject() - { - $entity = new Country(456, 'United Kingdom'); - - $this->expectException(ORMInvalidArgumentException::class); - - $this->_em->clear($entity); - } - - /** - * @group 6017 - */ - public function testClearManagerWithUnknownEntityName() - { - $this->expectException(MappingException::class); - - $this->_em->clear(uniqid('nonExisting', true)); - } - - /** - * @group 6017 - */ - public function testClearManagerWithProxyClassName() - { - $proxy = $this->_em->getReference(Country::class, ['id' => rand(457, 100000)]); - - $entity = new Country(456, 'United Kingdom'); - - $this->_em->persist($entity); - - $this->assertTrue($this->_em->contains($entity)); - - $this->_em->clear(get_class($proxy)); - - $this->assertFalse($this->_em->contains($entity)); - } - - /** - * @group 6017 - */ - public function testClearManagerWithNullValue() + public function testClearManager() { $entity = new Country(456, 'United Kingdom'); - $this->_em->persist($entity); + $this->em->persist($entity); - $this->assertTrue($this->_em->contains($entity)); + self::assertTrue($this->em->contains($entity)); - $this->_em->clear(null); + $this->em->clear(null); - $this->assertFalse($this->_em->contains($entity)); + self::assertFalse($this->em->contains($entity)); } } diff --git a/tests/Doctrine/Tests/ORM/EntityNotFoundExceptionTest.php b/tests/Doctrine/Tests/ORM/EntityNotFoundExceptionTest.php index ec1cfbfc99c..d43809eb9dc 100644 --- a/tests/Doctrine/Tests/ORM/EntityNotFoundExceptionTest.php +++ b/tests/Doctrine/Tests/ORM/EntityNotFoundExceptionTest.php @@ -1,16 +1,18 @@ 'bar'] ); - $this->assertInstanceOf(EntityNotFoundException::class, $exception); - $this->assertSame('Entity of type \'foo\' for IDs foo(bar) was not found', $exception->getMessage()); + self::assertInstanceOf(EntityNotFoundException::class, $exception); + self::assertSame('Entity of type \'foo\' for IDs foo(bar) was not found', $exception->getMessage()); $exception = EntityNotFoundException::fromClassNameAndIdentifier( 'foo', [] ); - $this->assertInstanceOf(EntityNotFoundException::class, $exception); - $this->assertSame('Entity of type \'foo\' was not found', $exception->getMessage()); + self::assertInstanceOf(EntityNotFoundException::class, $exception); + self::assertSame('Entity of type \'foo\' was not found', $exception->getMessage()); } } diff --git a/tests/Doctrine/Tests/ORM/Event/OnClassMetadataNotFoundEventArgsTest.php b/tests/Doctrine/Tests/ORM/Event/OnClassMetadataNotFoundEventArgsTest.php index e5f62bd26ae..074504de676 100644 --- a/tests/Doctrine/Tests/ORM/Event/OnClassMetadataNotFoundEventArgsTest.php +++ b/tests/Doctrine/Tests/ORM/Event/OnClassMetadataNotFoundEventArgsTest.php @@ -1,40 +1,49 @@ createMock(ObjectManager::class); + $entityManager = $this->createMock(EntityManagerInterface::class); + $metadataBuildingContext = new ClassMetadataBuildingContext( + $this->createMock(ClassMetadataFactory::class), + $this->createMock(ReflectionService::class) + ); - $args = new OnClassMetadataNotFoundEventArgs('foo', $objectManager); + $args = new OnClassMetadataNotFoundEventArgs('foo', $metadataBuildingContext, $entityManager); - $this->assertSame('foo', $args->getClassName()); - $this->assertSame($objectManager, $args->getObjectManager()); + self::assertSame('foo', $args->getClassName()); + self::assertSame($metadataBuildingContext, $args->getClassMetadataBuildingContext()); + self::assertSame($entityManager, $args->getObjectManager()); - $this->assertNull($args->getFoundMetadata()); + self::assertNull($args->getFoundMetadata()); - /* @var $metadata \Doctrine\Common\Persistence\Mapping\ClassMetadata */ + /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */ $metadata = $this->createMock(ClassMetadata::class); $args->setFoundMetadata($metadata); - $this->assertSame($metadata, $args->getFoundMetadata()); + self::assertSame($metadata, $args->getFoundMetadata()); $args->setFoundMetadata(null); - $this->assertNull($args->getFoundMetadata()); + self::assertNull($args->getFoundMetadata()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/AbstractManyToManyAssociationTestCase.php b/tests/Doctrine/Tests/ORM/Functional/AbstractManyToManyAssociationTestCase.php index 26445c1417a..f187fb0ed3e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/AbstractManyToManyAssociationTestCase.php +++ b/tests/Doctrine/Tests/ORM/Functional/AbstractManyToManyAssociationTestCase.php @@ -1,5 +1,7 @@ assertEquals(1, $this->_countForeignKeys($firstId, $secondId)); + self::assertEquals(1, $this->countForeignKeys($firstId, $secondId)); } public function assertForeignKeysNotContain($firstId, $secondId) { - $this->assertEquals(0, $this->_countForeignKeys($firstId, $secondId)); + self::assertEquals(0, $this->countForeignKeys($firstId, $secondId)); } - protected function _countForeignKeys($firstId, $secondId) + protected function countForeignKeys($firstId, $secondId) { - return count($this->_em->getConnection()->executeQuery(" - SELECT {$this->_firstField} - FROM {$this->_table} - WHERE {$this->_firstField} = ? - AND {$this->_secondField} = ? + return count($this->em->getConnection()->executeQuery(" + SELECT {$this->firstField} + FROM {$this->table} + WHERE {$this->firstField} = ? + AND {$this->secondField} = ? ", [$firstId, $secondId] )->fetchAll()); } diff --git a/tests/Doctrine/Tests/ORM/Functional/AdvancedAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/AdvancedAssociationTest.php index e6714500cd5..36289720e52 100644 --- a/tests/Doctrine/Tests/ORM/Functional/AdvancedAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/AdvancedAssociationTest.php @@ -1,8 +1,11 @@ schemaTool->createSchema( + [ + $this->em->getClassMetadata(Phrase::class), + $this->em->getClassMetadata(PhraseType::class), + $this->em->getClassMetadata(Definition::class), + $this->em->getClassMetadata(Lemma::class), + $this->em->getClassMetadata(Type::class) + ] + ); + } catch (\Exception $e) { + // Automatically mark failure + self::fail($e->getMessage()); + } + } + + protected function tearDown() + { + parent::tearDown(); + try { - $this->_schemaTool->createSchema( + $this->schemaTool->dropSchema( [ - $this->_em->getClassMetadata(Phrase::class), - $this->_em->getClassMetadata(PhraseType::class), - $this->_em->getClassMetadata(Definition::class), - $this->_em->getClassMetadata(Lemma::class), - $this->_em->getClassMetadata(Type::class) + $this->em->getClassMetadata(Phrase::class), + $this->em->getClassMetadata(PhraseType::class), + $this->em->getClassMetadata(Definition::class), + $this->em->getClassMetadata(Lemma::class), + $this->em->getClassMetadata(Type::class) ] ); } catch (\Exception $e) { - // Swallow all exceptions. We do not test the schema tool here. + // Automatically mark failure + self::fail($e->getMessage()); } } @@ -49,56 +74,56 @@ public function testIssue() $phrase->addDefinition($def1); $phrase->addDefinition($def2); - $this->_em->persist($phrase); - $this->_em->persist($type); + $this->em->persist($phrase); + $this->em->persist($type); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); //end setup // test1 - lazy-loading many-to-one after find() - $phrase2 = $this->_em->find(Phrase::class, $phrase->getId()); - $this->assertTrue(is_numeric($phrase2->getType()->getId())); + $phrase2 = $this->em->find(Phrase::class, $phrase->getId()); + self::assertTrue(is_numeric($phrase2->getType()->getId())); - $this->_em->clear(); + $this->em->clear(); // test2 - eager load in DQL query - $query = $this->_em->createQuery("SELECT p,t FROM Doctrine\Tests\ORM\Functional\Phrase p JOIN p.type t"); + $query = $this->em->createQuery("SELECT p,t FROM Doctrine\Tests\ORM\Functional\Phrase p JOIN p.type t"); $res = $query->getResult(); - $this->assertEquals(1, count($res)); - $this->assertInstanceOf(PhraseType::class, $res[0]->getType()); - $this->assertInstanceOf(PersistentCollection::class, $res[0]->getType()->getPhrases()); - $this->assertFalse($res[0]->getType()->getPhrases()->isInitialized()); + self::assertEquals(1, count($res)); + self::assertInstanceOf(PhraseType::class, $res[0]->getType()); + self::assertInstanceOf(PersistentCollection::class, $res[0]->getType()->getPhrases()); + self::assertFalse($res[0]->getType()->getPhrases()->isInitialized()); - $this->_em->clear(); + $this->em->clear(); // test2 - eager load in DQL query with double-join back and forth - $query = $this->_em->createQuery("SELECT p,t,pp FROM Doctrine\Tests\ORM\Functional\Phrase p JOIN p.type t JOIN t.phrases pp"); + $query = $this->em->createQuery("SELECT p,t,pp FROM Doctrine\Tests\ORM\Functional\Phrase p JOIN p.type t JOIN t.phrases pp"); $res = $query->getResult(); - $this->assertEquals(1, count($res)); - $this->assertInstanceOf(PhraseType::class, $res[0]->getType()); - $this->assertInstanceOf(PersistentCollection::class, $res[0]->getType()->getPhrases()); - $this->assertTrue($res[0]->getType()->getPhrases()->isInitialized()); + self::assertEquals(1, count($res)); + self::assertInstanceOf(PhraseType::class, $res[0]->getType()); + self::assertInstanceOf(PersistentCollection::class, $res[0]->getType()->getPhrases()); + self::assertTrue($res[0]->getType()->getPhrases()->isInitialized()); - $this->_em->clear(); + $this->em->clear(); // test3 - lazy-loading one-to-many after find() - $phrase3 = $this->_em->find(Phrase::class, $phrase->getId()); + $phrase3 = $this->em->find(Phrase::class, $phrase->getId()); $definitions = $phrase3->getDefinitions(); - $this->assertInstanceOf(PersistentCollection::class, $definitions); - $this->assertInstanceOf(Definition::class, $definitions[0]); + self::assertInstanceOf(PersistentCollection::class, $definitions); + self::assertInstanceOf(Definition::class, $definitions[0]); - $this->_em->clear(); + $this->em->clear(); // test4 - lazy-loading after DQL query - $query = $this->_em->createQuery("SELECT p FROM Doctrine\Tests\ORM\Functional\Phrase p"); + $query = $this->em->createQuery("SELECT p FROM Doctrine\Tests\ORM\Functional\Phrase p"); $res = $query->getResult(); $definitions = $res[0]->getDefinitions(); - $this->assertEquals(1, count($res)); + self::assertEquals(1, count($res)); - $this->assertInstanceOf(Definition::class, $definitions[0]); - $this->assertEquals(2, $definitions->count()); + self::assertInstanceOf(Definition::class, $definitions[0]); + self::assertEquals(2, $definitions->count()); } public function testManyToMany() @@ -112,84 +137,84 @@ public function testManyToMany() $lemma->addType($type); - $this->_em->persist($lemma); - $this->_em->persist($type); - $this->_em->flush(); + $this->em->persist($lemma); + $this->em->persist($type); + $this->em->flush(); // test5 ManyToMany - $query = $this->_em->createQuery("SELECT l FROM Doctrine\Tests\ORM\Functional\Lemma l"); + $query = $this->em->createQuery("SELECT l FROM Doctrine\Tests\ORM\Functional\Lemma l"); $res = $query->getResult(); $types = $res[0]->getTypes(); - $this->assertInstanceOf(Type::class, $types[0]); + self::assertInstanceOf(Type::class, $types[0]); } } /** - * @Entity - * @Table(name="lemma") + * @ORM\Entity + * @ORM\Table(name="lemma") */ -class Lemma { - - const CLASS_NAME = __CLASS__; - - /** - * @var int - * @Id - * @Column(type="integer", name="lemma_id") - * @GeneratedValue(strategy="AUTO") - */ - private $id; - - /** - * - * @var string - * @Column(type="string", name="lemma_name", unique=true, length=255) - */ - private $lemma; - - /** - * @var kateglo\application\utilities\collections\ArrayCollection - * @ManyToMany(targetEntity="Type", mappedBy="lemmas", cascade={"persist"}) - */ - private $types; - - public function __construct() { - $this->types = new ArrayCollection(); - } - - - /** - * - * @return int - */ - public function getId(){ - return $this->id; - } - - /** - * - * @param string $lemma - * @return void - */ - public function setLemma($lemma){ - $this->lemma = $lemma; - } - - /** - * - * @return string - */ - public function getLemma(){ - return $this->lemma; - } - - /** +class Lemma +{ + const CLASS_NAME = __CLASS__; + + /** + * @var int + * @ORM\Id + * @ORM\Column(type="integer", name="lemma_id") + * @ORM\GeneratedValue(strategy="AUTO") + */ + private $id; + + /** * - * @param kateglo\application\models\Type $type + * @var string + * @ORM\Column(type="string", name="lemma_name", unique=true, length=255) + */ + private $lemma; + + /** + * @ORM\ManyToMany(targetEntity="Type", mappedBy="lemmas", cascade={"persist"}) + */ + private $types; + + public function __construct() + { + $this->types = new ArrayCollection(); + } + + /** + * + * @return int + */ + public function getId() + { + return $this->id; + } + + /** + * + * @param string $lemma * @return void */ - public function addType(Type $type){ + public function setLemma($lemma) + { + $this->lemma = $lemma; + } + + /** + * + * @return string + */ + public function getLemma(){ + return $this->lemma; + } + + /** + * @return void + */ + public function addType(Type $type) + { if (!$this->types->contains($type)) { $this->types[] = $type; $type->addLemma($this); @@ -197,8 +222,6 @@ public function addType(Type $type){ } /** - * - * @param kateglo\application\models\Type $type * @return void */ public function removeType(Type $type) @@ -220,162 +243,168 @@ public function getTypes() } /** - * @Entity - * @Table(name="type") + * @ORM\Entity + * @ORM\Table(name="type") */ -class Type { - - const CLASS_NAME = __CLASS__; - - /** - * - * @var int - * @Id - * @Column(type="integer", name="type_id") - * @GeneratedValue(strategy="AUTO") - */ - private $id; - - /** - * - * @var string - * @Column(type="string", name="type_name", unique=true) - */ - private $type; - - /** - * - * @var string - * @Column(type="string", name="type_abbreviation", unique=true) - */ - private $abbreviation; - - /** - * @var kateglo\application\helpers\collections\ArrayCollection - * @ManyToMany(targetEntity="Lemma") - * @JoinTable(name="lemma_type", - * joinColumns={@JoinColumn(name="type_id", referencedColumnName="type_id")}, - * inverseJoinColumns={@JoinColumn(name="lemma_id", referencedColumnName="lemma_id")} - * ) - */ - private $lemmas; - - public function __construct(){ - $this->lemmas = new ArrayCollection(); - } - - /** - * - * @return int - */ - public function getId(){ - return $this->id; - } - - /** - * - * @param string $type - * @return void - */ - public function setType($type){ - $this->type = $type; - } - - /** - * - * @return string - */ - public function getType(){ - return $this->type; - } - - /** - * - * @param string $abbreviation - * @return void - */ - public function setAbbreviation($abbreviation){ - $this->abbreviation = $abbreviation; - } - - /** - * - * @return string - */ - public function getAbbreviation(){ - return $this->abbreviation; - } - - /** - * - * @param kateglo\application\models\Lemma $lemma - * @return void - */ - public function addLemma(Lemma $lemma) - { - if (!$this->lemmas->contains($lemma)) { - $this->lemmas[] = $lemma; - $lemma->addType($this); - } - } - - /** - * - * @param kateglo\application\models\Lemma $lemma - * @return void - */ - public function removeLEmma(Lemma $lemma) - { - $removed = $this->lemmas->removeElement($lemma); - if ($removed !== null) { - $removed->removeType($this); - } - } - - /** - * - * @return kateglo\application\helpers\collections\ArrayCollection - */ - public function getCategories() - { - return $this->categories; - } +class Type +{ + const CLASS_NAME = __CLASS__; -} + /** + * + * @var int + * @ORM\Id + * @ORM\Column(type="integer", name="type_id") + * @ORM\GeneratedValue(strategy="AUTO") + */ + private $id; + + /** + * + * @var string + * @ORM\Column(type="string", name="type_name", unique=true) + */ + private $type; + /** + * + * @var string + * @ORM\Column(type="string", name="type_abbreviation", unique=true) + */ + private $abbreviation; + + /** + * @var kateglo\application\helpers\collections\ArrayCollection + * @ORM\ManyToMany(targetEntity="Lemma") + * @ORM\JoinTable(name="lemma_type", + * joinColumns={@ORM\JoinColumn(name="type_id", referencedColumnName="type_id")}, + * inverseJoinColumns={@ORM\JoinColumn(name="lemma_id", referencedColumnName="lemma_id")} + * ) + */ + private $lemmas; + + public function __construct() + { + $this->lemmas = new ArrayCollection(); + } + + /** + * + * @return int + */ + public function getId() + { + return $this->id; + } + + /** + * + * @param string $type + * @return void + */ + public function setType($type) + { + $this->type = $type; + } + + /** + * + * @return string + */ + public function getType() + { + return $this->type; + } + + /** + * + * @param string $abbreviation + * @return void + */ + public function setAbbreviation($abbreviation) + { + $this->abbreviation = $abbreviation; + } + + /** + * + * @return string + */ + public function getAbbreviation() + { + return $this->abbreviation; + } + + /** + * + * @param kateglo\application\models\Lemma $lemma + * @return void + */ + public function addLemma(Lemma $lemma) + { + if (!$this->lemmas->contains($lemma)) { + $this->lemmas[] = $lemma; + $lemma->addType($this); + } + } + + /** + * + * @param kateglo\application\models\Lemma $lemma + * @return void + */ + public function removeLEmma(Lemma $lemma) + { + $removed = $this->lemmas->removeElement($lemma); + + if ($removed !== null) { + $removed->removeType($this); + } + } + + /** + * + * @return kateglo\application\helpers\collections\ArrayCollection + */ + public function getCategories() + { + return $this->categories; + } +} /** - * @Entity - * @Table(name="phrase") + * @ORM\Entity + * @ORM\Table(name="phrase") */ -class Phrase { - +class Phrase +{ const CLASS_NAME = __CLASS__; /** - * @Id - * @Column(type="integer", name="phrase_id") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer", name="phrase_id") + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** - * @Column(type="string", name="phrase_name", unique=true, length=255) + * @ORM\Column(type="string", name="phrase_name", unique=true, length=255) */ private $phrase; /** - * @ManyToOne(targetEntity="PhraseType") - * @JoinColumn(name="phrase_type_id", referencedColumnName="phrase_type_id") + * @ORM\ManyToOne(targetEntity="PhraseType") + * @ORM\JoinColumn(name="phrase_type_id", referencedColumnName="phrase_type_id") */ private $type; /** - * @OneToMany(targetEntity="Definition", mappedBy="phrase", cascade={"persist"}) + * @ORM\OneToMany(targetEntity="Definition", mappedBy="phrase", cascade={"persist"}) */ private $definitions; - public function __construct() { + public function __construct() + { $this->definitions = new ArrayCollection; } @@ -384,7 +413,8 @@ public function __construct() { * @param Definition $definition * @return void */ - public function addDefinition(Definition $definition){ + public function addDefinition(Definition $definition) + { $this->definitions[] = $definition; $definition->setPhrase($this); } @@ -392,7 +422,8 @@ public function addDefinition(Definition $definition){ /** * @return int */ - public function getId(){ + public function getId() + { return $this->id; } @@ -400,14 +431,16 @@ public function getId(){ * @param string $phrase * @return void */ - public function setPhrase($phrase){ + public function setPhrase($phrase) + { $this->phrase = $phrase; } /** * @return string */ - public function getPhrase(){ + public function getPhrase() + { return $this->phrase; } @@ -416,7 +449,8 @@ public function getPhrase(){ * @param PhraseType $type * @return void */ - public function setType(PhraseType $type){ + public function setType(PhraseType $type) + { $this->type = $type; } @@ -424,7 +458,8 @@ public function setType(PhraseType $type){ * * @return PhraseType */ - public function getType(){ + public function getType() + { return $this->type; } @@ -432,49 +467,52 @@ public function getType(){ * * @return ArrayCollection */ - public function getDefinitions(){ + public function getDefinitions() + { return $this->definitions; } } /** - * @Entity - * @Table(name="phrase_type") + * @ORM\Entity + * @ORM\Table(name="phrase_type") */ -class PhraseType { - +class PhraseType +{ const CLASS_NAME = __CLASS__; /** - * @Id - * @Column(type="integer", name="phrase_type_id") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer", name="phrase_type_id") + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** - * @Column(type="string", name="phrase_type_name", unique=true) + * @ORM\Column(type="string", name="phrase_type_name", unique=true) */ private $type; /** - * @Column(type="string", name="phrase_type_abbreviation", unique=true) + * @ORM\Column(type="string", name="phrase_type_abbreviation", unique=true) */ private $abbreviation; /** - * @OneToMany(targetEntity="Phrase", mappedBy="type") + * @ORM\OneToMany(targetEntity="Phrase", mappedBy="type") */ private $phrases; - public function __construct() { + public function __construct() + { $this->phrases = new ArrayCollection; } /** * @return int */ - public function getId(){ + public function getId() + { return $this->id; } @@ -482,14 +520,16 @@ public function getId(){ * @param string $type * @return void */ - public function setType($type){ + public function setType($type) + { $this->type = $type; } /** * @return string */ - public function getType(){ + public function getType() + { return $this->type; } @@ -497,14 +537,16 @@ public function getType(){ * @param string $abbreviation * @return void */ - public function setAbbreviation($abbreviation){ + public function setAbbreviation($abbreviation) + { $this->abbreviation = $abbreviation; } /** * @return string */ - public function getAbbreviation(){ + public function getAbbreviation() + { return $this->abbreviation; } @@ -512,7 +554,8 @@ public function getAbbreviation(){ * @param ArrayCollection $phrases * @return void */ - public function setPhrases($phrases){ + public function setPhrases($phrases) + { $this->phrases = $phrases; } @@ -520,42 +563,44 @@ public function setPhrases($phrases){ * * @return ArrayCollection */ - public function getPhrases(){ + public function getPhrases() + { return $this->phrases; } } /** - * @Entity - * @Table(name="definition") + * @ORM\Entity + * @ORM\Table(name="definition") */ -class Definition { - +class Definition +{ const CLASS_NAME = __CLASS__; /** - * @Id - * @Column(type="integer", name="definition_id") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer", name="definition_id") + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** - * @ManyToOne(targetEntity="Phrase") - * @JoinColumn(name="definition_phrase_id", referencedColumnName="phrase_id") + * @ORM\ManyToOne(targetEntity="Phrase") + * @ORM\JoinColumn(name="definition_phrase_id", referencedColumnName="phrase_id") */ private $phrase; /** - * @Column(type="text", name="definition_text") + * @ORM\Column(type="text", name="definition_text") */ private $definition; /** * @return int */ - public function getId(){ + public function getId() + { return $this->id; } @@ -563,18 +608,21 @@ public function getId(){ * @param Phrase $phrase * @return void */ - public function setPhrase(Phrase $phrase){ + public function setPhrase(Phrase $phrase) + { $this->phrase = $phrase; } /** * @return Phrase */ - public function getPhrase(){ + public function getPhrase() + { return $this->phrase; } - public function removePhrase() { + public function removePhrase() + { if ($this->phrase !== null) { /*@var $phrase kateglo\application\models\Phrase */ $phrase = $this->phrase; @@ -587,14 +635,16 @@ public function removePhrase() { * @param string $definition * @return void */ - public function setDefinition($definition){ + public function setDefinition($definition) + { $this->definition = $definition; } /** * @return string */ - public function getDefinition(){ + public function getDefinition() + { return $this->definition; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/AdvancedDqlQueryTest.php b/tests/Doctrine/Tests/ORM/Functional/AdvancedDqlQueryTest.php index a7c35412b52..bd7e153adb9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/AdvancedDqlQueryTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/AdvancedDqlQueryTest.php @@ -1,10 +1,12 @@ useModelSet('company'); + parent::setUp(); $this->generateFixture(); @@ -28,13 +31,13 @@ public function testAggregateWithHavingClause() 'FROM Doctrine\Tests\Models\Company\CompanyEmployee p '. 'GROUP BY p.department HAVING SUM(p.salary) > 200000 ORDER BY p.department'; - $result = $this->_em->createQuery($dql)->getScalarResult(); + $result = $this->em->createQuery($dql)->getScalarResult(); - $this->assertEquals(2, count($result)); - $this->assertEquals('IT', $result[0]['department']); - $this->assertEquals(150000, $result[0]['avgSalary']); - $this->assertEquals('IT2', $result[1]['department']); - $this->assertEquals(600000, $result[1]['avgSalary']); + self::assertEquals(2, count($result)); + self::assertEquals('IT', $result[0]['department']); + self::assertEquals(150000, $result[0]['avgSalary']); + self::assertEquals('IT2', $result[1]['department']); + self::assertEquals(600000, $result[1]['avgSalary']); } public function testUnnamedScalarResultsAreOneBased() @@ -43,11 +46,11 @@ public function testUnnamedScalarResultsAreOneBased() 'FROM Doctrine\Tests\Models\Company\CompanyEmployee p '. 'GROUP BY p.department HAVING SUM(p.salary) > 200000 ORDER BY p.department'; - $result = $this->_em->createQuery($dql)->getScalarResult(); + $result = $this->em->createQuery($dql)->getScalarResult(); - $this->assertEquals(2, count($result)); - $this->assertEquals(150000, $result[0][1]); - $this->assertEquals(600000, $result[1][1]); + self::assertEquals(2, count($result)); + self::assertEquals(150000, $result[0][1]); + self::assertEquals(600000, $result[1][1]); } public function testOrderByResultVariableCollectionSize() @@ -57,84 +60,84 @@ public function testOrderByResultVariableCollectionSize() 'WHERE p.friends IS NOT EMPTY ' . 'ORDER BY friends DESC, p.name DESC'; - $result = $this->_em->createQuery($dql)->getScalarResult(); + $result = $this->em->createQuery($dql)->getScalarResult(); - $this->assertEquals(4, count($result)); + self::assertEquals(4, count($result)); - $this->assertEquals("Jonathan W.", $result[0]['name']); - $this->assertEquals(3, $result[0]['friends']); + self::assertEquals("Jonathan W.", $result[0]['name']); + self::assertEquals(3, $result[0]['friends']); - $this->assertEquals('Guilherme B.', $result[1]['name']); - $this->assertEquals(2, $result[1]['friends']); + self::assertEquals('Guilherme B.', $result[1]['name']); + self::assertEquals(2, $result[1]['friends']); - $this->assertEquals('Benjamin E.', $result[2]['name']); - $this->assertEquals(2, $result[2]['friends']); + self::assertEquals('Benjamin E.', $result[2]['name']); + self::assertEquals(2, $result[2]['friends']); - $this->assertEquals('Roman B.', $result[3]['name']); - $this->assertEquals(1, $result[3]['friends']); + self::assertEquals('Roman B.', $result[3]['name']); + self::assertEquals(1, $result[3]['friends']); } public function testIsNullAssociation() { $dql = 'SELECT p FROM Doctrine\Tests\Models\Company\CompanyPerson p '. 'WHERE p.spouse IS NULL'; - $result = $this->_em->createQuery($dql)->getResult(); + $result = $this->em->createQuery($dql)->getResult(); - $this->assertEquals(2, count($result)); - $this->assertTrue($result[0]->getId() > 0); - $this->assertNull($result[0]->getSpouse()); + self::assertEquals(2, count($result)); + self::assertTrue($result[0]->getId() > 0); + self::assertNull($result[0]->getSpouse()); - $this->assertTrue($result[1]->getId() > 0); - $this->assertNull($result[1]->getSpouse()); + self::assertTrue($result[1]->getId() > 0); + self::assertNull($result[1]->getSpouse()); } public function testSelectSubselect() { $dql = 'SELECT p, (SELECT c.brand FROM Doctrine\Tests\Models\Company\CompanyCar c WHERE p.car = c) brandName '. 'FROM Doctrine\Tests\Models\Company\CompanyManager p'; - $result = $this->_em->createQuery($dql)->getArrayResult(); + $result = $this->em->createQuery($dql)->getArrayResult(); - $this->assertEquals(1, count($result)); - $this->assertEquals("Caramba", $result[0]['brandName']); + self::assertEquals(1, count($result)); + self::assertEquals("Caramba", $result[0]['brandName']); } public function testInSubselect() { $dql = "SELECT p.name FROM Doctrine\Tests\Models\Company\CompanyPerson p ". "WHERE p.name IN (SELECT n.name FROM Doctrine\Tests\Models\Company\CompanyPerson n WHERE n.name = 'Roman B.')"; - $result = $this->_em->createQuery($dql)->getScalarResult(); + $result = $this->em->createQuery($dql)->getScalarResult(); - $this->assertEquals(1, count($result)); - $this->assertEquals('Roman B.', $result[0]['name']); + self::assertEquals(1, count($result)); + self::assertEquals('Roman B.', $result[0]['name']); } public function testGroupByMultipleFields() { $dql = 'SELECT p.department, p.name, count(p.id) FROM Doctrine\Tests\Models\Company\CompanyEmployee p '. 'GROUP BY p.department, p.name'; - $result = $this->_em->createQuery($dql)->getResult(); + $result = $this->em->createQuery($dql)->getResult(); - $this->assertEquals(4, count($result)); + self::assertEquals(4, count($result)); } public function testUpdateAs() { $dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyEmployee AS p SET p.salary = 1'; - $this->_em->createQuery($dql)->execute(); + $this->em->createQuery($dql)->execute(); - $this->assertTrue(count($this->_em->createQuery( + self::assertTrue(count($this->em->createQuery( 'SELECT count(p.id) FROM Doctrine\Tests\Models\Company\CompanyEmployee p WHERE p.salary = 1')->getResult()) > 0); } public function testDeleteAs() { $dql = 'DELETE Doctrine\Tests\Models\Company\CompanyEmployee AS p'; - $this->_em->createQuery($dql)->getResult(); + $this->em->createQuery($dql)->getResult(); $dql = 'SELECT count(p) FROM Doctrine\Tests\Models\Company\CompanyEmployee p'; - $result = $this->_em->createQuery($dql)->getSingleScalarResult(); + $result = $this->em->createQuery($dql)->getSingleScalarResult(); - $this->assertEquals(0, $result); + self::assertEquals(0, $result); } public function generateFixture() @@ -170,12 +173,12 @@ public function generateFixture() $person2->addFriend($person4); $person3->addFriend($person4); - $this->_em->persist($car); - $this->_em->persist($manager1); - $this->_em->persist($person2); - $this->_em->persist($person3); - $this->_em->persist($person4); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($car); + $this->em->persist($manager1); + $this->em->persist($person2); + $this->em->persist($person3); + $this->em->persist($person4); + $this->em->flush(); + $this->em->clear(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/BasicFunctionalTest.php b/tests/Doctrine/Tests/ORM/Functional/BasicFunctionalTest.php index 7bdb846535c..0f7f28a232f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/BasicFunctionalTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/BasicFunctionalTest.php @@ -1,10 +1,13 @@ name = 'Roman'; $user->username = 'romanb'; $user->status = 'developer'; - $this->_em->persist($user); + $this->em->persist($user); - $this->_em->flush(); + $this->em->flush(); - $this->assertTrue(is_numeric($user->id)); - $this->assertTrue($this->_em->contains($user)); + self::assertTrue(is_numeric($user->id)); + self::assertTrue($this->em->contains($user)); // Read - $user2 = $this->_em->find(CmsUser::class, $user->id); - $this->assertTrue($user === $user2); + $user2 = $this->em->find(CmsUser::class, $user->id); + self::assertTrue($user === $user2); // Add a phonenumber $ph = new CmsPhonenumber; $ph->phonenumber = "12345"; $user->addPhonenumber($ph); - $this->_em->flush(); - $this->assertTrue($this->_em->contains($ph)); - $this->assertTrue($this->_em->contains($user)); + $this->em->flush(); + self::assertTrue($this->em->contains($ph)); + self::assertTrue($this->em->contains($user)); // Update name $user->name = 'guilherme'; - $this->_em->flush(); - $this->assertEquals('guilherme', $user->name); + $this->em->flush(); + self::assertEquals('guilherme', $user->name); // Add another phonenumber $ph2 = new CmsPhonenumber; $ph2->phonenumber = "6789"; $user->addPhonenumber($ph2); - $this->_em->flush(); - $this->assertTrue($this->_em->contains($ph2)); + $this->em->flush(); + self::assertTrue($this->em->contains($ph2)); // Delete - $this->_em->remove($user); - $this->assertTrue($this->_em->getUnitOfWork()->isScheduledForDelete($user)); - $this->assertTrue($this->_em->getUnitOfWork()->isScheduledForDelete($ph)); - $this->assertTrue($this->_em->getUnitOfWork()->isScheduledForDelete($ph2)); - $this->_em->flush(); - $this->assertFalse($this->_em->getUnitOfWork()->isScheduledForDelete($user)); - $this->assertFalse($this->_em->getUnitOfWork()->isScheduledForDelete($ph)); - $this->assertFalse($this->_em->getUnitOfWork()->isScheduledForDelete($ph2)); - $this->assertEquals(UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($user)); - $this->assertEquals(UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($ph)); - $this->assertEquals(UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($ph2)); + $this->em->remove($user); + self::assertTrue($this->em->getUnitOfWork()->isScheduledForDelete($user)); + self::assertTrue($this->em->getUnitOfWork()->isScheduledForDelete($ph)); + self::assertTrue($this->em->getUnitOfWork()->isScheduledForDelete($ph2)); + $this->em->flush(); + self::assertFalse($this->em->getUnitOfWork()->isScheduledForDelete($user)); + self::assertFalse($this->em->getUnitOfWork()->isScheduledForDelete($ph)); + self::assertFalse($this->em->getUnitOfWork()->isScheduledForDelete($ph2)); + self::assertEquals(\Doctrine\ORM\UnitOfWork::STATE_NEW, $this->em->getUnitOfWork()->getEntityState($user)); + self::assertEquals(\Doctrine\ORM\UnitOfWork::STATE_NEW, $this->em->getUnitOfWork()->getEntityState($ph)); + self::assertEquals(\Doctrine\ORM\UnitOfWork::STATE_NEW, $this->em->getUnitOfWork()->getEntityState($ph2)); } public function testOneToManyAssociationModification() @@ -92,22 +95,22 @@ public function testOneToManyAssociationModification() $user->addPhonenumber($ph1); $user->addPhonenumber($ph2); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); // Remove the first element from the collection unset($user->phonenumbers[0]); $ph1->user = null; // owning side! - $this->_em->flush(); + $this->em->flush(); - $this->assertEquals(1, count($user->phonenumbers)); - $this->assertNull($ph1->user); + self::assertEquals(1, count($user->phonenumbers)); + self::assertNull($ph1->user); } public function testBasicOneToOne() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $user = new CmsUser; $user->name = 'Roman'; $user->username = 'romanb'; @@ -121,24 +124,24 @@ public function testBasicOneToOne() $user->address = $address; // inverse side $address->user = $user; // owning side! - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); // Check that the foreign key has been set - $userId = $this->_em->getConnection()->executeQuery( + $userId = $this->em->getConnection()->executeQuery( "SELECT user_id FROM cms_addresses WHERE id=?", [$address->id] )->fetchColumn(); - $this->assertTrue(is_numeric($userId)); + self::assertTrue(is_numeric($userId)); - $this->_em->clear(); + $this->em->clear(); - $user2 = $this->_em->createQuery('select u from \Doctrine\Tests\Models\CMS\CmsUser u where u.id=?1') + $user2 = $this->em->createQuery('select u from \Doctrine\Tests\Models\CMS\CmsUser u where u.id=?1') ->setParameter(1, $userId) ->getSingleResult(); // Address has been eager-loaded because it cant be lazy - $this->assertInstanceOf(CmsAddress::class, $user2->address); - $this->assertNotInstanceOf(Proxy::class, $user2->address); + self::assertInstanceOf(CmsAddress::class, $user2->address); + self::assertNotInstanceOf(Proxy::class, $user2->address); } /** @@ -151,28 +154,28 @@ public function testRemove() $user->username = 'gblanco'; $user->status = 'developer'; - $this->assertEquals(UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($user), "State should be UnitOfWork::STATE_NEW"); + self::assertEquals(UnitOfWork::STATE_NEW, $this->em->getUnitOfWork()->getEntityState($user), "State should be UnitOfWork::STATE_NEW"); - $this->_em->persist($user); + $this->em->persist($user); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($user), "State should be UnitOfWork::STATE_MANAGED"); + self::assertEquals(UnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($user), "State should be UnitOfWork::STATE_MANAGED"); - $this->_em->remove($user); + $this->em->remove($user); - $this->assertEquals(UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($user), "State should be UnitOfWork::STATE_NEW"); + self::assertEquals(UnitOfWork::STATE_NEW, $this->em->getUnitOfWork()->getEntityState($user), "State should be UnitOfWork::STATE_NEW"); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); $id = $user->getId(); - $this->_em->remove($user); + $this->em->remove($user); - $this->assertEquals(UnitOfWork::STATE_REMOVED, $this->_em->getUnitOfWork()->getEntityState($user), "State should be UnitOfWork::STATE_REMOVED"); - $this->_em->flush(); + self::assertEquals(UnitOfWork::STATE_REMOVED, $this->em->getUnitOfWork()->getEntityState($user), "State should be UnitOfWork::STATE_REMOVED"); + $this->em->flush(); - $this->assertEquals(UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($user), "State should be UnitOfWork::STATE_NEW"); + self::assertEquals(UnitOfWork::STATE_NEW, $this->em->getUnitOfWork()->getEntityState($user), "State should be UnitOfWork::STATE_NEW"); - $this->assertNull($this->_em->find(CmsUser::class, $id)); + self::assertNull($this->em->find(CmsUser::class, $id)); } public function testOneToManyOrphanRemoval() @@ -188,23 +191,23 @@ public function testOneToManyOrphanRemoval() $user->addPhonenumber($phone); } - $this->_em->persist($user); + $this->em->persist($user); - $this->_em->flush(); + $this->em->flush(); $user->getPhonenumbers()->remove(0); - $this->assertEquals(2, count($user->getPhonenumbers())); + self::assertEquals(2, count($user->getPhonenumbers())); - $this->_em->flush(); + $this->em->flush(); // Check that there are just 2 phonenumbers left - $count = $this->_em->getConnection()->fetchColumn("SELECT COUNT(*) FROM cms_phonenumbers"); - $this->assertEquals(2, $count); // only 2 remaining + $count = $this->em->getConnection()->fetchColumn("SELECT COUNT(*) FROM cms_phonenumbers"); + self::assertEquals(2, $count); // only 2 remaining // check that clear() removes the others via orphan removal $user->getPhonenumbers()->clear(); - $this->_em->flush(); - $this->assertEquals(0, $this->_em->getConnection()->fetchColumn("select count(*) from cms_phonenumbers")); + $this->em->flush(); + self::assertEquals(0, $this->em->getConnection()->fetchColumn("select count(*) from cms_phonenumbers")); } public function testBasicQuery() @@ -213,35 +216,35 @@ public function testBasicQuery() $user->name = 'Guilherme'; $user->username = 'gblanco'; $user->status = 'developer'; - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); - $query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u"); + $query = $this->em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u"); $users = $query->getResult(); - $this->assertEquals(1, count($users)); - $this->assertEquals('Guilherme', $users[0]->name); - $this->assertEquals('gblanco', $users[0]->username); - $this->assertEquals('developer', $users[0]->status); - //$this->assertNull($users[0]->phonenumbers); - //$this->assertNull($users[0]->articles); + self::assertEquals(1, count($users)); + self::assertEquals('Guilherme', $users[0]->name); + self::assertEquals('gblanco', $users[0]->username); + self::assertEquals('developer', $users[0]->status); + //self::assertNull($users[0]->phonenumbers); + //self::assertNull($users[0]->articles); $usersArray = $query->getArrayResult(); - $this->assertTrue(is_array($usersArray)); - $this->assertEquals(1, count($usersArray)); - $this->assertEquals('Guilherme', $usersArray[0]['name']); - $this->assertEquals('gblanco', $usersArray[0]['username']); - $this->assertEquals('developer', $usersArray[0]['status']); + self::assertTrue(is_array($usersArray)); + self::assertEquals(1, count($usersArray)); + self::assertEquals('Guilherme', $usersArray[0]['name']); + self::assertEquals('gblanco', $usersArray[0]['username']); + self::assertEquals('developer', $usersArray[0]['status']); $usersScalar = $query->getScalarResult(); - $this->assertTrue(is_array($usersScalar)); - $this->assertEquals(1, count($usersScalar)); - $this->assertEquals('Guilherme', $usersScalar[0]['u_name']); - $this->assertEquals('gblanco', $usersScalar[0]['u_username']); - $this->assertEquals('developer', $usersScalar[0]['u_status']); + self::assertTrue(is_array($usersScalar)); + self::assertEquals(1, count($usersScalar)); + self::assertEquals('Guilherme', $usersScalar[0]['u_name']); + self::assertEquals('gblanco', $usersScalar[0]['u_username']); + self::assertEquals('developer', $usersScalar[0]['u_status']); } public function testBasicOneToManyInnerJoin() @@ -250,14 +253,14 @@ public function testBasicOneToManyInnerJoin() $user->name = 'Guilherme'; $user->username = 'gblanco'; $user->status = 'developer'; - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); - $query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u join u.phonenumbers p"); + $query = $this->em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u join u.phonenumbers p"); $users = $query->getResult(); - $this->assertEquals(0, count($users)); + self::assertEquals(0, count($users)); } public function testBasicOneToManyLeftJoin() @@ -266,20 +269,20 @@ public function testBasicOneToManyLeftJoin() $user->name = 'Guilherme'; $user->username = 'gblanco'; $user->status = 'developer'; - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); - $query = $this->_em->createQuery("select u,p from Doctrine\Tests\Models\CMS\CmsUser u left join u.phonenumbers p"); + $query = $this->em->createQuery("select u,p from Doctrine\Tests\Models\CMS\CmsUser u left join u.phonenumbers p"); $users = $query->getResult(); - $this->assertEquals(1, count($users)); - $this->assertEquals('Guilherme', $users[0]->name); - $this->assertEquals('gblanco', $users[0]->username); - $this->assertEquals('developer', $users[0]->status); - $this->assertInstanceOf(PersistentCollection::class, $users[0]->phonenumbers); - $this->assertTrue($users[0]->phonenumbers->isInitialized()); - $this->assertEquals(0, $users[0]->phonenumbers->count()); + self::assertEquals(1, count($users)); + self::assertEquals('Guilherme', $users[0]->name); + self::assertEquals('gblanco', $users[0]->username); + self::assertEquals('developer', $users[0]->status); + self::assertInstanceOf(PersistentCollection::class, $users[0]->phonenumbers); + self::assertTrue($users[0]->phonenumbers->isInitialized()); + self::assertEquals(0, $users[0]->phonenumbers->count()); } public function testBasicRefresh() @@ -289,14 +292,14 @@ public function testBasicRefresh() $user->username = 'gblanco'; $user->status = 'developer'; - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); $user->status = 'mascot'; - $this->assertEquals('mascot', $user->status); - $this->_em->refresh($user); - $this->assertEquals('developer', $user->status); + self::assertEquals('mascot', $user->status); + $this->em->refresh($user); + self::assertEquals('developer', $user->status); } /** @@ -318,17 +321,17 @@ public function testRefreshResetsCollection() $ph2 = new CmsPhonenumber; $ph2->phonenumber = "54321"; - $this->_em->persist($user); - $this->_em->persist($ph1); - $this->_em->persist($ph2); - $this->_em->flush(); + $this->em->persist($user); + $this->em->persist($ph1); + $this->em->persist($ph2); + $this->em->flush(); $user->addPhonenumber($ph2); - $this->assertEquals(2, count($user->phonenumbers)); - $this->_em->refresh($user); + self::assertEquals(2, count($user->phonenumbers)); + $this->em->refresh($user); - $this->assertEquals(1, count($user->phonenumbers)); + self::assertEquals(1, count($user->phonenumbers)); } /** @@ -350,21 +353,21 @@ public function testDqlRefreshResetsCollection() $ph2 = new CmsPhonenumber; $ph2->phonenumber = "54321"; - $this->_em->persist($user); - $this->_em->persist($ph1); - $this->_em->persist($ph2); - $this->_em->flush(); + $this->em->persist($user); + $this->em->persist($ph1); + $this->em->persist($ph2); + $this->em->flush(); $user->addPhonenumber($ph2); - $this->assertEquals(2, count($user->phonenumbers)); + self::assertEquals(2, count($user->phonenumbers)); $dql = "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1"; - $user = $this->_em->createQuery($dql) + $user = $this->em->createQuery($dql) ->setParameter(1, $user->id) ->setHint(Query::HINT_REFRESH, true) ->getSingleResult(); - $this->assertEquals(1, count($user->phonenumbers)); + self::assertEquals(1, count($user->phonenumbers)); } /** @@ -386,21 +389,21 @@ public function testCreateEntityOfProxy() $ph2 = new CmsPhonenumber; $ph2->phonenumber = "54321"; - $this->_em->persist($user); - $this->_em->persist($ph1); - $this->_em->persist($ph2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->persist($ph1); + $this->em->persist($ph2); + $this->em->flush(); + $this->em->clear(); $userId = $user->id; - $user = $this->_em->getReference(CmsUser::class, $user->id); + $user = $this->em->getReference(CmsUser::class, $user->id); $dql = "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1"; - $user = $this->_em->createQuery($dql) + $user = $this->em->createQuery($dql) ->setParameter(1, $userId) ->getSingleResult(); - $this->assertEquals(1, count($user->phonenumbers)); + self::assertEquals(1, count($user->phonenumbers)); } public function testAddToCollectionDoesNotInitialize() @@ -416,31 +419,31 @@ public function testAddToCollectionDoesNotInitialize() $user->addPhonenumber($phone); } - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $this->assertEquals(3, $user->getPhonenumbers()->count()); + self::assertEquals(3, $user->getPhonenumbers()->count()); - $query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username='gblanco'"); + $query = $this->em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username='gblanco'"); $gblanco = $query->getSingleResult(); - $this->assertFalse($gblanco->getPhonenumbers()->isInitialized()); + self::assertFalse($gblanco->getPhonenumbers()->isInitialized()); $newPhone = new CmsPhonenumber; $newPhone->phonenumber = 555; $gblanco->addPhonenumber($newPhone); - $this->assertFalse($gblanco->getPhonenumbers()->isInitialized()); - $this->_em->persist($gblanco); + self::assertFalse($gblanco->getPhonenumbers()->isInitialized()); + $this->em->persist($gblanco); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery("select u, p from Doctrine\Tests\Models\CMS\CmsUser u join u.phonenumbers p where u.username='gblanco'"); + $query = $this->em->createQuery("select u, p from Doctrine\Tests\Models\CMS\CmsUser u join u.phonenumbers p where u.username='gblanco'"); $gblanco2 = $query->getSingleResult(); - $this->assertEquals(4, $gblanco2->getPhonenumbers()->count()); + self::assertEquals(4, $gblanco2->getPhonenumbers()->count()); } public function testInitializeCollectionWithNewObjectsRetainsNewObjects() @@ -456,71 +459,32 @@ public function testInitializeCollectionWithNewObjectsRetainsNewObjects() $user->addPhonenumber($phone); } - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $this->assertEquals(3, $user->getPhonenumbers()->count()); + self::assertEquals(3, $user->getPhonenumbers()->count()); - $query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username='gblanco'"); + $query = $this->em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username='gblanco'"); $gblanco = $query->getSingleResult(); - $this->assertFalse($gblanco->getPhonenumbers()->isInitialized()); + self::assertFalse($gblanco->getPhonenumbers()->isInitialized()); $newPhone = new CmsPhonenumber; $newPhone->phonenumber = 555; $gblanco->addPhonenumber($newPhone); - $this->assertFalse($gblanco->getPhonenumbers()->isInitialized()); - $this->assertEquals(4, $gblanco->getPhonenumbers()->count()); - $this->assertTrue($gblanco->getPhonenumbers()->isInitialized()); + self::assertFalse($gblanco->getPhonenumbers()->isInitialized()); + self::assertEquals(4, $gblanco->getPhonenumbers()->count()); + self::assertTrue($gblanco->getPhonenumbers()->isInitialized()); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery("select u, p from Doctrine\Tests\Models\CMS\CmsUser u join u.phonenumbers p where u.username='gblanco'"); + $query = $this->em->createQuery("select u, p from Doctrine\Tests\Models\CMS\CmsUser u join u.phonenumbers p where u.username='gblanco'"); $gblanco2 = $query->getSingleResult(); - $this->assertEquals(4, $gblanco2->getPhonenumbers()->count()); - } - - public function testSetSetAssociationWithGetReference() - { - $user = new CmsUser; - $user->name = 'Guilherme'; - $user->username = 'gblanco'; - $user->status = 'developer'; - $this->_em->persist($user); - - $address = new CmsAddress; - $address->country = 'Germany'; - $address->city = 'Berlin'; - $address->zip = '12345'; - $this->_em->persist($address); - - $this->_em->flush(); - $this->_em->detach($address); - - $this->assertFalse($this->_em->contains($address)); - $this->assertTrue($this->_em->contains($user)); - - // Assume we only got the identifier of the address and now want to attach - // that address to the user without actually loading it, using getReference(). - $addressRef = $this->_em->getReference(CmsAddress::class, $address->getId()); - - $user->setAddress($addressRef); // Ugh! Initializes address 'cause of $address->setUser($user)! - - $this->_em->flush(); - $this->_em->clear(); - - // Check with a fresh load that the association is indeed there - $query = $this->_em->createQuery("select u, a from Doctrine\Tests\Models\CMS\CmsUser u join u.address a where u.username='gblanco'"); - $gblanco = $query->getSingleResult(); - - $this->assertInstanceOf(CmsUser::class, $gblanco); - $this->assertInstanceOf(CmsAddress::class, $gblanco->getAddress()); - $this->assertEquals('Berlin', $gblanco->getAddress()->getCity()); - + self::assertEquals(4, $gblanco2->getPhonenumbers()->count()); } public function testOneToManyCascadeRemove() @@ -536,23 +500,23 @@ public function testOneToManyCascadeRemove() $user->addPhonenumber($phone); } - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username='gblanco'"); + $query = $this->em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username='gblanco'"); $gblanco = $query->getSingleResult(); - $this->_em->remove($gblanco); - $this->_em->flush(); + $this->em->remove($gblanco); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); - $this->assertEquals(0, $this->_em->createQuery( + self::assertEquals(0, $this->em->createQuery( "select count(p.phonenumber) from Doctrine\Tests\Models\CMS\CmsPhonenumber p") ->getSingleScalarResult()); - $this->assertEquals(0, $this->_em->createQuery( + self::assertEquals(0, $this->em->createQuery( "select count(u.id) from Doctrine\Tests\Models\CMS\CmsUser u") ->getSingleScalarResult()); } @@ -564,34 +528,34 @@ public function testTextColumnSaveAndRetrieve() $user->username = 'gblanco'; $user->status = 'developer'; - $this->_em->persist($user); + $this->em->persist($user); $article = new CmsArticle(); $article->text = "Lorem ipsum dolor sunt."; $article->topic = "A Test Article!"; $article->setAuthor($user); - $this->_em->persist($article); - $this->_em->flush(); + $this->em->persist($article); + $this->em->flush(); $articleId = $article->id; - $this->_em->clear(); + $this->em->clear(); // test find() with leading backslash at the same time - $articleNew = $this->_em->find('\Doctrine\Tests\Models\CMS\CmsArticle', $articleId); - $this->assertTrue($this->_em->contains($articleNew)); - $this->assertEquals("Lorem ipsum dolor sunt.", $articleNew->text); + $articleNew = $this->em->find('\Doctrine\Tests\Models\CMS\CmsArticle', $articleId); + self::assertTrue($this->em->contains($articleNew)); + self::assertEquals("Lorem ipsum dolor sunt.", $articleNew->text); - $this->assertNotSame($article, $articleNew); + self::assertNotSame($article, $articleNew); $articleNew->text = "Lorem ipsum dolor sunt. And stuff!"; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $articleNew = $this->_em->find(CmsArticle::class, $articleId); - $this->assertEquals("Lorem ipsum dolor sunt. And stuff!", $articleNew->text); - $this->assertTrue($this->_em->contains($articleNew)); + $articleNew = $this->em->find(CmsArticle::class, $articleId); + self::assertEquals("Lorem ipsum dolor sunt. And stuff!", $articleNew->text); + self::assertTrue($this->em->contains($articleNew)); } public function testFlushDoesNotIssueUnnecessaryUpdates() @@ -614,28 +578,28 @@ public function testFlushDoesNotIssueUnnecessaryUpdates() $article->topic = "A Test Article!"; $article->setAuthor($user); - $this->_em->persist($article); - $this->_em->persist($user); + $this->em->persist($article); + $this->em->persist($user); - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery('select u,a,ad from Doctrine\Tests\Models\CMS\CmsUser u join u.articles a join u.address ad'); + $query = $this->em->createQuery('select u,a,ad from Doctrine\Tests\Models\CMS\CmsUser u join u.articles a join u.address ad'); $user2 = $query->getSingleResult(); - $this->assertEquals(1, count($user2->articles)); - $this->assertInstanceOf(CmsAddress::class, $user2->address); + self::assertEquals(1, count($user2->articles)); + self::assertInstanceOf(CmsAddress::class, $user2->address); - $oldLogger = $this->_em->getConnection()->getConfiguration()->getSQLLogger(); + $oldLogger = $this->em->getConnection()->getConfiguration()->getSQLLogger(); $debugStack = new DebugStack(); - $this->_em->getConnection()->getConfiguration()->setSQLLogger($debugStack); + $this->em->getConnection()->getConfiguration()->setSQLLogger($debugStack); - $this->_em->flush(); - $this->assertEquals(0, count($debugStack->queries)); + $this->em->flush(); + self::assertEquals(0, count($debugStack->queries)); - $this->_em->getConnection()->getConfiguration()->setSQLLogger($oldLogger); + $this->em->getConnection()->getConfiguration()->setSQLLogger($oldLogger); } public function testRemoveEntityByReference() @@ -645,20 +609,20 @@ public function testRemoveEntityByReference() $user->username = 'gblanco'; $user->status = 'developer'; - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $userRef = $this->_em->getReference(CmsUser::class, $user->getId()); - $this->_em->remove($userRef); - $this->_em->flush(); - $this->_em->clear(); + $userRef = $this->em->getReference(CmsUser::class, $user->getId()); + $this->em->remove($userRef); + $this->em->flush(); + $this->em->clear(); - $this->assertEquals(0, $this->_em->getConnection()->fetchColumn("select count(*) from cms_users")); + self::assertEquals(0, $this->em->getConnection()->fetchColumn("select count(*) from cms_users")); - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(null); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(null); } public function testQueryEntityByReference() @@ -675,24 +639,24 @@ public function testQueryEntityByReference() $user->setAddress($address); - $this->_em->transactional(function($em) use($user) { + $this->em->transactional(function($em) use($user) { $em->persist($user); }); - $this->_em->clear(); + $this->em->clear(); - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $userRef = $this->_em->getReference(CmsUser::class, $user->getId()); - $address2 = $this->_em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsAddress a where a.user = :user') + $userRef = $this->em->getReference(CmsUser::class, $user->getId()); + $address2 = $this->em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsAddress a where a.user = :user') ->setParameter('user', $userRef) ->getSingleResult(); - $this->assertInstanceOf(Proxy::class, $address2->getUser()); - $this->assertTrue($userRef === $address2->getUser()); - $this->assertFalse($userRef->__isInitialized__); - $this->assertEquals('Germany', $address2->country); - $this->assertEquals('Berlin', $address2->city); - $this->assertEquals('12345', $address2->zip); + self::assertInstanceOf(Proxy::class, $address2->getUser()); + self::assertTrue($userRef === $address2->getUser()); + self::assertFalse($userRef->__isInitialized()); + self::assertEquals('Germany', $address2->country); + self::assertEquals('Berlin', $address2->city); + self::assertEquals('12345', $address2->zip); } public function testOneToOneNullUpdate() @@ -709,16 +673,16 @@ public function testOneToOneNullUpdate() $address->street = "somestreet"; $address->user = $user; - $this->_em->persist($address); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($address); + $this->em->persist($user); + $this->em->flush(); - $this->assertEquals(1, $this->_em->getConnection()->fetchColumn("select 1 from cms_addresses where user_id = ".$user->id)); + self::assertEquals(1, $this->em->getConnection()->fetchColumn("select 1 from cms_addresses where user_id = ".$user->id)); $address->user = null; - $this->_em->flush(); + $this->em->flush(); - $this->assertNotEquals(1, $this->_em->getConnection()->fetchColumn("select 1 from cms_addresses where user_id = ".$user->id)); + self::assertNotEquals(1, $this->em->getConnection()->fetchColumn("select 1 from cms_addresses where user_id = ".$user->id)); } /** @@ -727,6 +691,8 @@ public function testOneToOneNullUpdate() */ public function testNewAssociatedEntityDuringFlushThrowsException() { + $this->expectException(\InvalidArgumentException::class); + $user = new CmsUser(); $user->username = "beberlei"; $user->name = "Benjamin E."; @@ -739,11 +705,10 @@ public function testNewAssociatedEntityDuringFlushThrowsException() $address->street = "somestreet"; $address->user = $user; - $this->_em->persist($address); + $this->em->persist($address); // flushing without persisting $user should raise an exception - $this->expectException(\InvalidArgumentException::class); - $this->_em->flush(); + $this->em->flush(); } /** @@ -752,6 +717,8 @@ public function testNewAssociatedEntityDuringFlushThrowsException() */ public function testNewAssociatedEntityDuringFlushThrowsException2() { + $this->expectException(\InvalidArgumentException::class); + $user = new CmsUser(); $user->username = "beberlei"; $user->name = "Benjamin E."; @@ -764,9 +731,9 @@ public function testNewAssociatedEntityDuringFlushThrowsException2() $address->street = "somestreet"; $address->user = $user; - $this->_em->persist($address); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($address); + $this->em->persist($user); + $this->em->flush(); $u2 = new CmsUser; $u2->username = "beberlei"; @@ -775,8 +742,7 @@ public function testNewAssociatedEntityDuringFlushThrowsException2() $address->user = $u2; // flushing without persisting $u2 should raise an exception - $this->expectException(\InvalidArgumentException::class); - $this->_em->flush(); + $this->em->flush(); } /** @@ -785,6 +751,8 @@ public function testNewAssociatedEntityDuringFlushThrowsException2() */ public function testNewAssociatedEntityDuringFlushThrowsException3() { + $this->expectException(\InvalidArgumentException::class); + $art = new CmsArticle(); $art->topic = 'topic'; $art->text = 'the text'; @@ -794,11 +762,10 @@ public function testNewAssociatedEntityDuringFlushThrowsException3() $com->text = 'Really good!'; $art->addComment($com); - $this->_em->persist($art); + $this->em->persist($art); // flushing without persisting $com should raise an exception - $this->expectException(\InvalidArgumentException::class); - $this->_em->flush(); + $this->em->flush(); } public function testOneToOneOrphanRemoval() @@ -816,27 +783,27 @@ public function testOneToOneOrphanRemoval() $address->user = $user; $user->address = $address; - $this->_em->persist($address); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($address); + $this->em->persist($user); + $this->em->flush(); $addressId = $address->getId(); $user->address = null; - $this->_em->flush(); + $this->em->flush(); - $this->assertEquals(0, $this->_em->getConnection()->fetchColumn("select count(*) from cms_addresses")); + self::assertEquals(0, $this->em->getConnection()->fetchColumn("select count(*) from cms_addresses")); // check orphan removal through replacement $user->address = $address; $address->user = $user; - $this->_em->flush(); - $this->assertEquals(1, $this->_em->getConnection()->fetchColumn("select count(*) from cms_addresses")); + $this->em->flush(); + self::assertEquals(1, $this->em->getConnection()->fetchColumn("select count(*) from cms_addresses")); // remove $address to free up unique key id - $this->_em->remove($address); - $this->_em->flush(); + $this->em->remove($address); + $this->em->flush(); $newAddress = new CmsAddress(); $newAddress->city = "NewBonn"; @@ -846,8 +813,8 @@ public function testOneToOneOrphanRemoval() $newAddress->user = $user; $user->address = $newAddress; - $this->_em->flush(); - $this->assertEquals(1, $this->_em->getConnection()->fetchColumn("select count(*) from cms_addresses")); + $this->em->flush(); + self::assertEquals(1, $this->em->getConnection()->fetchColumn("select count(*) from cms_addresses")); } public function testGetPartialReferenceToUpdateObjectWithoutLoadingIt() @@ -856,112 +823,21 @@ public function testGetPartialReferenceToUpdateObjectWithoutLoadingIt() $user->username = "beberlei"; $user->name = "Benjamin E."; $user->status = 'active'; - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); $userId = $user->id; - $this->_em->clear(); + $this->em->clear(); - $user = $this->_em->getPartialReference(CmsUser::class, $userId); - $this->assertTrue($this->_em->contains($user)); - $this->assertNull($user->getName()); - $this->assertEquals($userId, $user->id); + $user = $this->em->getPartialReference(CmsUser::class, $userId); + self::assertTrue($this->em->contains($user)); + self::assertNull($user->getName()); + self::assertEquals($userId, $user->id); $user->name = 'Stephan'; - $this->_em->flush(); - $this->_em->clear(); - - $this->assertEquals('Benjamin E.', $this->_em->find(get_class($user), $userId)->name); - } - - public function testMergePersistsNewEntities() - { - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin E."; - $user->status = 'active'; - - $managedUser = $this->_em->merge($user); - $this->assertEquals('beberlei', $managedUser->username); - $this->assertEquals('Benjamin E.', $managedUser->name); - $this->assertEquals('active', $managedUser->status); - - $this->assertTrue($user !== $managedUser); - $this->assertTrue($this->_em->contains($managedUser)); - - $this->_em->flush(); - $userId = $managedUser->id; - $this->_em->clear(); - - $user2 = $this->_em->find(get_class($managedUser), $userId); - $this->assertInstanceOf(CmsUser::class, $user2); - } - - public function testMergeNonPersistedProperties() - { - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin E."; - $user->status = 'active'; - $user->nonPersistedProperty = 'test'; - $user->nonPersistedPropertyObject = new CmsPhonenumber(); - - $managedUser = $this->_em->merge($user); - $this->assertEquals('test', $managedUser->nonPersistedProperty); - $this->assertSame($user->nonPersistedProperty, $managedUser->nonPersistedProperty); - $this->assertSame($user->nonPersistedPropertyObject, $managedUser->nonPersistedPropertyObject); - - $this->assertTrue($user !== $managedUser); - $this->assertTrue($this->_em->contains($managedUser)); - - $this->_em->flush(); - $userId = $managedUser->id; - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $user2 = $this->_em->find(get_class($managedUser), $userId); - $this->assertNull($user2->nonPersistedProperty); - $this->assertNull($user2->nonPersistedPropertyObject); - $this->assertEquals('active', $user2->status); - } - - public function testMergeThrowsExceptionIfEntityWithGeneratedIdentifierDoesNotExist() - { - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin E."; - $user->status = 'active'; - $user->id = 42; - - $this->expectException(EntityNotFoundException::class); - $this->_em->merge($user); - } - - /** - * @group DDC-634 - */ - public function testOneToOneMergeSetNull() - { - $user = new CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin E."; - $user->status = 'active'; - - $ph = new CmsPhonenumber(); - $ph->phonenumber = "12345"; - $user->addPhonenumber($ph); - - $this->_em->persist($user); - $this->_em->persist($ph); - $this->_em->flush(); - - $this->_em->clear(); - - $ph->user = null; - $managedPh = $this->_em->merge($ph); - - $this->_em->flush(); - $this->_em->clear(); - - $this->assertNull($this->_em->find(get_class($ph), $ph->phonenumber)->getUser()); + self::assertEquals('Benjamin E.', $this->em->find(get_class($user), $userId)->name); } /** @@ -979,26 +855,28 @@ public function testManyToOneFetchModeQuery() $article->text = "bar"; $article->user = $user; - $this->_em->persist($article); - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($article); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); $qc = $this->getCurrentQueryCount(); $dql = "SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.id = ?1"; - $article = $this->_em->createQuery($dql) - ->setParameter(1, $article->id) - ->setFetchMode(CmsArticle::class, 'user', ClassMetadata::FETCH_EAGER) - ->getSingleResult(); - $this->assertInstanceOf(Proxy::class, $article->user, "It IS a proxy, ..."); - $this->assertTrue($article->user->__isInitialized__, "...but its initialized!"); - $this->assertEquals($qc+2, $this->getCurrentQueryCount()); + $article = $this->em + ->createQuery($dql) + ->setParameter(1, $article->id) + ->setFetchMode(CmsArticle::class, 'user', FetchMode::EAGER) + ->getSingleResult(); + + self::assertInstanceOf(Proxy::class, $article->user, "It IS a proxy, ..."); + self::assertTrue($article->user->__isInitialized(), "...but its initialized!"); + self::assertEquals($qc+2, $this->getCurrentQueryCount()); } /** * @group DDC-1278 */ - public function testClearWithEntityName() + public function testClear() { $user = new CmsUser; $user->name = 'Dominik'; @@ -1024,252 +902,20 @@ public function testClearWithEntityName() $user->addArticle($article1); $user->addArticle($article2); - $this->_em->persist($article1); - $this->_em->persist($article2); - $this->_em->persist($address); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($article1); + $this->em->persist($article2); + $this->em->persist($address); + $this->em->persist($user); + $this->em->flush(); - $unitOfWork = $this->_em->getUnitOfWork(); + $unitOfWork = $this->em->getUnitOfWork(); - $this->_em->clear(CmsUser::class); + $this->em->clear(); - $this->assertEquals(UnitOfWork::STATE_DETACHED, $unitOfWork->getEntityState($user)); - $this->assertEquals(UnitOfWork::STATE_DETACHED, $unitOfWork->getEntityState($article1)); - $this->assertEquals(UnitOfWork::STATE_DETACHED, $unitOfWork->getEntityState($article2)); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $unitOfWork->getEntityState($address)); - - $this->_em->clear(); - - $this->assertEquals(UnitOfWork::STATE_DETACHED, $unitOfWork->getEntityState($address)); - } - - public function testFlushManyExplicitEntities() - { - $userA = new CmsUser; - $userA->username = 'UserA'; - $userA->name = 'UserA'; - - $userB = new CmsUser; - $userB->username = 'UserB'; - $userB->name = 'UserB'; - - $userC = new CmsUser; - $userC->username = 'UserC'; - $userC->name = 'UserC'; - - $this->_em->persist($userA); - $this->_em->persist($userB); - $this->_em->persist($userC); - - $this->_em->flush([$userA, $userB, $userB]); - - $userC->name = 'changed name'; - - $this->_em->flush([$userA, $userB]); - $this->_em->refresh($userC); - - $this->assertTrue($userA->id > 0, 'user a has an id'); - $this->assertTrue($userB->id > 0, 'user b has an id'); - $this->assertTrue($userC->id > 0, 'user c has an id'); - $this->assertEquals('UserC', $userC->name, 'name has not changed because we did not flush it'); - } - - /** - * @group DDC-720 - */ - public function testFlushSingleManagedEntity() - { - $user = new CmsUser; - $user->name = 'Dominik'; - $user->username = 'domnikl'; - $user->status = 'developer'; - - $this->_em->persist($user); - $this->_em->flush(); - - $user->status = 'administrator'; - $this->_em->flush($user); - $this->_em->clear(); - - $user = $this->_em->find(get_class($user), $user->id); - $this->assertEquals('administrator', $user->status); - } - - /** - * @group DDC-720 - */ - public function testFlushSingleUnmanagedEntity() - { - $user = new CmsUser; - $user->name = 'Dominik'; - $user->username = 'domnikl'; - $user->status = 'developer'; - - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('Entity has to be managed or scheduled for removal for single computation'); - - $this->_em->flush($user); - } - - /** - * @group DDC-720 - */ - public function testFlushSingleAndNewEntity() - { - $user = new CmsUser; - $user->name = 'Dominik'; - $user->username = 'domnikl'; - $user->status = 'developer'; - - $this->_em->persist($user); - $this->_em->flush(); - - $otherUser = new CmsUser; - $otherUser->name = 'Dominik2'; - $otherUser->username = 'domnikl2'; - $otherUser->status = 'developer'; - - $user->status = 'administrator'; - - $this->_em->persist($otherUser); - $this->_em->flush($user); - - $this->assertTrue($this->_em->contains($otherUser), "Other user is contained in EntityManager"); - $this->assertTrue($otherUser->id > 0, "other user has an id"); - } - - /** - * @group DDC-720 - */ - public function testFlushAndCascadePersist() - { - $user = new CmsUser; - $user->name = 'Dominik'; - $user->username = 'domnikl'; - $user->status = 'developer'; - - $this->_em->persist($user); - $this->_em->flush(); - - $address = new CmsAddress(); - $address->city = "Springfield"; - $address->zip = "12354"; - $address->country = "Germany"; - $address->street = "Foo Street"; - $address->user = $user; - $user->address = $address; - - $this->_em->flush($user); - - $this->assertTrue($this->_em->contains($address), "Other user is contained in EntityManager"); - $this->assertTrue($address->id > 0, "other user has an id"); - } - - /** - * @group DDC-720 - */ - public function testFlushSingleAndNoCascade() - { - $user = new CmsUser; - $user->name = 'Dominik'; - $user->username = 'domnikl'; - $user->status = 'developer'; - - $this->_em->persist($user); - $this->_em->flush(); - - $article1 = new CmsArticle(); - $article1->topic = 'Foo'; - $article1->text = 'Foo Text'; - $article1->author = $user; - $user->articles[] = $article1; - - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage("A new entity was found through the relationship 'Doctrine\Tests\Models\CMS\CmsUser#articles'"); - - $this->_em->flush($user); - } - - /** - * @group DDC-720 - * @group DDC-1612 - * @group DDC-2267 - */ - public function testFlushSingleNewEntityThenRemove() - { - $user = new CmsUser; - $user->name = 'Dominik'; - $user->username = 'domnikl'; - $user->status = 'developer'; - - $this->_em->persist($user); - $this->_em->flush($user); - - $userId = $user->id; - - $this->_em->remove($user); - $this->_em->flush($user); - $this->_em->clear(); - - $this->assertNull($this->_em->find(get_class($user), $userId)); - } - - /** - * @group DDC-720 - */ - public function testProxyIsIgnored() - { - $user = new CmsUser; - $user->name = 'Dominik'; - $user->username = 'domnikl'; - $user->status = 'developer'; - - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); - - $user = $this->_em->getReference(get_class($user), $user->id); - - $otherUser = new CmsUser; - $otherUser->name = 'Dominik2'; - $otherUser->username = 'domnikl2'; - $otherUser->status = 'developer'; - - $this->_em->persist($otherUser); - $this->_em->flush($user); - - $this->assertTrue($this->_em->contains($otherUser), "Other user is contained in EntityManager"); - $this->assertTrue($otherUser->id > 0, "other user has an id"); - } - - /** - * @group DDC-720 - */ - public function testFlushSingleSaveOnlySingle() - { - $user = new CmsUser; - $user->name = 'Dominik'; - $user->username = 'domnikl'; - $user->status = 'developer'; - $this->_em->persist($user); - - $user2 = new CmsUser; - $user2->name = 'Dominik'; - $user2->username = 'domnikl2'; - $user2->status = 'developer'; - $this->_em->persist($user2); - - $this->_em->flush(); - - $user->status = 'admin'; - $user2->status = 'admin'; - - $this->_em->flush($user); - $this->_em->clear(); - - $user2 = $this->_em->find(get_class($user2), $user2->id); - $this->assertEquals('developer', $user2->status); + self::assertEquals(UnitOfWork::STATE_DETACHED, $unitOfWork->getEntityState($user)); + self::assertEquals(UnitOfWork::STATE_DETACHED, $unitOfWork->getEntityState($article1)); + self::assertEquals(UnitOfWork::STATE_DETACHED, $unitOfWork->getEntityState($article2)); + self::assertEquals(UnitOfWork::STATE_DETACHED, $unitOfWork->getEntityState($address)); } /** @@ -1289,8 +935,7 @@ public function testWrongAssociationInstance() '"Doctrine\Tests\Models\CMS\CmsUser#$address", got "Doctrine\Tests\Models\CMS\CmsUser" instead.' ); - $this->_em->persist($user); - - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/CascadeRemoveOrderTest.php b/tests/Doctrine/Tests/ORM/Functional/CascadeRemoveOrderTest.php index 8908e51e009..a203437146e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/CascadeRemoveOrderTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/CascadeRemoveOrderTest.php @@ -1,8 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(CascadeRemoveOrderEntityO::class), - $this->_em->getClassMetadata(CascadeRemoveOrderEntityG::class), + $this->em->getClassMetadata(CascadeRemoveOrderEntityO::class), + $this->em->getClassMetadata(CascadeRemoveOrderEntityG::class), ] ); } @@ -26,10 +29,10 @@ protected function tearDown() { parent::tearDown(); - $this->_schemaTool->dropSchema( + $this->schemaTool->dropSchema( [ - $this->_em->getClassMetadata(CascadeRemoveOrderEntityO::class), - $this->_em->getClassMetadata(CascadeRemoveOrderEntityG::class), + $this->em->getClassMetadata(CascadeRemoveOrderEntityO::class), + $this->em->getClassMetadata(CascadeRemoveOrderEntityG::class), ] ); } @@ -39,16 +42,16 @@ public function testSingle() $eO = new CascadeRemoveOrderEntityO(); $eG = new CascadeRemoveOrderEntityG($eO); - $this->_em->persist($eO); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($eO); + $this->em->flush(); + $this->em->clear(); - $eOloaded = $this->_em->find(CascadeRemoveOrderEntityO::class, $eO->getId()); + $eOloaded = $this->em->find(CascadeRemoveOrderEntityO::class, $eO->getId()); - $this->_em->remove($eOloaded); - $this->_em->flush(); + $this->em->remove($eOloaded); + $this->em->flush(); - self::assertNull($this->_em->find(CascadeRemoveOrderEntityG::class, $eG->getId())); + self::assertNull($this->em->find(CascadeRemoveOrderEntityG::class, $eG->getId())); } public function testMany() @@ -60,40 +63,40 @@ public function testMany() $eO->setOneToOneG($eG2); - $this->_em->persist($eO); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($eO); + $this->em->flush(); + $this->em->clear(); - $eOloaded = $this->_em->find(CascadeRemoveOrderEntityO::class, $eO->getId()); + $eOloaded = $this->em->find(CascadeRemoveOrderEntityO::class, $eO->getId()); - $this->_em->remove($eOloaded); - $this->_em->flush(); + $this->em->remove($eOloaded); + $this->em->flush(); - self::assertNull($this->_em->find(CascadeRemoveOrderEntityG::class, $eG1->getId())); - self::assertNull($this->_em->find(CascadeRemoveOrderEntityG::class, $eG2->getId())); - self::assertNull($this->_em->find(CascadeRemoveOrderEntityG::class, $eG3->getId())); + self::assertNull($this->em->find(CascadeRemoveOrderEntityG::class, $eG1->getId())); + self::assertNull($this->em->find(CascadeRemoveOrderEntityG::class, $eG2->getId())); + self::assertNull($this->em->find(CascadeRemoveOrderEntityG::class, $eG3->getId())); } } /** - * @Entity + * @ORM\Entity */ class CascadeRemoveOrderEntityO { /** - * @Id @Column(type="integer") - * @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue */ private $id; /** - * @OneToOne(targetEntity="Doctrine\Tests\ORM\Functional\CascadeRemoveOrderEntityG") - * @JoinColumn(nullable=true, onDelete="SET NULL") + * @ORM\OneToOne(targetEntity="Doctrine\Tests\ORM\Functional\CascadeRemoveOrderEntityG") + * @ORM\JoinColumn(nullable=true, onDelete="SET NULL") */ private $oneToOneG; /** - * @OneToMany( + * @ORM\OneToMany( * targetEntity="Doctrine\Tests\ORM\Functional\CascadeRemoveOrderEntityG", * mappedBy="ownerO", * cascade={"persist", "remove"} @@ -134,18 +137,18 @@ public function getOneToManyGs() } /** - * @Entity + * @ORM\Entity */ class CascadeRemoveOrderEntityG { /** - * @Id @Column(type="integer") - * @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue */ private $id; /** - * @ManyToOne( + * @ORM\ManyToOne( * targetEntity="Doctrine\Tests\ORM\Functional\CascadeRemoveOrderEntityO", * inversedBy="oneToMany" * ) diff --git a/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest.php b/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest.php index 4ece24fa773..434e9a65908 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest.php @@ -1,5 +1,7 @@ setName('Roman S. Borschel'); - $this->_em->persist($person); + $this->em->persist($person); $employee = new CompanyEmployee; $employee->setName('Roman S. Borschel'); $employee->setSalary(100000); $employee->setDepartment('IT'); - $this->_em->persist($employee); + $this->em->persist($employee); $employee->setName('Guilherme Blanco'); - $this->_em->flush(); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); - $query = $this->_em->createQuery('select p from ' . CompanyPerson::class . ' p order by p.name desc'); + $query = $this->em->createQuery('select p from ' . CompanyPerson::class . ' p order by p.name desc'); $entities = $query->getResult(); - $this->assertCount(2, $entities); - $this->assertInstanceOf(CompanyPerson::class, $entities[0]); - $this->assertInstanceOf(CompanyEmployee::class, $entities[1]); - $this->assertTrue(is_numeric($entities[0]->getId())); - $this->assertTrue(is_numeric($entities[1]->getId())); - $this->assertEquals('Roman S. Borschel', $entities[0]->getName()); - $this->assertEquals('Guilherme Blanco', $entities[1]->getName()); - $this->assertEquals(100000, $entities[1]->getSalary()); + self::assertCount(2, $entities); + self::assertInstanceOf(CompanyPerson::class, $entities[0]); + self::assertInstanceOf(CompanyEmployee::class, $entities[1]); + self::assertTrue(is_numeric($entities[0]->getId())); + self::assertTrue(is_numeric($entities[1]->getId())); + self::assertEquals('Roman S. Borschel', $entities[0]->getName()); + self::assertEquals('Guilherme Blanco', $entities[1]->getName()); + self::assertEquals(100000, $entities[1]->getSalary()); - $this->_em->clear(); + $this->em->clear(); - $query = $this->_em->createQuery('select p from ' . CompanyEmployee::class . ' p'); + $query = $this->em->createQuery('select p from ' . CompanyEmployee::class . ' p'); $entities = $query->getResult(); - $this->assertCount(1, $entities); - $this->assertInstanceOf(CompanyEmployee::class, $entities[0]); - $this->assertTrue(is_numeric($entities[0]->getId())); - $this->assertEquals('Guilherme Blanco', $entities[0]->getName()); - $this->assertEquals(100000, $entities[0]->getSalary()); + self::assertCount(1, $entities); + self::assertInstanceOf(CompanyEmployee::class, $entities[0]); + self::assertTrue(is_numeric($entities[0]->getId())); + self::assertEquals('Guilherme Blanco', $entities[0]->getName()); + self::assertEquals(100000, $entities[0]->getSalary()); + + $this->em->clear(); + + $guilherme = $this->em->getRepository(get_class($employee))->findOneBy(['name' => 'Guilherme Blanco']); - $this->_em->clear(); + self::assertInstanceOf(CompanyEmployee::class, $guilherme); + self::assertEquals('Guilherme Blanco', $guilherme->getName()); - $guilherme = $this->_em->getRepository(get_class($employee))->findOneBy(['name' => 'Guilherme Blanco']); - $this->assertInstanceOf(CompanyEmployee::class, $guilherme); - $this->assertEquals('Guilherme Blanco', $guilherme->getName()); + $this->em->clear(); - $this->_em->clear(); + $query = $this->em->createQuery("update " . CompanyEmployee::class . " p set p.name = ?1, p.department = ?2 where p.name='Guilherme Blanco' and p.salary = ?3"); - $query = $this->_em->createQuery("update " . CompanyEmployee::class . " p set p.name = ?1, p.department = ?2 where p.name='Guilherme Blanco' and p.salary = ?3"); $query->setParameter(1, 'NewName', 'string'); $query->setParameter(2, 'NewDepartment'); $query->setParameter(3, 100000); $query->getSQL(); + $numUpdated = $query->execute(); - $this->assertEquals(1, $numUpdated); - $query = $this->_em->createQuery('delete from ' . CompanyPerson::class . ' p'); + self::assertEquals(1, $numUpdated); + + $query = $this->em->createQuery('delete from ' . CompanyPerson::class . ' p'); + $numDeleted = $query->execute(); - $this->assertEquals(2, $numDeleted); + + self::assertEquals(2, $numDeleted); } public function testMultiLevelUpdateAndFind() @@ -100,24 +108,24 @@ public function testMultiLevelUpdateAndFind() $manager->setSalary(100000); $manager->setDepartment('IT'); $manager->setTitle('CTO'); - $this->_em->persist($manager); - $this->_em->flush(); + $this->em->persist($manager); + $this->em->flush(); $manager->setName('Roman B.'); $manager->setSalary(119000); $manager->setTitle('CEO'); - $this->_em->persist($manager); - $this->_em->flush(); + $this->em->persist($manager); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); - $manager = $this->_em->find(CompanyManager::class, $manager->getId()); + $manager = $this->em->find(CompanyManager::class, $manager->getId()); - $this->assertInstanceOf(CompanyManager::class, $manager); - $this->assertEquals('Roman B.', $manager->getName()); - $this->assertEquals(119000, $manager->getSalary()); - $this->assertEquals('CEO', $manager->getTitle()); - $this->assertTrue(is_numeric($manager->getId())); + self::assertInstanceOf(CompanyManager::class, $manager); + self::assertEquals('Roman B.', $manager->getName()); + self::assertEquals(119000, $manager->getSalary()); + self::assertEquals('CEO', $manager->getTitle()); + self::assertTrue(is_numeric($manager->getId())); } public function testFindOnBaseClass() @@ -127,18 +135,18 @@ public function testFindOnBaseClass() $manager->setSalary(100000); $manager->setDepartment('IT'); $manager->setTitle('CTO'); - $this->_em->persist($manager); - $this->_em->flush(); + $this->em->persist($manager); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); - $person = $this->_em->find(CompanyPerson::class, $manager->getId()); + $person = $this->em->find(CompanyPerson::class, $manager->getId()); - $this->assertInstanceOf(CompanyManager::class, $person); - $this->assertEquals('Roman S. Borschel', $person->getName()); - $this->assertEquals(100000, $person->getSalary()); - $this->assertEquals('CTO', $person->getTitle()); - $this->assertTrue(is_numeric($person->getId())); + self::assertInstanceOf(CompanyManager::class, $person); + self::assertEquals('Roman S. Borschel', $person->getName()); + self::assertEquals(100000, $person->getSalary()); + self::assertEquals('CTO', $person->getTitle()); + self::assertTrue(is_numeric($person->getId())); } public function testSelfReferencingOneToOne() @@ -153,23 +161,24 @@ public function testSelfReferencingOneToOne() $wife->setName('Mary Smith'); $wife->setSpouse($manager); - $this->assertSame($manager, $wife->getSpouse()); - $this->assertSame($wife, $manager->getSpouse()); + self::assertSame($manager, $wife->getSpouse()); + self::assertSame($wife, $manager->getSpouse()); - $this->_em->persist($manager); - $this->_em->persist($wife); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($manager); + $this->em->persist($wife); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery('select p, s from ' . CompanyPerson::class . ' p join p.spouse s where p.name=\'Mary Smith\''); + $query = $this->em->createQuery('select p, s from ' . CompanyPerson::class . ' p join p.spouse s where p.name=\'Mary Smith\''); $result = $query->getResult(); - $this->assertCount(1, $result); - $this->assertInstanceOf(CompanyPerson::class, $result[0]); - $this->assertEquals('Mary Smith', $result[0]->getName()); - $this->assertInstanceOf(CompanyEmployee::class, $result[0]->getSpouse()); - $this->assertEquals('John Smith', $result[0]->getSpouse()->getName()); - $this->assertSame($result[0], $result[0]->getSpouse()->getSpouse()); + + self::assertCount(1, $result); + self::assertInstanceOf(CompanyPerson::class, $result[0]); + self::assertEquals('Mary Smith', $result[0]->getName()); + self::assertInstanceOf(CompanyEmployee::class, $result[0]->getSpouse()); + self::assertEquals('John Smith', $result[0]->getSpouse()->getName()); + self::assertSame($result[0], $result[0]->getSpouse()->getSpouse()); } public function testSelfReferencingManyToMany() @@ -182,27 +191,29 @@ public function testSelfReferencingManyToMany() $person1->addFriend($person2); - $this->assertCount(1, $person1->getFriends()); - $this->assertCount(1, $person2->getFriends()); + self::assertCount(1, $person1->getFriends()); + self::assertCount(1, $person2->getFriends()); + $this->em->persist($person1); + $this->em->persist($person2); - $this->_em->persist($person1); - $this->_em->persist($person2); + $this->em->flush(); - $this->_em->flush(); + $this->em->clear(); - $this->_em->clear(); + $query = $this->em->createQuery('select p, f from ' . CompanyPerson::class . ' p join p.friends f where p.name=?1'); - $query = $this->_em->createQuery('select p, f from ' . CompanyPerson::class . ' p join p.friends f where p.name=?1'); $query->setParameter(1, 'Roman'); $result = $query->getResult(); - $this->assertCount(1, $result); - $this->assertCount(1, $result[0]->getFriends()); - $this->assertEquals('Roman', $result[0]->getName()); + + self::assertCount(1, $result); + self::assertCount(1, $result[0]->getFriends()); + self::assertEquals('Roman', $result[0]->getName()); $friends = $result[0]->getFriends(); - $this->assertEquals('Jonathan', $friends[0]->getName()); + + self::assertEquals('Jonathan', $friends[0]->getName()); } public function testLazyLoading1() @@ -215,32 +226,33 @@ public function testLazyLoading1() $event2->setData('raffle'); $org->addEvent($event2); - $this->_em->persist($org); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($org); + $this->em->flush(); + $this->em->clear(); $orgId = $org->getId(); - $q = $this->_em->createQuery('select a from Doctrine\Tests\Models\Company\CompanyOrganization a where a.id = ?1'); + $q = $this->em->createQuery('select a from Doctrine\Tests\Models\Company\CompanyOrganization a where a.id = ?1'); $q->setParameter(1, $orgId); $result = $q->getResult(); - $this->assertCount(1, $result); - $this->assertInstanceOf(CompanyOrganization::class, $result[0]); - $this->assertNull($result[0]->getMainEvent()); + self::assertCount(1, $result); + self::assertInstanceOf(CompanyOrganization::class, $result[0]); + self::assertNull($result[0]->getMainEvent()); $events = $result[0]->getEvents(); - $this->assertInstanceOf(PersistentCollection::class, $events); - $this->assertFalse($events->isInitialized()); + self::assertInstanceOf(PersistentCollection::class, $events); + self::assertFalse($events->isInitialized()); + + self::assertCount(2, $events); - $this->assertCount(2, $events); if ($events[0] instanceof CompanyAuction) { - $this->assertInstanceOf(CompanyRaffle::class, $events[1]); + self::assertInstanceOf(CompanyRaffle::class, $events[1]); } else { - $this->assertInstanceOf(CompanyRaffle::class, $events[0]); - $this->assertInstanceOf(CompanyAuction::class, $events[1]); + self::assertInstanceOf(CompanyRaffle::class, $events[0]); + self::assertInstanceOf(CompanyAuction::class, $events[1]); } } @@ -251,31 +263,35 @@ public function testLazyLoading2() $event1->setData('auction'); $org->setMainEvent($event1); - $this->_em->persist($org); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($org); + $this->em->flush(); + $this->em->clear(); + + $q = $this->em->createQuery('select a from ' . CompanyEvent::class . ' a where a.id = ?1'); - $q = $this->_em->createQuery('select a from ' . CompanyEvent::class . ' a where a.id = ?1'); $q->setParameter(1, $event1->getId()); $result = $q->getResult(); - $this->assertCount(1, $result); - $this->assertInstanceOf(CompanyAuction::class, $result[0], sprintf("Is of class %s", get_class($result[0]))); - $this->_em->clear(); + self::assertCount(1, $result); + self::assertInstanceOf(CompanyAuction::class, $result[0], sprintf("Is of class %s",get_class($result[0]))); + + $this->em->clear(); + + $q = $this->em->createQuery('select a from ' . CompanyOrganization::class . ' a where a.id = ?1'); - $q = $this->_em->createQuery('select a from ' . CompanyOrganization::class . ' a where a.id = ?1'); $q->setParameter(1, $org->getId()); $result = $q->getResult(); - $this->assertCount(1, $result); - $this->assertInstanceOf(CompanyOrganization::class, $result[0]); + self::assertCount(1, $result); + self::assertInstanceOf(CompanyOrganization::class, $result[0]); $mainEvent = $result[0]->getMainEvent(); + // mainEvent should have been loaded because it can't be lazy - $this->assertInstanceOf(CompanyAuction::class, $mainEvent); - $this->assertNotInstanceOf(Proxy::class, $mainEvent); + self::assertInstanceOf(CompanyAuction::class, $mainEvent); + self::assertNotInstanceOf(Proxy::class, $mainEvent); } /** @@ -283,13 +299,13 @@ public function testLazyLoading2() */ public function testBulkUpdateIssueDDC368() { - $this->_em->createQuery('UPDATE ' . CompanyEmployee::class . ' AS p SET p.salary = 1') + $this->em->createQuery('UPDATE ' . CompanyEmployee::class . ' AS p SET p.salary = 1') ->execute(); - $result = $this->_em->createQuery('SELECT count(p.id) FROM ' . CompanyEmployee::class . ' p WHERE p.salary = 1') + $result = $this->em->createQuery('SELECT count(p.id) FROM ' . CompanyEmployee::class . ' p WHERE p.salary = 1') ->getResult(); - $this->assertGreaterThan(0, count($result)); + self::assertGreaterThan(0, count($result)); } /** @@ -297,12 +313,12 @@ public function testBulkUpdateIssueDDC368() */ public function testBulkUpdateNonScalarParameterDDC1341() { - $this->_em->createQuery('UPDATE ' . CompanyEmployee::class . ' AS p SET p.startDate = ?0 WHERE p.department = ?1') + $this->em->createQuery('UPDATE ' . CompanyEmployee::class . ' AS p SET p.startDate = ?0 WHERE p.department = ?1') ->setParameter(0, new \DateTime()) ->setParameter(1, 'IT') ->execute(); - $this->addToAssertionCount(1); + self::addToAssertionCount(1); } /** @@ -322,16 +338,16 @@ public function testDeleteJoinTableRecords() $employee1->addFriend($employee2); - $this->_em->persist($employee1); - $this->_em->persist($employee2); - $this->_em->flush(); + $this->em->persist($employee1); + $this->em->persist($employee2); + $this->em->flush(); $employee1Id = $employee1->getId(); - $this->_em->remove($employee1); - $this->_em->flush(); + $this->em->remove($employee1); + $this->em->flush(); - $this->assertNull($this->_em->find(get_class($employee1), $employee1Id)); + self::assertNull($this->em->find(get_class($employee1), $employee1Id)); } /** @@ -350,17 +366,17 @@ public function testQueryForInheritedSingleValuedAssociation() $manager->setSpouse($person); - $this->_em->persist($manager); - $this->_em->persist($person); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($manager); + $this->em->persist($person); + $this->em->flush(); + $this->em->clear(); - $dqlManager = $this->_em->createQuery('SELECT m FROM ' . CompanyManager::class . ' m WHERE m.spouse = ?1') + $dqlManager = $this->em->createQuery('SELECT m FROM ' . CompanyManager::class . ' m WHERE m.spouse = ?1') ->setParameter(1, $person->getId()) ->getSingleResult(); - $this->assertEquals($manager->getId(), $dqlManager->getId()); - $this->assertEquals($person->getId(), $dqlManager->getSpouse()->getId()); + self::assertEquals($manager->getId(), $dqlManager->getId()); + self::assertEquals($person->getId(), $dqlManager->getSpouse()->getId()); } /** @@ -379,20 +395,20 @@ public function testFindByAssociation() $manager->setSpouse($person); - $this->_em->persist($manager); - $this->_em->persist($person); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($manager); + $this->em->persist($person); + $this->em->flush(); + $this->em->clear(); - $repos = $this->_em->getRepository(CompanyManager::class); + $repos = $this->em->getRepository(CompanyManager::class); $pmanager = $repos->findOneBy(['spouse' => $person->getId()]); - $this->assertEquals($manager->getId(), $pmanager->getId()); + self::assertEquals($manager->getId(), $pmanager->getId()); - $repos = $this->_em->getRepository(CompanyPerson::class); + $repos = $this->em->getRepository(CompanyPerson::class); $pmanager = $repos->findOneBy(['spouse' => $person->getId()]); - $this->assertEquals($manager->getId(), $pmanager->getId()); + self::assertEquals($manager->getId(), $pmanager->getId()); } /** @@ -406,18 +422,18 @@ public function testGetReferenceEntityWithSubclasses() $manager->setTitle('Awesome!'); $manager->setDepartment('IT'); - $this->_em->persist($manager); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($manager); + $this->em->flush(); + $this->em->clear(); - $ref = $this->_em->getReference(CompanyPerson::class, $manager->getId()); - $this->assertNotInstanceOf(Proxy::class, $ref, "Cannot Request a proxy from a class that has subclasses."); - $this->assertInstanceOf(CompanyPerson::class, $ref); - $this->assertInstanceOf(CompanyEmployee::class, $ref, "Direct fetch of the reference has to load the child class Employee directly."); - $this->_em->clear(); + $ref = $this->em->getReference(CompanyPerson::class, $manager->getId()); + self::assertNotInstanceOf(Proxy::class, $ref, "Cannot Request a proxy from a class that has subclasses."); + self::assertInstanceOf(CompanyPerson::class, $ref); + self::assertInstanceOf(CompanyEmployee::class, $ref, "Direct fetch of the reference has to load the child class Employee directly."); + $this->em->clear(); - $ref = $this->_em->getReference(CompanyManager::class, $manager->getId()); - $this->assertInstanceOf(Proxy::class, $ref, "A proxy can be generated only if no subclasses exists for the requested reference."); + $ref = $this->em->getReference(CompanyManager::class, $manager->getId()); + self::assertInstanceOf(Proxy::class, $ref, "A proxy can be generated only if no subclasses exists for the requested reference."); } /** @@ -436,14 +452,14 @@ public function testGetSubClassManyToManyCollection() $manager->addFriend($person); - $this->_em->persist($manager); - $this->_em->persist($person); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($manager); + $this->em->persist($person); + $this->em->flush(); + $this->em->clear(); - $manager = $this->_em->find(CompanyManager::class, $manager->getId()); + $manager = $this->em->find(CompanyManager::class, $manager->getId()); - $this->assertCount(1, $manager->getFriends()); + self::assertCount(1, $manager->getFriends()); } /** @@ -457,12 +473,12 @@ public function testExistsSubclass() $manager->setTitle('Awesome!'); $manager->setDepartment('IT'); - $this->assertFalse($this->_em->getUnitOfWork()->getEntityPersister(get_class($manager))->exists($manager)); + self::assertFalse($this->em->getUnitOfWork()->getEntityPersister(get_class($manager))->exists($manager)); - $this->_em->persist($manager); - $this->_em->flush(); + $this->em->persist($manager); + $this->em->flush(); - $this->assertTrue($this->_em->getUnitOfWork()->getEntityPersister(get_class($manager))->exists($manager)); + self::assertTrue($this->em->getUnitOfWork()->getEntityPersister(get_class($manager))->exists($manager)); } /** @@ -476,19 +492,21 @@ public function testMatching() $manager->setTitle('Awesome!'); $manager->setDepartment('IT'); - $this->_em->persist($manager); - $this->_em->flush(); + $this->em->persist($manager); + $this->em->flush(); - $repository = $this->_em->getRepository(CompanyEmployee::class); + $repository = $this->em->getRepository(CompanyEmployee::class); $users = $repository->matching(new Criteria( Criteria::expr()->eq('department', 'IT') )); - $this->assertCount(1, $users); - $repository = $this->_em->getRepository(CompanyManager::class); + self::assertCount(1, $users); + + $repository = $this->em->getRepository(CompanyManager::class); $users = $repository->matching(new Criteria( Criteria::expr()->eq('department', 'IT') )); - $this->assertCount(1, $users); + + self::assertCount(1, $users); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest2.php b/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest2.php index 84949a6e3ed..57ba1cb4405 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest2.php +++ b/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest2.php @@ -1,5 +1,7 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(CTIParent::class), - $this->_em->getClassMetadata(CTIChild::class), - $this->_em->getClassMetadata(CTIRelated::class), - $this->_em->getClassMetadata(CTIRelated2::class) + $this->em->getClassMetadata(CTIParent::class), + $this->em->getClassMetadata(CTIChild::class), + $this->em->getClassMetadata(CTIRelated::class), + $this->em->getClassMetadata(CTIRelated2::class) ] ); } catch (\Exception $ignored) { @@ -37,60 +39,60 @@ public function testOneToOneAssocToBaseTypeBidirectional() $related = new CTIRelated; $related->setCTIParent($child); - $this->_em->persist($related); - $this->_em->persist($child); + $this->em->persist($related); + $this->em->persist($child); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $relatedId = $related->getId(); - $related2 = $this->_em->find(CTIRelated::class, $relatedId); + $related2 = $this->em->find(CTIRelated::class, $relatedId); - $this->assertInstanceOf(CTIRelated::class, $related2); - $this->assertInstanceOf(CTIChild::class, $related2->getCTIParent()); - $this->assertNotInstanceOf(Proxy::class, $related2->getCTIParent()); - $this->assertEquals('hello', $related2->getCTIParent()->getData()); + self::assertInstanceOf(CTIRelated::class, $related2); + self::assertInstanceOf(CTIChild::class, $related2->getCTIParent()); + self::assertNotInstanceOf(Proxy::class, $related2->getCTIParent()); + self::assertEquals('hello', $related2->getCTIParent()->getData()); - $this->assertSame($related2, $related2->getCTIParent()->getRelated()); + self::assertSame($related2, $related2->getCTIParent()->getRelated()); } public function testManyToManyToCTIHierarchy() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger()); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger()); $mmrel = new CTIRelated2; $child = new CTIChild; $child->setData('child'); $mmrel->addCTIChild($child); - $this->_em->persist($mmrel); - $this->_em->persist($child); + $this->em->persist($mmrel); + $this->em->persist($child); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $mmrel2 = $this->_em->find(get_class($mmrel), $mmrel->getId()); - $this->assertFalse($mmrel2->getCTIChildren()->isInitialized()); - $this->assertEquals(1, count($mmrel2->getCTIChildren())); - $this->assertTrue($mmrel2->getCTIChildren()->isInitialized()); - $this->assertInstanceOf(CTIChild::class, $mmrel2->getCTIChildren()->get(0)); + $mmrel2 = $this->em->find(get_class($mmrel), $mmrel->getId()); + self::assertFalse($mmrel2->getCTIChildren()->isInitialized()); + self::assertEquals(1, count($mmrel2->getCTIChildren())); + self::assertTrue($mmrel2->getCTIChildren()->isInitialized()); + self::assertInstanceOf(CTIChild::class, $mmrel2->getCTIChildren()->get(0)); } } /** - * @Entity @Table(name="cti_parents") - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="type", type="string") - * @DiscriminatorMap({"parent" = "CTIParent", "child" = "CTIChild"}) + * @ORM\Entity @ORM\Table(name="cti_parents") + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="type", type="string") + * @ORM\DiscriminatorMap({"parent" = "CTIParent", "child" = "CTIChild"}) */ class CTIParent { /** - * @Id @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; - /** @OneToOne(targetEntity="CTIRelated", mappedBy="ctiParent") */ + /** @ORM\OneToOne(targetEntity="CTIRelated", mappedBy="ctiParent") */ private $related; public function getId() { @@ -108,11 +110,11 @@ public function setRelated($related) { } /** - * @Entity @Table(name="cti_children") + * @ORM\Entity @ORM\Table(name="cti_children") */ class CTIChild extends CTIParent { /** - * @Column(type="string") + * @ORM\Column(type="string") */ private $data; @@ -126,17 +128,17 @@ public function setData($data) { } -/** @Entity */ +/** @ORM\Entity */ class CTIRelated { /** - * @Id @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** - * @OneToOne(targetEntity="CTIParent") - * @JoinColumn(name="ctiparent_id", referencedColumnName="id") + * @ORM\OneToOne(targetEntity="CTIParent") + * @ORM\JoinColumn(name="ctiparent_id", referencedColumnName="id") */ private $ctiParent; @@ -153,12 +155,12 @@ public function setCTIParent($ctiParent) { } } -/** @Entity */ +/** @ORM\Entity */ class CTIRelated2 { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ private $id; - /** @ManyToMany(targetEntity="CTIChild") */ + /** @ORM\ManyToMany(targetEntity="CTIChild") */ private $ctiChildren; diff --git a/tests/Doctrine/Tests/ORM/Functional/ClearEventTest.php b/tests/Doctrine/Tests/ORM/Functional/ClearEventTest.php index 8c234c0f3f3..83766435657 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ClearEventTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ClearEventTest.php @@ -1,5 +1,7 @@ _em->getEventManager()->addEventListener(Events::onClear, $listener); + $this->em->getEventManager()->addEventListener(Events::onClear, $listener); - $this->_em->clear(); + $this->em->clear(); - $this->assertTrue($listener->called); + self::assertTrue($listener->called); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyTest.php index 03bde6ba7cb..63e65053ebe 100644 --- a/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyTest.php @@ -1,6 +1,9 @@ _em->persist($country); + $this->em->persist($country); $poi = new NavPointOfInterest(100, 200, "Brandenburger Tor", $country); - $this->_em->persist($poi); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($poi); + $this->em->flush(); + $this->em->clear(); } public function putTripAroundEurope() { - $poi = $this->_em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); + $poi = $this->em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); $tour = new NavTour("Trip around Europe"); $tour->addPointOfInterest($poi); - $this->_em->persist($tour); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($tour); + $this->em->flush(); + $this->em->clear(); return $tour; } @@ -46,12 +49,12 @@ public function testPersistCompositePkEntity() { $this->putGermanysBrandenburderTor(); - $poi = $this->_em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); + $poi = $this->em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); - $this->assertInstanceOf(NavPointOfInterest::class, $poi); - $this->assertEquals(100, $poi->getLat()); - $this->assertEquals(200, $poi->getLong()); - $this->assertEquals('Brandenburger Tor', $poi->getName()); + self::assertInstanceOf(NavPointOfInterest::class, $poi); + self::assertEquals(100, $poi->getLat()); + self::assertEquals(200, $poi->getLong()); + self::assertEquals('Brandenburger Tor', $poi->getName()); } /** @@ -61,36 +64,36 @@ public function testSetParameterCompositeKeyObject() { $this->putGermanysBrandenburderTor(); - $poi = $this->_em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); + $poi = $this->em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); $photo = new NavPhotos($poi, "asdf"); - $this->_em->persist($photo); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($photo); + $this->em->flush(); + $this->em->clear(); $dql = 'SELECT t FROM Doctrine\Tests\Models\Navigation\NavPhotos t WHERE t.poi = ?1'; $this->expectException(QueryException::class); $this->expectExceptionMessage('A single-valued association path expression to an entity with a composite primary key is not supported.'); - $sql = $this->_em->createQuery($dql)->getSQL(); + $sql = $this->em->createQuery($dql)->getSQL(); } public function testIdentityFunctionWithCompositePrimaryKey() { $this->putGermanysBrandenburderTor(); - $poi = $this->_em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); + $poi = $this->em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); $photo = new NavPhotos($poi, "asdf"); - $this->_em->persist($photo); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($photo); + $this->em->flush(); + $this->em->clear(); $dql = "SELECT IDENTITY(p.poi, 'long') AS long, IDENTITY(p.poi, 'lat') AS lat FROM Doctrine\Tests\Models\Navigation\NavPhotos p"; - $result = $this->_em->createQuery($dql)->getResult(); + $result = $this->em->createQuery($dql)->getResult(); - $this->assertCount(1, $result); - $this->assertEquals(200, $result[0]['long']); - $this->assertEquals(100, $result[0]['lat']); + self::assertCount(1, $result); + self::assertEquals(200, $result[0]['long']); + self::assertEquals(100, $result[0]['lat']); } public function testManyToManyCompositeRelation() @@ -98,9 +101,9 @@ public function testManyToManyCompositeRelation() $this->putGermanysBrandenburderTor(); $tour = $this->putTripAroundEurope(); - $tour = $this->_em->find(NavTour::class, $tour->getId()); + $tour = $this->em->find(NavTour::class, $tour->getId()); - $this->assertEquals(1, count($tour->getPointOfInterests())); + self::assertEquals(1, count($tour->getPointOfInterests())); } public function testCompositeDqlEagerFetching() @@ -108,31 +111,38 @@ public function testCompositeDqlEagerFetching() $this->putGermanysBrandenburderTor(); $this->putTripAroundEurope(); - $dql = 'SELECT t, p, c FROM Doctrine\Tests\Models\Navigation\NavTour t ' . - 'INNER JOIN t.pois p INNER JOIN p.country c'; - $tours = $this->_em->createQuery($dql)->getResult(); + $dql = 'SELECT t, p, c ' + . 'FROM Doctrine\Tests\Models\Navigation\NavTour t ' + . 'INNER JOIN t.pois p ' + . 'INNER JOIN p.country c' + ; + + $tours = $this->em->createQuery($dql)->getResult(); - $this->assertEquals(1, count($tours)); + self::assertEquals(1, count($tours)); $pois = $tours[0]->getPointOfInterests(); - $this->assertEquals(1, count($pois)); - $this->assertEquals('Brandenburger Tor', $pois[0]->getName()); + self::assertEquals(1, count($pois)); + self::assertEquals('Brandenburger Tor', $pois[0]->getName()); } public function testCompositeCollectionMemberExpression() { - $this->markTestSkipped('How to test this?'); - + // Test should not throw any kind of exception $this->putGermanysBrandenburderTor(); $this->putTripAroundEurope(); - $dql = 'SELECT t FROM Doctrine\Tests\Models\Navigation\NavTour t, Doctrine\Tests\Models\Navigation\NavPointOfInterest p ' . - 'WHERE p MEMBER OF t.pois'; - $tours = $this->_em->createQuery($dql) - ->getResult(); + $dql = 'SELECT t ' + . 'FROM Doctrine\Tests\Models\Navigation\NavTour t ' + . ', Doctrine\Tests\Models\Navigation\NavPointOfInterest p ' + . 'WHERE p MEMBER OF t.pois' + ; + + $query = $this->em->createQuery($dql); + $tours = $query->getResult(); - $this->assertEquals(1, count($tours)); + self::assertEquals(0, count($tours)); } public function testSpecifyUnknownIdentifierPrimaryKeyFails() @@ -140,7 +150,7 @@ public function testSpecifyUnknownIdentifierPrimaryKeyFails() $this->expectException(ORMException::class); $this->expectExceptionMessage('The identifier long is missing for a query of Doctrine\Tests\Models\Navigation\NavPointOfInterest'); - $poi = $this->_em->find(NavPointOfInterest::class, ['key1' => 100]); + $poi = $this->em->find(NavPointOfInterest::class, ['key1' => 100]); } public function testUnrecognizedIdentifierFieldsOnGetReference() @@ -148,7 +158,7 @@ public function testUnrecognizedIdentifierFieldsOnGetReference() $this->expectException(ORMException::class); $this->expectExceptionMessage("Unrecognized identifier fields: 'key1'"); - $poi = $this->_em->getReference(NavPointOfInterest::class, ['lat' => 10, 'long' => 20, 'key1' => 100] + $poi = $this->em->getReference(NavPointOfInterest::class, ['lat' => 10, 'long' => 20, 'key1' => 100] ); } @@ -159,18 +169,18 @@ public function testDeleteCompositePersistentCollection() { $this->putGermanysBrandenburderTor(); - $poi = $this->_em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); + $poi = $this->em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); $poi->addVisitor(new NavUser("test1")); $poi->addVisitor(new NavUser("test2")); - $this->_em->flush(); + $this->em->flush(); $poi->getVisitors()->clear(); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $poi = $this->_em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); - $this->assertEquals(0, count($poi->getVisitors())); + $poi = $this->em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); + self::assertEquals(0, count($poi->getVisitors())); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyWithAssociationsTest.php b/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyWithAssociationsTest.php index 533f611d402..47e31afe9df 100644 --- a/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyWithAssociationsTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyWithAssociationsTest.php @@ -1,5 +1,7 @@ _em->persist($it); - $this->_em->flush(); + $this->em->persist($it); + $this->em->flush(); $admin1 = new Admin1(1, "Rome", $it); - $this->_em->persist($admin1); - $this->_em->flush(); + $this->em->persist($admin1); + $this->em->flush(); $name1 = new Admin1AlternateName(1, "Roma", $admin1); $name2 = new Admin1AlternateName(2, "Rome", $admin1); @@ -30,32 +32,32 @@ public function setUp() $admin1->names[] = $name1; $admin1->names[] = $name2; - $this->_em->persist($admin1); - $this->_em->persist($name1); - $this->_em->persist($name2); + $this->em->persist($admin1); + $this->em->persist($name1); + $this->em->persist($name2); - $this->_em->flush(); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); } public function testFindByAbleToGetCompositeEntitiesWithMixedTypeIdentifiers() { - $admin1Repo = $this->_em->getRepository(Admin1::class); - $admin1NamesRepo = $this->_em->getRepository(Admin1AlternateName::class); + $admin1Repo = $this->em->getRepository(Admin1::class); + $admin1NamesRepo = $this->em->getRepository(Admin1AlternateName::class); $admin1Rome = $admin1Repo->findOneBy(['country' => 'IT', 'id' => 1]); $names = $admin1NamesRepo->findBy(['admin1' => $admin1Rome]); - $this->assertCount(2, $names); + self::assertCount(2, $names); $name1 = $admin1NamesRepo->findOneBy(['admin1' => $admin1Rome, 'id' => 1]); $name2 = $admin1NamesRepo->findOneBy(['admin1' => $admin1Rome, 'id' => 2]); - $this->assertEquals(1, $name1->id); - $this->assertEquals("Roma", $name1->name); + self::assertEquals(1, $name1->id); + self::assertEquals("Roma", $name1->name); - $this->assertEquals(2, $name2->id); - $this->assertEquals("Rome", $name2->name); + self::assertEquals(2, $name2->id); + self::assertEquals("Rome", $name2->name); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/CustomFunctionsTest.php b/tests/Doctrine/Tests/ORM/Functional/CustomFunctionsTest.php index 79668b8f2cc..7549c4bbc16 100644 --- a/tests/Doctrine/Tests/ORM/Functional/CustomFunctionsTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/CustomFunctionsTest.php @@ -1,5 +1,7 @@ name = 'Bob'; $user->username = 'Dylan'; - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); // Instead of defining the function with the class name, we use a callback - $this->_em->getConfiguration()->addCustomStringFunction('FOO', function($funcName) { + $this->em->getConfiguration()->addCustomStringFunction('FOO', function($funcName) { return new NoOp($funcName); }); - $this->_em->getConfiguration()->addCustomNumericFunction('BAR', function($funcName) { + $this->em->getConfiguration()->addCustomNumericFunction('BAR', function($funcName) { return new NoOp($funcName); }); - $query = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u' + $query = $this->em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u' . ' WHERE FOO(u.name) = \'Bob\'' . ' AND BAR(1) = 1'); $users = $query->getResult(); - $this->assertEquals(1, count($users)); - $this->assertSame($user, $users[0]); + self::assertEquals(1, count($users)); + self::assertSame($user, $users[0]); } public function testCustomFunctionOverride() @@ -53,16 +55,17 @@ public function testCustomFunctionOverride() $user = new CmsUser(); $user->name = 'Bob'; $user->username = 'Dylan'; - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->getConfiguration()->addCustomStringFunction('COUNT', 'Doctrine\Tests\ORM\Functional\CustomCount'); + $this->em->persist($user); + $this->em->flush(); + + $this->em->getConfiguration()->addCustomStringFunction('COUNT', 'Doctrine\Tests\ORM\Functional\CustomCount'); - $query = $this->_em->createQuery('SELECT COUNT(DISTINCT u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u'); + $query = $this->em->createQuery('SELECT COUNT(DISTINCT u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u'); $usersCount = $query->getSingleScalarResult(); - $this->assertEquals(1, $usersCount); + self::assertEquals(1, $usersCount); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/CustomIdObjectTypeTest.php b/tests/Doctrine/Tests/ORM/Functional/CustomIdObjectTypeTest.php index 08d89fa8ec2..7f75cb080d7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/CustomIdObjectTypeTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/CustomIdObjectTypeTest.php @@ -1,5 +1,7 @@ _em->persist($parent); - $this->_em->flush(); + $this->em->persist($parent); + $this->em->flush(); - $result = $this->_em->find(CustomIdObjectTypeParent::class, $parent->id); + $result = $this->em->find(CustomIdObjectTypeParent::class, $parent->id); - $this->assertSame($parent, $result); + self::assertSame($parent, $result); } /** @@ -46,11 +48,11 @@ public function testFetchJoinCustomIdObject() $parent->children->add(new CustomIdObjectTypeChild(new CustomIdObject('bar'), $parent)); - $this->_em->persist($parent); - $this->_em->flush(); + $this->em->persist($parent); + $this->em->flush(); $result = $this - ->_em + ->em ->createQuery( 'SELECT parent, children FROM ' . CustomIdObjectTypeParent::class @@ -58,8 +60,8 @@ public function testFetchJoinCustomIdObject() ) ->getResult(); - $this->assertCount(1, $result); - $this->assertSame($parent, $result[0]); + self::assertCount(1, $result); + self::assertSame($parent, $result[0]); } /** @@ -72,12 +74,12 @@ public function testFetchJoinWhereCustomIdObject() $parent->children->add(new CustomIdObjectTypeChild(new CustomIdObject('bar'), $parent)); - $this->_em->persist($parent); - $this->_em->flush(); + $this->em->persist($parent); + $this->em->flush(); // note: hydration is willingly broken in this example: $result = $this - ->_em + ->em ->createQuery( 'SELECT parent, children FROM ' . CustomIdObjectTypeParent::class @@ -87,7 +89,7 @@ public function testFetchJoinWhereCustomIdObject() ->setParameter(1, $parent->children->first()->id) ->getResult(); - $this->assertCount(1, $result); - $this->assertSame($parent, $result[0]); + self::assertCount(1, $result); + self::assertSame($parent, $result[0]); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTest.php b/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTest.php index 5d08039e504..397a88c2aab 100644 --- a/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTest.php @@ -1,25 +1,29 @@ useModelSet('cms'); + parent::setUp(); - $this->_sm = $this->_em->getConnection()->getSchemaManager(); + $this->sm = $this->em->getConnection()->getSchemaManager(); } /** @@ -27,7 +31,7 @@ public function setUp() */ public function testIssue2059() { - if (!$this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { + if (!$this->em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { $this->markTestSkipped('Platform does not support foreign keys.'); } @@ -43,13 +47,13 @@ public function testIssue2059() $metadata = $this->convertToClassMetadata([$project, $user], []); - $this->assertTrue(isset($metadata['Ddc2059Project']->fieldMappings['user'])); - $this->assertTrue(isset($metadata['Ddc2059Project']->associationMappings['user2'])); + self::assertNotNull($metadata['Ddc2059Project']->getProperty('user')); + self::assertNotNull($metadata['Ddc2059Project']->getProperty('user2')); } public function testLoadMetadataFromDatabase() { - if (!$this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { + if (!$this->em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { $this->markTestSkipped('Platform does not support foreign keys.'); } @@ -58,29 +62,36 @@ public function testLoadMetadataFromDatabase() $table->setPrimaryKey(['id']); $table->addColumn('bar', 'string', ['notnull' => false, 'length' => 200]); - $this->_sm->dropAndCreateTable($table); + $this->sm->dropAndCreateTable($table); $metadatas = $this->extractClassMetadata(["DbdriverFoo"]); - $this->assertArrayHasKey('DbdriverFoo', $metadatas); + self::assertArrayHasKey('DbdriverFoo', $metadatas); + $metadata = $metadatas['DbdriverFoo']; - $this->assertArrayHasKey('id', $metadata->fieldMappings); - $this->assertEquals('id', $metadata->fieldMappings['id']['fieldName']); - $this->assertEquals('id', strtolower($metadata->fieldMappings['id']['columnName'])); - $this->assertEquals('integer', (string)$metadata->fieldMappings['id']['type']); - - $this->assertArrayHasKey('bar', $metadata->fieldMappings); - $this->assertEquals('bar', $metadata->fieldMappings['bar']['fieldName']); - $this->assertEquals('bar', strtolower($metadata->fieldMappings['bar']['columnName'])); - $this->assertEquals('string', (string)$metadata->fieldMappings['bar']['type']); - $this->assertEquals(200, $metadata->fieldMappings['bar']['length']); - $this->assertTrue($metadata->fieldMappings['bar']['nullable']); + self::assertNotNull($metadata->getProperty('id')); + + $idProperty = $metadata->getProperty('id'); + + self::assertEquals('id', $idProperty->getName()); + self::assertEquals('id', $idProperty->getColumnName()); + self::assertEquals('integer', $idProperty->getTypeName()); + + self::assertNotNull($metadata->getProperty('bar')); + + $barProperty = $metadata->getProperty('bar'); + + self::assertEquals('bar', $barProperty->getName()); + self::assertEquals('bar', $barProperty->getColumnName()); + self::assertEquals('string', $barProperty->getTypeName()); + self::assertEquals(200, $barProperty->getLength()); + self::assertTrue($barProperty->isNullable()); } public function testLoadMetadataWithForeignKeyFromDatabase() { - if (!$this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { + if (!$this->em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { $this->markTestSkipped('Platform does not support foreign keys.'); } @@ -88,7 +99,7 @@ public function testLoadMetadataWithForeignKeyFromDatabase() $tableB->addColumn('id', 'integer'); $tableB->setPrimaryKey(['id']); - $this->_sm->dropAndCreateTable($tableB); + $this->sm->dropAndCreateTable($tableB); $tableA = new Table("dbdriver_baz"); $tableA->addColumn('id', 'integer'); @@ -96,40 +107,39 @@ public function testLoadMetadataWithForeignKeyFromDatabase() $tableA->addColumn('bar_id', 'integer'); $tableA->addForeignKeyConstraint('dbdriver_bar', ['bar_id'], ['id']); - $this->_sm->dropAndCreateTable($tableA); + $this->sm->dropAndCreateTable($tableA); $metadatas = $this->extractClassMetadata(["DbdriverBar", "DbdriverBaz"]); - $this->assertArrayHasKey('DbdriverBaz', $metadatas); - $bazMetadata = $metadatas['DbdriverBaz']; + self::assertArrayHasKey('DbdriverBaz', $metadatas); - $this->assertArrayNotHasKey('barId', $bazMetadata->fieldMappings, "The foreign Key field should not be inflected as 'barId' field, its an association."); - $this->assertArrayHasKey('id', $bazMetadata->fieldMappings); + $bazMetadata = $metadatas['DbdriverBaz']; - $bazMetadata->associationMappings = \array_change_key_case($bazMetadata->associationMappings, \CASE_LOWER); + self::assertNull($bazMetadata->getProperty('barId'), "The foreign Key field should not be inflected, as 'barId' field is an association."); + self::assertNotNull($bazMetadata->getProperty('id')); - $this->assertArrayHasKey('bar', $bazMetadata->associationMappings); - $this->assertEquals(ClassMetadataInfo::MANY_TO_ONE, $bazMetadata->associationMappings['bar']['type']); + self::assertArrayHasKey('bar', $bazMetadata->getDeclaredPropertiesIterator()); + self::assertInstanceOf(ManyToOneAssociationMetadata::class, $bazMetadata->getProperty('bar')); } public function testDetectManyToManyTables() { - if (!$this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { + if (!$this->em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { $this->markTestSkipped('Platform does not support foreign keys.'); } $metadatas = $this->extractClassMetadata(["CmsUsers", "CmsGroups", "CmsTags"]); - $this->assertArrayHasKey('CmsUsers', $metadatas, 'CmsUsers entity was not detected.'); - $this->assertArrayHasKey('CmsGroups', $metadatas, 'CmsGroups entity was not detected.'); - $this->assertArrayHasKey('CmsTags', $metadatas, 'CmsTags entity was not detected.'); + self::assertArrayHasKey('CmsUsers', $metadatas, 'CmsUsers entity was not detected.'); + self::assertArrayHasKey('CmsGroups', $metadatas, 'CmsGroups entity was not detected.'); + self::assertArrayHasKey('CmsTags', $metadatas, 'CmsTags entity was not detected.'); - $this->assertEquals(3, count($metadatas['CmsUsers']->associationMappings)); - $this->assertArrayHasKey('group', $metadatas['CmsUsers']->associationMappings); - $this->assertEquals(1, count($metadatas['CmsGroups']->associationMappings)); - $this->assertArrayHasKey('user', $metadatas['CmsGroups']->associationMappings); - $this->assertEquals(1, count($metadatas['CmsTags']->associationMappings)); - $this->assertArrayHasKey('user', $metadatas['CmsGroups']->associationMappings); + self::assertCount(3, $metadatas['CmsUsers']->getProperties()); + self::assertArrayHasKey('group', $metadatas['CmsUsers']->getProperties()); + self::assertCount(1, $metadatas['CmsGroups']->getProperties()); + self::assertArrayHasKey('user', $metadatas['CmsGroups']->getProperties()); + self::assertCount(1, $metadatas['CmsTags']->getProperties()); + self::assertArrayHasKey('user', $metadatas['CmsGroups']->getProperties()); } public function testIgnoreManyToManyTableWithoutFurtherForeignKeyDetails() @@ -149,12 +159,12 @@ public function testIgnoreManyToManyTableWithoutFurtherForeignKeyDetails() $metadatas = $this->convertToClassMetadata([$tableA, $tableB], [$tableMany]); - $this->assertEquals(0, count($metadatas['DbdriverBaz']->associationMappings), "no association mappings should be detected."); + self::assertCount(1, $metadatas['DbdriverBaz']->getDeclaredPropertiesIterator(), "no association mappings should be detected."); } public function testLoadMetadataFromDatabaseDetail() { - if ( ! $this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { + if ( ! $this->em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { $this->markTestSkipped('Platform does not support foreign keys.'); } @@ -175,47 +185,77 @@ public function testLoadMetadataFromDatabaseDetail() $table->addColumn('column_unique_index2', 'string'); $table->addUniqueIndex(['column_unique_index1', 'column_unique_index2'], 'unique_index1'); - $this->_sm->dropAndCreateTable($table); + $this->sm->dropAndCreateTable($table); $metadatas = $this->extractClassMetadata(["DbdriverFoo"]); - $this->assertArrayHasKey('DbdriverFoo', $metadatas); + self::assertArrayHasKey('DbdriverFoo', $metadatas); $metadata = $metadatas['DbdriverFoo']; - $this->assertArrayHasKey('id', $metadata->fieldMappings); - $this->assertEquals('id', $metadata->fieldMappings['id']['fieldName']); - $this->assertEquals('id', strtolower($metadata->fieldMappings['id']['columnName'])); - $this->assertEquals('integer', (string) $metadata->fieldMappings['id']['type']); + self::assertNotNull($metadata->getProperty('id')); + + $idProperty = $metadata->getProperty('id'); + + self::assertEquals('id', $idProperty->getName()); + self::assertEquals('id', $idProperty->getColumnName()); + self::assertEquals('integer', $idProperty->getTypeName()); // FIXME: Condition here is fugly. // NOTE: PostgreSQL and SQL SERVER do not support UNSIGNED integer - if ( ! $this->_em->getConnection()->getDatabasePlatform() instanceof PostgreSqlPlatform AND - ! $this->_em->getConnection()->getDatabasePlatform() instanceof SQLServerPlatform) { - $this->assertArrayHasKey('columnUnsigned', $metadata->fieldMappings); - $this->assertTrue($metadata->fieldMappings['columnUnsigned']['options']['unsigned']); + if ( ! $this->em->getConnection()->getDatabasePlatform() instanceof PostgreSqlPlatform AND + ! $this->em->getConnection()->getDatabasePlatform() instanceof SQLServerPlatform) { + self::assertNotNull($metadata->getProperty('columnUnsigned')); + + $columnUnsignedProperty = $metadata->getProperty('columnUnsigned'); + $columnUnsignedOptions = $columnUnsignedProperty->getOptions(); + + self::assertArrayHasKey('unsigned', $columnUnsignedOptions); + self::assertTrue($columnUnsignedOptions['unsigned']); } - $this->assertArrayHasKey('columnComment', $metadata->fieldMappings); - $this->assertEquals('test_comment', $metadata->fieldMappings['columnComment']['options']['comment']); + // Check comment + self::assertNotNull($metadata->getProperty('columnComment')); + + $columnCommentProperty = $metadata->getProperty('columnComment'); + $columnCommentOptions = $columnCommentProperty->getOptions(); + + self::assertArrayHasKey('comment', $columnCommentOptions); + self::assertEquals('test_comment', $columnCommentOptions['comment']); + + // Check default + self::assertNotNull($metadata->getProperty('columnDefault')); - $this->assertArrayHasKey('columnDefault', $metadata->fieldMappings); - $this->assertEquals('test_default', $metadata->fieldMappings['columnDefault']['options']['default']); + $columnDefaultProperty = $metadata->getProperty('columnDefault'); + $columnDefaultOptions = $columnDefaultProperty->getOptions(); - $this->assertArrayHasKey('columnDecimal', $metadata->fieldMappings); - $this->assertEquals(4, $metadata->fieldMappings['columnDecimal']['precision']); - $this->assertEquals(3, $metadata->fieldMappings['columnDecimal']['scale']); + self::assertArrayHasKey('default', $columnDefaultOptions); + self::assertEquals('test_default', $columnDefaultOptions['default']); - $this->assertTrue( ! empty($metadata->table['indexes']['index1']['columns'])); - $this->assertEquals( + // Check decimal + self::assertNotNull($metadata->getProperty('columnDecimal')); + + $columnDecimalProperty = $metadata->getProperty('columnDecimal'); + + self::assertEquals(4, $columnDecimalProperty->getPrecision()); + self::assertEquals(3, $columnDecimalProperty->getScale()); + + // Check indexes + $indexes = $metadata->table->getIndexes(); + + self::assertTrue( ! empty($indexes['index1']['columns'])); + self::assertEquals( ['column_index1','column_index2'], - $metadata->table['indexes']['index1']['columns'] + $indexes['index1']['columns'] ); - $this->assertTrue( ! empty($metadata->table['uniqueConstraints']['unique_index1']['columns'])); - $this->assertEquals( + // Check unique constraints + $uniqueConstraints = $metadata->table->getUniqueConstraints(); + + self::assertTrue( ! empty($uniqueConstraints['unique_index1']['columns'])); + self::assertEquals( ['column_unique_index1', 'column_unique_index2'], - $metadata->table['uniqueConstraints']['unique_index1']['columns'] + $uniqueConstraints['unique_index1']['columns'] ); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTestCase.php b/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTestCase.php index 89d3cd3583c..d826c45040c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTestCase.php +++ b/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTestCase.php @@ -1,10 +1,15 @@ _em->getConnection()->getSchemaManager(); + $metadataBuildingContext = new ClassMetadataBuildingContext( + $this->createMock(ClassMetadataFactory::class), + $this->createMock(ReflectionService::class) + ); + $sm = $this->em->getConnection()->getSchemaManager(); $driver = new DatabaseDriver($sm); $driver->setTables($entityTables, $manyTables); $metadatas = []; + foreach ($driver->getAllClassNames() AS $className) { - $class = new ClassMetadataInfo($className); - $driver->loadMetadataForClass($className, $class); + $class = new ClassMetadata($className, $metadataBuildingContext); + + $driver->loadMetadataForClass($className, $class, $metadataBuildingContext); + $metadatas[$className] = $class; } @@ -33,18 +45,25 @@ protected function convertToClassMetadata(array $entityTables, array $manyTables */ protected function extractClassMetadata(array $classNames) { + $metadataBuildingContext = new ClassMetadataBuildingContext( + $this->createMock(ClassMetadataFactory::class), + $this->createMock(ReflectionService::class) + ); $classNames = array_map('strtolower', $classNames); $metadatas = []; - $sm = $this->_em->getConnection()->getSchemaManager(); + $sm = $this->em->getConnection()->getSchemaManager(); $driver = new DatabaseDriver($sm); foreach ($driver->getAllClassNames() as $className) { if (!in_array(strtolower($className), $classNames)) { continue; } - $class = new ClassMetadataInfo($className); + + $class = new ClassMetadata($className, $metadataBuildingContext); + $driver->loadMetadataForClass($className, $class); + $metadatas[$className] = $class; } diff --git a/tests/Doctrine/Tests/ORM/Functional/DefaultValuesTest.php b/tests/Doctrine/Tests/ORM/Functional/DefaultValuesTest.php index 2797ba8337b..9d870e21aef 100644 --- a/tests/Doctrine/Tests/ORM/Functional/DefaultValuesTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/DefaultValuesTest.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DefaultValueUser::class), - $this->_em->getClassMetadata(DefaultValueAddress::class) + $this->em->getClassMetadata(DefaultValueUser::class), + $this->em->getClassMetadata(DefaultValueAddress::class) ] ); } catch (\Exception $e) { @@ -32,15 +35,15 @@ protected function setUp() public function testSimpleDetachMerge() { $user = new DefaultValueUser; $user->name = 'romanb'; - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); $userId = $user->id; // e.g. from $_REQUEST - $user2 = $this->_em->getReference(get_class($user), $userId); + $user2 = $this->em->getReference(get_class($user), $userId); - $this->_em->flush(); - $this->assertFalse($user2->__isInitialized__); + $this->em->flush(); + self::assertFalse($user2->__isInitialized()); $a = new DefaultValueAddress; $a->country = 'de'; @@ -49,16 +52,16 @@ public function testSimpleDetachMerge() { $a->street = 'Sesamestreet'; $a->user = $user2; - $this->_em->persist($a); - $this->_em->flush(); + $this->em->persist($a); + $this->em->flush(); - $this->assertFalse($user2->__isInitialized__); - $this->_em->clear(); + self::assertFalse($user2->__isInitialized()); + $this->em->clear(); - $a2 = $this->_em->find(get_class($a), $a->id); - $this->assertInstanceOf(DefaultValueUser::class, $a2->getUser()); - $this->assertEquals($userId, $a2->getUser()->getId()); - $this->assertEquals('Poweruser', $a2->getUser()->type); + $a2 = $this->em->find(get_class($a), $a->id); + self::assertInstanceOf(DefaultValueUser::class, $a2->getUser()); + self::assertEquals($userId, $a2->getUser()->getId()); + self::assertEquals('Poweruser', $a2->getUser()->type); } /** @@ -70,43 +73,43 @@ public function testGetPartialReferenceWithDefaultValueNotEvaluatedInFlush() $user->name = 'romanb'; $user->type = 'Normaluser'; - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $user = $this->_em->getPartialReference(DefaultValueUser::class, $user->id); - $this->assertTrue($this->_em->getUnitOfWork()->isReadOnly($user)); + $user = $this->em->getPartialReference(DefaultValueUser::class, $user->id); + self::assertTrue($this->em->getUnitOfWork()->isReadOnly($user)); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $user = $this->_em->find(DefaultValueUser::class, $user->id); + $user = $this->em->find(DefaultValueUser::class, $user->id); - $this->assertEquals('Normaluser', $user->type); + self::assertEquals('Normaluser', $user->type); } } /** - * @Entity @Table(name="defaultvalueuser") + * @ORM\Entity @ORM\Table(name="defaultvalueuser") */ class DefaultValueUser { /** - * @Id @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $name = ''; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $type = 'Poweruser'; /** - * @OneToOne(targetEntity="DefaultValueAddress", mappedBy="user", cascade={"persist"}) + * @ORM\OneToOne(targetEntity="DefaultValueAddress", mappedBy="user", cascade={"persist"}) */ public $address; @@ -116,28 +119,28 @@ public function getId() {return $this->id;} /** * CmsAddress * - * @Entity @Table(name="defaultvalueaddresses") + * @ORM\Entity @ORM\Table(name="defaultvalueaddresses") */ class DefaultValueAddress { /** - * @Column(type="integer") - * @Id @GeneratedValue(strategy="AUTO") + * @ORM\Column(type="integer") + * @ORM\Id @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @Column(type="string", length=50) + * @ORM\Column(type="string", length=50) */ public $country; /** - * @Column(type="string", length=50) + * @ORM\Column(type="string", length=50) */ public $zip; /** - * @Column(type="string", length=50) + * @ORM\Column(type="string", length=50) */ public $city; @@ -147,8 +150,8 @@ class DefaultValueAddress public $street; /** - * @OneToOne(targetEntity="DefaultValueUser") - * @JoinColumn(name="user_id", referencedColumnName="id") + * @ORM\OneToOne(targetEntity="DefaultValueUser") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id") */ public $user; diff --git a/tests/Doctrine/Tests/ORM/Functional/DetachedEntityTest.php b/tests/Doctrine/Tests/ORM/Functional/DetachedEntityTest.php deleted file mode 100644 index 523c98c0943..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/DetachedEntityTest.php +++ /dev/null @@ -1,228 +0,0 @@ -useModelSet('cms'); - parent::setUp(); - } - - public function testSimpleDetachMerge() - { - $user = new CmsUser; - $user->name = 'Roman'; - $user->username = 'romanb'; - $user->status = 'dev'; - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); - - // $user is now detached - $this->assertFalse($this->_em->contains($user)); - - $user->name = 'Roman B.'; - - $user2 = $this->_em->merge($user); - - $this->assertFalse($user === $user2); - $this->assertTrue($this->_em->contains($user2)); - $this->assertEquals('Roman B.', $user2->name); - } - - public function testSerializeUnserializeModifyMerge() - { - $user = new CmsUser; - $user->name = 'Guilherme'; - $user->username = 'gblanco'; - $user->status = 'developer'; - - $ph1 = new CmsPhonenumber; - $ph1->phonenumber = "1234"; - $user->addPhonenumber($ph1); - - $this->_em->persist($user); - $this->_em->flush(); - - $this->assertTrue($this->_em->contains($user)); - $this->assertTrue($user->phonenumbers->isInitialized()); - - $serialized = serialize($user); - - $this->_em->clear(); - - $this->assertFalse($this->_em->contains($user)); - - unset($user); - - $user = unserialize($serialized); - - $this->assertEquals(1, count($user->getPhonenumbers()), "Pre-Condition: 1 Phonenumber"); - - $ph2 = new CmsPhonenumber; - - $ph2->phonenumber = "56789"; - $user->addPhonenumber($ph2); - - $oldPhonenumbers = $user->getPhonenumbers(); - - $this->assertEquals(2, count($oldPhonenumbers), "Pre-Condition: 2 Phonenumbers"); - $this->assertFalse($this->_em->contains($user)); - - $this->_em->persist($ph2); - - // Merge back in - $user = $this->_em->merge($user); // merge cascaded to phonenumbers - $this->assertInstanceOf(CmsUser::class, $user->phonenumbers[0]->user); - $this->assertInstanceOf(CmsUser::class, $user->phonenumbers[1]->user); - $im = $this->_em->getUnitOfWork()->getIdentityMap(); - $this->_em->flush(); - - $this->assertTrue($this->_em->contains($user), "Failed to assert that merged user is contained inside EntityManager persistence context."); - $phonenumbers = $user->getPhonenumbers(); - $this->assertNotSame($oldPhonenumbers, $phonenumbers, "Merge should replace the Detached Collection with a new PersistentCollection."); - $this->assertEquals(2, count($phonenumbers), "Failed to assert that two phonenumbers are contained in the merged users phonenumber collection."); - - $this->assertInstanceOf(CmsPhonenumber::class, $phonenumbers[1]); - $this->assertTrue($this->_em->contains($phonenumbers[1]), "Failed to assert that second phonenumber in collection is contained inside EntityManager persistence context."); - - $this->assertInstanceOf(CmsPhonenumber::class, $phonenumbers[0]); - $this->assertTrue($this->_em->getUnitOfWork()->isInIdentityMap($phonenumbers[0])); - $this->assertTrue($this->_em->contains($phonenumbers[0]), "Failed to assert that first phonenumber in collection is contained inside EntityManager persistence context."); - } - - /** - * @group DDC-203 - */ - public function testDetachedEntityThrowsExceptionOnFlush() - { - $ph = new CmsPhonenumber(); - $ph->phonenumber = '12345'; - - $this->_em->persist($ph); - $this->_em->flush(); - $this->_em->clear(); - - $this->_em->persist($ph); - - // since it tries to insert the object twice (with the same PK) - $this->expectException(UniqueConstraintViolationException::class); - $this->_em->flush(); - } - - public function testUninitializedLazyAssociationsAreIgnoredOnMerge() - { - $user = new CmsUser; - $user->name = 'Guilherme'; - $user->username = 'gblanco'; - $user->status = 'developer'; - - $address = new CmsAddress; - $address->city = 'Berlin'; - $address->country = 'Germany'; - $address->street = 'Sesamestreet'; - $address->zip = 12345; - $address->setUser($user); - $this->_em->persist($address); - $this->_em->persist($user); - - $this->_em->flush(); - $this->_em->clear(); - - $address2 = $this->_em->find(get_class($address), $address->id); - $this->assertInstanceOf(Proxy::class, $address2->user); - $this->assertFalse($address2->user->__isInitialized__); - $detachedAddress2 = unserialize(serialize($address2)); - $this->assertInstanceOf(Proxy::class, $detachedAddress2->user); - $this->assertFalse($detachedAddress2->user->__isInitialized__); - - $managedAddress2 = $this->_em->merge($detachedAddress2); - $this->assertInstanceOf(Proxy::class, $managedAddress2->user); - $this->assertFalse($managedAddress2->user === $detachedAddress2->user); - $this->assertFalse($managedAddress2->user->__isInitialized__); - } - - /** - * @group DDC-822 - */ - public function testUseDetachedEntityAsQueryParameter() - { - $user = new CmsUser; - $user->name = 'Guilherme'; - $user->username = 'gblanco'; - $user->status = 'developer'; - - $this->_em->persist($user); - - $this->_em->flush(); - $this->_em->detach($user); - - $dql = 'SELECT u FROM ' . CmsUser::class . ' u WHERE u.id = ?1'; - $query = $this->_em->createQuery($dql); - $query->setParameter(1, $user); - - $newUser = $query->getSingleResult(); - - $this->assertInstanceOf(CmsUser::class, $newUser); - $this->assertEquals('gblanco', $newUser->username); - } - - /** - * @group DDC-920 - */ - public function testDetachManagedUnpersistedEntity() - { - $user = new CmsUser; - $user->name = 'Guilherme'; - $user->username = 'gblanco'; - $user->status = 'developer'; - - $this->_em->persist($user); - $this->_em->detach($user); - - $this->_em->flush(); - - $this->assertFalse($this->_em->contains($user)); - $this->assertFalse($this->_em->getUnitOfWork()->isInIdentityMap($user)); - } - - /** - * @group DDC-1340 - */ - public function testMergeArticleWrongVersion() - { - $article = new CmsArticle(); - $article->topic = "test"; - $article->text = "test"; - - $this->_em->persist($article); - $this->_em->flush(); - - $this->_em->detach($article); - - $sql = 'UPDATE cms_articles SET version = version + 1 WHERE id = ' . $article->id; - $this->_em->getConnection()->executeUpdate($sql); - - $this->expectException(OptimisticLockException::class); - $this->expectExceptionMessage('The optimistic lock failed, version 1 was expected, but is actually 2'); - - $this->_em->merge($article); - } -} - diff --git a/tests/Doctrine/Tests/ORM/Functional/EntityListenersTest.php b/tests/Doctrine/Tests/ORM/Functional/EntityListenersTest.php index 98457dd49db..67440bcf26f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/EntityListenersTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/EntityListenersTest.php @@ -1,5 +1,7 @@ useModelSet('company'); parent::setUp(); - $this->listener = $this->_em->getConfiguration() + $this->listener = $this->em->getConfiguration() ->getEntityListenerResolver() ->resolve(CompanyContractListener::class); } @@ -37,13 +39,13 @@ public function testPreFlushListeners() $this->listener->preFlushCalls = []; - $this->_em->persist($fix); - $this->_em->flush(); + $this->em->persist($fix); + $this->em->flush(); - $this->assertCount(1,$this->listener->preFlushCalls); - $this->assertSame($fix, $this->listener->preFlushCalls[0][0]); - $this->assertInstanceOf(CompanyFixContract::class, $this->listener->preFlushCalls[0][0]); - $this->assertInstanceOf(PreFlushEventArgs::class, $this->listener->preFlushCalls[0][1]); + self::assertCount(1,$this->listener->preFlushCalls); + self::assertSame($fix, $this->listener->preFlushCalls[0][0]); + self::assertInstanceOf(CompanyFixContract::class, $this->listener->preFlushCalls[0][0]); + self::assertInstanceOf(PreFlushEventArgs::class, $this->listener->preFlushCalls[0][1]); } public function testPostLoadListeners() @@ -51,19 +53,19 @@ public function testPostLoadListeners() $fix = new CompanyFixContract(); $fix->setFixPrice(2000); - $this->_em->persist($fix); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($fix); + $this->em->flush(); + $this->em->clear(); $this->listener->postLoadCalls = []; $dql = "SELECT f FROM Doctrine\Tests\Models\Company\CompanyFixContract f WHERE f.id = ?1"; - $fix = $this->_em->createQuery($dql)->setParameter(1, $fix->getId())->getSingleResult(); + $fix = $this->em->createQuery($dql)->setParameter(1, $fix->getId())->getSingleResult(); - $this->assertCount(1,$this->listener->postLoadCalls); - $this->assertSame($fix, $this->listener->postLoadCalls[0][0]); - $this->assertInstanceOf(CompanyFixContract::class, $this->listener->postLoadCalls[0][0]); - $this->assertInstanceOf(LifecycleEventArgs::class, $this->listener->postLoadCalls[0][1]); + self::assertCount(1,$this->listener->postLoadCalls); + self::assertSame($fix, $this->listener->postLoadCalls[0][0]); + self::assertInstanceOf(CompanyFixContract::class, $this->listener->postLoadCalls[0][0]); + self::assertInstanceOf(LifecycleEventArgs::class, $this->listener->postLoadCalls[0][1]); } public function testPrePersistListeners() @@ -73,13 +75,13 @@ public function testPrePersistListeners() $this->listener->prePersistCalls = []; - $this->_em->persist($fix); - $this->_em->flush(); + $this->em->persist($fix); + $this->em->flush(); - $this->assertCount(1,$this->listener->prePersistCalls); - $this->assertSame($fix, $this->listener->prePersistCalls[0][0]); - $this->assertInstanceOf(CompanyFixContract::class, $this->listener->prePersistCalls[0][0]); - $this->assertInstanceOf(LifecycleEventArgs::class, $this->listener->prePersistCalls[0][1]); + self::assertCount(1,$this->listener->prePersistCalls); + self::assertSame($fix, $this->listener->prePersistCalls[0][0]); + self::assertInstanceOf(CompanyFixContract::class, $this->listener->prePersistCalls[0][0]); + self::assertInstanceOf(LifecycleEventArgs::class, $this->listener->prePersistCalls[0][1]); } public function testPostPersistListeners() @@ -89,13 +91,13 @@ public function testPostPersistListeners() $this->listener->postPersistCalls = []; - $this->_em->persist($fix); - $this->_em->flush(); + $this->em->persist($fix); + $this->em->flush(); - $this->assertCount(1,$this->listener->postPersistCalls); - $this->assertSame($fix, $this->listener->postPersistCalls[0][0]); - $this->assertInstanceOf(CompanyFixContract::class, $this->listener->postPersistCalls[0][0]); - $this->assertInstanceOf(LifecycleEventArgs::class, $this->listener->postPersistCalls[0][1]); + self::assertCount(1,$this->listener->postPersistCalls); + self::assertSame($fix, $this->listener->postPersistCalls[0][0]); + self::assertInstanceOf(CompanyFixContract::class, $this->listener->postPersistCalls[0][0]); + self::assertInstanceOf(LifecycleEventArgs::class, $this->listener->postPersistCalls[0][1]); } public function testPreUpdateListeners() @@ -103,20 +105,20 @@ public function testPreUpdateListeners() $fix = new CompanyFixContract(); $fix->setFixPrice(1000); - $this->_em->persist($fix); - $this->_em->flush(); + $this->em->persist($fix); + $this->em->flush(); $this->listener->preUpdateCalls = []; $fix->setFixPrice(2000); - $this->_em->persist($fix); - $this->_em->flush(); + $this->em->persist($fix); + $this->em->flush(); - $this->assertCount(1,$this->listener->preUpdateCalls); - $this->assertSame($fix, $this->listener->preUpdateCalls[0][0]); - $this->assertInstanceOf(CompanyFixContract::class, $this->listener->preUpdateCalls[0][0]); - $this->assertInstanceOf(PreUpdateEventArgs::class, $this->listener->preUpdateCalls[0][1]); + self::assertCount(1,$this->listener->preUpdateCalls); + self::assertSame($fix, $this->listener->preUpdateCalls[0][0]); + self::assertInstanceOf(CompanyFixContract::class, $this->listener->preUpdateCalls[0][0]); + self::assertInstanceOf(PreUpdateEventArgs::class, $this->listener->preUpdateCalls[0][1]); } public function testPostUpdateListeners() @@ -124,20 +126,20 @@ public function testPostUpdateListeners() $fix = new CompanyFixContract(); $fix->setFixPrice(1000); - $this->_em->persist($fix); - $this->_em->flush(); + $this->em->persist($fix); + $this->em->flush(); $this->listener->postUpdateCalls = []; $fix->setFixPrice(2000); - $this->_em->persist($fix); - $this->_em->flush(); + $this->em->persist($fix); + $this->em->flush(); - $this->assertCount(1,$this->listener->postUpdateCalls); - $this->assertSame($fix, $this->listener->postUpdateCalls[0][0]); - $this->assertInstanceOf(CompanyFixContract::class, $this->listener->postUpdateCalls[0][0]); - $this->assertInstanceOf(LifecycleEventArgs::class, $this->listener->postUpdateCalls[0][1]); + self::assertCount(1,$this->listener->postUpdateCalls); + self::assertSame($fix, $this->listener->postUpdateCalls[0][0]); + self::assertInstanceOf(CompanyFixContract::class, $this->listener->postUpdateCalls[0][0]); + self::assertInstanceOf(LifecycleEventArgs::class, $this->listener->postUpdateCalls[0][1]); } public function testPreRemoveListeners() @@ -145,18 +147,18 @@ public function testPreRemoveListeners() $fix = new CompanyFixContract(); $fix->setFixPrice(1000); - $this->_em->persist($fix); - $this->_em->flush(); + $this->em->persist($fix); + $this->em->flush(); $this->listener->preRemoveCalls = []; - $this->_em->remove($fix); - $this->_em->flush(); + $this->em->remove($fix); + $this->em->flush(); - $this->assertCount(1,$this->listener->preRemoveCalls); - $this->assertSame($fix, $this->listener->preRemoveCalls[0][0]); - $this->assertInstanceOf(CompanyFixContract::class, $this->listener->preRemoveCalls[0][0]); - $this->assertInstanceOf(LifecycleEventArgs::class, $this->listener->preRemoveCalls[0][1]); + self::assertCount(1,$this->listener->preRemoveCalls); + self::assertSame($fix, $this->listener->preRemoveCalls[0][0]); + self::assertInstanceOf(CompanyFixContract::class, $this->listener->preRemoveCalls[0][0]); + self::assertInstanceOf(LifecycleEventArgs::class, $this->listener->preRemoveCalls[0][1]); } public function testPostRemoveListeners() @@ -164,17 +166,17 @@ public function testPostRemoveListeners() $fix = new CompanyFixContract(); $fix->setFixPrice(1000); - $this->_em->persist($fix); - $this->_em->flush(); + $this->em->persist($fix); + $this->em->flush(); $this->listener->postRemoveCalls = []; - $this->_em->remove($fix); - $this->_em->flush(); + $this->em->remove($fix); + $this->em->flush(); - $this->assertCount(1,$this->listener->postRemoveCalls); - $this->assertSame($fix, $this->listener->postRemoveCalls[0][0]); - $this->assertInstanceOf(CompanyFixContract::class, $this->listener->postRemoveCalls[0][0]); - $this->assertInstanceOf(LifecycleEventArgs::class, $this->listener->postRemoveCalls[0][1]); + self::assertCount(1,$this->listener->postRemoveCalls); + self::assertSame($fix, $this->listener->postRemoveCalls[0][0]); + self::assertInstanceOf(CompanyFixContract::class, $this->listener->postRemoveCalls[0][0]); + self::assertInstanceOf(LifecycleEventArgs::class, $this->listener->postRemoveCalls[0][1]); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryCriteriaTest.php b/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryCriteriaTest.php index 700964b97da..be671a3bcaa 100644 --- a/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryCriteriaTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryCriteriaTest.php @@ -1,5 +1,7 @@ _em) { - $this->_em->getConfiguration()->setEntityNamespaces([]); + if ($this->em) { + $this->em->getConfiguration()->setEntityNamespaces([]); } parent::tearDown(); } @@ -36,41 +38,41 @@ public function loadFixture() $today->date = $today->time = new \DateTime('today'); - $this->_em->persist($today); + $this->em->persist($today); $tomorrow = new DateTimeModel(); $tomorrow->datetime = $tomorrow->date = $tomorrow->time = new \DateTime('tomorrow'); - $this->_em->persist($tomorrow); + $this->em->persist($tomorrow); $yesterday = new DateTimeModel(); $yesterday->datetime = $yesterday->date = $yesterday->time = new \DateTime('yesterday'); - $this->_em->persist($yesterday); + $this->em->persist($yesterday); - $this->_em->flush(); + $this->em->flush(); unset($today); unset($tomorrow); unset($yesterday); - $this->_em->clear(); + $this->em->clear(); } public function testLteDateComparison() { $this->loadFixture(); - $repository = $this->_em->getRepository(DateTimeModel::class); + $repository = $this->em->getRepository(DateTimeModel::class); $dates = $repository->matching(new Criteria( Criteria::expr()->lte('datetime', new \DateTime('today')) )); - $this->assertEquals(2, count($dates)); + self::assertEquals(2, count($dates)); } private function loadNullFieldFixtures() @@ -80,107 +82,107 @@ private function loadNullFieldFixtures() $today->date = new \DateTime('today'); - $this->_em->persist($today); + $this->em->persist($today); $tomorrow = new DateTimeModel(); $tomorrow->datetime = $tomorrow->date = $tomorrow->time = new \DateTime('tomorrow'); - $this->_em->persist($tomorrow); + $this->em->persist($tomorrow); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); } public function testIsNullComparison() { $this->loadNullFieldFixtures(); - $repository = $this->_em->getRepository(DateTimeModel::class); + $repository = $this->em->getRepository(DateTimeModel::class); $dates = $repository->matching(new Criteria( Criteria::expr()->isNull('time') )); - $this->assertEquals(1, count($dates)); + self::assertEquals(1, count($dates)); } public function testEqNullComparison() { $this->loadNullFieldFixtures(); - $repository = $this->_em->getRepository(DateTimeModel::class); + $repository = $this->em->getRepository(DateTimeModel::class); $dates = $repository->matching(new Criteria( Criteria::expr()->eq('time', null) )); - $this->assertEquals(1, count($dates)); + self::assertEquals(1, count($dates)); } public function testNotEqNullComparison() { $this->loadNullFieldFixtures(); - $repository = $this->_em->getRepository(DateTimeModel::class); + $repository = $this->em->getRepository(DateTimeModel::class); $dates = $repository->matching(new Criteria( Criteria::expr()->neq('time', null) )); - $this->assertEquals(1, count($dates)); + self::assertEquals(1, count($dates)); } public function testCanCountWithoutLoadingCollection() { $this->loadFixture(); - $repository = $this->_em->getRepository(DateTimeModel::class); + $repository = $this->em->getRepository(DateTimeModel::class); $dates = $repository->matching(new Criteria()); - $this->assertFalse($dates->isInitialized()); - $this->assertCount(3, $dates); - $this->assertFalse($dates->isInitialized()); + self::assertFalse($dates->isInitialized()); + self::assertCount(3, $dates); + self::assertFalse($dates->isInitialized()); // Test it can work even with a constraint $dates = $repository->matching(new Criteria( Criteria::expr()->lte('datetime', new \DateTime('today')) )); - $this->assertFalse($dates->isInitialized()); - $this->assertCount(2, $dates); - $this->assertFalse($dates->isInitialized()); + self::assertFalse($dates->isInitialized()); + self::assertCount(2, $dates); + self::assertFalse($dates->isInitialized()); // Trigger a loading, to make sure collection is initialized $date = $dates[0]; - $this->assertTrue($dates->isInitialized()); + self::assertTrue($dates->isInitialized()); } public function testCanContainsWithoutLoadingCollection() { $user = new User(); $user->name = 'Marco'; - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); $tweet = new Tweet(); $tweet->author = $user; $tweet->content = 'Criteria is awesome'; - $this->_em->persist($tweet); - $this->_em->flush(); + $this->em->persist($tweet); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); $criteria = new Criteria(); $criteria->andWhere($criteria->expr()->contains('content', 'Criteria')); - $user = $this->_em->find(User::class, $user->id); + $user = $this->em->find(User::class, $user->id); $tweets = $user->tweets->matching($criteria); - $this->assertInstanceOf(LazyCriteriaCollection::class, $tweets); - $this->assertFalse($tweets->isInitialized()); + self::assertInstanceOf(LazyCriteriaCollection::class, $tweets); + self::assertFalse($tweets->isInitialized()); $tweets->contains($tweet); - $this->assertTrue($tweets->contains($tweet)); + self::assertTrue($tweets->contains($tweet)); - $this->assertFalse($tweets->isInitialized()); + self::assertFalse($tweets->isInitialized()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryTest.php b/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryTest.php index ebc7acee973..e0ef7348a82 100644 --- a/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryTest.php @@ -1,5 +1,7 @@ _em) { - $this->_em->getConfiguration()->setEntityNamespaces([]); + if ($this->em) { + $this->em->getConfiguration()->setEntityNamespaces([]); } parent::tearDown(); } @@ -46,27 +48,27 @@ public function loadFixture() $user->name = 'Roman'; $user->username = 'romanb'; $user->status = 'freak'; - $this->_em->persist($user); + $this->em->persist($user); $user2 = new CmsUser; $user2->name = 'Guilherme'; $user2->username = 'gblanco'; $user2->status = 'dev'; - $this->_em->persist($user2); + $this->em->persist($user2); $user3 = new CmsUser; $user3->name = 'Benjamin'; $user3->username = 'beberlei'; $user3->status = null; - $this->_em->persist($user3); + $this->em->persist($user3); $user4 = new CmsUser; $user4->name = 'Alexander'; $user4->username = 'asm89'; $user4->status = 'dev'; - $this->_em->persist($user4); + $this->em->persist($user4); - $this->_em->flush(); + $this->em->flush(); $user1Id = $user->getId(); @@ -75,7 +77,7 @@ public function loadFixture() unset($user3); unset($user4); - $this->_em->clear(); + $this->em->clear(); return $user1Id; } @@ -94,10 +96,10 @@ public function loadAssociatedFixture() $user->status = 'freak'; $user->setAddress($address); - $this->_em->persist($user); - $this->_em->persist($address); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->persist($address); + $this->em->flush(); + $this->em->clear(); return [$user->id, $address->id]; } @@ -132,16 +134,16 @@ public function loadFixtureUserEmail() $user2->setEmail($email2); $user3->setEmail($email3); - $this->_em->persist($user1); - $this->_em->persist($user2); - $this->_em->persist($user3); + $this->em->persist($user1); + $this->em->persist($user2); + $this->em->persist($user3); - $this->_em->persist($email1); - $this->_em->persist($email2); - $this->_em->persist($email3); + $this->em->persist($email1); + $this->em->persist($email2); + $this->em->persist($email3); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); return [$user1, $user2, $user3]; } @@ -154,8 +156,8 @@ public function buildUser($name, $username, $status, $address) $user->status = $status; $user->setAddress($address); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); return $user; } @@ -168,8 +170,8 @@ public function buildAddress($country, $city, $street, $zip) $address->street = $street; $address->zip = $zip; - $this->_em->persist($address); - $this->_em->flush(); + $this->em->persist($address); + $this->em->flush(); return $address; } @@ -177,24 +179,24 @@ public function buildAddress($country, $city, $street, $zip) public function testBasicFind() { $user1Id = $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $user = $repos->find($user1Id); - $this->assertInstanceOf(CmsUser::class,$user); - $this->assertEquals('Roman', $user->name); - $this->assertEquals('freak', $user->status); + self::assertInstanceOf(CmsUser::class,$user); + self::assertEquals('Roman', $user->name); + self::assertEquals('freak', $user->status); } public function testFindByField() { $user1Id = $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $users = $repos->findBy(['status' => 'dev']); - $this->assertEquals(2, count($users)); - $this->assertInstanceOf(CmsUser::class,$users[0]); - $this->assertEquals('Guilherme', $users[0]->name); - $this->assertEquals('dev', $users[0]->status); + self::assertEquals(2, count($users)); + self::assertInstanceOf(CmsUser::class,$users[0]); + self::assertEquals('Guilherme', $users[0]->name); + self::assertEquals('dev', $users[0]->status); } public function testFindByAssociationWithIntegerAsParameter() @@ -212,13 +214,13 @@ public function testFindByAssociationWithIntegerAsParameter() unset($address2); unset($address3); - $this->_em->clear(); + $this->em->clear(); - $repository = $this->_em->getRepository(CmsAddress::class); + $repository = $this->em->getRepository(CmsAddress::class); $addresses = $repository->findBy(['user' => [$user1->getId(), $user2->getId()]]); - $this->assertEquals(2, count($addresses)); - $this->assertInstanceOf(CmsAddress::class,$addresses[0]); + self::assertEquals(2, count($addresses)); + self::assertInstanceOf(CmsAddress::class,$addresses[0]); } public function testFindByAssociationWithObjectAsParameter() @@ -236,78 +238,78 @@ public function testFindByAssociationWithObjectAsParameter() unset($address2); unset($address3); - $this->_em->clear(); + $this->em->clear(); - $repository = $this->_em->getRepository(CmsAddress::class); + $repository = $this->em->getRepository(CmsAddress::class); $addresses = $repository->findBy(['user' => [$user1, $user2]]); - $this->assertEquals(2, count($addresses)); - $this->assertInstanceOf(CmsAddress::class,$addresses[0]); + self::assertEquals(2, count($addresses)); + self::assertInstanceOf(CmsAddress::class,$addresses[0]); } public function testFindFieldByMagicCall() { $user1Id = $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $users = $repos->findByStatus('dev'); - $this->assertEquals(2, count($users)); - $this->assertInstanceOf(CmsUser::class,$users[0]); - $this->assertEquals('Guilherme', $users[0]->name); - $this->assertEquals('dev', $users[0]->status); + self::assertEquals(2, count($users)); + self::assertInstanceOf(CmsUser::class,$users[0]); + self::assertEquals('Guilherme', $users[0]->name); + self::assertEquals('dev', $users[0]->status); } public function testFindAll() { $user1Id = $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $users = $repos->findAll(); - $this->assertEquals(4, count($users)); + self::assertEquals(4, count($users)); } public function testFindByAlias() { $user1Id = $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); - $this->_em->getConfiguration()->addEntityNamespace('CMS', 'Doctrine\Tests\Models\CMS'); + $this->em->getConfiguration()->addEntityNamespace('CMS', 'Doctrine\Tests\Models\CMS'); - $repos = $this->_em->getRepository('CMS:CmsUser'); + $repos = $this->em->getRepository('CMS:CmsUser'); $users = $repos->findAll(); - $this->assertEquals(4, count($users)); + self::assertEquals(4, count($users)); } public function testCount() { $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $userCount = $repos->count([]); - $this->assertSame(4, $userCount); + self::assertSame(4, $userCount); $userCount = $repos->count(['status' => 'dev']); - $this->assertSame(2, $userCount); + self::assertSame(2, $userCount); $userCount = $repos->count(['status' => 'nonexistent']); - $this->assertSame(0, $userCount); + self::assertSame(0, $userCount); } public function testCountBy() { $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $userCount = $repos->countByStatus('dev'); - $this->assertSame(2, $userCount); + self::assertSame(2, $userCount); } /** * @expectedException \Doctrine\ORM\ORMException */ public function testExceptionIsThrownWhenCallingFindByWithoutParameter() { - $this->_em->getRepository(CmsUser::class) + $this->em->getRepository(CmsUser::class) ->findByStatus(); } @@ -315,7 +317,7 @@ public function testExceptionIsThrownWhenCallingFindByWithoutParameter() { * @expectedException \Doctrine\ORM\ORMException */ public function testExceptionIsThrownWhenUsingInvalidFieldName() { - $this->_em->getRepository(CmsUser::class) + $this->em->getRepository(CmsUser::class) ->findByThisFieldDoesNotExist('testvalue'); } @@ -327,7 +329,7 @@ public function testPessimisticReadLockWithoutTransaction_ThrowsException() { $this->expectException(TransactionRequiredException::class); - $this->_em->getRepository(CmsUser::class) + $this->em->getRepository(CmsUser::class) ->find(1, LockMode::PESSIMISTIC_READ); } @@ -339,7 +341,7 @@ public function testPessimisticWriteLockWithoutTransaction_ThrowsException() { $this->expectException(TransactionRequiredException::class); - $this->_em->getRepository(CmsUser::class) + $this->em->getRepository(CmsUser::class) ->find(1, LockMode::PESSIMISTIC_WRITE); } @@ -351,7 +353,7 @@ public function testOptimisticLockUnversionedEntity_ThrowsException() { $this->expectException(OptimisticLockException::class); - $this->_em->getRepository(CmsUser::class) + $this->em->getRepository(CmsUser::class) ->find(1, LockMode::OPTIMISTIC); } @@ -365,16 +367,16 @@ public function testIdentityMappedOptimisticLockUnversionedEntity_ThrowsExceptio $user->name = 'Roman'; $user->username = 'romanb'; $user->status = 'freak'; - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); $userId = $user->id; - $this->_em->find(CmsUser::class, $userId); + $this->em->find(CmsUser::class, $userId); $this->expectException(OptimisticLockException::class); - $this->_em->find(CmsUser::class, $userId, LockMode::OPTIMISTIC); + $this->em->find(CmsUser::class, $userId, LockMode::OPTIMISTIC); } /** @@ -384,10 +386,10 @@ public function testFindMagicCallByNullValue() { $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $users = $repos->findByStatus(null); - $this->assertEquals(1, count($users)); + self::assertEquals(1, count($users)); } /** @@ -397,7 +399,7 @@ public function testInvalidMagicCall() { $this->expectException(\BadMethodCallException::class); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $repos->foo(); } @@ -407,7 +409,7 @@ public function testInvalidMagicCall() public function testFindByAssociationKey_ExceptionOnInverseSide() { list($userId, $addressId) = $this->loadAssociatedFixture(); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $this->expectException(ORMException::class); $this->expectExceptionMessage("You cannot search for the association field 'Doctrine\Tests\Models\CMS\CmsUser#address', because it is the inverse side of an association. Find methods only work on owning side associations."); @@ -421,11 +423,11 @@ public function testFindByAssociationKey_ExceptionOnInverseSide() public function testFindOneByAssociationKey() { list($userId, $addressId) = $this->loadAssociatedFixture(); - $repos = $this->_em->getRepository(CmsAddress::class); + $repos = $this->em->getRepository(CmsAddress::class); $address = $repos->findOneBy(['user' => $userId]); - $this->assertInstanceOf(CmsAddress::class, $address); - $this->assertEquals($addressId, $address->id); + self::assertInstanceOf(CmsAddress::class, $address); + self::assertEquals($addressId, $address->id); } /** @@ -435,11 +437,11 @@ public function testFindOneByOrderBy() { $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $userAsc = $repos->findOneBy([], ["username" => "ASC"]); $userDesc = $repos->findOneBy([], ["username" => "DESC"]); - $this->assertNotSame($userAsc, $userDesc); + self::assertNotSame($userAsc, $userDesc); } /** @@ -448,12 +450,12 @@ public function testFindOneByOrderBy() public function testFindByAssociationKey() { list($userId, $addressId) = $this->loadAssociatedFixture(); - $repos = $this->_em->getRepository(CmsAddress::class); + $repos = $this->em->getRepository(CmsAddress::class); $addresses = $repos->findBy(['user' => $userId]); - $this->assertContainsOnly(CmsAddress::class, $addresses); - $this->assertEquals(1, count($addresses)); - $this->assertEquals($addressId, $addresses[0]->id); + self::assertContainsOnly(CmsAddress::class, $addresses); + self::assertEquals(1, count($addresses)); + self::assertEquals($addressId, $addresses[0]->id); } /** @@ -462,12 +464,12 @@ public function testFindByAssociationKey() public function testFindAssociationByMagicCall() { list($userId, $addressId) = $this->loadAssociatedFixture(); - $repos = $this->_em->getRepository(CmsAddress::class); + $repos = $this->em->getRepository(CmsAddress::class); $addresses = $repos->findByUser($userId); - $this->assertContainsOnly(CmsAddress::class, $addresses); - $this->assertEquals(1, count($addresses)); - $this->assertEquals($addressId, $addresses[0]->id); + self::assertContainsOnly(CmsAddress::class, $addresses); + self::assertEquals(1, count($addresses)); + self::assertEquals($addressId, $addresses[0]->id); } /** @@ -476,26 +478,26 @@ public function testFindAssociationByMagicCall() public function testFindOneAssociationByMagicCall() { list($userId, $addressId) = $this->loadAssociatedFixture(); - $repos = $this->_em->getRepository(CmsAddress::class); + $repos = $this->em->getRepository(CmsAddress::class); $address = $repos->findOneByUser($userId); - $this->assertInstanceOf(CmsAddress::class, $address); - $this->assertEquals($addressId, $address->id); + self::assertInstanceOf(CmsAddress::class, $address); + self::assertEquals($addressId, $address->id); } public function testValidNamedQueryRetrieval() { - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $query = $repos->createNamedQuery('all'); - $this->assertInstanceOf(Query::class, $query); - $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $query->getDQL()); + self::assertInstanceOf(Query::class, $query); + self::assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $query->getDQL()); } public function testInvalidNamedQueryRetrieval() { - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); @@ -507,22 +509,22 @@ public function testInvalidNamedQueryRetrieval() */ public function testIsNullCriteriaDoesNotGenerateAParameter() { - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $users = $repos->findBy(['status' => null, 'username' => 'romanb']); - $params = $this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['params']; - $this->assertEquals(1, count($params), "Should only execute with one parameter."); - $this->assertEquals(['romanb'], $params); + $params = $this->sqlLoggerStack->queries[$this->sqlLoggerStack->currentQuery]['params']; + self::assertEquals(1, count($params), "Should only execute with one parameter."); + self::assertEquals(['romanb'], $params); } public function testIsNullCriteria() { $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $users = $repos->findBy(['status' => null]); - $this->assertEquals(1, count($users)); + self::assertEquals(1, count($users)); } /** @@ -532,15 +534,15 @@ public function testFindByLimitOffset() { $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $users1 = $repos->findBy([], null, 1, 0); $users2 = $repos->findBy([], null, 1, 1); - $this->assertEquals(4, count($repos->findBy([]))); - $this->assertEquals(1, count($users1)); - $this->assertEquals(1, count($users2)); - $this->assertNotSame($users1[0], $users2[0]); + self::assertEquals(4, count($repos->findBy([]))); + self::assertEquals(1, count($users1)); + self::assertEquals(1, count($users2)); + self::assertNotSame($users1[0], $users2[0]); } /** @@ -550,14 +552,14 @@ public function testFindByOrderBy() { $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $usersAsc = $repos->findBy([], ["username" => "ASC"]); $usersDesc = $repos->findBy([], ["username" => "DESC"]); - $this->assertEquals(4, count($usersAsc), "Pre-condition: only four users in fixture"); - $this->assertEquals(4, count($usersDesc), "Pre-condition: only four users in fixture"); - $this->assertSame($usersAsc[0], $usersDesc[3]); - $this->assertSame($usersAsc[3], $usersDesc[0]); + self::assertEquals(4, count($usersAsc), "Pre-condition: only four users in fixture"); + self::assertEquals(4, count($usersDesc), "Pre-condition: only four users in fixture"); + self::assertSame($usersAsc[0], $usersDesc[3]); + self::assertSame($usersAsc[3], $usersDesc[0]); } /** @@ -567,15 +569,15 @@ public function testFindByOrderByAssociation() { $this->loadFixtureUserEmail(); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $resultAsc = $repository->findBy([], ['email' => 'ASC']); $resultDesc = $repository->findBy([], ['email' => 'DESC']); - $this->assertCount(3, $resultAsc); - $this->assertCount(3, $resultDesc); + self::assertCount(3, $resultAsc); + self::assertCount(3, $resultDesc); - $this->assertEquals($resultAsc[0]->getEmail()->getId(), $resultDesc[2]->getEmail()->getId()); - $this->assertEquals($resultAsc[2]->getEmail()->getId(), $resultDesc[0]->getEmail()->getId()); + self::assertEquals($resultAsc[0]->getEmail()->getId(), $resultDesc[2]->getEmail()->getId()); + self::assertEquals($resultAsc[2]->getEmail()->getId(), $resultDesc[0]->getEmail()->getId()); } /** @@ -584,20 +586,20 @@ public function testFindByOrderByAssociation() public function testFindFieldByMagicCallOrderBy() { $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $usersAsc = $repos->findByStatus('dev', ['username' => "ASC"]); $usersDesc = $repos->findByStatus('dev', ['username' => "DESC"]); - $this->assertEquals(2, count($usersAsc)); - $this->assertEquals(2, count($usersDesc)); + self::assertEquals(2, count($usersAsc)); + self::assertEquals(2, count($usersDesc)); - $this->assertInstanceOf(CmsUser::class,$usersAsc[0]); - $this->assertEquals('Alexander', $usersAsc[0]->name); - $this->assertEquals('dev', $usersAsc[0]->status); + self::assertInstanceOf(CmsUser::class,$usersAsc[0]); + self::assertEquals('Alexander', $usersAsc[0]->name); + self::assertEquals('dev', $usersAsc[0]->status); - $this->assertSame($usersAsc[0], $usersDesc[1]); - $this->assertSame($usersAsc[1], $usersDesc[0]); + self::assertSame($usersAsc[0], $usersDesc[1]); + self::assertSame($usersAsc[1], $usersDesc[0]); } /** @@ -606,14 +608,14 @@ public function testFindFieldByMagicCallOrderBy() public function testFindFieldByMagicCallLimitOffset() { $this->loadFixture(); - $repos = $this->_em->getRepository(CmsUser::class); + $repos = $this->em->getRepository(CmsUser::class); $users1 = $repos->findByStatus('dev', [], 1, 0); $users2 = $repos->findByStatus('dev', [], 1, 1); - $this->assertEquals(1, count($users1)); - $this->assertEquals(1, count($users2)); - $this->assertNotSame($users1[0], $users2[0]); + self::assertEquals(1, count($users1)); + self::assertEquals(1, count($users2)); + self::assertNotSame($users1[0], $users2[0]); } /** @@ -621,22 +623,22 @@ public function testFindFieldByMagicCallLimitOffset() */ public function testDefaultRepositoryClassName() { - $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), EntityRepository::class); - $this->_em->getConfiguration()->setDefaultRepositoryClassName(DDC753DefaultRepository::class); - $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), DDC753DefaultRepository::class); + self::assertEquals($this->em->getConfiguration()->getDefaultRepositoryClassName(), EntityRepository::class); + $this->em->getConfiguration()->setDefaultRepositoryClassName(DDC753DefaultRepository::class); + self::assertEquals($this->em->getConfiguration()->getDefaultRepositoryClassName(), DDC753DefaultRepository::class); - $repos = $this->_em->getRepository(DDC753EntityWithDefaultCustomRepository::class); - $this->assertInstanceOf(DDC753DefaultRepository::class, $repos); - $this->assertTrue($repos->isDefaultRepository()); + $repos = $this->em->getRepository(DDC753EntityWithDefaultCustomRepository::class); + self::assertInstanceOf(DDC753DefaultRepository::class, $repos); + self::assertTrue($repos->isDefaultRepository()); - $repos = $this->_em->getRepository(DDC753EntityWithCustomRepository::class); - $this->assertInstanceOf(DDC753CustomRepository::class, $repos); - $this->assertTrue($repos->isCustomRepository()); + $repos = $this->em->getRepository(DDC753EntityWithCustomRepository::class); + self::assertInstanceOf(DDC753CustomRepository::class, $repos); + self::assertTrue($repos->isCustomRepository()); - $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), DDC753DefaultRepository::class); - $this->_em->getConfiguration()->setDefaultRepositoryClassName(EntityRepository::class); - $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), EntityRepository::class); + self::assertEquals($this->em->getConfiguration()->getDefaultRepositoryClassName(), DDC753DefaultRepository::class); + $this->em->getConfiguration()->setDefaultRepositoryClassName(EntityRepository::class); + self::assertEquals($this->em->getConfiguration()->getDefaultRepositoryClassName(), EntityRepository::class); } @@ -647,8 +649,8 @@ public function testDefaultRepositoryClassName() */ public function testSetDefaultRepositoryInvalidClassError() { - $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), EntityRepository::class); - $this->_em->getConfiguration()->setDefaultRepositoryClassName(DDC753InvalidRepository::class); + self::assertEquals($this->em->getConfiguration()->getDefaultRepositoryClassName(), EntityRepository::class); + $this->em->getConfiguration()->setDefaultRepositoryClassName(DDC753InvalidRepository::class); } /** @@ -656,15 +658,15 @@ public function testSetDefaultRepositoryInvalidClassError() */ public function testSingleRepositoryInstanceForDifferentEntityAliases() { - $config = $this->_em->getConfiguration(); + $config = $this->em->getConfiguration(); $config->addEntityNamespace('Aliased', 'Doctrine\Tests\Models\CMS'); $config->addEntityNamespace('AliasedAgain', 'Doctrine\Tests\Models\CMS'); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); - $this->assertSame($repository, $this->_em->getRepository('Aliased:CmsUser')); - $this->assertSame($repository, $this->_em->getRepository('AliasedAgain:CmsUser')); + self::assertSame($repository, $this->em->getRepository('Aliased:CmsUser')); + self::assertSame($repository, $this->em->getRepository('AliasedAgain:CmsUser')); } /** @@ -672,9 +674,9 @@ public function testSingleRepositoryInstanceForDifferentEntityAliases() */ public function testCanRetrieveRepositoryFromClassNameWithLeadingBackslash() { - $this->assertSame( - $this->_em->getRepository('\\' . CmsUser::class), - $this->_em->getRepository(CmsUser::class) + self::assertSame( + $this->em->getRepository('\\' . CmsUser::class), + $this->em->getRepository(CmsUser::class) ); } @@ -686,7 +688,7 @@ public function testCanRetrieveRepositoryFromClassNameWithLeadingBackslash() */ public function testInvalidOrderByAssociation() { - $this->_em->getRepository(CmsUser::class) + $this->em->getRepository(CmsUser::class) ->findBy(['status' => 'test'], ['address' => 'ASC']); } @@ -698,7 +700,7 @@ public function testInvalidOrientation() $this->expectException(ORMException::class); $this->expectExceptionMessage('Invalid order by orientation specified for Doctrine\Tests\Models\CMS\CmsUser#username'); - $repo = $this->_em->getRepository(CmsUser::class); + $repo = $this->em->getRepository(CmsUser::class); $repo->findBy(['status' => 'test'], ['username' => 'INVALID']); } @@ -707,12 +709,12 @@ public function testInvalidOrientation() */ public function testFindByAssociationArray() { - $repo = $this->_em->getRepository(CmsAddress::class); + $repo = $this->em->getRepository(CmsAddress::class); $data = $repo->findBy(['user' => [1, 2, 3]]); - $query = array_pop($this->_sqlLoggerStack->queries); - $this->assertEquals([1,2,3], $query['params'][0]); - $this->assertEquals(Connection::PARAM_INT_ARRAY, $query['types'][0]); + $query = array_pop($this->sqlLoggerStack->queries); + self::assertEquals([1,2,3], $query['params'][0]); + self::assertEquals(Connection::PARAM_INT_ARRAY, $query['types'][0]); } /** @@ -722,10 +724,10 @@ public function testMatchingEmptyCriteria() { $this->loadFixture(); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria()); - $this->assertEquals(4, count($users)); + self::assertEquals(4, count($users)); } /** @@ -735,12 +737,12 @@ public function testMatchingCriteriaEqComparison() { $this->loadFixture(); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria( Criteria::expr()->eq('username', 'beberlei') )); - $this->assertEquals(1, count($users)); + self::assertEquals(1, count($users)); } /** @@ -750,12 +752,12 @@ public function testMatchingCriteriaNeqComparison() { $this->loadFixture(); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria( Criteria::expr()->neq('username', 'beberlei') )); - $this->assertEquals(3, count($users)); + self::assertEquals(3, count($users)); } /** @@ -765,12 +767,12 @@ public function testMatchingCriteriaInComparison() { $this->loadFixture(); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria( Criteria::expr()->in('username', ['beberlei', 'gblanco']) )); - $this->assertEquals(2, count($users)); + self::assertEquals(2, count($users)); } /** @@ -780,12 +782,12 @@ public function testMatchingCriteriaNotInComparison() { $this->loadFixture(); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria( Criteria::expr()->notIn('username', ['beberlei', 'gblanco', 'asm89']) )); - $this->assertEquals(1, count($users)); + self::assertEquals(1, count($users)); } /** @@ -795,12 +797,12 @@ public function testMatchingCriteriaLtComparison() { $firstUserId = $this->loadFixture(); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria( Criteria::expr()->lt('id', $firstUserId + 1) )); - $this->assertEquals(1, count($users)); + self::assertEquals(1, count($users)); } /** @@ -810,12 +812,12 @@ public function testMatchingCriteriaLeComparison() { $firstUserId = $this->loadFixture(); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria( Criteria::expr()->lte('id', $firstUserId + 1) )); - $this->assertEquals(2, count($users)); + self::assertEquals(2, count($users)); } /** @@ -825,12 +827,12 @@ public function testMatchingCriteriaGtComparison() { $firstUserId = $this->loadFixture(); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria( Criteria::expr()->gt('id', $firstUserId) )); - $this->assertEquals(3, count($users)); + self::assertEquals(3, count($users)); } /** @@ -840,12 +842,12 @@ public function testMatchingCriteriaGteComparison() { $firstUserId = $this->loadFixture(); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria( Criteria::expr()->gte('id', $firstUserId) )); - $this->assertEquals(4, count($users)); + self::assertEquals(4, count($users)); } /** @@ -855,20 +857,20 @@ public function testMatchingCriteriaAssocationByObjectInMemory() { list($userId, $addressId) = $this->loadAssociatedFixture(); - $user = $this->_em->find(CmsUser::class, $userId); + $user = $this->em->find(CmsUser::class, $userId); $criteria = new Criteria( Criteria::expr()->eq('user', $user) ); - $repository = $this->_em->getRepository(CmsAddress::class); + $repository = $this->em->getRepository(CmsAddress::class); $addresses = $repository->matching($criteria); - $this->assertEquals(1, count($addresses)); + self::assertEquals(1, count($addresses)); $addresses = new ArrayCollection($repository->findAll()); - $this->assertEquals(1, count($addresses->matching($criteria))); + self::assertEquals(1, count($addresses->matching($criteria))); } /** @@ -878,68 +880,68 @@ public function testMatchingCriteriaAssocationInWithArray() { list($userId, $addressId) = $this->loadAssociatedFixture(); - $user = $this->_em->find(CmsUser::class, $userId); + $user = $this->em->find(CmsUser::class, $userId); $criteria = new Criteria( Criteria::expr()->in('user', [$user]) ); - $repository = $this->_em->getRepository(CmsAddress::class); + $repository = $this->em->getRepository(CmsAddress::class); $addresses = $repository->matching($criteria); - $this->assertEquals(1, count($addresses)); + self::assertEquals(1, count($addresses)); $addresses = new ArrayCollection($repository->findAll()); - $this->assertEquals(1, count($addresses->matching($criteria))); + self::assertEquals(1, count($addresses->matching($criteria))); } public function testMatchingCriteriaContainsComparison() { $this->loadFixture(); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria(Criteria::expr()->contains('name', 'Foobar'))); - $this->assertEquals(0, count($users)); + self::assertEquals(0, count($users)); $users = $repository->matching(new Criteria(Criteria::expr()->contains('name', 'Rom'))); - $this->assertEquals(1, count($users)); + self::assertEquals(1, count($users)); $users = $repository->matching(new Criteria(Criteria::expr()->contains('status', 'dev'))); - $this->assertEquals(2, count($users)); + self::assertEquals(2, count($users)); } public function testMatchingCriteriaStartsWithComparison() { $this->loadFixture(); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria(Criteria::expr()->startsWith('name', 'Foo'))); - $this->assertCount(0, $users); + self::assertCount(0, $users); $users = $repository->matching(new Criteria(Criteria::expr()->startsWith('name', 'R'))); - $this->assertCount(1, $users); + self::assertCount(1, $users); $users = $repository->matching(new Criteria(Criteria::expr()->startsWith('status', 'de'))); - $this->assertCount(2, $users); + self::assertCount(2, $users); } public function testMatchingCriteriaEndsWithComparison() { $this->loadFixture(); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria(Criteria::expr()->endsWith('name', 'foo'))); - $this->assertCount(0, $users); + self::assertCount(0, $users); $users = $repository->matching(new Criteria(Criteria::expr()->endsWith('name', 'oman'))); - $this->assertCount(1, $users); + self::assertCount(1, $users); $users = $repository->matching(new Criteria(Criteria::expr()->endsWith('status', 'ev'))); - $this->assertCount(2, $users); + self::assertCount(2, $users); } /** @@ -948,27 +950,26 @@ public function testMatchingCriteriaEndsWithComparison() public function testMatchingCriteriaNullAssocComparison() { $fixtures = $this->loadFixtureUserEmail(); - $user = $this->_em->merge($fixtures[0]); - $repository = $this->_em->getRepository(CmsUser::class); + $user = $this->em->find(get_class($fixtures[0]), $fixtures[0]->id); + $repository = $this->em->getRepository(CmsUser::class); $criteriaIsNull = Criteria::create()->where(Criteria::expr()->isNull('email')); $criteriaEqNull = Criteria::create()->where(Criteria::expr()->eq('email', null)); $user->setEmail(null); - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $usersIsNull = $repository->matching($criteriaIsNull); $usersEqNull = $repository->matching($criteriaEqNull); - $this->assertCount(1, $usersIsNull); - $this->assertCount(1, $usersEqNull); + self::assertCount(1, $usersIsNull); + self::assertCount(1, $usersEqNull); - $this->assertInstanceOf(CmsUser::class, $usersIsNull[0]); - $this->assertInstanceOf(CmsUser::class, $usersEqNull[0]); + self::assertInstanceOf(CmsUser::class, $usersIsNull[0]); + self::assertInstanceOf(CmsUser::class, $usersEqNull[0]); - $this->assertNull($usersIsNull[0]->getEmail()); - $this->assertNull($usersEqNull[0]->getEmail()); + self::assertNull($usersIsNull[0]->getEmail()); + self::assertNull($usersEqNull[0]->getEmail()); } /** @@ -976,11 +977,11 @@ public function testMatchingCriteriaNullAssocComparison() */ public function testCreateResultSetMappingBuilder() { - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $rsm = $repository->createResultSetMappingBuilder('u'); - $this->assertInstanceOf(Query\ResultSetMappingBuilder::class, $rsm); - $this->assertEquals(['u' => CmsUser::class], $rsm->aliasMap); + self::assertInstanceOf(Query\ResultSetMappingBuilder::class, $rsm); + self::assertEquals(['u' => CmsUser::class], $rsm->aliasMap); } /** @@ -991,7 +992,7 @@ public function testFindByFieldInjectionPrevented() $this->expectException(ORMException::class); $this->expectExceptionMessage('Unrecognized field: '); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $repository->findBy(['username = ?; DELETE FROM cms_users; SELECT 1 WHERE 1' => 'test']); } @@ -1003,7 +1004,7 @@ public function testFindOneByFieldInjectionPrevented() $this->expectException(ORMException::class); $this->expectExceptionMessage('Unrecognized field: '); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $repository->findOneBy(['username = ?; DELETE FROM cms_users; SELECT 1 WHERE 1' => 'test']); } @@ -1015,7 +1016,7 @@ public function testMatchingInjectionPrevented() $this->expectException(ORMException::class); $this->expectExceptionMessage('Unrecognized field: '); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $result = $repository->matching(new Criteria( Criteria::expr()->eq('username = ?; DELETE FROM cms_users; SELECT 1 WHERE 1', 'beberlei') )); @@ -1032,7 +1033,7 @@ public function testFindInjectionPrevented() $this->expectException(ORMException::class); $this->expectExceptionMessage('Unrecognized identifier fields: '); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $repository->find(['username = ?; DELETE FROM cms_users; SELECT 1 WHERE 1' => 'test', 'id' => 1]); } @@ -1051,14 +1052,14 @@ public function testFindByNullValueInInCondition() $user2->name = 'Steve'; $user2->status = 'dbal maintainer'; - $this->_em->persist($user1); - $this->_em->persist($user2); - $this->_em->flush(); + $this->em->persist($user1); + $this->em->persist($user2); + $this->em->flush(); - $users = $this->_em->getRepository(CmsUser::class)->findBy(['status' => [null]]); + $users = $this->em->getRepository(CmsUser::class)->findBy(['status' => [null]]); - $this->assertCount(1, $users); - $this->assertSame($user1, reset($users)); + self::assertCount(1, $users); + self::assertSame($user1, reset($users)); } /** @@ -1076,17 +1077,17 @@ public function testFindByNullValueInMultipleInCriteriaValues() $user2->name = 'Steve'; $user2->status = 'dbal maintainer'; - $this->_em->persist($user1); - $this->_em->persist($user2); - $this->_em->flush(); + $this->em->persist($user1); + $this->em->persist($user2); + $this->em->flush(); $users = $this - ->_em + ->em ->getRepository(CmsUser::class) ->findBy(['status' => ['foo', null]]); - $this->assertCount(1, $users); - $this->assertSame($user1, reset($users)); + self::assertCount(1, $users); + self::assertSame($user1, reset($users)); } /** @@ -1104,19 +1105,19 @@ public function testFindMultipleByNullValueInMultipleInCriteriaValues() $user2->name = 'Steve'; $user2->status = 'dbal maintainer'; - $this->_em->persist($user1); - $this->_em->persist($user2); - $this->_em->flush(); + $this->em->persist($user1); + $this->em->persist($user2); + $this->em->flush(); $users = $this - ->_em + ->em ->getRepository(CmsUser::class) ->findBy(['status' => ['dbal maintainer', null]]); - $this->assertCount(2, $users); + self::assertCount(2, $users); foreach ($users as $user) { - $this->assertTrue(in_array($user, [$user1, $user2])); + self::assertTrue(in_array($user, [$user1, $user2])); } } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ExtraLazyCollectionTest.php b/tests/Doctrine/Tests/ORM/Functional/ExtraLazyCollectionTest.php index e7f4fd29803..23e4cc48f7a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ExtraLazyCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ExtraLazyCollectionTest.php @@ -1,8 +1,11 @@ useModelSet('ddc2504'); parent::setUp(); - $class = $this->_em->getClassMetadata(CmsUser::class); - $class->associationMappings['groups']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; - $class->associationMappings['groups']['indexBy'] = 'name'; - $class->associationMappings['articles']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; - $class->associationMappings['articles']['indexBy'] = 'topic'; - $class->associationMappings['phonenumbers']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; - $class->associationMappings['phonenumbers']['indexBy'] = 'phonenumber'; + $class = $this->em->getClassMetadata(CmsUser::class); + + $class->getProperty('groups')->setFetchMode(FetchMode::EXTRA_LAZY); + $class->getProperty('articles')->setFetchMode(FetchMode::EXTRA_LAZY); + $class->getProperty('phonenumbers')->setFetchMode(FetchMode::EXTRA_LAZY); + + $class->getProperty('groups')->setIndexedBy('name'); + $class->getProperty('articles')->setIndexedBy('topic'); + $class->getProperty('phonenumbers')->setIndexedBy('phonenumber'); + + $class->getProperty('groups')->setCache(null); + $class->getProperty('articles')->setCache(null); + $class->getProperty('phonenumbers')->setCache(null); - unset($class->associationMappings['phonenumbers']['cache']); - unset($class->associationMappings['articles']['cache']); - unset($class->associationMappings['users']['cache']); + $class = $this->em->getClassMetadata(CmsGroup::class); - $class = $this->_em->getClassMetadata(CmsGroup::class); - $class->associationMappings['users']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; - $class->associationMappings['users']['indexBy'] = 'username'; + $class->getProperty('users')->setFetchMode(FetchMode::EXTRA_LAZY); + + $class->getProperty('users')->setIndexedBy('username'); $this->loadFixture(); } @@ -63,19 +70,21 @@ public function tearDown() { parent::tearDown(); - $class = $this->_em->getClassMetadata(CmsUser::class); - $class->associationMappings['groups']['fetch'] = ClassMetadataInfo::FETCH_LAZY; - $class->associationMappings['articles']['fetch'] = ClassMetadataInfo::FETCH_LAZY; - $class->associationMappings['phonenumbers']['fetch'] = ClassMetadataInfo::FETCH_LAZY; + $class = $this->em->getClassMetadata(CmsUser::class); + + $class->getProperty('groups')->setFetchMode(FetchMode::LAZY); + $class->getProperty('articles')->setFetchMode(FetchMode::LAZY); + $class->getProperty('phonenumbers')->setFetchMode(FetchMode::LAZY); + + $class->getProperty('groups')->setIndexedBy(null); + $class->getProperty('articles')->setIndexedBy(null); + $class->getProperty('phonenumbers')->setIndexedBy(null); - unset($class->associationMappings['groups']['indexBy']); - unset($class->associationMappings['articles']['indexBy']); - unset($class->associationMappings['phonenumbers']['indexBy']); + $class = $this->em->getClassMetadata(CmsGroup::class); - $class = $this->_em->getClassMetadata(CmsGroup::class); - $class->associationMappings['users']['fetch'] = ClassMetadataInfo::FETCH_LAZY; + $class->getProperty('users')->setFetchMode(FetchMode::LAZY); - unset($class->associationMappings['users']['indexBy']); + $class->getProperty('users')->setIndexedBy(null); } /** @@ -84,16 +93,16 @@ public function tearDown() */ public function testCountNotInitializesCollection() { - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); - $this->assertFalse($user->groups->isInitialized()); - $this->assertEquals(3, count($user->groups)); - $this->assertFalse($user->groups->isInitialized()); + self::assertFalse($user->groups->isInitialized()); + self::assertEquals(3, count($user->groups)); + self::assertFalse($user->groups->isInitialized()); foreach ($user->groups AS $group) { } - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount(), "Expecting two queries to be fired for count, then iteration."); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount(), "Expecting two queries to be fired for count, then iteration."); } /** @@ -101,17 +110,17 @@ public function testCountNotInitializesCollection() */ public function testCountWhenNewEntityPresent() { - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); $newGroup = new CmsGroup(); $newGroup->name = "Test4"; $user->addGroup($newGroup); - $this->_em->persist($newGroup); + $this->em->persist($newGroup); - $this->assertFalse($user->groups->isInitialized()); - $this->assertEquals(4, count($user->groups)); - $this->assertFalse($user->groups->isInitialized()); + self::assertFalse($user->groups->isInitialized()); + self::assertEquals(4, count($user->groups)); + self::assertFalse($user->groups->isInitialized()); } /** @@ -120,14 +129,14 @@ public function testCountWhenNewEntityPresent() */ public function testCountWhenInitialized() { - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); foreach ($user->groups AS $group) { } - $this->assertTrue($user->groups->isInitialized()); - $this->assertEquals(3, count($user->groups)); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Should only execute one query to initialize collection, no extra query for count() more."); + self::assertTrue($user->groups->isInitialized()); + self::assertEquals(3, count($user->groups)); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Should only execute one query to initialize collection, no extra query for count() more."); } /** @@ -135,11 +144,11 @@ public function testCountWhenInitialized() */ public function testCountInverseCollection() { - $group = $this->_em->find(CmsGroup::class, $this->groupId); - $this->assertFalse($group->users->isInitialized(), "Pre-Condition"); + $group = $this->em->find(CmsGroup::class, $this->groupId); + self::assertFalse($group->users->isInitialized(), "Pre-Condition"); - $this->assertEquals(4, count($group->users)); - $this->assertFalse($group->users->isInitialized(), "Extra Lazy collection should not be initialized by counting the collection."); + self::assertEquals(4, count($group->users)); + self::assertFalse($group->users->isInitialized(), "Extra Lazy collection should not be initialized by counting the collection."); } /** @@ -147,10 +156,10 @@ public function testCountInverseCollection() */ public function testCountOneToMany() { - $user = $this->_em->find(CmsUser::class, $this->userId); - $this->assertFalse($user->groups->isInitialized(), "Pre-Condition"); + $user = $this->em->find(CmsUser::class, $this->userId); + self::assertFalse($user->groups->isInitialized(), "Pre-Condition"); - $this->assertEquals(2, count($user->articles)); + self::assertEquals(2, count($user->articles)); } /** @@ -158,10 +167,10 @@ public function testCountOneToMany() */ public function testCountOneToManyJoinedInheritance() { - $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); + $otherClass = $this->em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); - $this->assertFalse($otherClass->childClasses->isInitialized(), "Pre-Condition"); - $this->assertEquals(2, count($otherClass->childClasses)); + self::assertFalse($otherClass->childClasses->isInitialized(), "Pre-Condition"); + self::assertEquals(2, count($otherClass->childClasses)); } /** @@ -169,11 +178,11 @@ public function testCountOneToManyJoinedInheritance() */ public function testFullSlice() { - $user = $this->_em->find(CmsUser::class, $this->userId); - $this->assertFalse($user->groups->isInitialized(), "Pre-Condition: Collection is not initialized."); + $user = $this->em->find(CmsUser::class, $this->userId); + self::assertFalse($user->groups->isInitialized(), "Pre-Condition: Collection is not initialized."); $someGroups = $user->groups->slice(null); - $this->assertEquals(3, count($someGroups)); + self::assertEquals(3, count($someGroups)); } /** @@ -182,29 +191,29 @@ public function testFullSlice() */ public function testSlice() { - $user = $this->_em->find(CmsUser::class, $this->userId); - $this->assertFalse($user->groups->isInitialized(), "Pre-Condition: Collection is not initialized."); + $user = $this->em->find(CmsUser::class, $this->userId); + self::assertFalse($user->groups->isInitialized(), "Pre-Condition: Collection is not initialized."); $queryCount = $this->getCurrentQueryCount(); $someGroups = $user->groups->slice(0, 2); - $this->assertContainsOnly(CmsGroup::class, $someGroups); - $this->assertEquals(2, count($someGroups)); - $this->assertFalse($user->groups->isInitialized(), "Slice should not initialize the collection if it wasn't before!"); + self::assertContainsOnly(CmsGroup::class, $someGroups); + self::assertEquals(2, count($someGroups)); + self::assertFalse($user->groups->isInitialized(), "Slice should not initialize the collection if it wasn't before!"); $otherGroup = $user->groups->slice(2, 1); - $this->assertContainsOnly(CmsGroup::class, $otherGroup); - $this->assertEquals(1, count($otherGroup)); - $this->assertFalse($user->groups->isInitialized()); + self::assertContainsOnly(CmsGroup::class, $otherGroup); + self::assertEquals(1, count($otherGroup)); + self::assertFalse($user->groups->isInitialized()); foreach ($user->groups AS $group) { } - $this->assertTrue($user->groups->isInitialized()); - $this->assertEquals(3, count($user->groups)); + self::assertTrue($user->groups->isInitialized()); + self::assertEquals(3, count($user->groups)); - $this->assertEquals($queryCount + 3, $this->getCurrentQueryCount()); + self::assertEquals($queryCount + 3, $this->getCurrentQueryCount()); } /** @@ -213,18 +222,18 @@ public function testSlice() */ public function testSliceInitializedCollection() { - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); foreach ($user->groups AS $group) { } $someGroups = $user->groups->slice(0, 2); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertEquals(2, count($someGroups)); - $this->assertTrue($user->groups->contains(array_shift($someGroups))); - $this->assertTrue($user->groups->contains(array_shift($someGroups))); + self::assertEquals(2, count($someGroups)); + self::assertTrue($user->groups->contains(array_shift($someGroups))); + self::assertTrue($user->groups->contains(array_shift($someGroups))); } /** @@ -232,20 +241,20 @@ public function testSliceInitializedCollection() */ public function testSliceInverseCollection() { - $group = $this->_em->find(CmsGroup::class, $this->groupId); - $this->assertFalse($group->users->isInitialized(), "Pre-Condition"); + $group = $this->em->find(CmsGroup::class, $this->groupId); + self::assertFalse($group->users->isInitialized(), "Pre-Condition"); $queryCount = $this->getCurrentQueryCount(); $someUsers = $group->users->slice(0, 2); $otherUsers = $group->users->slice(2, 2); - $this->assertContainsOnly(CmsUser::class, $someUsers); - $this->assertContainsOnly(CmsUser::class, $otherUsers); - $this->assertEquals(2, count($someUsers)); - $this->assertEquals(2, count($otherUsers)); + self::assertContainsOnly(CmsUser::class, $someUsers); + self::assertContainsOnly(CmsUser::class, $otherUsers); + self::assertEquals(2, count($someUsers)); + self::assertEquals(2, count($otherUsers)); // +2 queries executed by slice - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount(), "Slicing two parts should only execute two additional queries."); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount(), "Slicing two parts should only execute two additional queries."); } /** @@ -253,15 +262,15 @@ public function testSliceInverseCollection() */ public function testSliceOneToMany() { - $user = $this->_em->find(CmsUser::class, $this->userId); - $this->assertFalse($user->articles->isInitialized(), "Pre-Condition: Collection is not initialized."); + $user = $this->em->find(CmsUser::class, $this->userId); + self::assertFalse($user->articles->isInitialized(), "Pre-Condition: Collection is not initialized."); $queryCount = $this->getCurrentQueryCount(); $someArticle = $user->articles->slice(0, 1); $otherArticle = $user->articles->slice(1, 1); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount()); } /** @@ -269,16 +278,16 @@ public function testSliceOneToMany() */ public function testContainsOneToMany() { - $user = $this->_em->find(CmsUser::class, $this->userId); - $this->assertFalse($user->articles->isInitialized(), "Pre-Condition: Collection is not initialized."); + $user = $this->em->find(CmsUser::class, $this->userId); + self::assertFalse($user->articles->isInitialized(), "Pre-Condition: Collection is not initialized."); // Test One to Many existence retrieved from DB - $article = $this->_em->find(CmsArticle::class, $this->articleId); + $article = $this->em->find(CmsArticle::class, $this->articleId); $queryCount = $this->getCurrentQueryCount(); - $this->assertTrue($user->articles->contains($article)); - $this->assertFalse($user->articles->isInitialized(), "Post-Condition: Collection is not initialized."); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertTrue($user->articles->contains($article)); + self::assertFalse($user->articles->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); // Test One to Many existence with state new $article = new CmsArticle(); @@ -286,30 +295,30 @@ public function testContainsOneToMany() $article->text = "blub"; $queryCount = $this->getCurrentQueryCount(); - $this->assertFalse($user->articles->contains($article)); - $this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Checking for contains of new entity should cause no query to be executed."); + self::assertFalse($user->articles->contains($article)); + self::assertEquals($queryCount, $this->getCurrentQueryCount(), "Checking for contains of new entity should cause no query to be executed."); // Test One to Many existence with state clear - $this->_em->persist($article); - $this->_em->flush(); + $this->em->persist($article); + $this->em->flush(); $queryCount = $this->getCurrentQueryCount(); - $this->assertFalse($user->articles->contains($article)); - $this->assertEquals($queryCount+1, $this->getCurrentQueryCount(), "Checking for contains of persisted entity should cause one query to be executed."); - $this->assertFalse($user->articles->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertFalse($user->articles->contains($article)); + self::assertEquals($queryCount+1, $this->getCurrentQueryCount(), "Checking for contains of persisted entity should cause one query to be executed."); + self::assertFalse($user->articles->isInitialized(), "Post-Condition: Collection is not initialized."); // Test One to Many existence with state managed $article = new CmsArticle(); $article->topic = "How to not fail anymore on tests"; $article->text = "That is simple! Just write more tests!"; - $this->_em->persist($article); + $this->em->persist($article); $queryCount = $this->getCurrentQueryCount(); - $this->assertFalse($user->articles->contains($article)); - $this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Checking for contains of managed entity (but not persisted) should cause no query to be executed."); - $this->assertFalse($user->articles->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertFalse($user->articles->contains($article)); + self::assertEquals($queryCount, $this->getCurrentQueryCount(), "Checking for contains of managed entity (but not persisted) should cause no query to be executed."); + self::assertFalse($user->articles->isInitialized(), "Post-Condition: Collection is not initialized."); } /** @@ -317,9 +326,9 @@ public function testContainsOneToMany() */ public function testLazyOneToManyJoinedInheritanceIsLazilyInitialized() { - $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); + $otherClass = $this->em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); - $this->assertFalse($otherClass->childClasses->isInitialized(), 'Collection is not initialized.'); + self::assertFalse($otherClass->childClasses->isInitialized(), 'Collection is not initialized.'); } /** @@ -327,15 +336,15 @@ public function testLazyOneToManyJoinedInheritanceIsLazilyInitialized() */ public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollectionWhenMatchingItemIsFound() { - $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); + $otherClass = $this->em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); // Test One to Many existence retrieved from DB - $childClass = $this->_em->find(DDC2504ChildClass::class, $this->ddc2504ChildClassId); + $childClass = $this->em->find(DDC2504ChildClass::class, $this->ddc2504ChildClassId); $queryCount = $this->getCurrentQueryCount(); - $this->assertTrue($otherClass->childClasses->contains($childClass)); - $this->assertFalse($otherClass->childClasses->isInitialized(), 'Collection is not initialized.'); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), 'Search operation was performed via SQL'); + self::assertTrue($otherClass->childClasses->contains($childClass)); + self::assertFalse($otherClass->childClasses->isInitialized(), 'Collection is not initialized.'); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount(), 'Search operation was performed via SQL'); } /** @@ -343,11 +352,11 @@ public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollect */ public function testContainsOnOneToManyJoinedInheritanceWillNotCauseQueriesWhenNonPersistentItemIsMatched() { - $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); + $otherClass = $this->em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $queryCount = $this->getCurrentQueryCount(); - $this->assertFalse($otherClass->childClasses->contains(new DDC2504ChildClass())); - $this->assertEquals( + self::assertFalse($otherClass->childClasses->contains(new DDC2504ChildClass())); + self::assertEquals( $queryCount, $this->getCurrentQueryCount(), 'Checking for contains of new entity should cause no query to be executed.' @@ -359,17 +368,17 @@ public function testContainsOnOneToManyJoinedInheritanceWillNotCauseQueriesWhenN */ public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollectionWithClearStateMatchingItem() { - $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); + $otherClass = $this->em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $childClass = new DDC2504ChildClass(); // Test One to Many existence with state clear - $this->_em->persist($childClass); - $this->_em->flush(); + $this->em->persist($childClass); + $this->em->flush(); $queryCount = $this->getCurrentQueryCount(); - $this->assertFalse($otherClass->childClasses->contains($childClass)); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Checking for contains of persisted entity should cause one query to be executed."); - $this->assertFalse($otherClass->childClasses->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertFalse($otherClass->childClasses->contains($childClass)); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Checking for contains of persisted entity should cause one query to be executed."); + self::assertFalse($otherClass->childClasses->isInitialized(), "Post-Condition: Collection is not initialized."); } /** @@ -377,16 +386,16 @@ public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollect */ public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollectionWithNewStateNotMatchingItem() { - $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); + $otherClass = $this->em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $childClass = new DDC2504ChildClass(); - $this->_em->persist($childClass); + $this->em->persist($childClass); $queryCount = $this->getCurrentQueryCount(); - $this->assertFalse($otherClass->childClasses->contains($childClass)); - $this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Checking for contains of managed entity (but not persisted) should cause no query to be executed."); - $this->assertFalse($otherClass->childClasses->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertFalse($otherClass->childClasses->contains($childClass)); + self::assertEquals($queryCount, $this->getCurrentQueryCount(), "Checking for contains of managed entity (but not persisted) should cause no query to be executed."); + self::assertFalse($otherClass->childClasses->isInitialized(), "Post-Condition: Collection is not initialized."); } /** @@ -394,11 +403,11 @@ public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollect */ public function testCountingOnOneToManyJoinedInheritanceWillNotInitializeCollection() { - $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); + $otherClass = $this->em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); - $this->assertEquals(2, count($otherClass->childClasses)); + self::assertEquals(2, count($otherClass->childClasses)); - $this->assertFalse($otherClass->childClasses->isInitialized()); + self::assertFalse($otherClass->childClasses->isInitialized()); } /** @@ -406,16 +415,16 @@ public function testCountingOnOneToManyJoinedInheritanceWillNotInitializeCollect */ public function testContainsManyToMany() { - $user = $this->_em->find(CmsUser::class, $this->userId); - $this->assertFalse($user->groups->isInitialized(), "Pre-Condition: Collection is not initialized."); + $user = $this->em->find(CmsUser::class, $this->userId); + self::assertFalse($user->groups->isInitialized(), "Pre-Condition: Collection is not initialized."); // Test Many to Many existence retrieved from DB - $group = $this->_em->find(CmsGroup::class, $this->groupId); + $group = $this->em->find(CmsGroup::class, $this->groupId); $queryCount = $this->getCurrentQueryCount(); - $this->assertTrue($user->groups->contains($group)); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Checking for contains of managed entity should cause one query to be executed."); - $this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertTrue($user->groups->contains($group)); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Checking for contains of managed entity should cause one query to be executed."); + self::assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); // Test Many to Many existence with state new $group = new CmsGroup(); @@ -423,31 +432,31 @@ public function testContainsManyToMany() $queryCount = $this->getCurrentQueryCount(); - $this->assertFalse($user->groups->contains($group)); - $this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Checking for contains of new entity should cause no query to be executed."); - $this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertFalse($user->groups->contains($group)); + self::assertEquals($queryCount, $this->getCurrentQueryCount(), "Checking for contains of new entity should cause no query to be executed."); + self::assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); // Test Many to Many existence with state clear - $this->_em->persist($group); - $this->_em->flush(); + $this->em->persist($group); + $this->em->flush(); $queryCount = $this->getCurrentQueryCount(); - $this->assertFalse($user->groups->contains($group)); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Checking for contains of persisted entity should cause one query to be executed."); - $this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertFalse($user->groups->contains($group)); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Checking for contains of persisted entity should cause one query to be executed."); + self::assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); // Test Many to Many existence with state managed $group = new CmsGroup(); $group->name = "My managed group"; - $this->_em->persist($group); + $this->em->persist($group); $queryCount = $this->getCurrentQueryCount(); - $this->assertFalse($user->groups->contains($group)); - $this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Checking for contains of managed entity (but not persisted) should cause no query to be executed."); - $this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertFalse($user->groups->contains($group)); + self::assertEquals($queryCount, $this->getCurrentQueryCount(), "Checking for contains of managed entity (but not persisted) should cause no query to be executed."); + self::assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); } /** @@ -455,23 +464,23 @@ public function testContainsManyToMany() */ public function testContainsManyToManyInverse() { - $group = $this->_em->find(CmsGroup::class, $this->groupId); - $this->assertFalse($group->users->isInitialized(), "Pre-Condition: Collection is not initialized."); + $group = $this->em->find(CmsGroup::class, $this->groupId); + self::assertFalse($group->users->isInitialized(), "Pre-Condition: Collection is not initialized."); - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); - $this->assertTrue($group->users->contains($user)); - $this->assertEquals($queryCount+1, $this->getCurrentQueryCount(), "Checking for contains of managed entity should cause one query to be executed."); - $this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertTrue($group->users->contains($user)); + self::assertEquals($queryCount+1, $this->getCurrentQueryCount(), "Checking for contains of managed entity should cause one query to be executed."); + self::assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); $newUser = new CmsUser(); $newUser->name = "A New group!"; $queryCount = $this->getCurrentQueryCount(); - $this->assertFalse($group->users->contains($newUser)); - $this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Checking for contains of new entity should cause no query to be executed."); - $this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertFalse($group->users->contains($newUser)); + self::assertEquals($queryCount, $this->getCurrentQueryCount(), "Checking for contains of new entity should cause no query to be executed."); + self::assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); } /** @@ -479,17 +488,17 @@ public function testContainsManyToManyInverse() */ public function testRemoveElementOneToMany() { - $user = $this->_em->find(CmsUser::class, $this->userId); - $this->assertFalse($user->articles->isInitialized(), "Pre-Condition: Collection is not initialized."); + $user = $this->em->find(CmsUser::class, $this->userId); + self::assertFalse($user->articles->isInitialized(), "Pre-Condition: Collection is not initialized."); // Test One to Many removal with Entity retrieved from DB - $article = $this->_em->find(CmsArticle::class, $this->articleId); + $article = $this->em->find(CmsArticle::class, $this->articleId); $queryCount = $this->getCurrentQueryCount(); $user->articles->removeElement($article); - $this->assertFalse($user->articles->isInitialized(), "Post-Condition: Collection is not initialized."); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertFalse($user->articles->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); // Test One to Many removal with Entity state as new $article = new CmsArticle(); @@ -500,31 +509,31 @@ public function testRemoveElementOneToMany() $user->articles->removeElement($article); - $this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Removing a new entity should cause no query to be executed."); + self::assertEquals($queryCount, $this->getCurrentQueryCount(), "Removing a new entity should cause no query to be executed."); // Test One to Many removal with Entity state as clean - $this->_em->persist($article); - $this->_em->flush(); + $this->em->persist($article); + $this->em->flush(); $queryCount = $this->getCurrentQueryCount(); $user->articles->removeElement($article); - $this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Removing a persisted entity will not cause queries when the owning side doesn't actually change."); - $this->assertFalse($user->articles->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertEquals($queryCount, $this->getCurrentQueryCount(), "Removing a persisted entity will not cause queries when the owning side doesn't actually change."); + self::assertFalse($user->articles->isInitialized(), "Post-Condition: Collection is not initialized."); // Test One to Many removal with Entity state as managed $article = new CmsArticle(); $article->topic = "How to not fail anymore on tests"; $article->text = "That is simple! Just write more tests!"; - $this->_em->persist($article); + $this->em->persist($article); $queryCount = $this->getCurrentQueryCount(); $user->articles->removeElement($article); - $this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Removing a managed entity should cause no query to be executed."); + self::assertEquals($queryCount, $this->getCurrentQueryCount(), "Removing a managed entity should cause no query to be executed."); } /** @@ -533,36 +542,36 @@ public function testRemoveElementOneToMany() public function testRemovalOfManagedElementFromOneToManyJoinedInheritanceCollectionDoesNotInitializeIt() { /* @var $otherClass DDC2504OtherClass */ - $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); + $otherClass = $this->em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); /* @var $childClass DDC2504ChildClass */ - $childClass = $this->_em->find(DDC2504ChildClass::class, $this->ddc2504ChildClassId); + $childClass = $this->em->find(DDC2504ChildClass::class, $this->ddc2504ChildClassId); $queryCount = $this->getCurrentQueryCount(); $otherClass->childClasses->removeElement($childClass); $childClass->other = null; // updating owning side - $this->assertFalse($otherClass->childClasses->isInitialized(), 'Collection is not initialized.'); + self::assertFalse($otherClass->childClasses->isInitialized(), 'Collection is not initialized.'); - $this->assertEquals( + self::assertEquals( $queryCount, $this->getCurrentQueryCount(), 'No queries have been executed' ); - $this->assertTrue( + self::assertTrue( $otherClass->childClasses->contains($childClass), 'Collection item still not updated (needs flushing)' ); - $this->_em->flush(); + $this->em->flush(); - $this->assertFalse( + self::assertFalse( $otherClass->childClasses->contains($childClass), 'Referenced item was removed in the transaction' ); - $this->assertFalse($otherClass->childClasses->isInitialized(), 'Collection is not initialized.'); + self::assertFalse($otherClass->childClasses->isInitialized(), 'Collection is not initialized.'); } /** @@ -571,12 +580,12 @@ public function testRemovalOfManagedElementFromOneToManyJoinedInheritanceCollect public function testRemovalOfNonManagedElementFromOneToManyJoinedInheritanceCollectionDoesNotInitializeIt() { /* @var $otherClass DDC2504OtherClass */ - $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); + $otherClass = $this->em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $queryCount = $this->getCurrentQueryCount(); $otherClass->childClasses->removeElement(new DDC2504ChildClass()); - $this->assertEquals( + self::assertEquals( $queryCount, $this->getCurrentQueryCount(), 'Removing an unmanaged entity should cause no query to be executed.' @@ -589,16 +598,16 @@ public function testRemovalOfNonManagedElementFromOneToManyJoinedInheritanceColl public function testRemovalOfNewElementFromOneToManyJoinedInheritanceCollectionDoesNotInitializeIt() { /* @var $otherClass DDC2504OtherClass */ - $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); + $otherClass = $this->em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $childClass = new DDC2504ChildClass(); - $this->_em->persist($childClass); + $this->em->persist($childClass); $queryCount = $this->getCurrentQueryCount(); $otherClass->childClasses->removeElement($childClass); - $this->assertEquals( + self::assertEquals( $queryCount, $this->getCurrentQueryCount(), 'Removing a new entity should cause no query to be executed.' @@ -610,22 +619,22 @@ public function testRemovalOfNewElementFromOneToManyJoinedInheritanceCollectionD */ public function testRemovalOfNewManagedElementFromOneToManyJoinedInheritanceCollectionDoesNotInitializeIt() { - $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); + $otherClass = $this->em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $childClass = new DDC2504ChildClass(); - $this->_em->persist($childClass); - $this->_em->flush(); + $this->em->persist($childClass); + $this->em->flush(); $queryCount = $this->getCurrentQueryCount(); $otherClass->childClasses->removeElement($childClass); - $this->assertEquals( + self::assertEquals( $queryCount, $this->getCurrentQueryCount(), 'No queries are executed, as the owning side of the association is not actually updated.' ); - $this->assertFalse($otherClass->childClasses->isInitialized(), 'Collection is not initialized.'); + self::assertFalse($otherClass->childClasses->isInitialized(), 'Collection is not initialized.'); } /** @@ -633,19 +642,19 @@ public function testRemovalOfNewManagedElementFromOneToManyJoinedInheritanceColl */ public function testRemoveElementManyToMany() { - $user = $this->_em->find(CmsUser::class, $this->userId); - $this->assertFalse($user->groups->isInitialized(), "Pre-Condition: Collection is not initialized."); + $user = $this->em->find(CmsUser::class, $this->userId); + self::assertFalse($user->groups->isInitialized(), "Pre-Condition: Collection is not initialized."); // Test Many to Many removal with Entity retrieved from DB - $group = $this->_em->find(CmsGroup::class, $this->groupId); + $group = $this->em->find(CmsGroup::class, $this->groupId); $queryCount = $this->getCurrentQueryCount(); - $this->assertTrue($user->groups->removeElement($group)); + self::assertTrue($user->groups->removeElement($group)); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Removing a persisted entity should cause one query to be executed."); - $this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Removing a persisted entity should cause one query to be executed."); + self::assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); - $this->assertFalse($user->groups->removeElement($group), "Removing an already removed element returns false"); + self::assertFalse($user->groups->removeElement($group), "Removing an already removed element returns false"); // Test Many to Many removal with Entity state as new $group = new CmsGroup(); @@ -655,32 +664,32 @@ public function testRemoveElementManyToMany() $user->groups->removeElement($group); - $this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Removing new entity should cause no query to be executed."); - $this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertEquals($queryCount, $this->getCurrentQueryCount(), "Removing new entity should cause no query to be executed."); + self::assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); // Test Many to Many removal with Entity state as clean - $this->_em->persist($group); - $this->_em->flush(); + $this->em->persist($group); + $this->em->flush(); $queryCount = $this->getCurrentQueryCount(); $user->groups->removeElement($group); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Removing a persisted entity should cause one query to be executed."); - $this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Removing a persisted entity should cause one query to be executed."); + self::assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); // Test Many to Many removal with Entity state as managed $group = new CmsGroup(); $group->name = "A New group!"; - $this->_em->persist($group); + $this->em->persist($group); $queryCount = $this->getCurrentQueryCount(); $user->groups->removeElement($group); - $this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Removing a managed entity should cause no query to be executed."); - $this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertEquals($queryCount, $this->getCurrentQueryCount(), "Removing a managed entity should cause no query to be executed."); + self::assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); } /** @@ -688,16 +697,16 @@ public function testRemoveElementManyToMany() */ public function testRemoveElementManyToManyInverse() { - $group = $this->_em->find(CmsGroup::class, $this->groupId); - $this->assertFalse($group->users->isInitialized(), "Pre-Condition: Collection is not initialized."); + $group = $this->em->find(CmsGroup::class, $this->groupId); + self::assertFalse($group->users->isInitialized(), "Pre-Condition: Collection is not initialized."); - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); $group->users->removeElement($user); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Removing a managed entity should cause one query to be executed."); - $this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Removing a managed entity should cause one query to be executed."); + self::assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); $newUser = new CmsUser(); $newUser->name = "A New group!"; @@ -706,8 +715,8 @@ public function testRemoveElementManyToManyInverse() $group->users->removeElement($newUser); - $this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Removing a new entity should cause no query to be executed."); - $this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); + self::assertEquals($queryCount, $this->getCurrentQueryCount(), "Removing a new entity should cause no query to be executed."); + self::assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); } /** @@ -715,21 +724,21 @@ public function testRemoveElementManyToManyInverse() */ public function testCountAfterAddThenFlush() { - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); $newGroup = new CmsGroup(); $newGroup->name = "Test4"; $user->addGroup($newGroup); - $this->_em->persist($newGroup); + $this->em->persist($newGroup); - $this->assertFalse($user->groups->isInitialized()); - $this->assertEquals(4, count($user->groups)); - $this->assertFalse($user->groups->isInitialized()); + self::assertFalse($user->groups->isInitialized()); + self::assertEquals(4, count($user->groups)); + self::assertFalse($user->groups->isInitialized()); - $this->_em->flush(); + $this->em->flush(); - $this->assertEquals(4, count($user->groups)); + self::assertEquals(4, count($user->groups)); } /** @@ -738,20 +747,20 @@ public function testCountAfterAddThenFlush() */ public function testSliceOnDirtyCollection() { - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); /* @var $user CmsUser */ $newGroup = new CmsGroup(); $newGroup->name = "Test4"; $user->addGroup($newGroup); - $this->_em->persist($newGroup); + $this->em->persist($newGroup); $qc = $this->getCurrentQueryCount(); $groups = $user->groups->slice(0, 10); - $this->assertEquals(4, count($groups)); - $this->assertEquals($qc + 1, $this->getCurrentQueryCount()); + self::assertEquals(4, count($groups)); + self::assertEquals($qc + 1, $this->getCurrentQueryCount()); } /** @@ -760,18 +769,18 @@ public function testSliceOnDirtyCollection() */ public function testGetIndexByIdentifier() { - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); /* @var $user CmsUser */ $queryCount = $this->getCurrentQueryCount(); $phonenumber = $user->phonenumbers->get($this->phonenumber); - $this->assertFalse($user->phonenumbers->isInitialized()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertSame($phonenumber, $this->_em->find(CmsPhonenumber::class, $this->phonenumber)); + self::assertFalse($user->phonenumbers->isInitialized()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertSame($phonenumber, $this->em->find(CmsPhonenumber::class, $this->phonenumber)); $article = $user->phonenumbers->get($this->phonenumber); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Getting the same entity should not cause an extra query to be executed"); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Getting the same entity should not cause an extra query to be executed"); } /** @@ -779,16 +788,16 @@ public function testGetIndexByIdentifier() */ public function testGetIndexByOneToMany() { - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); /* @var $user CmsUser */ $queryCount = $this->getCurrentQueryCount(); $article = $user->articles->get($this->topic); - $this->assertFalse($user->articles->isInitialized()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertSame($article, $this->_em->find(CmsArticle::class, $this->articleId)); + self::assertFalse($user->articles->isInitialized()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertSame($article, $this->em->find(CmsArticle::class, $this->articleId)); } /** @@ -796,16 +805,16 @@ public function testGetIndexByOneToMany() */ public function testGetIndexByManyToManyInverseSide() { - $group = $this->_em->find(CmsGroup::class, $this->groupId); + $group = $this->em->find(CmsGroup::class, $this->groupId); /* @var $group CmsGroup */ $queryCount = $this->getCurrentQueryCount(); $user = $group->users->get($this->username); - $this->assertFalse($group->users->isInitialized()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertSame($user, $this->_em->find(CmsUser::class, $this->userId)); + self::assertFalse($group->users->isInitialized()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertSame($user, $this->em->find(CmsUser::class, $this->userId)); } /** @@ -813,16 +822,16 @@ public function testGetIndexByManyToManyInverseSide() */ public function testGetIndexByManyToManyOwningSide() { - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); /* @var $user CmsUser */ $queryCount = $this->getCurrentQueryCount(); $group = $user->groups->get($this->groupname); - $this->assertFalse($user->groups->isInitialized()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertSame($group, $this->_em->find(CmsGroup::class, $this->groupId)); + self::assertFalse($user->groups->isInitialized()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertSame($group, $this->em->find(CmsGroup::class, $this->groupId)); } /** @@ -830,125 +839,125 @@ public function testGetIndexByManyToManyOwningSide() */ public function testGetNonExistentIndexBy() { - $user = $this->_em->find(CmsUser::class, $this->userId); - $this->assertNull($user->articles->get(-1)); - $this->assertNull($user->groups->get(-1)); + $user = $this->em->find(CmsUser::class, $this->userId); + self::assertNull($user->articles->get(-1)); + self::assertNull($user->groups->get(-1)); } public function testContainsKeyIndexByOneToMany() { - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); /* @var $user CmsUser */ $queryCount = $this->getCurrentQueryCount(); $contains = $user->articles->containsKey($this->topic); - $this->assertTrue($contains); - $this->assertFalse($user->articles->isInitialized()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertTrue($contains); + self::assertFalse($user->articles->isInitialized()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } public function testContainsKeyIndexByOneToManyJoinedInheritance() { - $class = $this->_em->getClassMetadata(DDC2504OtherClass::class); - $class->associationMappings['childClasses']['indexBy'] = 'id'; + $class = $this->em->getClassMetadata(DDC2504OtherClass::class); + $class->getProperty('childClasses')->setIndexedBy('id'); - $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); + $otherClass = $this->em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $queryCount = $this->getCurrentQueryCount(); $contains = $otherClass->childClasses->containsKey($this->ddc2504ChildClassId); - $this->assertTrue($contains); - $this->assertFalse($otherClass->childClasses->isInitialized()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertTrue($contains); + self::assertFalse($otherClass->childClasses->isInitialized()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } public function testContainsKeyIndexByManyToMany() { - $user = $this->_em->find(CmsUser::class, $this->userId2); + $user = $this->em->find(CmsUser::class, $this->userId2); - $group = $this->_em->find(CmsGroup::class, $this->groupId); + $group = $this->em->find(CmsGroup::class, $this->groupId); $queryCount = $this->getCurrentQueryCount(); $contains = $user->groups->containsKey($group->name); - $this->assertTrue($contains, "The item is not into collection"); - $this->assertFalse($user->groups->isInitialized(), "The collection must not be initialized"); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertTrue($contains, "The item is not into collection"); + self::assertFalse($user->groups->isInitialized(), "The collection must not be initialized"); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } public function testContainsKeyIndexByManyToManyNonOwning() { - $user = $this->_em->find(CmsUser::class, $this->userId2); - $group = $this->_em->find(CmsGroup::class, $this->groupId); + $user = $this->em->find(CmsUser::class, $this->userId2); + $group = $this->em->find(CmsGroup::class, $this->groupId); $queryCount = $this->getCurrentQueryCount(); $contains = $group->users->containsKey($user->username); - $this->assertTrue($contains, "The item is not into collection"); - $this->assertFalse($group->users->isInitialized(), "The collection must not be initialized"); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertTrue($contains, "The item is not into collection"); + self::assertFalse($group->users->isInitialized(), "The collection must not be initialized"); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } public function testContainsKeyIndexByWithPkManyToMany() { - $class = $this->_em->getClassMetadata(CmsUser::class); - $class->associationMappings['groups']['indexBy'] = 'id'; + $class = $this->em->getClassMetadata(CmsUser::class); + $class->getProperty('groups')->setIndexedBy('id'); - $user = $this->_em->find(CmsUser::class, $this->userId2); + $user = $this->em->find(CmsUser::class, $this->userId2); $queryCount = $this->getCurrentQueryCount(); $contains = $user->groups->containsKey($this->groupId); - $this->assertTrue($contains, "The item is not into collection"); - $this->assertFalse($user->groups->isInitialized(), "The collection must not be initialized"); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertTrue($contains, "The item is not into collection"); + self::assertFalse($user->groups->isInitialized(), "The collection must not be initialized"); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } public function testContainsKeyIndexByWithPkManyToManyNonOwning() { - $class = $this->_em->getClassMetadata(CmsGroup::class); - $class->associationMappings['users']['indexBy'] = 'id'; + $class = $this->em->getClassMetadata(CmsGroup::class); + $class->getProperty('users')->setIndexedBy('id'); - $group = $this->_em->find(CmsGroup::class, $this->groupId); + $group = $this->em->find(CmsGroup::class, $this->groupId); $queryCount = $this->getCurrentQueryCount(); $contains = $group->users->containsKey($this->userId2); - $this->assertTrue($contains, "The item is not into collection"); - $this->assertFalse($group->users->isInitialized(), "The collection must not be initialized"); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertTrue($contains, "The item is not into collection"); + self::assertFalse($group->users->isInitialized(), "The collection must not be initialized"); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } public function testContainsKeyNonExistentIndexByOneToMany() { - $user = $this->_em->find(CmsUser::class, $this->userId2); + $user = $this->em->find(CmsUser::class, $this->userId2); $queryCount = $this->getCurrentQueryCount(); $contains = $user->articles->containsKey("NonExistentTopic"); - $this->assertFalse($contains); - $this->assertFalse($user->articles->isInitialized()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertFalse($contains); + self::assertFalse($user->articles->isInitialized()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } public function testContainsKeyNonExistentIndexByManyToMany() { - $user = $this->_em->find(CmsUser::class, $this->userId2); + $user = $this->em->find(CmsUser::class, $this->userId2); $queryCount = $this->getCurrentQueryCount(); $contains = $user->groups->containsKey("NonExistentTopic"); - $this->assertFalse($contains); - $this->assertFalse($user->groups->isInitialized()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertFalse($contains); + self::assertFalse($user->groups->isInitialized()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } private function loadFixture() @@ -973,10 +982,10 @@ private function loadFixture() $user4->name = "Guilherme"; $user4->status = "active"; - $this->_em->persist($user1); - $this->_em->persist($user2); - $this->_em->persist($user3); - $this->_em->persist($user4); + $this->em->persist($user1); + $this->em->persist($user2); + $this->em->persist($user3); + $this->em->persist($user4); $group1 = new CmsGroup(); $group1->name = "Test1"; @@ -995,9 +1004,9 @@ private function loadFixture() $user3->addGroup($group1); $user4->addGroup($group1); - $this->_em->persist($group1); - $this->_em->persist($group2); - $this->_em->persist($group3); + $this->em->persist($group1); + $this->em->persist($group2); + $this->em->persist($group3); $article1 = new CmsArticle(); $article1->topic = "Test1"; @@ -1009,8 +1018,8 @@ private function loadFixture() $article2->text = "Test2"; $article2->setAuthor($user1); - $this->_em->persist($article1); - $this->_em->persist($article2); + $this->em->persist($article1); + $this->em->persist($article2); $phonenumber1 = new CmsPhonenumber(); $phonenumber1->phonenumber = '12345'; @@ -1018,8 +1027,8 @@ private function loadFixture() $phonenumber2 = new CmsPhonenumber(); $phonenumber2->phonenumber = '67890'; - $this->_em->persist($phonenumber1); - $this->_em->persist($phonenumber2); + $this->em->persist($phonenumber1); + $this->em->persist($phonenumber2); $user1->addPhonenumber($phonenumber1); @@ -1034,12 +1043,12 @@ private function loadFixture() $otherClass->childClasses[] = $childClass1; $otherClass->childClasses[] = $childClass2; - $this->_em->persist($childClass1); - $this->_em->persist($childClass2); - $this->_em->persist($otherClass); + $this->em->persist($childClass1); + $this->em->persist($childClass2); + $this->em->persist($otherClass); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $this->articleId = $article1->id; $this->userId = $user1->getId(); @@ -1063,16 +1072,16 @@ public function testRemoveManagedElementFromOneToManyExtraLazyCollectionIsNoOp() list($userId, $tweetId) = $this->loadTweetFixture(); /* @var $user User */ - $user = $this->_em->find(User::class, $userId); + $user = $this->em->find(User::class, $userId); - $user->tweets->removeElement($this->_em->find(Tweet::class, $tweetId)); + $user->tweets->removeElement($this->em->find(Tweet::class, $tweetId)); - $this->_em->clear(); + $this->em->clear(); /* @var $user User */ - $user = $this->_em->find(User::class, $userId); + $user = $this->em->find(User::class, $userId); - $this->assertCount(1, $user->tweets, 'Element was not removed - need to update the owning side first'); + self::assertCount(1, $user->tweets, 'Element was not removed - need to update the owning side first'); } /** @@ -1083,22 +1092,22 @@ public function testRemoveManagedElementFromOneToManyExtraLazyCollectionWithoutD list($userId, $tweetId) = $this->loadTweetFixture(); /* @var $user User */ - $user = $this->_em->find(User::class, $userId); - $tweet = $this->_em->find(Tweet::class, $tweetId); + $user = $this->em->find(User::class, $userId); + $tweet = $this->em->find(Tweet::class, $tweetId); $user->tweets->removeElement($tweet); - $this->_em->clear(); + $this->em->clear(); /* @var $tweet Tweet */ - $tweet = $this->_em->find(Tweet::class, $tweetId); - $this->assertInstanceOf( + $tweet = $this->em->find(Tweet::class, $tweetId); + self::assertInstanceOf( Tweet::class, $tweet, 'Even though the collection is extra lazy, the tweet should not have been deleted' ); - $this->assertInstanceOf( + self::assertInstanceOf( User::class, $tweet->author, 'Tweet author link has not been removed - need to update the owning side first' @@ -1113,27 +1122,27 @@ public function testRemovingManagedLazyProxyFromExtraLazyOneToManyDoesRemoveTheA list($userId, $tweetId) = $this->loadTweetFixture(); /* @var $user User */ - $user = $this->_em->find(User::class, $userId); - $tweet = $this->_em->getReference(Tweet::class, $tweetId); + $user = $this->em->find(User::class, $userId); + $tweet = $this->em->getReference(Tweet::class, $tweetId); - $user->tweets->removeElement($this->_em->getReference(Tweet::class, $tweetId)); + $user->tweets->removeElement($this->em->getReference(Tweet::class, $tweetId)); - $this->_em->clear(); + $this->em->clear(); /* @var $tweet Tweet */ - $tweet = $this->_em->find(Tweet::class, $tweet->id); - $this->assertInstanceOf( + $tweet = $this->em->find(Tweet::class, $tweet->id); + self::assertInstanceOf( Tweet::class, $tweet, 'Even though the collection is extra lazy, the tweet should not have been deleted' ); - $this->assertInstanceOf(User::class, $tweet->author); + self::assertInstanceOf(User::class, $tweet->author); /* @var $user User */ - $user = $this->_em->find(User::class, $userId); + $user = $this->em->find(User::class, $userId); - $this->assertCount(1, $user->tweets, 'Element was not removed - need to update the owning side first'); + self::assertCount(1, $user->tweets, 'Element was not removed - need to update the owning side first'); } /** @@ -1144,18 +1153,18 @@ public function testRemoveOrphanedManagedElementFromOneToManyExtraLazyCollection list($userId, $userListId) = $this->loadUserListFixture(); /* @var $user User */ - $user = $this->_em->find(User::class, $userId); + $user = $this->em->find(User::class, $userId); - $user->userLists->removeElement($this->_em->find(UserList::class, $userListId)); + $user->userLists->removeElement($this->em->find(UserList::class, $userListId)); - $this->_em->clear(); + $this->em->clear(); /* @var $user User */ - $user = $this->_em->find(User::class, $userId); + $user = $this->em->find(User::class, $userId); - $this->assertCount(0, $user->userLists, 'Element was removed from association due to orphan removal'); - $this->assertNull( - $this->_em->find(UserList::class, $userListId), + self::assertCount(0, $user->userLists, 'Element was removed from association due to orphan removal'); + self::assertNull( + $this->em->find(UserList::class, $userListId), 'Element was deleted due to orphan removal' ); } @@ -1168,21 +1177,21 @@ public function testRemoveOrphanedUnManagedElementFromOneToManyExtraLazyCollecti list($userId, $userListId) = $this->loadUserListFixture(); /* @var $user User */ - $user = $this->_em->find(User::class, $userId); + $user = $this->em->find(User::class, $userId); $user->userLists->removeElement(new UserList()); - $this->_em->clear(); + $this->em->clear(); /* @var $userList UserList */ - $userList = $this->_em->find(UserList::class, $userListId); - $this->assertInstanceOf( + $userList = $this->em->find(UserList::class, $userListId); + self::assertInstanceOf( UserList::class, $userList, 'Even though the collection is extra lazy + orphan removal, the user list should not have been deleted' ); - $this->assertInstanceOf( + self::assertInstanceOf( User::class, $userList->owner, 'User list to owner link has not been removed' @@ -1197,18 +1206,18 @@ public function testRemoveOrphanedManagedLazyProxyFromExtraLazyOneToMany() list($userId, $userListId) = $this->loadUserListFixture(); /* @var $user User */ - $user = $this->_em->find(User::class, $userId); + $user = $this->em->find(User::class, $userId); - $user->userLists->removeElement($this->_em->getReference(UserList::class, $userListId)); + $user->userLists->removeElement($this->em->getReference(UserList::class, $userListId)); - $this->_em->clear(); + $this->em->clear(); /* @var $user User */ - $user = $this->_em->find(User::class, $userId); + $user = $this->em->find(User::class, $userId); - $this->assertCount(0, $user->userLists, 'Element was removed from association due to orphan removal'); - $this->assertNull( - $this->_em->find(UserList::class, $userListId), + self::assertCount(0, $user->userLists, 'Element was removed from association due to orphan removal'); + self::assertNull( + $this->em->find(UserList::class, $userListId), 'Element was deleted due to orphan removal' ); } @@ -1226,10 +1235,10 @@ private function loadTweetFixture() $user->addTweet($tweet); - $this->_em->persist($user); - $this->_em->persist($tweet); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->persist($tweet); + $this->em->flush(); + $this->em->clear(); return [$user->id, $tweet->id]; } @@ -1247,10 +1256,10 @@ private function loadUserListFixture() $user->addUserList($userList); - $this->_em->persist($user); - $this->_em->persist($userList); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->persist($userList); + $this->em->flush(); + $this->em->clear(); return [$user->id, $userList->id]; } diff --git a/tests/Doctrine/Tests/ORM/Functional/FlushEventTest.php b/tests/Doctrine/Tests/ORM/Functional/FlushEventTest.php index b9298e3dc09..ee862e63599 100644 --- a/tests/Doctrine/Tests/ORM/Functional/FlushEventTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/FlushEventTest.php @@ -1,5 +1,7 @@ _em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_em->getEventManager()->addEventListener(Events::onFlush, new OnFlushListener); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + $this->em->getEventManager()->addEventListener(Events::onFlush, new OnFlushListener); $user = new CmsUser; $user->username = 'romanb'; $user->name = 'Roman'; $user->status = 'Dev'; - $this->_em->persist($user); + $this->em->persist($user); - $this->assertEquals(0, $user->phonenumbers->count()); + self::assertEquals(0, $user->phonenumbers->count()); - $this->_em->flush(); + $this->em->flush(); - $this->assertEquals(1, $user->phonenumbers->count()); - $this->assertTrue($this->_em->contains($user->phonenumbers->get(0))); - $this->assertTrue($user->phonenumbers->get(0)->getUser() === $user); + self::assertEquals(1, $user->phonenumbers->count()); + self::assertTrue($this->em->contains($user->phonenumbers->get(0))); + self::assertTrue($user->phonenumbers->get(0)->getUser() === $user); - $this->assertFalse($user->phonenumbers->isDirty()); + self::assertFalse($user->phonenumbers->isDirty()); // Can be used together with SQL Logging to check that a subsequent flush has // nothing to do. This proofs the correctness of the changes that happened in onFlush. //echo "SECOND FLUSH"; - //$this->_em->flush(); + //$this->em->flush(); } /** @@ -55,19 +57,19 @@ public function testPersistNewEntitiesOnPreFlush() public function testPreAndOnFlushCalledAlways() { $listener = new OnFlushCalledListener(); - $this->_em->getEventManager()->addEventListener(Events::onFlush, $listener); - $this->_em->getEventManager()->addEventListener(Events::preFlush, $listener); - $this->_em->getEventManager()->addEventListener(Events::postFlush, $listener); + $this->em->getEventManager()->addEventListener(Events::onFlush, $listener); + $this->em->getEventManager()->addEventListener(Events::preFlush, $listener); + $this->em->getEventManager()->addEventListener(Events::postFlush, $listener); - $this->_em->flush(); + $this->em->flush(); - $this->assertEquals(1, $listener->preFlush); - $this->assertEquals(1, $listener->onFlush); + self::assertEquals(1, $listener->preFlush); + self::assertEquals(1, $listener->onFlush); - $this->_em->flush(); + $this->em->flush(); - $this->assertEquals(2, $listener->preFlush); - $this->assertEquals(2, $listener->onFlush); + self::assertEquals(2, $listener->preFlush); + self::assertEquals(2, $listener->onFlush); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/HydrationCacheTest.php b/tests/Doctrine/Tests/ORM/Functional/HydrationCacheTest.php index dc84ac4ed1f..058853aabdd 100644 --- a/tests/Doctrine/Tests/ORM/Functional/HydrationCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/HydrationCacheTest.php @@ -1,5 +1,7 @@ username = "beberlei"; $user->status = 'active'; - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); } public function testHydrationCache() @@ -33,39 +35,39 @@ public function testHydrationCache() $cache = new ArrayCache(); $dql = "SELECT u FROM Doctrine\Tests\Models\Cms\CmsUser u"; - $users = $this->_em->createQuery($dql) + $users = $this->em->createQuery($dql) ->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache)) ->getResult(); $c = $this->getCurrentQueryCount(); - $users = $this->_em->createQuery($dql) + $users = $this->em->createQuery($dql) ->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache)) ->getResult(); - $this->assertEquals($c, $this->getCurrentQueryCount(), "Should not execute query. Its cached!"); + self::assertEquals($c, $this->getCurrentQueryCount(), "Should not execute query. Its cached!"); - $users = $this->_em->createQuery($dql) + $users = $this->em->createQuery($dql) ->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache)) ->getArrayResult(); - $this->assertEquals($c + 1, $this->getCurrentQueryCount(), "Hydration is part of cache key."); + self::assertEquals($c + 1, $this->getCurrentQueryCount(), "Hydration is part of cache key."); - $users = $this->_em->createQuery($dql) + $users = $this->em->createQuery($dql) ->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache)) ->getArrayResult(); - $this->assertEquals($c + 1, $this->getCurrentQueryCount(), "Hydration now cached"); + self::assertEquals($c + 1, $this->getCurrentQueryCount(), "Hydration now cached"); - $users = $this->_em->createQuery($dql) + $users = $this->em->createQuery($dql) ->setHydrationCacheProfile(new QueryCacheProfile(null, 'cachekey', $cache)) ->getArrayResult(); - $this->assertTrue($cache->contains('cachekey'), 'Explicit cache key'); + self::assertTrue($cache->contains('cachekey'), 'Explicit cache key'); - $users = $this->_em->createQuery($dql) + $users = $this->em->createQuery($dql) ->setHydrationCacheProfile(new QueryCacheProfile(null, 'cachekey', $cache)) ->getArrayResult(); - $this->assertEquals($c + 2, $this->getCurrentQueryCount(), "Hydration now cached"); + self::assertEquals($c + 2, $this->getCurrentQueryCount(), "Hydration now cached"); } public function testHydrationParametersSerialization() @@ -73,7 +75,7 @@ public function testHydrationParametersSerialization() $cache = new ArrayCache(); $dql = "SELECT u FROM Doctrine\Tests\Models\Cms\CmsUser u WHERE u.id = ?1"; - $query = $this->_em->createQuery($dql) + $query = $this->em->createQuery($dql) ->setParameter(1, $userId = 1) ->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache)); @@ -83,7 +85,7 @@ public function testHydrationParametersSerialization() $query->getResult(); - $this->assertEquals($c, $this->getCurrentQueryCount(), "Should not execute query. Its cached!"); + self::assertEquals($c, $this->getCurrentQueryCount(), "Should not execute query. Its cached!"); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/IdentityMapTest.php b/tests/Doctrine/Tests/ORM/Functional/IdentityMapTest.php index 15929ae270d..ff1fb4130f9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/IdentityMapTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/IdentityMapTest.php @@ -1,5 +1,7 @@ setAddress($address); - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $user2 = $this->_em->find(get_class($user), $user->getId()); - $this->assertTrue($user2 !== $user); - $user3 = $this->_em->find(get_class($user), $user->getId()); - $this->assertTrue($user2 === $user3); + $user2 = $this->em->find(get_class($user), $user->getId()); + self::assertTrue($user2 !== $user); + $user3 = $this->em->find(get_class($user), $user->getId()); + self::assertTrue($user2 === $user3); - $address2 = $this->_em->find(get_class($address), $address->getId()); - $this->assertTrue($address2 !== $address); - $address3 = $this->_em->find(get_class($address), $address->getId()); - $this->assertTrue($address2 === $address3); + $address2 = $this->em->find(get_class($address), $address->getId()); + self::assertTrue($address2 !== $address); + $address3 = $this->em->find(get_class($address), $address->getId()); + self::assertTrue($address2 === $address3); - $this->assertTrue($user2->getAddress() === $address2); // !!! + self::assertTrue($user2->getAddress() === $address2); // !!! } public function testSingleValuedAssociationIdentityMapBehaviorWithRefresh() @@ -74,27 +76,27 @@ public function testSingleValuedAssociationIdentityMapBehaviorWithRefresh() $address->setUser($user1); - $this->_em->persist($address); - $this->_em->persist($user1); - $this->_em->persist($user2); - $this->_em->flush(); + $this->em->persist($address); + $this->em->persist($user1); + $this->em->persist($user2); + $this->em->flush(); - $this->assertSame($user1, $address->user); + self::assertSame($user1, $address->user); //external update to CmsAddress - $this->_em->getConnection()->executeUpdate('update cms_addresses set user_id = ?', [$user2->getId()]); + $this->em->getConnection()->executeUpdate('update cms_addresses set user_id = ?', [$user2->getId()]); // But we want to have this external change! // Solution 1: refresh(), broken atm! - $this->_em->refresh($address); + $this->em->refresh($address); // Now the association should be "correct", referencing $user2 - $this->assertSame($user2, $address->user); - $this->assertSame($user2->address, $address); // check back reference also + self::assertSame($user2, $address->user); + self::assertSame($user2->address, $address); // check back reference also // Attention! refreshes can result in broken bidirectional associations! this is currently expected! // $user1 still points to $address! - $this->assertSame($user1->address, $address); + self::assertSame($user1->address, $address); } public function testSingleValuedAssociationIdentityMapBehaviorWithRefreshQuery() @@ -116,42 +118,42 @@ public function testSingleValuedAssociationIdentityMapBehaviorWithRefreshQuery() $address->setUser($user1); - $this->_em->persist($address); - $this->_em->persist($user1); - $this->_em->persist($user2); - $this->_em->flush(); + $this->em->persist($address); + $this->em->persist($user1); + $this->em->persist($user2); + $this->em->flush(); - $this->assertSame($user1, $address->user); + self::assertSame($user1, $address->user); //external update to CmsAddress - $this->_em->getConnection()->executeUpdate('update cms_addresses set user_id = ?', [$user2->getId()]); + $this->em->getConnection()->executeUpdate('update cms_addresses set user_id = ?', [$user2->getId()]); //select - $q = $this->_em->createQuery('select a, u from Doctrine\Tests\Models\CMS\CmsAddress a join a.user u'); + $q = $this->em->createQuery('select a, u from Doctrine\Tests\Models\CMS\CmsAddress a join a.user u'); $address2 = $q->getSingleResult(); - $this->assertSame($address, $address2); + self::assertSame($address, $address2); // Should still be $user1 - $this->assertSame($user1, $address2->user); - $this->assertTrue($user2->address === null); + self::assertSame($user1, $address2->user); + self::assertTrue($user2->address === null); // But we want to have this external change! // Solution 2: Alternatively, a refresh query should work - $q = $this->_em->createQuery('select a, u from Doctrine\Tests\Models\CMS\CmsAddress a join a.user u'); + $q = $this->em->createQuery('select a, u from Doctrine\Tests\Models\CMS\CmsAddress a join a.user u'); $q->setHint(Query::HINT_REFRESH, true); $address3 = $q->getSingleResult(); - $this->assertSame($address, $address3); // should still be the same, always from identity map + self::assertSame($address, $address3); // should still be the same, always from identity map // Now the association should be "correct", referencing $user2 - $this->assertSame($user2, $address2->user); - $this->assertSame($user2->address, $address2); // check back reference also + self::assertSame($user2, $address2->user); + self::assertSame($user2->address, $address2); // check back reference also // Attention! refreshes can result in broken bidirectional associations! this is currently expected! // $user1 still points to $address2! - $this->assertSame($user1->address, $address2); + self::assertSame($user1->address, $address2); } public function testCollectionValuedAssociationIdentityMapBehaviorWithRefreshQuery() @@ -174,37 +176,37 @@ public function testCollectionValuedAssociationIdentityMapBehaviorWithRefreshQue $user->addPhonenumber($phone2); $user->addPhonenumber($phone3); - $this->_em->persist($user); // cascaded to phone numbers - $this->_em->flush(); + $this->em->persist($user); // cascaded to phone numbers + $this->em->flush(); - $this->assertEquals(3, count($user->getPhonenumbers())); - $this->assertFalse($user->getPhonenumbers()->isDirty()); + self::assertEquals(3, count($user->getPhonenumbers())); + self::assertFalse($user->getPhonenumbers()->isDirty()); //external update to CmsAddress - $this->_em->getConnection()->executeUpdate('insert into cms_phonenumbers (phonenumber, user_id) VALUES (?,?)', [999, $user->getId()] + $this->em->getConnection()->executeUpdate('insert into cms_phonenumbers (phonenumber, user_id) VALUES (?,?)', [999, $user->getId()] ); //select - $q = $this->_em->createQuery('select u, p from Doctrine\Tests\Models\CMS\CmsUser u join u.phonenumbers p'); + $q = $this->em->createQuery('select u, p from Doctrine\Tests\Models\CMS\CmsUser u join u.phonenumbers p'); $user2 = $q->getSingleResult(); - $this->assertSame($user, $user2); + self::assertSame($user, $user2); // Should still be the same 3 phonenumbers - $this->assertEquals(3, count($user2->getPhonenumbers())); + self::assertEquals(3, count($user2->getPhonenumbers())); // But we want to have this external change! // Solution 1: refresh(). - //$this->_em->refresh($user2); broken atm! + //$this->em->refresh($user2); broken atm! // Solution 2: Alternatively, a refresh query should work - $q = $this->_em->createQuery('select u, p from Doctrine\Tests\Models\CMS\CmsUser u join u.phonenumbers p'); + $q = $this->em->createQuery('select u, p from Doctrine\Tests\Models\CMS\CmsUser u join u.phonenumbers p'); $q->setHint(Query::HINT_REFRESH, true); $user3 = $q->getSingleResult(); - $this->assertSame($user, $user3); // should still be the same, always from identity map + self::assertSame($user, $user3); // should still be the same, always from identity map // Now the collection should be refreshed with correct count - $this->assertEquals(4, count($user3->getPhonenumbers())); + self::assertEquals(4, count($user3->getPhonenumbers())); } public function testCollectionValuedAssociationIdentityMapBehaviorWithRefresh() @@ -227,32 +229,32 @@ public function testCollectionValuedAssociationIdentityMapBehaviorWithRefresh() $user->addPhonenumber($phone2); $user->addPhonenumber($phone3); - $this->_em->persist($user); // cascaded to phone numbers - $this->_em->flush(); + $this->em->persist($user); // cascaded to phone numbers + $this->em->flush(); - $this->assertEquals(3, count($user->getPhonenumbers())); + self::assertEquals(3, count($user->getPhonenumbers())); //external update to CmsAddress - $this->_em->getConnection()->executeUpdate('insert into cms_phonenumbers (phonenumber, user_id) VALUES (?,?)', [999, $user->getId()] + $this->em->getConnection()->executeUpdate('insert into cms_phonenumbers (phonenumber, user_id) VALUES (?,?)', [999, $user->getId()] ); //select - $q = $this->_em->createQuery('select u, p from Doctrine\Tests\Models\CMS\CmsUser u join u.phonenumbers p'); + $q = $this->em->createQuery('select u, p from Doctrine\Tests\Models\CMS\CmsUser u join u.phonenumbers p'); $user2 = $q->getSingleResult(); - $this->assertSame($user, $user2); + self::assertSame($user, $user2); // Should still be the same 3 phonenumbers - $this->assertEquals(3, count($user2->getPhonenumbers())); + self::assertEquals(3, count($user2->getPhonenumbers())); // But we want to have this external change! // Solution 1: refresh(). - $this->_em->refresh($user2); + $this->em->refresh($user2); - $this->assertSame($user, $user2); // should still be the same, always from identity map + self::assertSame($user, $user2); // should still be the same, always from identity map // Now the collection should be refreshed with correct count - $this->assertEquals(4, count($user2->getPhonenumbers())); + self::assertEquals(4, count($user2->getPhonenumbers())); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/IndexByAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/IndexByAssociationTest.php index 289e55807f8..73ee441bdc5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/IndexByAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/IndexByAssociationTest.php @@ -1,5 +1,7 @@ bond->addStock($stock1); $this->bond->addStock($stock2); - $this->_em->persist($this->market); - $this->_em->persist($stock1); - $this->_em->persist($stock2); - $this->_em->persist($this->bond); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($this->market); + $this->em->persist($stock1); + $this->em->persist($stock2); + $this->em->persist($this->bond); + $this->em->flush(); + $this->em->clear(); } public function testManyToOneFinder() { /* @var $market Market */ - $market = $this->_em->find(Market::class, $this->market->getId()); + $market = $this->em->find(Market::class, $this->market->getId()); - $this->assertEquals(2, count($market->stocks)); - $this->assertTrue(isset($market->stocks['AAPL']), "AAPL symbol has to be key in indexed association."); - $this->assertTrue(isset($market->stocks['GOOG']), "GOOG symbol has to be key in indexed association."); - $this->assertEquals("AAPL", $market->stocks['AAPL']->getSymbol()); - $this->assertEquals("GOOG", $market->stocks['GOOG']->getSymbol()); + self::assertEquals(2, count($market->stocks)); + self::assertTrue(isset($market->stocks['AAPL']), "AAPL symbol has to be key in indexed association."); + self::assertTrue(isset($market->stocks['GOOG']), "GOOG symbol has to be key in indexed association."); + self::assertEquals("AAPL", $market->stocks['AAPL']->getSymbol()); + self::assertEquals("GOOG", $market->stocks['GOOG']->getSymbol()); } public function testManyToOneDQL() { $dql = "SELECT m, s FROM Doctrine\Tests\Models\StockExchange\Market m JOIN m.stocks s WHERE m.id = ?1"; - $market = $this->_em->createQuery($dql)->setParameter(1, $this->market->getId())->getSingleResult(); + $market = $this->em->createQuery($dql)->setParameter(1, $this->market->getId())->getSingleResult(); - $this->assertEquals(2, count($market->stocks)); - $this->assertTrue(isset($market->stocks['AAPL']), "AAPL symbol has to be key in indexed association."); - $this->assertTrue(isset($market->stocks['GOOG']), "GOOG symbol has to be key in indexed association."); - $this->assertEquals("AAPL", $market->stocks['AAPL']->getSymbol()); - $this->assertEquals("GOOG", $market->stocks['GOOG']->getSymbol()); + self::assertEquals(2, count($market->stocks)); + self::assertTrue(isset($market->stocks['AAPL']), "AAPL symbol has to be key in indexed association."); + self::assertTrue(isset($market->stocks['GOOG']), "GOOG symbol has to be key in indexed association."); + self::assertEquals("AAPL", $market->stocks['AAPL']->getSymbol()); + self::assertEquals("GOOG", $market->stocks['GOOG']->getSymbol()); } public function testManyToMany() { - $bond = $this->_em->find(Bond::class, $this->bond->getId()); + $bond = $this->em->find(Bond::class, $this->bond->getId()); - $this->assertEquals(2, count($bond->stocks)); - $this->assertTrue(isset($bond->stocks['AAPL']), "AAPL symbol has to be key in indexed association."); - $this->assertTrue(isset($bond->stocks['GOOG']), "GOOG symbol has to be key in indexed association."); - $this->assertEquals("AAPL", $bond->stocks['AAPL']->getSymbol()); - $this->assertEquals("GOOG", $bond->stocks['GOOG']->getSymbol()); + self::assertEquals(2, count($bond->stocks)); + self::assertTrue(isset($bond->stocks['AAPL']), "AAPL symbol has to be key in indexed association."); + self::assertTrue(isset($bond->stocks['GOOG']), "GOOG symbol has to be key in indexed association."); + self::assertEquals("AAPL", $bond->stocks['AAPL']->getSymbol()); + self::assertEquals("GOOG", $bond->stocks['GOOG']->getSymbol()); } public function testManytoManyDQL() { $dql = "SELECT b, s FROM Doctrine\Tests\Models\StockExchange\Bond b JOIN b.stocks s WHERE b.id = ?1"; - $bond = $this->_em->createQuery($dql)->setParameter(1, $this->bond->getId())->getSingleResult(); + $bond = $this->em->createQuery($dql)->setParameter(1, $this->bond->getId())->getSingleResult(); - $this->assertEquals(2, count($bond->stocks)); - $this->assertTrue(isset($bond->stocks['AAPL']), "AAPL symbol has to be key in indexed association."); - $this->assertTrue(isset($bond->stocks['GOOG']), "GOOG symbol has to be key in indexed association."); - $this->assertEquals("AAPL", $bond->stocks['AAPL']->getSymbol()); - $this->assertEquals("GOOG", $bond->stocks['GOOG']->getSymbol()); + self::assertEquals(2, count($bond->stocks)); + self::assertTrue(isset($bond->stocks['AAPL']), "AAPL symbol has to be key in indexed association."); + self::assertTrue(isset($bond->stocks['GOOG']), "GOOG symbol has to be key in indexed association."); + self::assertEquals("AAPL", $bond->stocks['AAPL']->getSymbol()); + self::assertEquals("GOOG", $bond->stocks['GOOG']->getSymbol()); } public function testDqlOverrideIndexBy() { $dql = "SELECT b, s FROM Doctrine\Tests\Models\StockExchange\Bond b JOIN b.stocks s INDEX BY s.id WHERE b.id = ?1"; - $bond = $this->_em->createQuery($dql)->setParameter(1, $this->bond->getId())->getSingleResult(); + $bond = $this->em->createQuery($dql)->setParameter(1, $this->bond->getId())->getSingleResult(); - $this->assertEquals(2, count($bond->stocks)); - $this->assertFalse(isset($bond->stocks['AAPL']), "AAPL symbol not exists in re-indexed association."); - $this->assertFalse(isset($bond->stocks['GOOG']), "GOOG symbol not exists in re-indexed association."); + self::assertEquals(2, count($bond->stocks)); + self::assertFalse(isset($bond->stocks['AAPL']), "AAPL symbol not exists in re-indexed association."); + self::assertFalse(isset($bond->stocks['GOOG']), "GOOG symbol not exists in re-indexed association."); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/JoinedTableCompositeKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/JoinedTableCompositeKeyTest.php index ab5c394e020..e3aab496b2d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/JoinedTableCompositeKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/JoinedTableCompositeKeyTest.php @@ -1,4 +1,6 @@ _em->persist($childEntity); - $this->_em->flush(); + $this->em->persist($childEntity); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); $entity = $this->findEntity(); - $this->assertEquals($childEntity, $entity); + self::assertEquals($childEntity, $entity); } /** @@ -36,20 +38,20 @@ public function testInsertWithCompositeKey() public function testUpdateWithCompositeKey() { $childEntity = new JoinedChildClass(); - $this->_em->persist($childEntity); - $this->_em->flush(); + $this->em->persist($childEntity); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); $entity = $this->findEntity(); $entity->extension = 'ext-new'; - $this->_em->persist($entity); - $this->_em->flush(); + $this->em->persist($entity); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); $persistedEntity = $this->findEntity(); - $this->assertEquals($entity, $persistedEntity); + self::assertEquals($entity, $persistedEntity); } /** @@ -57,7 +59,7 @@ public function testUpdateWithCompositeKey() */ private function findEntity() { - return $this->_em->find( + return $this->em->find( JoinedRootClass::class, ['keyPart1' => 'part-1', 'keyPart2' => 'part-2'] ); diff --git a/tests/Doctrine/Tests/ORM/Functional/LifecycleCallbackTest.php b/tests/Doctrine/Tests/ORM/Functional/LifecycleCallbackTest.php index 914acbecf86..ec7c2e0c113 100644 --- a/tests/Doctrine/Tests/ORM/Functional/LifecycleCallbackTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/LifecycleCallbackTest.php @@ -1,8 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(LifecycleCallbackEventArgEntity::class), - $this->_em->getClassMetadata(LifecycleCallbackTestEntity::class), - $this->_em->getClassMetadata(LifecycleCallbackTestUser::class), - $this->_em->getClassMetadata(LifecycleCallbackCascader::class), + $this->em->getClassMetadata(LifecycleCallbackEventArgEntity::class), + $this->em->getClassMetadata(LifecycleCallbackTestEntity::class), + $this->em->getClassMetadata(LifecycleCallbackTestUser::class), + $this->em->getClassMetadata(LifecycleCallbackCascader::class), ] ); } catch (\Exception $e) { @@ -32,46 +35,46 @@ public function testPreSavePostSaveCallbacksAreInvoked() { $entity = new LifecycleCallbackTestEntity; $entity->value = 'hello'; - $this->_em->persist($entity); - $this->_em->flush(); + $this->em->persist($entity); + $this->em->flush(); - $this->assertTrue($entity->prePersistCallbackInvoked); - $this->assertTrue($entity->postPersistCallbackInvoked); + self::assertTrue($entity->prePersistCallbackInvoked); + self::assertTrue($entity->postPersistCallbackInvoked); - $this->_em->clear(); + $this->em->clear(); - $query = $this->_em->createQuery("select e from Doctrine\Tests\ORM\Functional\LifecycleCallbackTestEntity e"); + $query = $this->em->createQuery("select e from Doctrine\Tests\ORM\Functional\LifecycleCallbackTestEntity e"); $result = $query->getResult(); - $this->assertTrue($result[0]->postLoadCallbackInvoked); + self::assertTrue($result[0]->postLoadCallbackInvoked); $result[0]->value = 'hello again'; - $this->_em->flush(); + $this->em->flush(); - $this->assertEquals('changed from preUpdate callback!', $result[0]->value); + self::assertEquals('changed from preUpdate callback!', $result[0]->value); } public function testPreFlushCallbacksAreInvoked() { $entity = new LifecycleCallbackTestEntity; $entity->value = 'hello'; - $this->_em->persist($entity); + $this->em->persist($entity); - $this->_em->flush(); + $this->em->flush(); - $this->assertTrue($entity->prePersistCallbackInvoked); - $this->assertTrue($entity->preFlushCallbackInvoked); + self::assertTrue($entity->prePersistCallbackInvoked); + self::assertTrue($entity->preFlushCallbackInvoked); $entity->preFlushCallbackInvoked = false; - $this->_em->flush(); + $this->em->flush(); - $this->assertTrue($entity->preFlushCallbackInvoked); + self::assertTrue($entity->preFlushCallbackInvoked); $entity->value = 'bye'; $entity->preFlushCallbackInvoked = false; - $this->_em->flush(); + $this->em->flush(); - $this->assertTrue($entity->preFlushCallbackInvoked); + self::assertTrue($entity->preFlushCallbackInvoked); } public function testChangesDontGetLost() @@ -79,18 +82,18 @@ public function testChangesDontGetLost() $user = new LifecycleCallbackTestUser; $user->setName('Bob'); $user->setValue('value'); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); $user->setName('Alice'); - $this->_em->flush(); // Triggers preUpdate + $this->em->flush(); // Triggers preUpdate - $this->_em->clear(); + $this->em->clear(); - $user2 = $this->_em->find(get_class($user), $user->getId()); + $user2 = $this->em->find(get_class($user), $user->getId()); - $this->assertEquals('Alice', $user2->getName()); - $this->assertEquals('Hello World', $user2->getValue()); + self::assertEquals('Alice', $user2->getName()); + self::assertEquals('Hello World', $user2->getValue()); } /** @@ -100,17 +103,17 @@ public function testGetReferenceWithPostLoadEventIsDelayedUntilProxyTrigger() { $entity = new LifecycleCallbackTestEntity; $entity->value = 'hello'; - $this->_em->persist($entity); - $this->_em->flush(); + $this->em->persist($entity); + $this->em->flush(); $id = $entity->getId(); - $this->_em->clear(); + $this->em->clear(); - $reference = $this->_em->getReference(LifecycleCallbackTestEntity::class, $id); - $this->assertFalse($reference->postLoadCallbackInvoked); + $reference = $this->em->getReference(LifecycleCallbackTestEntity::class, $id); + self::assertFalse($reference->postLoadCallbackInvoked); $reference->getValue(); // trigger proxy load - $this->assertTrue($reference->postLoadCallbackInvoked); + self::assertTrue($reference->postLoadCallbackInvoked); } /** @@ -120,18 +123,18 @@ public function testPostLoadTriggeredOnRefresh() { $entity = new LifecycleCallbackTestEntity; $entity->value = 'hello'; - $this->_em->persist($entity); - $this->_em->flush(); + $this->em->persist($entity); + $this->em->flush(); $id = $entity->getId(); - $this->_em->clear(); + $this->em->clear(); - $reference = $this->_em->find(LifecycleCallbackTestEntity::class, $id); - $this->assertTrue($reference->postLoadCallbackInvoked); + $reference = $this->em->find(LifecycleCallbackTestEntity::class, $id); + self::assertTrue($reference->postLoadCallbackInvoked); $reference->postLoadCallbackInvoked = false; - $this->_em->refresh($reference); - $this->assertTrue($reference->postLoadCallbackInvoked, "postLoad should be invoked when refresh() is called."); + $this->em->refresh($reference); + self::assertTrue($reference->postLoadCallbackInvoked, "postLoad should be invoked when refresh() is called."); } /** @@ -139,24 +142,24 @@ public function testPostLoadTriggeredOnRefresh() */ public function testCascadedEntitiesCallsPrePersist() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $e1 = new LifecycleCallbackTestEntity; $e2 = new LifecycleCallbackTestEntity; $c = new LifecycleCallbackCascader(); - $this->_em->persist($c); + $this->em->persist($c); $c->entities[] = $e1; $c->entities[] = $e2; $e1->cascader = $c; $e2->cascader = $c; - //$this->_em->persist($c); - $this->_em->flush(); + //$this->em->persist($c); + $this->em->flush(); - $this->assertTrue($e1->prePersistCallbackInvoked); - $this->assertTrue($e2->prePersistCallbackInvoked); + self::assertTrue($e1->prePersistCallbackInvoked); + self::assertTrue($e2->prePersistCallbackInvoked); } /** @@ -169,15 +172,15 @@ public function testCascadedEntitiesLoadedInPostLoad() $e2 = new LifecycleCallbackTestEntity(); $c = new LifecycleCallbackCascader(); - $this->_em->persist($c); + $this->em->persist($c); $c->entities[] = $e1; $c->entities[] = $e2; $e1->cascader = $c; $e2->cascader = $c; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $dql = <<<'DQL' SELECT @@ -191,14 +194,14 @@ public function testCascadedEntitiesLoadedInPostLoad() DQL; $entities = $this - ->_em + ->em ->createQuery(sprintf($dql, $e1->getId(), $e2->getId())) ->getResult(); - $this->assertTrue(current($entities)->postLoadCallbackInvoked); - $this->assertTrue(current($entities)->postLoadCascaderNotNull); - $this->assertTrue(current($entities)->cascader->postLoadCallbackInvoked); - $this->assertEquals(current($entities)->cascader->postLoadEntitiesCount, 2); + self::assertTrue(current($entities)->postLoadCallbackInvoked); + self::assertTrue(current($entities)->postLoadCascaderNotNull); + self::assertTrue(current($entities)->cascader->postLoadCallbackInvoked); + self::assertEquals(current($entities)->cascader->postLoadEntitiesCount, 2); } /** @@ -211,15 +214,15 @@ public function testCascadedEntitiesNotLoadedInPostLoadDuringIteration() $e2 = new LifecycleCallbackTestEntity(); $c = new LifecycleCallbackCascader(); - $this->_em->persist($c); + $this->em->persist($c); $c->entities[] = $e1; $c->entities[] = $e2; $e1->cascader = $c; $e2->cascader = $c; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $dql = <<<'DQL' SELECT @@ -233,13 +236,13 @@ public function testCascadedEntitiesNotLoadedInPostLoadDuringIteration() DQL; $result = $this - ->_em + ->em ->createQuery(sprintf($dql, $e1->getId(), $e2->getId())) ->iterate(); foreach ($result as $entity) { - $this->assertTrue($entity[0]->postLoadCallbackInvoked); - $this->assertFalse($entity[0]->postLoadCascaderNotNull); + self::assertTrue($entity[0]->postLoadCallbackInvoked); + self::assertFalse($entity[0]->postLoadCascaderNotNull); break; } @@ -250,33 +253,33 @@ public function testCascadedEntitiesNotLoadedInPostLoadDuringIteration() */ public function testCascadedEntitiesNotLoadedInPostLoadDuringIterationWithSimpleObjectHydrator() { - $this->_em->persist(new LifecycleCallbackTestEntity()); - $this->_em->persist(new LifecycleCallbackTestEntity()); + $this->em->persist(new LifecycleCallbackTestEntity()); + $this->em->persist(new LifecycleCallbackTestEntity()); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $result = $this - ->_em + ->em ->createQuery('SELECT e FROM Doctrine\Tests\ORM\Functional\LifecycleCallbackTestEntity AS e') ->iterate(null, Query::HYDRATE_SIMPLEOBJECT); foreach ($result as $entity) { - $this->assertTrue($entity[0]->postLoadCallbackInvoked); - $this->assertFalse($entity[0]->postLoadCascaderNotNull); + self::assertTrue($entity[0]->postLoadCallbackInvoked); + self::assertFalse($entity[0]->postLoadCascaderNotNull); break; } } - + /** * https://github.com/doctrine/doctrine2/issues/6568 */ public function testPostLoadIsInvokedOnFetchJoinedEntities() { $entA = new LifecycleCallbackCascader(); - $this->_em->persist($entA); - + $this->em->persist($entA); + $entB_1 = new LifecycleCallbackTestEntity(); $entB_2 = new LifecycleCallbackTestEntity(); @@ -285,8 +288,8 @@ public function testPostLoadIsInvokedOnFetchJoinedEntities() $entB_1->cascader = $entA; $entB_2->cascader = $entA; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $dql = <<<'DQL' SELECT @@ -300,46 +303,46 @@ public function testPostLoadIsInvokedOnFetchJoinedEntities() DQL; $fetchedA = $this - ->_em + ->em ->createQuery($dql)->setParameter('entA_id', $entA->getId()) ->getOneOrNullResult(); - $this->assertTrue($fetchedA->postLoadCallbackInvoked); + self::assertTrue($fetchedA->postLoadCallbackInvoked); foreach ($fetchedA->entities as $fetchJoinedEntB) { - $this->assertTrue($fetchJoinedEntB->postLoadCallbackInvoked); + self::assertTrue($fetchJoinedEntB->postLoadCallbackInvoked); } } public function testLifecycleCallbacksGetInherited() { - $childMeta = $this->_em->getClassMetadata(LifecycleCallbackChildEntity::class); - $this->assertEquals(['prePersist' => [0 => 'doStuff']], $childMeta->lifecycleCallbacks); + $childMeta = $this->em->getClassMetadata(LifecycleCallbackChildEntity::class); + self::assertEquals(['prePersist' => [0 => 'doStuff']], $childMeta->lifecycleCallbacks); } public function testLifecycleListener_ChangeUpdateChangeSet() { $listener = new LifecycleListenerPreUpdate; - $this->_em->getEventManager()->addEventListener(['preUpdate'], $listener); + $this->em->getEventManager()->addEventListener(['preUpdate'], $listener); $user = new LifecycleCallbackTestUser; $user->setName('Bob'); $user->setValue('value'); - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); $dql = "SELECT u FROM Doctrine\Tests\ORM\Functional\LifecycleCallbackTestUser u WHERE u.name = 'Bob'"; - $bob = $this->_em->createQuery($dql)->getSingleResult(); + $bob = $this->em->createQuery($dql)->getSingleResult(); $bob->setName('Alice'); - $this->_em->flush(); // preUpdate reverts Alice to Bob - $this->_em->clear(); + $this->em->flush(); // preUpdate reverts Alice to Bob + $this->em->clear(); - $this->_em->getEventManager()->removeEventListener(['preUpdate'], $listener); + $this->em->getEventManager()->removeEventListener(['preUpdate'], $listener); - $bob = $this->_em->createQuery($dql)->getSingleResult(); + $bob = $this->em->createQuery($dql)->getSingleResult(); - $this->assertEquals('Bob', $bob->getName()); + self::assertEquals('Bob', $bob->getName()); } /** @@ -350,60 +353,60 @@ public function testLifecycleCallbackEventArgs() $e = new LifecycleCallbackEventArgEntity; $e->value = 'foo'; - $this->_em->persist($e); - $this->_em->flush(); + $this->em->persist($e); + $this->em->flush(); $e->value = 'var'; - $this->_em->persist($e); - $this->_em->flush(); + $this->em->persist($e); + $this->em->flush(); - $this->_em->refresh($e); + $this->em->refresh($e); - $this->_em->remove($e); - $this->_em->flush(); + $this->em->remove($e); + $this->em->flush(); - $this->assertArrayHasKey('preFlushHandler', $e->calls); - $this->assertArrayHasKey('postLoadHandler', $e->calls); - $this->assertArrayHasKey('prePersistHandler', $e->calls); - $this->assertArrayHasKey('postPersistHandler', $e->calls); - $this->assertArrayHasKey('preUpdateHandler', $e->calls); - $this->assertArrayHasKey('postUpdateHandler', $e->calls); - $this->assertArrayHasKey('preRemoveHandler', $e->calls); - $this->assertArrayHasKey('postRemoveHandler', $e->calls); + self::assertArrayHasKey('preFlushHandler', $e->calls); + self::assertArrayHasKey('postLoadHandler', $e->calls); + self::assertArrayHasKey('prePersistHandler', $e->calls); + self::assertArrayHasKey('postPersistHandler', $e->calls); + self::assertArrayHasKey('preUpdateHandler', $e->calls); + self::assertArrayHasKey('postUpdateHandler', $e->calls); + self::assertArrayHasKey('preRemoveHandler', $e->calls); + self::assertArrayHasKey('postRemoveHandler', $e->calls); - $this->assertInstanceOf(PreFlushEventArgs::class, $e->calls['preFlushHandler']); - $this->assertInstanceOf(LifecycleEventArgs::class, $e->calls['postLoadHandler']); - $this->assertInstanceOf(LifecycleEventArgs::class, $e->calls['prePersistHandler']); - $this->assertInstanceOf(LifecycleEventArgs::class, $e->calls['postPersistHandler']); - $this->assertInstanceOf(PreUpdateEventArgs::class, $e->calls['preUpdateHandler']); - $this->assertInstanceOf(LifecycleEventArgs::class, $e->calls['postUpdateHandler']); - $this->assertInstanceOf(LifecycleEventArgs::class, $e->calls['preRemoveHandler']); - $this->assertInstanceOf(LifecycleEventArgs::class, $e->calls['postRemoveHandler']); + self::assertInstanceOf(PreFlushEventArgs::class, $e->calls['preFlushHandler']); + self::assertInstanceOf(LifecycleEventArgs::class, $e->calls['postLoadHandler']); + self::assertInstanceOf(LifecycleEventArgs::class, $e->calls['prePersistHandler']); + self::assertInstanceOf(LifecycleEventArgs::class, $e->calls['postPersistHandler']); + self::assertInstanceOf(PreUpdateEventArgs::class, $e->calls['preUpdateHandler']); + self::assertInstanceOf(LifecycleEventArgs::class, $e->calls['postUpdateHandler']); + self::assertInstanceOf(LifecycleEventArgs::class, $e->calls['preRemoveHandler']); + self::assertInstanceOf(LifecycleEventArgs::class, $e->calls['postRemoveHandler']); } } -/** @Entity @HasLifecycleCallbacks */ +/** @ORM\Entity @ORM\HasLifecycleCallbacks */ class LifecycleCallbackTestUser { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ private $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ private $value; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ private $name; public function getId() {return $this->id;} public function getValue() {return $this->value;} public function setValue($value) {$this->value = $value;} public function getName() {return $this->name;} public function setName($name) {$this->name = $name;} - /** @PreUpdate */ + /** @ORM\PreUpdate */ public function testCallback() {$this->value = 'Hello World';} } /** - * @Entity - * @HasLifecycleCallbacks - * @Table(name="lc_cb_test_entity") + * @ORM\Entity + * @ORM\HasLifecycleCallbacks + * @ORM\Table(name="lc_cb_test_entity") */ class LifecycleCallbackTestEntity { @@ -415,18 +418,18 @@ class LifecycleCallbackTestEntity public $preFlushCallbackInvoked = false; /** - * @Id @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** - * @Column(type="string", nullable=true) + * @ORM\Column(type="string", nullable=true) */ public $value; /** - * @ManyToOne(targetEntity="LifecycleCallbackCascader") - * @JoinColumn(name="cascader_id", referencedColumnName="id") + * @ORM\ManyToOne(targetEntity="LifecycleCallbackCascader") + * @ORM\JoinColumn(name="cascader_id", referencedColumnName="id") */ public $cascader; @@ -438,36 +441,36 @@ public function getValue() { return $this->value; } - /** @PrePersist */ + /** @ORM\PrePersist */ public function doStuffOnPrePersist() { $this->prePersistCallbackInvoked = true; } - /** @PostPersist */ + /** @ORM\PostPersist */ public function doStuffOnPostPersist() { $this->postPersistCallbackInvoked = true; } - /** @PostLoad */ + /** @ORM\PostLoad */ public function doStuffOnPostLoad() { $this->postLoadCallbackInvoked = true; $this->postLoadCascaderNotNull = isset($this->cascader); } - /** @PreUpdate */ + /** @ORM\PreUpdate */ public function doStuffOnPreUpdate() { $this->value = 'changed from preUpdate callback!'; } - /** @PreFlush */ + /** @ORM\PreFlush */ public function doStuffOnPreFlush() { $this->preFlushCallbackInvoked = true; } } /** - * @Entity @HasLifecycleCallbacks - * @Table(name="lc_cb_test_cascade") + * @ORM\Entity @ORM\HasLifecycleCallbacks + * @ORM\Table(name="lc_cb_test_cascade") */ class LifecycleCallbackCascader { @@ -476,13 +479,13 @@ class LifecycleCallbackCascader public $postLoadEntitiesCount = 0; /** - * @Id @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** - * @OneToMany(targetEntity="LifecycleCallbackTestEntity", mappedBy="cascader", cascade={"persist"}) + * @ORM\OneToMany(targetEntity="LifecycleCallbackTestEntity", mappedBy="cascader", cascade={"persist"}) */ public $entities; @@ -491,28 +494,28 @@ public function __construct() $this->entities = new ArrayCollection(); } - /** @PostLoad */ + /** @ORM\PostLoad */ public function doStuffOnPostLoad() { $this->postLoadCallbackInvoked = true; $this->postLoadEntitiesCount = count($this->entities); } - + public function getId() { return $this->id; } } -/** @MappedSuperclass @HasLifecycleCallbacks */ +/** @ORM\MappedSuperclass @ORM\HasLifecycleCallbacks */ class LifecycleCallbackParentEntity { - /** @PrePersist */ + /** @ORM\PrePersist */ function doStuff() { } } -/** @Entity @Table(name="lc_cb_childentity") */ +/** @ORM\Entity @ORM\Table(name="lc_cb_childentity") */ class LifecycleCallbackChildEntity extends LifecycleCallbackParentEntity { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ private $id; } @@ -524,19 +527,19 @@ public function preUpdate(PreUpdateEventArgs $eventArgs) } } -/** @Entity @HasLifecycleCallbacks */ +/** @ORM\Entity @ORM\HasLifecycleCallbacks */ class LifecycleCallbackEventArgEntity { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @Column() */ + /** @ORM\Column() */ public $value; public $calls = []; /** - * @PostPersist + * @ORM\PostPersist */ public function postPersistHandler(LifecycleEventArgs $event) { @@ -544,7 +547,7 @@ public function postPersistHandler(LifecycleEventArgs $event) } /** - * @PrePersist + * @ORM\PrePersist */ public function prePersistHandler(LifecycleEventArgs $event) { @@ -552,7 +555,7 @@ public function prePersistHandler(LifecycleEventArgs $event) } /** - * @PostUpdate + * @ORM\PostUpdate */ public function postUpdateHandler(LifecycleEventArgs $event) { @@ -560,7 +563,7 @@ public function postUpdateHandler(LifecycleEventArgs $event) } /** - * @PreUpdate + * @ORM\PreUpdate */ public function preUpdateHandler(PreUpdateEventArgs $event) { @@ -568,7 +571,7 @@ public function preUpdateHandler(PreUpdateEventArgs $event) } /** - * @PostRemove + * @ORM\PostRemove */ public function postRemoveHandler(LifecycleEventArgs $event) { @@ -576,7 +579,7 @@ public function postRemoveHandler(LifecycleEventArgs $event) } /** - * @PreRemove + * @ORM\PreRemove */ public function preRemoveHandler(LifecycleEventArgs $event) { @@ -584,7 +587,7 @@ public function preRemoveHandler(LifecycleEventArgs $event) } /** - * @PreFlush + * @ORM\PreFlush */ public function preFlushHandler(PreFlushEventArgs $event) { @@ -592,7 +595,7 @@ public function preFlushHandler(PreFlushEventArgs $event) } /** - * @PostLoad + * @ORM\PostLoad */ public function postLoadHandler(LifecycleEventArgs $event) { diff --git a/tests/Doctrine/Tests/ORM/Functional/Locking/GearmanLockTest.php b/tests/Doctrine/Tests/ORM/Functional/Locking/GearmanLockTest.php index 9c8d4b7eaf2..66dfeb9b99b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Locking/GearmanLockTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/Locking/GearmanLockTest.php @@ -1,5 +1,7 @@ text = "my article"; $article->topic = "Hello"; - $this->_em->persist($article); - $this->_em->flush(); + $this->em->persist($article); + $this->em->flush(); $this->articleId = $article->id; } @@ -52,7 +54,7 @@ public function testFindWithLock() $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); - $this->assertLockWorked(); + self::assertLockWorked(); } public function testFindWithWriteThenReadLock() @@ -60,7 +62,7 @@ public function testFindWithWriteThenReadLock() $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_READ); - $this->assertLockWorked(); + self::assertLockWorked(); } public function testFindWithReadThenWriteLock() @@ -68,7 +70,7 @@ public function testFindWithReadThenWriteLock() $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_READ); $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); - $this->assertLockWorked(); + self::assertLockWorked(); } public function testFindWithOneLock() @@ -76,7 +78,7 @@ public function testFindWithOneLock() $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::NONE); - $this->assertLockDoesNotBlock(); + self::assertLockDoesNotBlock(); } public function testDqlWithLock() @@ -84,7 +86,7 @@ public function testDqlWithLock() $this->asyncDqlWithLock('SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a', [], LockMode::PESSIMISTIC_WRITE); $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); - $this->assertLockWorked(); + self::assertLockWorked(); } public function testLock() @@ -92,7 +94,7 @@ public function testLock() $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); $this->asyncLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); - $this->assertLockWorked(); + self::assertLockWorked(); } public function testLock2() @@ -100,7 +102,7 @@ public function testLock2() $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); $this->asyncLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_READ); - $this->assertLockWorked(); + self::assertLockWorked(); } public function testLock3() @@ -108,7 +110,7 @@ public function testLock3() $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_READ); $this->asyncLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); - $this->assertLockWorked(); + self::assertLockWorked(); } public function testLock4() @@ -116,12 +118,12 @@ public function testLock4() $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::NONE); $this->asyncLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); - $this->assertLockDoesNotBlock(); + self::assertLockDoesNotBlock(); } protected function assertLockDoesNotBlock() { - $this->assertLockWorked($onlyForSeconds = 1); + self::assertLockWorked($onlyForSeconds = 1); } protected function assertLockWorked($forTime = 2, $notLongerThan = null) @@ -132,10 +134,10 @@ protected function assertLockWorked($forTime = 2, $notLongerThan = null) $this->gearman->runTasks(); - $this->assertTrue($this->maxRunTime > $forTime, + self::assertTrue($this->maxRunTime > $forTime, "Because of locking this tests should have run at least " . $forTime . " seconds, ". "but only did for " . $this->maxRunTime . " seconds."); - $this->assertTrue($this->maxRunTime < $notLongerThan, + self::assertTrue($this->maxRunTime < $notLongerThan, "The longest task should not run longer than " . $notLongerThan . " seconds, ". "but did for " . $this->maxRunTime . " seconds." ); @@ -175,11 +177,11 @@ protected function startJob($fn, $fixture) { $this->gearman->addTask($fn, serialize( [ - 'conn' => $this->_em->getConnection()->getParams(), + 'conn' => $this->em->getConnection()->getParams(), 'fixture' => $fixture ] )); - $this->assertEquals(GEARMAN_SUCCESS, $this->gearman->returnCode()); + self::assertEquals(GEARMAN_SUCCESS, $this->gearman->returnCode()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Locking/LockAgentWorker.php b/tests/Doctrine/Tests/ORM/Functional/Locking/LockAgentWorker.php index c7b82f7a87d..8bcac9254df 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Locking/LockAgentWorker.php +++ b/tests/Doctrine/Tests/ORM/Functional/Locking/LockAgentWorker.php @@ -1,5 +1,7 @@ setProxyNamespace('MyProject\Proxies'); $config->setAutoGenerateProxyClasses(true); - $annotDriver = $config->newDefaultAnnotationDriver([__DIR__ . '/../../../Models/'], true); + $annotDriver = $config->newDefaultAnnotationDriver([__DIR__ . '/../../../Models/']); $config->setMetadataDriverImpl($annotDriver); $cache = new ArrayCache(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Locking/LockTest.php b/tests/Doctrine/Tests/ORM/Functional/Locking/LockTest.php index d515e95bff7..50833ede5a9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Locking/LockTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/Locking/LockTest.php @@ -1,5 +1,7 @@ text = "my article"; $article->topic = "Hello"; - $this->_em->persist($article); - $this->_em->flush(); + $this->em->persist($article); + $this->em->flush(); - $this->_em->lock($article, LockMode::OPTIMISTIC, $article->version); + $this->em->lock($article, LockMode::OPTIMISTIC, $article->version); - $this->addToAssertionCount(1); + self::addToAssertionCount(1); } /** @@ -51,12 +53,12 @@ public function testLockVersionedEntity_MismatchThrowsException() $article->text = "my article"; $article->topic = "Hello"; - $this->_em->persist($article); - $this->_em->flush(); + $this->em->persist($article); + $this->em->flush(); $this->expectException(OptimisticLockException::class); - $this->_em->lock($article, LockMode::OPTIMISTIC, $article->version + 1); + $this->em->lock($article, LockMode::OPTIMISTIC, $article->version + 1); } /** @@ -70,12 +72,12 @@ public function testLockUnversionedEntity_ThrowsException() $user->status = "active"; $user->username = "foo"; - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); $this->expectException(OptimisticLockException::class); - $this->_em->lock($user, LockMode::OPTIMISTIC); + $this->em->lock($user, LockMode::OPTIMISTIC); } /** @@ -89,7 +91,7 @@ public function testLockUnmanagedEntity_ThrowsException() $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Entity ' . CmsArticle::class); - $this->_em->lock($article, LockMode::OPTIMISTIC, $article->version + 1); + $this->em->lock($article, LockMode::OPTIMISTIC, $article->version + 1); } /** @@ -102,12 +104,12 @@ public function testLockPessimisticRead_NoTransaction_ThrowsException() $article->text = "my article"; $article->topic = "Hello"; - $this->_em->persist($article); - $this->_em->flush(); + $this->em->persist($article); + $this->em->flush(); $this->expectException(TransactionRequiredException::class); - $this->_em->lock($article, LockMode::PESSIMISTIC_READ); + $this->em->lock($article, LockMode::PESSIMISTIC_READ); } /** @@ -120,12 +122,12 @@ public function testLockPessimisticWrite_NoTransaction_ThrowsException() $article->text = "my article"; $article->topic = "Hello"; - $this->_em->persist($article); - $this->_em->flush(); + $this->em->persist($article); + $this->em->flush(); $this->expectException(TransactionRequiredException::class); - $this->_em->lock($article, LockMode::PESSIMISTIC_WRITE); + $this->em->lock($article, LockMode::PESSIMISTIC_WRITE); } /** @@ -134,7 +136,7 @@ public function testLockPessimisticWrite_NoTransaction_ThrowsException() */ public function testLockPessimisticWrite() { - $writeLockSql = $this->_em->getConnection()->getDatabasePlatform()->getWriteLockSQL(); + $writeLockSql = $this->em->getConnection()->getDatabasePlatform()->getWriteLockSQL(); if (! $writeLockSql) { $this->markTestSkipped('Database Driver has no Write Lock support.'); @@ -144,21 +146,24 @@ public function testLockPessimisticWrite() $article->text = "my article"; $article->topic = "Hello"; - $this->_em->persist($article); - $this->_em->flush(); + $this->em->persist($article); + $this->em->flush(); + + $this->em->beginTransaction(); - $this->_em->beginTransaction(); try { - $this->_em->lock($article, LockMode::PESSIMISTIC_WRITE); - $this->_em->commit(); + $this->em->lock($article, LockMode::PESSIMISTIC_WRITE); + $this->em->commit(); } catch (\Exception $e) { - $this->_em->rollback(); + $this->em->rollback(); throw $e; } - $query = array_pop( $this->_sqlLoggerStack->queries ); - $query = array_pop( $this->_sqlLoggerStack->queries ); - $this->assertContains($writeLockSql, $query['sql']); + array_pop($this->sqlLoggerStack->queries); + + $query = array_pop($this->sqlLoggerStack->queries); + + self::assertContains($writeLockSql, $query['sql']); } /** @@ -166,7 +171,7 @@ public function testLockPessimisticWrite() */ public function testLockPessimisticRead() { - $readLockSql = $this->_em->getConnection()->getDatabasePlatform()->getReadLockSQL(); + $readLockSql = $this->em->getConnection()->getDatabasePlatform()->getReadLockSQL(); if (! $readLockSql) { $this->markTestSkipped('Database Driver has no Write Lock support.'); @@ -176,23 +181,24 @@ public function testLockPessimisticRead() $article->text = "my article"; $article->topic = "Hello"; - $this->_em->persist($article); - $this->_em->flush(); + $this->em->persist($article); + $this->em->flush(); - $this->_em->beginTransaction(); + $this->em->beginTransaction(); try { - $this->_em->lock($article, LockMode::PESSIMISTIC_READ); - $this->_em->commit(); + $this->em->lock($article, LockMode::PESSIMISTIC_READ); + $this->em->commit(); } catch (\Exception $e) { - $this->_em->rollback(); + $this->em->rollback(); throw $e; } - array_pop($this->_sqlLoggerStack->queries); - $query = array_pop($this->_sqlLoggerStack->queries); + array_pop($this->sqlLoggerStack->queries); + + $query = array_pop($this->sqlLoggerStack->queries); - $this->assertContains($readLockSql, $query['sql']); + self::assertContains($readLockSql, $query['sql']); } /** @@ -205,7 +211,7 @@ public function testLockOptimisticNonVersionedThrowsExceptionInDQL() $this->expectException(OptimisticLockException::class); $this->expectExceptionMessage('The optimistic lock on an entity failed.'); - $this->_em->createQuery($dql) + $this->em->createQuery($dql) ->setHint(Query::HINT_LOCK_MODE, LockMode::OPTIMISTIC) ->getSQL(); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Locking/OptimisticTest.php b/tests/Doctrine/Tests/ORM/Functional/Locking/OptimisticTest.php index 8b8113b6a66..f525d8f221f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Locking/OptimisticTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/Locking/OptimisticTest.php @@ -1,9 +1,12 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(OptimisticJoinedParent::class), - $this->_em->getClassMetadata(OptimisticJoinedChild::class), - $this->_em->getClassMetadata(OptimisticStandard::class), - $this->_em->getClassMetadata(OptimisticTimestamp::class) + $this->em->getClassMetadata(OptimisticJoinedParent::class), + $this->em->getClassMetadata(OptimisticJoinedChild::class), + $this->em->getClassMetadata(OptimisticStandard::class), + $this->em->getClassMetadata(OptimisticTimestamp::class) ] ); } catch (\Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } - $this->_conn = $this->_em->getConnection(); + $this->conn = $this->em->getConnection(); } public function testJoinedChildInsertSetsInitialVersionValue() @@ -36,10 +39,10 @@ public function testJoinedChildInsertSetsInitialVersionValue() $test->name = 'child'; $test->whatever = 'whatever'; - $this->_em->persist($test); - $this->_em->flush(); + $this->em->persist($test); + $this->em->flush(); - $this->assertEquals(1, $test->version); + self::assertEquals(1, $test->version); return $test; } @@ -49,7 +52,7 @@ public function testJoinedChildInsertSetsInitialVersionValue() */ public function testJoinedChildFailureThrowsException(OptimisticJoinedChild $child) { - $q = $this->_em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticJoinedChild t WHERE t.id = :id'); + $q = $this->em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticJoinedChild t WHERE t.id = :id'); $q->setParameter('id', $child->id); @@ -58,15 +61,15 @@ public function testJoinedChildFailureThrowsException(OptimisticJoinedChild $chi // Manually update/increment the version so we can try and save the same // $test and make sure the exception is thrown saying the record was // changed or updated since you read it - $this->_conn->executeQuery('UPDATE optimistic_joined_parent SET version = ? WHERE id = ?', [2, $test->id]); + $this->conn->executeQuery('UPDATE optimistic_joined_parent SET version = ? WHERE id = ?', [2, $test->id]); // Now lets change a property and try and save it again $test->whatever = 'ok'; try { - $this->_em->flush(); + $this->em->flush(); } catch (OptimisticLockException $e) { - $this->assertSame($test, $e->getEntity()); + self::assertSame($test, $e->getEntity()); } } @@ -76,10 +79,10 @@ public function testJoinedParentInsertSetsInitialVersionValue() $test->name = 'parent'; - $this->_em->persist($test); - $this->_em->flush(); + $this->em->persist($test); + $this->em->flush(); - $this->assertEquals(1, $test->version); + self::assertEquals(1, $test->version); return $test; } @@ -89,7 +92,7 @@ public function testJoinedParentInsertSetsInitialVersionValue() */ public function testJoinedParentFailureThrowsException(OptimisticJoinedParent $parent) { - $q = $this->_em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticJoinedParent t WHERE t.id = :id'); + $q = $this->em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticJoinedParent t WHERE t.id = :id'); $q->setParameter('id', $parent->id); @@ -98,15 +101,15 @@ public function testJoinedParentFailureThrowsException(OptimisticJoinedParent $p // Manually update/increment the version so we can try and save the same // $test and make sure the exception is thrown saying the record was // changed or updated since you read it - $this->_conn->executeQuery('UPDATE optimistic_joined_parent SET version = ? WHERE id = ?', [2, $test->id]); + $this->conn->executeQuery('UPDATE optimistic_joined_parent SET version = ? WHERE id = ?', [2, $test->id]); // Now lets change a property and try and save it again $test->name = 'WHATT???'; try { - $this->_em->flush(); + $this->em->flush(); } catch (OptimisticLockException $e) { - $this->assertSame($test, $e->getEntity()); + self::assertSame($test, $e->getEntity()); } } @@ -117,11 +120,11 @@ public function testMultipleFlushesDoIncrementalUpdates() for ($i = 0; $i < 5; $i++) { $test->name = 'test' . $i; - $this->_em->persist($test); - $this->_em->flush(); + $this->em->persist($test); + $this->em->flush(); - $this->assertInternalType('int', $test->getVersion()); - $this->assertEquals($i + 1, $test->getVersion()); + self::assertInternalType('int', $test->getVersion()); + self::assertEquals($i + 1, $test->getVersion()); } } @@ -131,11 +134,11 @@ public function testStandardInsertSetsInitialVersionValue() $test->name = 'test'; - $this->_em->persist($test); - $this->_em->flush(); + $this->em->persist($test); + $this->em->flush(); - $this->assertInternalType('int', $test->getVersion()); - $this->assertEquals(1, $test->getVersion()); + self::assertInternalType('int', $test->getVersion()); + self::assertEquals(1, $test->getVersion()); return $test; } @@ -145,7 +148,7 @@ public function testStandardInsertSetsInitialVersionValue() */ public function testStandardFailureThrowsException(OptimisticStandard $entity) { - $q = $this->_em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticStandard t WHERE t.id = :id'); + $q = $this->em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticStandard t WHERE t.id = :id'); $q->setParameter('id', $entity->id); @@ -154,15 +157,15 @@ public function testStandardFailureThrowsException(OptimisticStandard $entity) // Manually update/increment the version so we can try and save the same // $test and make sure the exception is thrown saying the record was // changed or updated since you read it - $this->_conn->executeQuery('UPDATE optimistic_standard SET version = ? WHERE id = ?', [2, $test->id]); + $this->conn->executeQuery('UPDATE optimistic_standard SET version = ? WHERE id = ?', [2, $test->id]); // Now lets change a property and try and save it again $test->name = 'WHATT???'; try { - $this->_em->flush(); + $this->em->flush(); } catch (OptimisticLockException $e) { - $this->assertSame($test, $e->getEntity()); + self::assertSame($test, $e->getEntity()); } } @@ -171,15 +174,15 @@ public function testLockWorksWithProxy() $test = new OptimisticStandard(); $test->name = 'test'; - $this->_em->persist($test); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($test); + $this->em->flush(); + $this->em->clear(); - $proxy = $this->_em->getReference(OptimisticStandard::class, $test->id); + $proxy = $this->em->getReference(OptimisticStandard::class, $test->id); - $this->_em->lock($proxy, LockMode::OPTIMISTIC, 1); + $this->em->lock($proxy, LockMode::OPTIMISTIC, 1); - $this->addToAssertionCount(1); + self::addToAssertionCount(1); } public function testOptimisticTimestampSetsDefaultValue() @@ -188,12 +191,12 @@ public function testOptimisticTimestampSetsDefaultValue() $test->name = 'Testing'; - $this->assertNull($test->version, "Pre-Condition"); + self::assertNull($test->version, "Pre-Condition"); - $this->_em->persist($test); - $this->_em->flush(); + $this->em->persist($test); + $this->em->flush(); - $this->assertInstanceOf('DateTime', $test->version); + self::assertInstanceOf('DateTime', $test->version); return $test; } @@ -203,18 +206,18 @@ public function testOptimisticTimestampSetsDefaultValue() */ public function testOptimisticTimestampFailureThrowsException(OptimisticTimestamp $entity) { - $q = $this->_em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticTimestamp t WHERE t.id = :id'); + $q = $this->em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticTimestamp t WHERE t.id = :id'); $q->setParameter('id', $entity->id); $test = $q->getSingleResult(); - $this->assertInstanceOf('DateTime', $test->version); + self::assertInstanceOf('DateTime', $test->version); // Manually increment the version datetime column - $format = $this->_em->getConnection()->getDatabasePlatform()->getDateTimeFormatString(); + $format = $this->em->getConnection()->getDatabasePlatform()->getDateTimeFormatString(); - $this->_conn->executeQuery('UPDATE optimistic_timestamp SET version = ? WHERE id = ?', [date($format, strtotime($test->version->format($format)) + 3600), $test->id] + $this->conn->executeQuery('UPDATE optimistic_timestamp SET version = ? WHERE id = ?', [date($format, strtotime($test->version->format($format)) + 3600), $test->id] ); // Try and update the record and it should throw an exception @@ -222,13 +225,13 @@ public function testOptimisticTimestampFailureThrowsException(OptimisticTimestam $test->name = 'Testing again'; try { - $this->_em->flush(); + $this->em->flush(); } catch (OptimisticLockException $e) { $caughtException = $e; } - $this->assertNotNull($caughtException, "No OptimisticLockingException was thrown"); - $this->assertSame($test, $caughtException->getEntity()); + self::assertNotNull($caughtException, "No OptimisticLockingException was thrown"); + self::assertSame($test, $caughtException->getEntity()); } @@ -237,89 +240,89 @@ public function testOptimisticTimestampFailureThrowsException(OptimisticTimestam */ public function testOptimisticTimestampLockFailureThrowsException(OptimisticTimestamp $entity) { - $q = $this->_em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticTimestamp t WHERE t.id = :id'); + $q = $this->em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticTimestamp t WHERE t.id = :id'); $q->setParameter('id', $entity->id); $test = $q->getSingleResult(); - $this->assertInstanceOf('DateTime', $test->version); + self::assertInstanceOf('DateTime', $test->version); // Try to lock the record with an older timestamp and it should throw an exception $caughtException = null; try { - $expectedVersionExpired = DateTime::createFromFormat('U', $test->version->getTimestamp()-3600); + $expectedVersionExpired = DateTime::createFromFormat('U', (string) ($test->version->getTimestamp()-3600)); - $this->_em->lock($test, LockMode::OPTIMISTIC, $expectedVersionExpired); + $this->em->lock($test, LockMode::OPTIMISTIC, $expectedVersionExpired); } catch (OptimisticLockException $e) { $caughtException = $e; } - $this->assertNotNull($caughtException, "No OptimisticLockingException was thrown"); - $this->assertSame($test, $caughtException->getEntity()); + self::assertNotNull($caughtException, "No OptimisticLockingException was thrown"); + self::assertSame($test, $caughtException->getEntity()); } } /** - * @Entity - * @Table(name="optimistic_joined_parent") - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="discr", type="string") - * @DiscriminatorMap({"parent" = "OptimisticJoinedParent", "child" = "OptimisticJoinedChild"}) + * @ORM\Entity + * @ORM\Table(name="optimistic_joined_parent") + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="discr", type="string") + * @ORM\DiscriminatorMap({"parent" = "OptimisticJoinedParent", "child" = "OptimisticJoinedChild"}) */ class OptimisticJoinedParent { /** - * @Id @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @Column(type="string", length=255) + * @ORM\Column(type="string", length=255) */ public $name; /** - * @Version @Column(type="integer") + * @ORM\Version @ORM\Column(type="integer") */ public $version; } /** - * @Entity - * @Table(name="optimistic_joined_child") + * @ORM\Entity + * @ORM\Table(name="optimistic_joined_child") */ class OptimisticJoinedChild extends OptimisticJoinedParent { /** - * @Column(type="string", length=255) + * @ORM\Column(type="string", length=255) */ public $whatever; } /** - * @Entity - * @Table(name="optimistic_standard") + * @ORM\Entity + * @ORM\Table(name="optimistic_standard") */ class OptimisticStandard { /** - * @Id @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @Column(type="string", length=255) + * @ORM\Column(type="string", length=255) */ public $name; /** - * @Version @Column(type="integer") + * @ORM\Version @ORM\Column(type="integer") */ private $version; @@ -330,24 +333,24 @@ public function getVersion() } /** - * @Entity - * @Table(name="optimistic_timestamp") + * @ORM\Entity + * @ORM\Table(name="optimistic_timestamp") */ class OptimisticTimestamp { /** - * @Id @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @Column(type="string", length=255) + * @ORM\Column(type="string", length=255) */ public $name; /** - * @Version @Column(type="datetime") + * @ORM\Version @ORM\Column(type="datetime") */ public $version; } diff --git a/tests/Doctrine/Tests/ORM/Functional/ManyToManyBasicAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/ManyToManyBasicAssociationTest.php index 0436b2af762..59377e160c9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ManyToManyBasicAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToManyBasicAssociationTest.php @@ -1,9 +1,12 @@ groups[0]->users[0]); // inverse side unset($user->groups[0]); // owning side! - $this->_em->flush(); + $this->em->flush(); // Check that the link in the association table has been deleted - $this->assertGblancoGroupCountIs(0); + self::assertGblancoGroupCountIs(0); } public function testBasicManyToManyJoin() { $user = $this->addCmsUserGblancoWithGroups(1); - $this->_em->clear(); + $this->em->clear(); - $this->assertEquals(0, $this->_em->getUnitOfWork()->size()); + self::assertEquals(0, $this->em->getUnitOfWork()->size()); - $query = $this->_em->createQuery("select u, g from Doctrine\Tests\Models\CMS\CmsUser u join u.groups g"); + $query = $this->em->createQuery("select u, g from Doctrine\Tests\Models\CMS\CmsUser u join u.groups g"); $result = $query->getResult(); - $this->assertEquals(2, $this->_em->getUnitOfWork()->size()); - $this->assertInstanceOf(CmsUser::class, $result[0]); - $this->assertEquals('Guilherme', $result[0]->name); - $this->assertEquals(1, $result[0]->getGroups()->count()); + self::assertEquals(2, $this->em->getUnitOfWork()->size()); + self::assertInstanceOf(CmsUser::class, $result[0]); + self::assertEquals('Guilherme', $result[0]->name); + self::assertEquals(1, $result[0]->getGroups()->count()); $groups = $result[0]->getGroups(); - $this->assertEquals('Developers_0', $groups[0]->getName()); + self::assertEquals('Developers_0', $groups[0]->getName()); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($result[0])); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($groups[0])); + self::assertEquals(UnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($result[0])); + self::assertEquals(UnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($groups[0])); - $this->assertInstanceOf(PersistentCollection::class, $groups); - $this->assertInstanceOf(PersistentCollection::class, $groups[0]->getUsers()); + self::assertInstanceOf(PersistentCollection::class, $groups); + self::assertInstanceOf(PersistentCollection::class, $groups[0]->getUsers()); $groups[0]->getUsers()->clear(); $groups->clear(); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery("select u, g from Doctrine\Tests\Models\CMS\CmsUser u join u.groups g"); - $this->assertEquals(0, count($query->getResult())); + $query = $this->em->createQuery("select u, g from Doctrine\Tests\Models\CMS\CmsUser u join u.groups g"); + self::assertEquals(0, count($query->getResult())); } public function testManyToManyAddRemove() { $user = $this->addCmsUserGblancoWithGroups(2); - $this->_em->clear(); + $this->em->clear(); - $uRep = $this->_em->getRepository(get_class($user)); + $uRep = $this->em->getRepository(get_class($user)); // Get user $user = $uRep->findOneById($user->getId()); - $this->assertNotNull($user, "Has to return exactly one entry."); + self::assertNotNull($user, "Has to return exactly one entry."); - $this->assertFalse($user->getGroups()->isInitialized()); + self::assertFalse($user->getGroups()->isInitialized()); // Check groups - $this->assertEquals(2, $user->getGroups()->count()); + self::assertEquals(2, $user->getGroups()->count()); - $this->assertTrue($user->getGroups()->isInitialized()); + self::assertTrue($user->getGroups()->isInitialized()); // Remove first group unset($user->groups[0]); //$user->getGroups()->remove(0); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); // Reload same user $user2 = $uRep->findOneById($user->getId()); // Check groups - $this->assertEquals(1, $user2->getGroups()->count()); + self::assertEquals(1, $user2->getGroups()->count()); } public function testManyToManyInverseSideIgnored() @@ -115,16 +118,16 @@ public function testManyToManyInverseSideIgnored() // modify directly, addUser() would also (properly) set the owning side $group->users[] = $user; - $this->_em->persist($user); - $this->_em->persist($group); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->persist($group); + $this->em->flush(); + $this->em->clear(); // Association should not exist - $user2 = $this->_em->find(get_class($user), $user->getId()); + $user2 = $this->em->find(get_class($user), $user->getId()); - $this->assertNotNull($user2, "Has to return exactly one entry."); - $this->assertEquals(0, $user2->getGroups()->count()); + self::assertNotNull($user2, "Has to return exactly one entry."); + self::assertEquals(0, $user2->getGroups()->count()); } public function testManyToManyCollectionClearing() @@ -132,14 +135,14 @@ public function testManyToManyCollectionClearing() $user = $this->addCmsUserGblancoWithGroups($groupCount = 10); // Check that there are indeed 10 links in the association table - $this->assertGblancoGroupCountIs($groupCount); + self::assertGblancoGroupCountIs($groupCount); $user->groups->clear(); - $this->_em->flush(); + $this->em->flush(); // Check that the links in the association table have been deleted - $this->assertGblancoGroupCountIs(0); + self::assertGblancoGroupCountIs(0); } public function testManyToManyCollectionClearAndAdd() @@ -153,14 +156,14 @@ public function testManyToManyCollectionClearAndAdd() $user->groups[] = $group; } - $this->assertInstanceOf(PersistentCollection::class, $user->groups); - $this->assertTrue($user->groups->isDirty()); + self::assertInstanceOf(PersistentCollection::class, $user->groups); + self::assertTrue($user->groups->isDirty()); - $this->assertEquals($groupCount, count($user->groups), "There should be 10 groups in the collection."); + self::assertEquals($groupCount, count($user->groups), "There should be 10 groups in the collection."); - $this->_em->flush(); + $this->em->flush(); - $this->assertGblancoGroupCountIs($groupCount); + self::assertGblancoGroupCountIs($groupCount); } /** @@ -169,9 +172,9 @@ public function testManyToManyCollectionClearAndAdd() public function assertGblancoGroupCountIs($expectedGroupCount) { $countDql = "SELECT count(g.id) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g WHERE u.username = 'gblanco'"; - $this->assertEquals( + self::assertEquals( $expectedGroupCount, - $this->_em->createQuery($countDql)->getSingleScalarResult(), + $this->em->createQuery($countDql)->getSingleScalarResult(), "Failed to verify that CmsUser with username 'gblanco' has a group count of 10 with a DQL count query." ); } @@ -182,29 +185,29 @@ public function testRetrieveManyToManyAndAddMore() $group = new CmsGroup(); $group->name = 'Developers_Fresh'; - $this->_em->persist($group); - $this->_em->flush(); + $this->em->persist($group); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); /* @var $freshUser CmsUser */ - $freshUser = $this->_em->find(CmsUser::class, $user->getId()); + $freshUser = $this->em->find(CmsUser::class, $user->getId()); $newGroup = new CmsGroup(); $newGroup->setName('12Monkeys'); $freshUser->addGroup($newGroup); - $this->assertFalse($freshUser->groups->isInitialized(), "CmsUser::groups Collection has to be uninitialized for this test."); + self::assertFalse($freshUser->groups->isInitialized(), "CmsUser::groups Collection has to be uninitialized for this test."); - $this->_em->flush(); + $this->em->flush(); - $this->assertFalse($freshUser->groups->isInitialized(), "CmsUser::groups Collection has to be uninitialized for this test."); - $this->assertEquals(3, count($freshUser->getGroups())); - $this->assertEquals(3, count($freshUser->getGroups()->getSnapshot()), "Snapshot of CmsUser::groups should contain 3 entries."); + self::assertFalse($freshUser->groups->isInitialized(), "CmsUser::groups Collection has to be uninitialized for this test."); + self::assertEquals(3, count($freshUser->getGroups())); + self::assertEquals(3, count($freshUser->getGroups()->getSnapshot()), "Snapshot of CmsUser::groups should contain 3 entries."); - $this->_em->clear(); + $this->em->clear(); - $freshUser = $this->_em->find(CmsUser::class, $user->getId()); - $this->assertEquals(3, count($freshUser->getGroups())); + $freshUser = $this->em->find(CmsUser::class, $user->getId()); + self::assertEquals(3, count($freshUser->getGroups())); } /** @@ -215,11 +218,11 @@ public function testRemoveUserWithManyGroups() $user = $this->addCmsUserGblancoWithGroups(2); $userId = $user->getId(); - $this->_em->remove($user); - $this->_em->flush(); + $this->em->remove($user); + $this->em->flush(); - $newUser = $this->_em->find(get_class($user), $userId); - $this->assertNull($newUser); + $newUser = $this->em->find(get_class($user), $userId); + self::assertNull($newUser); } /** @@ -230,13 +233,13 @@ public function testRemoveGroupWithUser() $user = $this->addCmsUserGblancoWithGroups(2); foreach ($user->getGroups() AS $group) { - $this->_em->remove($group); + $this->em->remove($group); } - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $newUser = $this->_em->find(get_class($user), $user->getId()); - $this->assertEquals(0, count($newUser->getGroups())); + $newUser = $this->em->find(get_class($user), $user->getId()); + self::assertEquals(0, count($newUser->getGroups())); } public function testDereferenceCollectionDelete() @@ -244,11 +247,11 @@ public function testDereferenceCollectionDelete() $user = $this->addCmsUserGblancoWithGroups(2); $user->groups = null; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $newUser = $this->_em->find(get_class($user), $user->getId()); - $this->assertEquals(0, count($newUser->getGroups())); + $newUser = $this->em->find(get_class($user), $user->getId()); + self::assertEquals(0, count($newUser->getGroups())); } /** @@ -259,24 +262,24 @@ public function testWorkWithDqlHydratedEmptyCollection() $user = $this->addCmsUserGblancoWithGroups(0); $group = new CmsGroup(); $group->name = "Developers0"; - $this->_em->persist($group); + $this->em->persist($group); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $newUser = $this->_em->createQuery('SELECT u, g FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.groups g WHERE u.id = ?1') + $newUser = $this->em->createQuery('SELECT u, g FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.groups g WHERE u.id = ?1') ->setParameter(1, $user->getId()) ->getSingleResult(); - $this->assertEquals(0, count($newUser->groups)); - $this->assertInternalType('array', $newUser->groups->getMapping()); + self::assertEquals(0, count($newUser->groups)); + self::assertInstanceOf(ManyToManyAssociationMetadata::class, $newUser->groups->getMapping()); $newUser->addGroup($group); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $newUser = $this->_em->find(get_class($user), $user->getId()); - $this->assertEquals(1, count($newUser->groups)); + $newUser = $this->em->find(get_class($user), $user->getId()); + self::assertEquals(1, count($newUser->groups)); } /** @@ -296,14 +299,23 @@ public function addCmsUserGblancoWithGroups($groupCount = 1) $user->addGroup($group); } - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); - $this->assertNotNull($user->getId(), "User 'gblanco' should have an ID assigned after the persist()/flush() operation."); + self::assertNotNull($user->getId(), "User 'gblanco' should have an ID assigned after the persist()/flush() operation."); return $user; } + /** + * @group DDC-980 + */ + public function testUpdateDeleteSizeSubselectQueries() + { + $this->em->createQuery("DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE SIZE(u.groups) = 10")->execute(); + $this->em->createQuery("UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = 'inactive' WHERE SIZE(u.groups) = 10")->execute(); + } + /** * @group DDC-978 */ @@ -315,26 +327,26 @@ public function testClearAndResetCollection() $group2 = new CmsGroup; $group2->name = 'Developers_New2'; - $this->_em->persist($group1); - $this->_em->persist($group2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($group1); + $this->em->persist($group2); + $this->em->flush(); + $this->em->clear(); - $user = $this->_em->find(get_class($user), $user->id); + $user = $this->em->find(get_class($user), $user->id); $coll = new ArrayCollection([$group1, $group2]); $user->groups = $coll; - $this->_em->flush(); - $this->assertInstanceOf(PersistentCollection::class, $user->groups, + $this->em->flush(); + self::assertInstanceOf(PersistentCollection::class, $user->groups, "UnitOfWork should have replaced ArrayCollection with PersistentCollection."); - $this->_em->flush(); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); - $user = $this->_em->find(get_class($user), $user->id); - $this->assertEquals(2, count($user->groups)); - $this->assertEquals('Developers_New1', $user->groups[0]->name); - $this->assertEquals('Developers_New2', $user->groups[1]->name); + $user = $this->em->find(get_class($user), $user->id); + self::assertEquals(2, count($user->groups)); + self::assertEquals('Developers_New1', $user->groups[0]->name); + self::assertEquals('Developers_New2', $user->groups[1]->name); } /** @@ -343,13 +355,13 @@ public function testClearAndResetCollection() public function testInitializePersistentCollection() { $user = $this->addCmsUserGblancoWithGroups(2); - $this->_em->clear(); + $this->em->clear(); - $user = $this->_em->find(get_class($user), $user->id); + $user = $this->em->find(get_class($user), $user->id); - $this->assertFalse($user->groups->isInitialized(), "Pre-condition: lazy collection"); - $this->_em->getUnitOfWork()->initializeObject($user->groups); - $this->assertTrue($user->groups->isInitialized(), "Collection should be initialized after calling UnitOfWork::initializeObject()"); + self::assertFalse($user->groups->isInitialized(), "Pre-condition: lazy collection"); + $this->em->getUnitOfWork()->initializeObject($user->groups); + self::assertTrue($user->groups->isInitialized(), "Collection should be initialized after calling UnitOfWork::initializeObject()"); } /** @@ -360,16 +372,16 @@ public function testClearBeforeLazyLoad() { $user = $this->addCmsUserGblancoWithGroups(4); - $this->_em->clear(); + $this->em->clear(); - $user = $this->_em->find(get_class($user), $user->id); + $user = $this->em->find(get_class($user), $user->id); $user->groups->clear(); - $this->assertEquals(0, count($user->groups)); + self::assertEquals(0, count($user->groups)); - $this->_em->flush(); + $this->em->flush(); - $user = $this->_em->find(get_class($user), $user->id); - $this->assertEquals(0, count($user->groups)); + $user = $this->em->find(get_class($user), $user->id); + self::assertEquals(0, count($user->groups)); } /** @@ -391,17 +403,17 @@ public function testManyToManyOrderByIsNotIgnored() $user->addGroup($group2); $user->addGroup($group3); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); - $user = $this->_em->find(get_class($user), $user->id); + $user = $this->em->find(get_class($user), $user->id); $criteria = Criteria::create() ->orderBy(['name' => Criteria::ASC]); - $this->assertEquals( + self::assertEquals( ['A', 'B', 'C', 'Developers_0'], $user ->getGroups() @@ -435,17 +447,17 @@ public function testManyToManyOrderByHonorsFieldNameColumnNameAliases() $user->addTag($tag2); $user->addTag($tag3); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); - $user = $this->_em->find(get_class($user), $user->id); + $user = $this->em->find(get_class($user), $user->id); $criteria = Criteria::create() ->orderBy(['name' => Criteria::ASC]); - $this->assertEquals( + self::assertEquals( ['A', 'B', 'C'], $user ->getTags() @@ -460,84 +472,89 @@ public function testManyToManyOrderByHonorsFieldNameColumnNameAliases() public function testMatchingWithLimit() { $user = $this->addCmsUserGblancoWithGroups(2); - $this->_em->clear(); + $this->em->clear(); - $user = $this->_em->find(get_class($user), $user->id); + $user = $this->em->find(get_class($user), $user->id); $groups = $user->groups; - $this->assertFalse($user->groups->isInitialized(), "Pre-condition: lazy collection"); + self::assertFalse($user->groups->isInitialized(), "Pre-condition: lazy collection"); $criteria = Criteria::create()->setMaxResults(1); $result = $groups->matching($criteria); - $this->assertCount(1, $result); + self::assertCount(1, $result); - $this->assertFalse($user->groups->isInitialized(), "Post-condition: matching does not initialize collection"); + self::assertFalse($user->groups->isInitialized(), "Post-condition: matching does not initialize collection"); } public function testMatchingWithOffset() { $user = $this->addCmsUserGblancoWithGroups(2); - $this->_em->clear(); + $this->em->clear(); - $user = $this->_em->find(get_class($user), $user->id); + $user = $this->em->find(get_class($user), $user->id); $groups = $user->groups; - $this->assertFalse($user->groups->isInitialized(), "Pre-condition: lazy collection"); + self::assertFalse($user->groups->isInitialized(), "Pre-condition: lazy collection"); $criteria = Criteria::create()->setFirstResult(1); $result = $groups->matching($criteria); - $this->assertCount(1, $result); + self::assertCount(1, $result); $firstGroup = $result->first(); - $this->assertEquals('Developers_1', $firstGroup->name); + self::assertEquals('Developers_1', $firstGroup->name); - $this->assertFalse($user->groups->isInitialized(), "Post-condition: matching does not initialize collection"); + self::assertFalse($user->groups->isInitialized(), "Post-condition: matching does not initialize collection"); } public function testMatchingWithLimitAndOffset() { $user = $this->addCmsUserGblancoWithGroups(5); - $this->_em->clear(); + $this->em->clear(); - $user = $this->_em->find(get_class($user), $user->id); + $user = $this->em->find(get_class($user), $user->id); $groups = $user->groups; - $this->assertFalse($user->groups->isInitialized(), "Pre-condition: lazy collection"); + self::assertFalse($user->groups->isInitialized(), "Pre-condition: lazy collection"); - $criteria = Criteria::create()->setFirstResult(1)->setMaxResults(3); - $result = $groups->matching($criteria); + $criteria = Criteria::create() + ->orderBy(['id' => Criteria::ASC]) + ->setFirstResult(1) + ->setMaxResults(3) + ; + + $result = $groups->matching($criteria); - $this->assertCount(3, $result); + self::assertCount(3, $result); $firstGroup = $result->first(); - $this->assertEquals('Developers_1', $firstGroup->name); + self::assertEquals('Developers_1', $firstGroup->name); $lastGroup = $result->last(); - $this->assertEquals('Developers_3', $lastGroup->name); + self::assertEquals('Developers_3', $lastGroup->name); - $this->assertFalse($user->groups->isInitialized(), "Post-condition: matching does not initialize collection"); + self::assertFalse($user->groups->isInitialized(), "Post-condition: matching does not initialize collection"); } public function testMatching() { $user = $this->addCmsUserGblancoWithGroups(2); - $this->_em->clear(); + $this->em->clear(); - $user = $this->_em->find(get_class($user), $user->id); + $user = $this->em->find(get_class($user), $user->id); $groups = $user->groups; - $this->assertFalse($user->groups->isInitialized(), "Pre-condition: lazy collection"); + self::assertFalse($user->groups->isInitialized(), "Pre-condition: lazy collection"); $criteria = Criteria::create()->where(Criteria::expr()->eq('name', (string) 'Developers_0')); $result = $groups->matching($criteria); - $this->assertCount(1, $result); + self::assertCount(1, $result); $firstGroup = $result->first(); - $this->assertEquals('Developers_0', $firstGroup->name); + self::assertEquals('Developers_0', $firstGroup->name); - $this->assertFalse($user->groups->isInitialized(), "Post-condition: matching does not initialize collection"); + self::assertFalse($user->groups->isInitialized(), "Post-condition: matching does not initialize collection"); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ManyToManyBidirectionalAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/ManyToManyBidirectionalAssociationTest.php index 9c70ab7f6aa..f55885aecec 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ManyToManyBidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToManyBidirectionalAssociationTest.php @@ -1,5 +1,7 @@ useModelSet('ecommerce'); + parent::setUp(); + $this->firstProduct = new ECommerceProduct(); $this->firstProduct->setName("First Product"); + $this->secondProduct = new ECommerceProduct(); $this->secondProduct->setName("Second Product"); + $this->firstCategory = new ECommerceCategory(); $this->firstCategory->setName("Business"); + $this->secondCategory = new ECommerceCategory(); $this->secondCategory->setName("Home"); } @@ -39,91 +46,110 @@ public function testSavesAManyToManyAssociationWithCascadeSaveSet() { $this->firstProduct->addCategory($this->firstCategory); $this->firstProduct->addCategory($this->secondCategory); - $this->_em->persist($this->firstProduct); - $this->_em->flush(); + + $this->em->persist($this->firstProduct); + $this->em->flush(); - $this->assertForeignKeysContain($this->firstProduct->getId(), $this->firstCategory->getId()); - $this->assertForeignKeysContain($this->firstProduct->getId(), $this->secondCategory->getId()); + self::assertForeignKeysContain($this->firstProduct->getId(), $this->firstCategory->getId()); + self::assertForeignKeysContain($this->firstProduct->getId(), $this->secondCategory->getId()); } public function testRemovesAManyToManyAssociation() { $this->firstProduct->addCategory($this->firstCategory); $this->firstProduct->addCategory($this->secondCategory); - $this->_em->persist($this->firstProduct); + + $this->em->persist($this->firstProduct); + $this->firstProduct->removeCategory($this->firstCategory); - $this->_em->flush(); + $this->em->flush(); - $this->assertForeignKeysNotContain($this->firstProduct->getId(), $this->firstCategory->getId()); - $this->assertForeignKeysContain($this->firstProduct->getId(), $this->secondCategory->getId()); + self::assertForeignKeysNotContain($this->firstProduct->getId(), $this->firstCategory->getId()); + self::assertForeignKeysContain($this->firstProduct->getId(), $this->secondCategory->getId()); $this->firstProduct->getCategories()->remove(1); - $this->_em->flush(); + + $this->em->flush(); - $this->assertForeignKeysNotContain($this->firstProduct->getId(), $this->secondCategory->getId()); + self::assertForeignKeysNotContain($this->firstProduct->getId(), $this->secondCategory->getId()); } public function testEagerLoadFromInverseSideAndLazyLoadFromOwningSide() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_createLoadingFixture(); - $categories = $this->_findCategories(); - $this->assertLazyLoadFromOwningSide($categories); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + $this->createLoadingFixture(); + + $categories = $this->findCategories(); + + self::assertLazyLoadFromOwningSide($categories); } public function testEagerLoadFromOwningSideAndLazyLoadFromInverseSide() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_createLoadingFixture(); - $products = $this->_findProducts(); - $this->assertLazyLoadFromInverseSide($products); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + $this->createLoadingFixture(); + + $products = $this->findProducts(); + + self::assertLazyLoadFromInverseSide($products); } - private function _createLoadingFixture() + private function createLoadingFixture() { $this->firstProduct->addCategory($this->firstCategory); $this->firstProduct->addCategory($this->secondCategory); + $this->secondProduct->addCategory($this->firstCategory); $this->secondProduct->addCategory($this->secondCategory); - $this->_em->persist($this->firstProduct); - $this->_em->persist($this->secondProduct); + + $this->em->persist($this->firstProduct); + $this->em->persist($this->secondProduct); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); } - protected function _findProducts() + protected function findProducts() { - $query = $this->_em->createQuery('SELECT p, c FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p LEFT JOIN p.categories c ORDER BY p.id, c.id'); + $query = $this->em->createQuery('SELECT p, c FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p LEFT JOIN p.categories c ORDER BY p.id, c.id'); //$query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true); + $result = $query->getResult(); - $this->assertEquals(2, count($result)); + + self::assertEquals(2, count($result)); + $cats1 = $result[0]->getCategories(); $cats2 = $result[1]->getCategories(); - $this->assertTrue($cats1->isInitialized()); - $this->assertTrue($cats2->isInitialized()); - $this->assertFalse($cats1[0]->getProducts()->isInitialized()); - $this->assertFalse($cats2[0]->getProducts()->isInitialized()); + + self::assertTrue($cats1->isInitialized()); + self::assertTrue($cats2->isInitialized()); + + self::assertFalse($cats1[0]->getProducts()->isInitialized()); + self::assertFalse($cats2[0]->getProducts()->isInitialized()); return $result; } - protected function _findCategories() + protected function findCategories() { - $query = $this->_em->createQuery('SELECT c, p FROM Doctrine\Tests\Models\ECommerce\ECommerceCategory c LEFT JOIN c.products p ORDER BY c.id, p.id'); + $query = $this->em->createQuery('SELECT c, p FROM Doctrine\Tests\Models\ECommerce\ECommerceCategory c LEFT JOIN c.products p ORDER BY c.id, p.id'); //$query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true); + $result = $query->getResult(); - $this->assertEquals(2, count($result)); - $this->assertInstanceOf(ECommerceCategory::class, $result[0]); - $this->assertInstanceOf(ECommerceCategory::class, $result[1]); + + self::assertEquals(2, count($result)); + self::assertInstanceOf(ECommerceCategory::class, $result[0]); + self::assertInstanceOf(ECommerceCategory::class, $result[1]); + $prods1 = $result[0]->getProducts(); $prods2 = $result[1]->getProducts(); - $this->assertTrue($prods1->isInitialized()); - $this->assertTrue($prods2->isInitialized()); + + self::assertTrue($prods1->isInitialized()); + self::assertTrue($prods2->isInitialized()); - $this->assertFalse($prods1[0]->getCategories()->isInitialized()); - $this->assertFalse($prods2[0]->getCategories()->isInitialized()); + self::assertFalse($prods1[0]->getCategories()->isInitialized()); + self::assertFalse($prods2[0]->getCategories()->isInitialized()); return $result; } @@ -135,32 +161,32 @@ public function assertLazyLoadFromInverseSide($products) $firstProductCategories = $firstProduct->getCategories(); $secondProductCategories = $secondProduct->getCategories(); - $this->assertEquals(2, count($firstProductCategories)); - $this->assertEquals(2, count($secondProductCategories)); + self::assertEquals(2, count($firstProductCategories)); + self::assertEquals(2, count($secondProductCategories)); - $this->assertTrue($firstProductCategories[0] === $secondProductCategories[0]); - $this->assertTrue($firstProductCategories[1] === $secondProductCategories[1]); + self::assertTrue($firstProductCategories[0] === $secondProductCategories[0]); + self::assertTrue($firstProductCategories[1] === $secondProductCategories[1]); $firstCategoryProducts = $firstProductCategories[0]->getProducts(); $secondCategoryProducts = $firstProductCategories[1]->getProducts(); - $this->assertFalse($firstCategoryProducts->isInitialized()); - $this->assertFalse($secondCategoryProducts->isInitialized()); - $this->assertEquals(0, $firstCategoryProducts->unwrap()->count()); - $this->assertEquals(0, $secondCategoryProducts->unwrap()->count()); + self::assertFalse($firstCategoryProducts->isInitialized()); + self::assertFalse($secondCategoryProducts->isInitialized()); + self::assertEquals(0, $firstCategoryProducts->unwrap()->count()); + self::assertEquals(0, $secondCategoryProducts->unwrap()->count()); - $this->assertEquals(2, count($firstCategoryProducts)); // lazy-load - $this->assertTrue($firstCategoryProducts->isInitialized()); - $this->assertFalse($secondCategoryProducts->isInitialized()); - $this->assertEquals(2, count($secondCategoryProducts)); // lazy-load - $this->assertTrue($secondCategoryProducts->isInitialized()); + self::assertEquals(2, count($firstCategoryProducts)); // lazy-load + self::assertTrue($firstCategoryProducts->isInitialized()); + self::assertFalse($secondCategoryProducts->isInitialized()); + self::assertEquals(2, count($secondCategoryProducts)); // lazy-load + self::assertTrue($secondCategoryProducts->isInitialized()); - $this->assertInstanceOf(ECommerceProduct::class, $firstCategoryProducts[0]); - $this->assertInstanceOf(ECommerceProduct::class, $firstCategoryProducts[1]); - $this->assertInstanceOf(ECommerceProduct::class, $secondCategoryProducts[0]); - $this->assertInstanceOf(ECommerceProduct::class, $secondCategoryProducts[1]); + self::assertInstanceOf(ECommerceProduct::class, $firstCategoryProducts[0]); + self::assertInstanceOf(ECommerceProduct::class, $firstCategoryProducts[1]); + self::assertInstanceOf(ECommerceProduct::class, $secondCategoryProducts[0]); + self::assertInstanceOf(ECommerceProduct::class, $secondCategoryProducts[1]); - $this->assertCollectionEquals($firstCategoryProducts, $secondCategoryProducts); + self::assertCollectionEquals($firstCategoryProducts, $secondCategoryProducts); } public function assertLazyLoadFromOwningSide($categories) @@ -170,31 +196,31 @@ public function assertLazyLoadFromOwningSide($categories) $firstCategoryProducts = $firstCategory->getProducts(); $secondCategoryProducts = $secondCategory->getProducts(); - $this->assertEquals(2, count($firstCategoryProducts)); - $this->assertEquals(2, count($secondCategoryProducts)); + self::assertEquals(2, count($firstCategoryProducts)); + self::assertEquals(2, count($secondCategoryProducts)); - $this->assertTrue($firstCategoryProducts[0] === $secondCategoryProducts[0]); - $this->assertTrue($firstCategoryProducts[1] === $secondCategoryProducts[1]); + self::assertTrue($firstCategoryProducts[0] === $secondCategoryProducts[0]); + self::assertTrue($firstCategoryProducts[1] === $secondCategoryProducts[1]); $firstProductCategories = $firstCategoryProducts[0]->getCategories(); $secondProductCategories = $firstCategoryProducts[1]->getCategories(); - $this->assertFalse($firstProductCategories->isInitialized()); - $this->assertFalse($secondProductCategories->isInitialized()); - $this->assertEquals(0, $firstProductCategories->unwrap()->count()); - $this->assertEquals(0, $secondProductCategories->unwrap()->count()); + self::assertFalse($firstProductCategories->isInitialized()); + self::assertFalse($secondProductCategories->isInitialized()); + self::assertEquals(0, $firstProductCategories->unwrap()->count()); + self::assertEquals(0, $secondProductCategories->unwrap()->count()); - $this->assertEquals(2, count($firstProductCategories)); // lazy-load - $this->assertTrue($firstProductCategories->isInitialized()); - $this->assertFalse($secondProductCategories->isInitialized()); - $this->assertEquals(2, count($secondProductCategories)); // lazy-load - $this->assertTrue($secondProductCategories->isInitialized()); + self::assertEquals(2, count($firstProductCategories)); // lazy-load + self::assertTrue($firstProductCategories->isInitialized()); + self::assertFalse($secondProductCategories->isInitialized()); + self::assertEquals(2, count($secondProductCategories)); // lazy-load + self::assertTrue($secondProductCategories->isInitialized()); - $this->assertInstanceOf(ECommerceCategory::class, $firstProductCategories[0]); - $this->assertInstanceOf(ECommerceCategory::class, $firstProductCategories[1]); - $this->assertInstanceOf(ECommerceCategory::class, $secondProductCategories[0]); - $this->assertInstanceOf(ECommerceCategory::class, $secondProductCategories[1]); + self::assertInstanceOf(ECommerceCategory::class, $firstProductCategories[0]); + self::assertInstanceOf(ECommerceCategory::class, $firstProductCategories[1]); + self::assertInstanceOf(ECommerceCategory::class, $secondProductCategories[0]); + self::assertInstanceOf(ECommerceCategory::class, $secondProductCategories[1]); - $this->assertCollectionEquals($firstProductCategories, $secondProductCategories); + self::assertCollectionEquals($firstProductCategories, $secondProductCategories); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ManyToManyEventTest.php b/tests/Doctrine/Tests/ORM/Functional/ManyToManyEventTest.php index 87283ec4bf1..047d6e10a65 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ManyToManyEventTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToManyEventTest.php @@ -1,5 +1,7 @@ useModelSet('cms'); parent::setUp(); $this->listener = new PostUpdateListener(); - $evm = $this->_em->getEventManager(); + $evm = $this->em->getEventManager(); $evm->addEventListener(Events::postUpdate, $this->listener); } public function testListenerShouldBeNotifiedOnlyWhenUpdating() { $user = $this->createNewValidUser(); - $this->_em->persist($user); - $this->_em->flush(); - $this->assertFalse($this->listener->wasNotified); + $this->em->persist($user); + $this->em->flush(); + self::assertFalse($this->listener->wasNotified); $group = new CmsGroup(); $group->name = "admins"; $user->addGroup($group); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); - $this->assertTrue($this->listener->wasNotified); + self::assertTrue($this->listener->wasNotified); } /** diff --git a/tests/Doctrine/Tests/ORM/Functional/ManyToManySelfReferentialAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/ManyToManySelfReferentialAssociationTest.php index 559cd4ba662..6c5524d6e28 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ManyToManySelfReferentialAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToManySelfReferentialAssociationTest.php @@ -1,7 +1,10 @@ useModelSet('ecommerce'); + parent::setUp(); + $this->firstProduct = new ECommerceProduct(); $this->secondProduct = new ECommerceProduct(); $this->firstRelated = new ECommerceProduct(); + $this->firstRelated->setName("Business"); + $this->secondRelated = new ECommerceProduct(); + $this->secondRelated->setName("Home"); } @@ -37,86 +45,88 @@ public function testSavesAManyToManyAssociationWithCascadeSaveSet() { $this->firstProduct->addRelated($this->firstRelated); $this->firstProduct->addRelated($this->secondRelated); - $this->_em->persist($this->firstProduct); - $this->_em->flush(); - $this->assertForeignKeysContain($this->firstProduct->getId(), - $this->firstRelated->getId()); - $this->assertForeignKeysContain($this->firstProduct->getId(), - $this->secondRelated->getId()); + $this->em->persist($this->firstProduct); + $this->em->flush(); + + self::assertForeignKeysContain($this->firstProduct->getId(), $this->firstRelated->getId()); + self::assertForeignKeysContain($this->firstProduct->getId(), $this->secondRelated->getId()); } public function testRemovesAManyToManyAssociation() { $this->firstProduct->addRelated($this->firstRelated); $this->firstProduct->addRelated($this->secondRelated); - $this->_em->persist($this->firstProduct); + + $this->em->persist($this->firstProduct); + $this->firstProduct->removeRelated($this->firstRelated); - $this->_em->flush(); + $this->em->flush(); - $this->assertForeignKeysNotContain($this->firstProduct->getId(), - $this->firstRelated->getId()); - $this->assertForeignKeysContain($this->firstProduct->getId(), - $this->secondRelated->getId()); + self::assertForeignKeysNotContain($this->firstProduct->getId(), $this->firstRelated->getId()); + self::assertForeignKeysContain($this->firstProduct->getId(), $this->secondRelated->getId()); } public function testEagerLoadsOwningSide() { - $this->_createLoadingFixture(); - $products = $this->_findProducts(); - $this->assertLoadingOfOwningSide($products); + $this->createLoadingFixture(); + + $products = $this->findProducts(); + + self::assertLoadingOfOwningSide($products); } public function testLazyLoadsOwningSide() { - $this->_createLoadingFixture(); + $this->createLoadingFixture(); - $metadata = $this->_em->getClassMetadata(ECommerceProduct::class); - $metadata->associationMappings['related']['fetch'] = ClassMetadata::FETCH_LAZY; + $metadata = $this->em->getClassMetadata(ECommerceProduct::class); + $metadata->getProperty('related')->setFetchMode(FetchMode::LAZY); - $query = $this->_em->createQuery('SELECT p FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p'); + $query = $this->em->createQuery('SELECT p FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p'); $products = $query->getResult(); - $this->assertLoadingOfOwningSide($products); + + self::assertLoadingOfOwningSide($products); } public function assertLoadingOfOwningSide($products) { list ($firstProduct, $secondProduct) = $products; - $this->assertEquals(2, count($firstProduct->getRelated())); - $this->assertEquals(2, count($secondProduct->getRelated())); + self::assertEquals(2, count($firstProduct->getRelated())); + self::assertEquals(2, count($secondProduct->getRelated())); $categories = $firstProduct->getRelated(); $firstRelatedBy = $categories[0]->getRelated(); $secondRelatedBy = $categories[1]->getRelated(); - $this->assertEquals(2, count($firstRelatedBy)); - $this->assertEquals(2, count($secondRelatedBy)); + self::assertEquals(2, count($firstRelatedBy)); + self::assertEquals(2, count($secondRelatedBy)); - $this->assertInstanceOf(ECommerceProduct::class, $firstRelatedBy[0]); - $this->assertInstanceOf(ECommerceProduct::class, $firstRelatedBy[1]); - $this->assertInstanceOf(ECommerceProduct::class, $secondRelatedBy[0]); - $this->assertInstanceOf(ECommerceProduct::class, $secondRelatedBy[1]); + self::assertInstanceOf(ECommerceProduct::class, $firstRelatedBy[0]); + self::assertInstanceOf(ECommerceProduct::class, $firstRelatedBy[1]); + self::assertInstanceOf(ECommerceProduct::class, $secondRelatedBy[0]); + self::assertInstanceOf(ECommerceProduct::class, $secondRelatedBy[1]); - $this->assertCollectionEquals($firstRelatedBy, $secondRelatedBy); + self::assertCollectionEquals($firstRelatedBy, $secondRelatedBy); } - protected function _createLoadingFixture() + protected function createLoadingFixture() { $this->firstProduct->addRelated($this->firstRelated); $this->firstProduct->addRelated($this->secondRelated); $this->secondProduct->addRelated($this->firstRelated); $this->secondProduct->addRelated($this->secondRelated); - $this->_em->persist($this->firstProduct); - $this->_em->persist($this->secondProduct); + $this->em->persist($this->firstProduct); + $this->em->persist($this->secondProduct); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); } - protected function _findProducts() + protected function findProducts() { - $query = $this->_em->createQuery('SELECT p, r FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p LEFT JOIN p.related r ORDER BY p.id, r.id'); + $query = $this->em->createQuery('SELECT p, r FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p LEFT JOIN p.related r ORDER BY p.id, r.id'); return $query->getResult(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ManyToManyUnidirectionalAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/ManyToManyUnidirectionalAssociationTest.php index 20e31db00df..ca862c3cbbb 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ManyToManyUnidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToManyUnidirectionalAssociationTest.php @@ -1,7 +1,10 @@ useModelSet('ecommerce'); + parent::setUp(); + $this->firstProduct = new ECommerceProduct(); + $this->firstProduct->setName('Doctrine 1.x Manual'); + $this->secondProduct = new ECommerceProduct(); + $this->secondProduct->setName('Doctrine 2.x Manual'); + $this->firstCart = new ECommerceCart(); $this->secondCart = new ECommerceCart(); } @@ -37,70 +46,71 @@ public function testSavesAManyToManyAssociationWithCascadeSaveSet() { $this->firstCart->addProduct($this->firstProduct); $this->firstCart->addProduct($this->secondProduct); - $this->_em->persist($this->firstCart); - $this->_em->flush(); - $this->assertForeignKeysContain($this->firstCart->getId(), $this->firstProduct->getId()); - $this->assertForeignKeysContain($this->firstCart->getId(), $this->secondProduct->getId()); + $this->em->persist($this->firstCart); + $this->em->flush(); + + self::assertForeignKeysContain($this->firstCart->getId(), $this->firstProduct->getId()); + self::assertForeignKeysContain($this->firstCart->getId(), $this->secondProduct->getId()); } public function testRemovesAManyToManyAssociation() { $this->firstCart->addProduct($this->firstProduct); $this->firstCart->addProduct($this->secondProduct); - $this->_em->persist($this->firstCart); + $this->em->persist($this->firstCart); $this->firstCart->removeProduct($this->firstProduct); - $this->_em->flush(); + $this->em->flush(); - $this->assertForeignKeysNotContain($this->firstCart->getId(), $this->firstProduct->getId()); - $this->assertForeignKeysContain($this->firstCart->getId(), $this->secondProduct->getId()); + self::assertForeignKeysNotContain($this->firstCart->getId(), $this->firstProduct->getId()); + self::assertForeignKeysContain($this->firstCart->getId(), $this->secondProduct->getId()); } public function testEagerLoad() { - $this->_createFixture(); + $this->createFixture(); - $query = $this->_em->createQuery('SELECT c, p FROM Doctrine\Tests\Models\ECommerce\ECommerceCart c LEFT JOIN c.products p ORDER BY c.id, p.id'); + $query = $this->em->createQuery('SELECT c, p FROM Doctrine\Tests\Models\ECommerce\ECommerceCart c LEFT JOIN c.products p ORDER BY c.id, p.id'); $result = $query->getResult(); $firstCart = $result[0]; $products = $firstCart->getProducts(); $secondCart = $result[1]; - $this->assertInstanceOf(ECommerceProduct::class, $products[0]); - $this->assertInstanceOf(ECommerceProduct::class, $products[1]); - $this->assertCollectionEquals($products, $secondCart->getProducts()); - //$this->assertEquals("Doctrine 1.x Manual", $products[0]->getName()); - //$this->assertEquals("Doctrine 2.x Manual", $products[1]->getName()); + self::assertInstanceOf(ECommerceProduct::class, $products[0]); + self::assertInstanceOf(ECommerceProduct::class, $products[1]); + self::assertCollectionEquals($products, $secondCart->getProducts()); + //self::assertEquals("Doctrine 1.x Manual", $products[0]->getName()); + //self::assertEquals("Doctrine 2.x Manual", $products[1]->getName()); } public function testLazyLoadsCollection() { - $this->_createFixture(); - $metadata = $this->_em->getClassMetadata(ECommerceCart::class); - $metadata->associationMappings['products']['fetch'] = ClassMetadata::FETCH_LAZY; + $this->createFixture(); + $metadata = $this->em->getClassMetadata(ECommerceCart::class); + $metadata->getProperty('products')->setFetchMode(FetchMode::LAZY); - $query = $this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\ECommerce\ECommerceCart c'); + $query = $this->em->createQuery('SELECT c FROM Doctrine\Tests\Models\ECommerce\ECommerceCart c'); $result = $query->getResult(); $firstCart = $result[0]; $products = $firstCart->getProducts(); $secondCart = $result[1]; - $this->assertInstanceOf(ECommerceProduct::class, $products[0]); - $this->assertInstanceOf(ECommerceProduct::class, $products[1]); - $this->assertCollectionEquals($products, $secondCart->getProducts()); + self::assertInstanceOf(ECommerceProduct::class, $products[0]); + self::assertInstanceOf(ECommerceProduct::class, $products[1]); + self::assertCollectionEquals($products, $secondCart->getProducts()); } - private function _createFixture() + private function createFixture() { $this->firstCart->addProduct($this->firstProduct); $this->firstCart->addProduct($this->secondProduct); $this->secondCart->addProduct($this->firstProduct); $this->secondCart->addProduct($this->secondProduct); - $this->_em->persist($this->firstCart); - $this->_em->persist($this->secondCart); + $this->em->persist($this->firstCart); + $this->em->persist($this->secondCart); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/MappedSuperclassTest.php b/tests/Doctrine/Tests/ORM/Functional/MappedSuperclassTest.php index 97c34bba335..aa44e28c7e9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/MappedSuperclassTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/MappedSuperclassTest.php @@ -1,5 +1,7 @@ useModelSet('directorytree'); + parent::setUp(); } @@ -32,19 +36,19 @@ public function testCRUD() $file = new File($directory); $file->setName('test-b.html'); - $this->_em->persist($root); - $this->_em->persist($directory); - $this->_em->persist($file); + $this->em->persist($root); + $this->em->persist($directory); + $this->em->persist($file); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $cleanFile = $this->_em->find(get_class($file), $file->getId()); + $cleanFile = $this->em->find(File::class, $file->getId()); - $this->assertInstanceOf(Directory::class, $cleanFile->getParent()); - $this->assertInstanceOf(Proxy::class, $cleanFile->getParent()); - $this->assertEquals($directory->getId(), $cleanFile->getParent()->getId()); - $this->assertInstanceOf(Directory::class, $cleanFile->getParent()->getParent()); - $this->assertEquals($root->getId(), $cleanFile->getParent()->getParent()->getId()); + self::assertInstanceOf(Directory::class, $cleanFile->getParent()); + self::assertInstanceOf(Proxy::class, $cleanFile->getParent()); + self::assertEquals($directory->getId(), $cleanFile->getParent()->getId()); + self::assertInstanceOf(Directory::class, $cleanFile->getParent()->getParent()); + self::assertEquals($root->getId(), $cleanFile->getParent()->getParent()->getId()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/MergeCompositeToOneKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/MergeCompositeToOneKeyTest.php deleted file mode 100644 index fab94a9066c..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/MergeCompositeToOneKeyTest.php +++ /dev/null @@ -1,47 +0,0 @@ -_schemaTool->createSchema( - [ - $this->_em->getClassMetadata(Country::class), - $this->_em->getClassMetadata(CompositeToOneKeyState::class), - ] - ); - } - - /** - * @group DDC-3378 - * @group 1176 - */ - public function testMergingOfEntityWithCompositeIdentifierContainingToOneAssociation() - { - $country = new Country(); - $country->country = 'US'; - - $state = new CompositeToOneKeyState(); - $state->state = 'CA'; - $state->country = $country; - - /* @var $merged CompositeToOneKeyState */ - $merged = $this->_em->merge($state); - - $this->assertInstanceOf(CompositeToOneKeyState::class, $state); - $this->assertNotSame($state, $merged); - $this->assertInstanceOf(Country::class, $merged->country); - $this->assertNotSame($country, $merged->country); - } -} diff --git a/tests/Doctrine/Tests/ORM/Functional/MergeProxiesTest.php b/tests/Doctrine/Tests/ORM/Functional/MergeProxiesTest.php deleted file mode 100644 index 3d0acd1f898..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/MergeProxiesTest.php +++ /dev/null @@ -1,266 +0,0 @@ -useModelSet('generic'); - - parent::setUp(); - } - - /** - * @group DDC-1392 - * @group DDC-1734 - * @group DDC-3368 - * @group #1172 - */ - public function testMergeDetachedUnInitializedProxy() - { - $detachedUninitialized = $this->_em->getReference(DateTimeModel::class, 123); - - $this->_em->clear(); - - $managed = $this->_em->getReference(DateTimeModel::class, 123); - - $this->assertSame($managed, $this->_em->merge($detachedUninitialized)); - - $this->assertFalse($managed->__isInitialized()); - $this->assertFalse($detachedUninitialized->__isInitialized()); - } - - /** - * @group DDC-1392 - * @group DDC-1734 - * @group DDC-3368 - * @group #1172 - */ - public function testMergeUnserializedUnInitializedProxy() - { - $detachedUninitialized = $this->_em->getReference(DateTimeModel::class, 123); - - $this->_em->clear(); - - $managed = $this->_em->getReference(DateTimeModel::class, 123); - - $this->assertSame( - $managed, - $this->_em->merge(unserialize(serialize($this->_em->merge($detachedUninitialized)))) - ); - - $this->assertFalse($managed->__isInitialized()); - $this->assertFalse($detachedUninitialized->__isInitialized()); - } - - /** - * @group DDC-1392 - * @group DDC-1734 - * @group DDC-3368 - * @group #1172 - */ - public function testMergeManagedProxy() - { - $managed = $this->_em->getReference(DateTimeModel::class, 123); - - $this->assertSame($managed, $this->_em->merge($managed)); - - $this->assertFalse($managed->__isInitialized()); - } - - /** - * @group DDC-1392 - * @group DDC-1734 - * @group DDC-3368 - * @group #1172 - * - * Bug discovered while working on DDC-2704 - merging towards un-initialized proxies does not initialize them, - * causing merged data to be lost when they are actually initialized - */ - public function testMergeWithExistingUninitializedManagedProxy() - { - $date = new DateTimeModel(); - - $this->_em->persist($date); - $this->_em->flush($date); - $this->_em->clear(); - - $managed = $this->_em->getReference(DateTimeModel::class, $date->id); - - $this->assertInstanceOf(Proxy::class, $managed); - $this->assertFalse($managed->__isInitialized()); - - $date->date = $dateTime = new \DateTime(); - - $this->assertSame($managed, $this->_em->merge($date)); - $this->assertTrue($managed->__isInitialized()); - $this->assertSame($dateTime, $managed->date, 'Data was merged into the proxy after initialization'); - } - - /** - * @group DDC-1392 - * @group DDC-1734 - * @group DDC-3368 - * @group #1172 - */ - public function testMergingProxyFromDifferentEntityManagerWithExistingManagedInstanceDoesNotReplaceInitializer() - { - $em1 = $this->createEntityManager($logger1 = new DebugStack()); - $em2 = $this->createEntityManager($logger2 = new DebugStack()); - - $file1 = new DateTimeModel(); - $file2 = new DateTimeModel(); - - $em1->persist($file1); - $em2->persist($file2); - $em1->flush(); - $em2->flush(); - $em1->clear(); - $em2->clear(); - - $queryCount1 = count($logger1->queries); - $queryCount2 = count($logger2->queries); - - $proxy1 = $em1->getReference(DateTimeModel::class, $file1->id); - $proxy2 = $em2->getReference(DateTimeModel::class, $file1->id); - $merged2 = $em2->merge($proxy1); - - $this->assertNotSame($proxy1, $merged2); - $this->assertSame($proxy2, $merged2); - - $this->assertFalse($proxy1->__isInitialized()); - $this->assertFalse($proxy2->__isInitialized()); - - $proxy1->__load(); - - $this->assertCount( - $queryCount1 + 1, - $logger1->queries, - 'Loading the first proxy was done through the first entity manager' - ); - $this->assertCount( - $queryCount2, - $logger2->queries, - 'No queries were executed on the second entity manager, as it is unrelated with the first proxy' - ); - - $proxy2->__load(); - - $this->assertCount( - $queryCount1 + 1, - $logger1->queries, - 'Loading the second proxy does not affect the first entity manager' - ); - $this->assertCount( - $queryCount2 + 1, - $logger2->queries, - 'Loading of the second proxy instance was done through the second entity manager' - ); - } - - /** - * @group DDC-1392 - * @group DDC-1734 - * @group DDC-3368 - * @group #1172 - */ - public function testMergingUnInitializedProxyDoesNotInitializeIt() - { - $em1 = $this->createEntityManager($logger1 = new DebugStack()); - $em2 = $this->createEntityManager($logger2 = new DebugStack()); - - $file1 = new DateTimeModel(); - $file2 = new DateTimeModel(); - - $em1->persist($file1); - $em2->persist($file2); - $em1->flush(); - $em2->flush(); - $em1->clear(); - $em2->clear(); - - $queryCount1 = count($logger1->queries); - $queryCount2 = count($logger1->queries); - - $unManagedProxy = $em1->getReference(DateTimeModel::class, $file1->id); - $mergedInstance = $em2->merge($unManagedProxy); - - $this->assertNotInstanceOf(Proxy::class, $mergedInstance); - $this->assertNotSame($unManagedProxy, $mergedInstance); - $this->assertFalse($unManagedProxy->__isInitialized()); - - $this->assertCount( - $queryCount1, - $logger1->queries, - 'Loading the merged instance affected only the first entity manager' - ); - $this->assertCount( - $queryCount1 + 1, - $logger2->queries, - 'Loading the merged instance was done via the second entity manager' - ); - - $unManagedProxy->__load(); - - $this->assertCount( - $queryCount1 + 1, - $logger1->queries, - 'Loading the first proxy was done through the first entity manager' - ); - $this->assertCount( - $queryCount2 + 1, - $logger2->queries, - 'No queries were executed on the second entity manager, as it is unrelated with the first proxy' - ); - } - - /** - * @param SQLLogger $logger - * - * @return EntityManager - */ - private function createEntityManager(SQLLogger $logger) - { - $config = new Configuration(); - - $config->setProxyDir(realpath(__DIR__ . '/../../Proxies')); - $config->setProxyNamespace('Doctrine\Tests\Proxies'); - $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver( - [realpath(__DIR__ . '/../../Models/Cache')], - true - )); - $config->setSQLLogger($logger); - - // always runs on sqlite to prevent multi-connection race-conditions with the test suite - // multi-connection is not relevant for the purpose of checking locking here, but merely - // to stub out DB-level access and intercept it - $connection = DriverManager::getConnection( - [ - 'driver' => 'pdo_sqlite', - 'memory' => true - ], - $config - ); - - - $entityManager = EntityManager::create($connection, $config); - - (new SchemaTool($entityManager))->createSchema([$entityManager->getClassMetadata(DateTimeModel::class)]); - - return $entityManager; - } -} diff --git a/tests/Doctrine/Tests/ORM/Functional/MergeSharedEntitiesTest.php b/tests/Doctrine/Tests/ORM/Functional/MergeSharedEntitiesTest.php deleted file mode 100644 index b549a420108..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/MergeSharedEntitiesTest.php +++ /dev/null @@ -1,140 +0,0 @@ -_schemaTool->createSchema( - [ - $this->_em->getClassMetadata(MSEFile::class), - $this->_em->getClassMetadata(MSEPicture::class), - ] - ); - } catch (ToolsException $ignored) { - } - } - - public function testMergeSharedNewEntities() - { - $file = new MSEFile; - $picture = new MSEPicture; - - $picture->file = $file; - $picture->otherFile = $file; - - $picture = $this->_em->merge($picture); - - $this->assertEquals($picture->file, $picture->otherFile, 'Identical entities must remain identical'); - } - - public function testMergeSharedManagedEntities() - { - $file = new MSEFile; - $picture = new MSEPicture; - - $picture->file = $file; - $picture->otherFile = $file; - - $this->_em->persist($file); - $this->_em->persist($picture); - $this->_em->flush(); - $this->_em->clear(); - - $picture = $this->_em->merge($picture); - - $this->assertEquals($picture->file, $picture->otherFile, 'Identical entities must remain identical'); - } - - public function testMergeSharedDetachedSerializedEntities() - { - $file = new MSEFile; - $picture = new MSEPicture; - - $picture->file = $file; - $picture->otherFile = $file; - - $serializedPicture = serialize($picture); - - $this->_em->persist($file); - $this->_em->persist($picture); - $this->_em->flush(); - $this->_em->clear(); - - $picture = $this->_em->merge(unserialize($serializedPicture)); - - $this->assertEquals($picture->file, $picture->otherFile, 'Identical entities must remain identical'); - } - - /** - * @group DDC-2704 - */ - public function testMergeInheritedTransientPrivateProperties() - { - $admin1 = new MSEAdmin(); - $admin2 = new MSEAdmin(); - - $admin1->id = 123; - $admin2->id = 123; - - $this->_em->persist($admin1); - - $admin2->setSession('zeh current session data'); - - $this->assertSame($admin1, $this->_em->merge($admin2)); - $this->assertSame('zeh current session data', $admin1->getSession()); - } -} - -/** @Entity */ -class MSEPicture -{ - /** @Column(type="integer") @Id @GeneratedValue */ - public $id; - - /** @ManyToOne(targetEntity="MSEFile", cascade={"merge"}) */ - public $file; - - /** @ManyToOne(targetEntity="MSEFile", cascade={"merge"}) */ - public $otherFile; -} - -/** @Entity */ -class MSEFile -{ - /** @Column(type="integer") @Id @GeneratedValue(strategy="AUTO") */ - public $id; -} - -/** @MappedSuperclass */ -abstract class MSEUser -{ - private $session; // intentionally transient property - - public function getSession() - { - return $this->session; - } - - public function setSession($session) - { - $this->session = $session; - } -} - -/** @Entity */ -class MSEAdmin extends MSEUser -{ - /** @Column(type="integer") @Id @GeneratedValue(strategy="NONE") */ - public $id; -} diff --git a/tests/Doctrine/Tests/ORM/Functional/MergeVersionedManyToOneTest.php b/tests/Doctrine/Tests/ORM/Functional/MergeVersionedManyToOneTest.php deleted file mode 100644 index 43af6720c83..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/MergeVersionedManyToOneTest.php +++ /dev/null @@ -1,44 +0,0 @@ -useModelSet('versioned_many_to_one'); - - parent::setUp(); - } - - /** - * This test case asserts that a detached and unmodified entity could be merge without firing - * OptimisticLockException. - */ - public function testSetVersionOnCreate() - { - $category = new Category(); - $article = new Article(); - - $article->name = 'Article'; - $article->category = $category; - - $this->_em->persist($article); - $this->_em->flush(); - $this->_em->clear(); - - $articleMerged = $this->_em->merge($article); - - $articleMerged->name = 'Article Merged'; - - $this->_em->flush(); - $this->assertEquals(2, $articleMerged->version); - } -} diff --git a/tests/Doctrine/Tests/ORM/Functional/NativeQueryTest.php b/tests/Doctrine/Tests/ORM/Functional/NativeQueryTest.php index 31c19a1cd4c..3dd81535f11 100644 --- a/tests/Doctrine/Tests/ORM/Functional/NativeQueryTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/NativeQueryTest.php @@ -1,8 +1,12 @@ useModelSet('cms'); $this->useModelSet('company'); + parent::setUp(); - $this->platform = $this->_em->getConnection()->getDatabasePlatform(); + $this->platform = $this->em->getConnection()->getDatabasePlatform(); } public function testBasicNativeQuery() { $user = new CmsUser; + $user->name = 'Roman'; $user->username = 'romanb'; $user->status = 'dev'; - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); $rsm = new ResultSetMapping; + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('id'), 'id'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('name'), 'name'); - $query = $this->_em->createNativeQuery('SELECT id, name FROM cms_users WHERE username = ?', $rsm); + $query = $this->em->createNativeQuery('SELECT id, name FROM cms_users WHERE username = ?', $rsm); + $query->setParameter(1, 'romanb'); $users = $query->getResult(); - $this->assertEquals(1, count($users)); - $this->assertInstanceOf(CmsUser::class, $users[0]); - $this->assertEquals('Roman', $users[0]->name); + self::assertEquals(1, count($users)); + self::assertInstanceOf(CmsUser::class, $users[0]); + self::assertEquals('Roman', $users[0]->name); } public function testBasicNativeQueryWithMetaResult() { $user = new CmsUser; + $user->name = 'Roman'; $user->username = 'romanb'; $user->status = 'dev'; $addr = new CmsAddress; + $addr->country = 'germany'; $addr->zip = 10827; $addr->city = 'Berlin'; - $user->setAddress($addr); - $this->_em->persist($user); - $this->_em->flush(); - - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); $rsm = new ResultSetMapping; + $rsm->addEntityResult(CmsAddress::class, 'a'); $rsm->addFieldResult('a', $this->platform->getSQLResultCasing('id'), 'id'); $rsm->addFieldResult('a', $this->platform->getSQLResultCasing('country'), 'country'); $rsm->addFieldResult('a', $this->platform->getSQLResultCasing('zip'), 'zip'); $rsm->addFieldResult('a', $this->platform->getSQLResultCasing('city'), 'city'); - $rsm->addMetaResult('a', $this->platform->getSQLResultCasing('user_id'), 'user_id', false, 'integer'); + $rsm->addMetaResult('a', $this->platform->getSQLResultCasing('user_id'), 'user_id', false, DBALType::getType('integer')); + + $query = $this->em->createNativeQuery('SELECT a.id, a.country, a.zip, a.city, a.user_id FROM cms_addresses a WHERE a.id = ?', $rsm); - $query = $this->_em->createNativeQuery('SELECT a.id, a.country, a.zip, a.city, a.user_id FROM cms_addresses a WHERE a.id = ?', $rsm); $query->setParameter(1, $addr->id); $addresses = $query->getResult(); - $this->assertEquals(1, count($addresses)); - $this->assertTrue($addresses[0] instanceof CmsAddress); - $this->assertEquals($addr->country, $addresses[0]->country); - $this->assertEquals($addr->zip, $addresses[0]->zip); - $this->assertEquals($addr->city, $addresses[0]->city); - $this->assertEquals($addr->street, $addresses[0]->street); - $this->assertTrue($addresses[0]->user instanceof CmsUser); + self::assertEquals(1, count($addresses)); + self::assertTrue($addresses[0] instanceof CmsAddress); + self::assertEquals($addr->country, $addresses[0]->country); + self::assertEquals($addr->zip, $addresses[0]->zip); + self::assertEquals($addr->city, $addresses[0]->city); + self::assertEquals($addr->street, $addresses[0]->street); + self::assertTrue($addresses[0]->user instanceof CmsUser); } public function testJoinedOneToManyNativeQuery() { $user = new CmsUser; + $user->name = 'Roman'; $user->username = 'romanb'; $user->status = 'dev'; $phone = new CmsPhonenumber; + $phone->phonenumber = 424242; $user->addPhonenumber($phone); - $this->_em->persist($user); - $this->_em->flush(); - - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); $rsm = new ResultSetMapping; + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('id'), 'id'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('name'), 'name'); @@ -132,44 +144,47 @@ public function testJoinedOneToManyNativeQuery() $rsm->addJoinedEntityResult(CmsPhonenumber::class, 'p', 'u', 'phonenumbers'); $rsm->addFieldResult('p', $this->platform->getSQLResultCasing('phonenumber'), 'phonenumber'); - $query = $this->_em->createNativeQuery('SELECT id, name, status, phonenumber FROM cms_users INNER JOIN cms_phonenumbers ON id = user_id WHERE username = ?', $rsm); + $query = $this->em->createNativeQuery('SELECT id, name, status, phonenumber FROM cms_users INNER JOIN cms_phonenumbers ON id = user_id WHERE username = ?', $rsm); + $query->setParameter(1, 'romanb'); $users = $query->getResult(); - $this->assertEquals(1, count($users)); - $this->assertInstanceOf(CmsUser::class, $users[0]); - $this->assertEquals('Roman', $users[0]->name); - $this->assertInstanceOf(PersistentCollection::class, $users[0]->getPhonenumbers()); - $this->assertTrue($users[0]->getPhonenumbers()->isInitialized()); - $this->assertEquals(1, count($users[0]->getPhonenumbers())); + + self::assertEquals(1, count($users)); + self::assertInstanceOf(CmsUser::class, $users[0]); + self::assertEquals('Roman', $users[0]->name); + self::assertInstanceOf(PersistentCollection::class, $users[0]->getPhonenumbers()); + self::assertTrue($users[0]->getPhonenumbers()->isInitialized()); + self::assertEquals(1, count($users[0]->getPhonenumbers())); + $phones = $users[0]->getPhonenumbers(); - $this->assertEquals(424242, $phones[0]->phonenumber); - $this->assertTrue($phones[0]->getUser() === $users[0]); + self::assertEquals(424242, $phones[0]->phonenumber); + self::assertTrue($phones[0]->getUser() === $users[0]); } public function testJoinedOneToOneNativeQuery() { $user = new CmsUser; + $user->name = 'Roman'; $user->username = 'romanb'; $user->status = 'dev'; $addr = new CmsAddress; + $addr->country = 'germany'; $addr->zip = 10827; $addr->city = 'Berlin'; - $user->setAddress($addr); - $this->_em->persist($user); - $this->_em->flush(); - - $this->_em->clear(); - + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); $rsm = new ResultSetMapping; + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('id'), 'id'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('name'), 'name'); @@ -180,32 +195,34 @@ public function testJoinedOneToOneNativeQuery() $rsm->addFieldResult('a', $this->platform->getSQLResultCasing('zip'), 'zip'); $rsm->addFieldResult('a', $this->platform->getSQLResultCasing('city'), 'city'); - $query = $this->_em->createNativeQuery('SELECT u.id, u.name, u.status, a.id AS a_id, a.country, a.zip, a.city FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id WHERE u.username = ?', $rsm); + $query = $this->em->createNativeQuery('SELECT u.id, u.name, u.status, a.id AS a_id, a.country, a.zip, a.city FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id WHERE u.username = ?', $rsm); + $query->setParameter(1, 'romanb'); $users = $query->getResult(); - $this->assertEquals(1, count($users)); - $this->assertInstanceOf(CmsUser::class, $users[0]); - $this->assertEquals('Roman', $users[0]->name); - $this->assertInstanceOf(PersistentCollection::class, $users[0]->getPhonenumbers()); - $this->assertFalse($users[0]->getPhonenumbers()->isInitialized()); - $this->assertInstanceOf(CmsAddress::class, $users[0]->getAddress()); - $this->assertTrue($users[0]->getAddress()->getUser() == $users[0]); - $this->assertEquals('germany', $users[0]->getAddress()->getCountry()); - $this->assertEquals(10827, $users[0]->getAddress()->getZipCode()); - $this->assertEquals('Berlin', $users[0]->getAddress()->getCity()); + self::assertEquals(1, count($users)); + self::assertInstanceOf(CmsUser::class, $users[0]); + self::assertEquals('Roman', $users[0]->name); + self::assertInstanceOf(PersistentCollection::class, $users[0]->getPhonenumbers()); + self::assertFalse($users[0]->getPhonenumbers()->isInitialized()); + self::assertInstanceOf(CmsAddress::class, $users[0]->getAddress()); + self::assertTrue($users[0]->getAddress()->getUser() == $users[0]); + self::assertEquals('germany', $users[0]->getAddress()->getCountry()); + self::assertEquals(10827, $users[0]->getAddress()->getZipCode()); + self::assertEquals('Berlin', $users[0]->getAddress()->getCity()); } public function testFluentInterface() { $parameters = new ArrayCollection; + $parameters->add(new Parameter(1, 'foo')); $parameters->add(new Parameter(2, 'bar')); $rsm = new ResultSetMapping; - $q = $this->_em->createNativeQuery('SELECT id, name, status, phonenumber FROM cms_users INNER JOIN cms_phonenumbers ON id = user_id WHERE username = ?', $rsm); + $q = $this->em->createNativeQuery('SELECT id, name, status, phonenumber FROM cms_users INNER JOIN cms_phonenumbers ON id = user_id WHERE username = ?', $rsm); $q2 = $q->setSQL('foo') ->setResultSetMapping($rsm) ->expireResultCache(true) @@ -215,107 +232,121 @@ public function testFluentInterface() ->setResultCacheDriver(null) ->setResultCacheLifetime(3500); - $this->assertSame($q, $q2); + self::assertSame($q, $q2); } public function testJoinedOneToManyNativeQueryWithRSMBuilder() { $user = new CmsUser; + $user->name = 'Roman'; $user->username = 'romanb'; $user->status = 'dev'; $phone = new CmsPhonenumber; + $phone->phonenumber = 424242; $user->addPhonenumber($phone); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $this->_em->clear(); + $rsm = new ResultSetMappingBuilder($this->em); - $rsm = new ResultSetMappingBuilder($this->_em); $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); $rsm->addJoinedEntityFromClassMetadata(CmsPhonenumber::class, 'p', 'u', 'phonenumbers'); - $query = $this->_em->createNativeQuery('SELECT u.*, p.* FROM cms_users u LEFT JOIN cms_phonenumbers p ON u.id = p.user_id WHERE username = ?', $rsm); + $query = $this->em->createNativeQuery('SELECT u.*, p.* FROM cms_users u LEFT JOIN cms_phonenumbers p ON u.id = p.user_id WHERE username = ?', $rsm); + $query->setParameter(1, 'romanb'); $users = $query->getResult(); - $this->assertEquals(1, count($users)); - $this->assertInstanceOf(CmsUser::class, $users[0]); - $this->assertEquals('Roman', $users[0]->name); - $this->assertInstanceOf(PersistentCollection::class, $users[0]->getPhonenumbers()); - $this->assertTrue($users[0]->getPhonenumbers()->isInitialized()); - $this->assertEquals(1, count($users[0]->getPhonenumbers())); + + self::assertEquals(1, count($users)); + self::assertInstanceOf(CmsUser::class, $users[0]); + self::assertEquals('Roman', $users[0]->name); + self::assertInstanceOf(PersistentCollection::class, $users[0]->getPhonenumbers()); + self::assertTrue($users[0]->getPhonenumbers()->isInitialized()); + self::assertEquals(1, count($users[0]->getPhonenumbers())); + $phones = $users[0]->getPhonenumbers(); - $this->assertEquals(424242, $phones[0]->phonenumber); - $this->assertTrue($phones[0]->getUser() === $users[0]); - $this->_em->clear(); + self::assertEquals(424242, $phones[0]->phonenumber); + self::assertTrue($phones[0]->getUser() === $users[0]); + + $this->em->clear(); + + $rsm = new ResultSetMappingBuilder($this->em); - $rsm = new ResultSetMappingBuilder($this->_em); $rsm->addRootEntityFromClassMetadata(CmsPhonenumber::class, 'p'); - $query = $this->_em->createNativeQuery('SELECT p.* FROM cms_phonenumbers p WHERE p.phonenumber = ?', $rsm); + + $query = $this->em->createNativeQuery('SELECT p.* FROM cms_phonenumbers p WHERE p.phonenumber = ?', $rsm); + $query->setParameter(1, $phone->phonenumber); + $phone = $query->getSingleResult(); - $this->assertNotNull($phone->getUser()); - $this->assertEquals($user->name, $phone->getUser()->getName()); + self::assertNotNull($phone->getUser()); + self::assertEquals($user->name, $phone->getUser()->getName()); } public function testJoinedOneToOneNativeQueryWithRSMBuilder() { $user = new CmsUser; + $user->name = 'Roman'; $user->username = 'romanb'; $user->status = 'dev'; $addr = new CmsAddress; + $addr->country = 'germany'; $addr->zip = 10827; $addr->city = 'Berlin'; - $user->setAddress($addr); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $this->_em->clear(); + $rsm = new ResultSetMappingBuilder($this->em); - - $rsm = new ResultSetMappingBuilder($this->_em); $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); - $rsm->addJoinedEntityFromClassMetadata(CmsAddress::class, 'a', 'u', 'address', ['id' => 'a_id'] - ); + $rsm->addJoinedEntityFromClassMetadata(CmsAddress::class, 'a', 'u', 'address', ['id' => 'a_id']); + + $query = $this->em->createNativeQuery('SELECT u.*, a.*, a.id AS a_id FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id WHERE u.username = ?', $rsm); - $query = $this->_em->createNativeQuery('SELECT u.*, a.*, a.id AS a_id FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id WHERE u.username = ?', $rsm); $query->setParameter(1, 'romanb'); $users = $query->getResult(); - $this->assertEquals(1, count($users)); - $this->assertInstanceOf(CmsUser::class, $users[0]); - $this->assertEquals('Roman', $users[0]->name); - $this->assertInstanceOf(PersistentCollection::class, $users[0]->getPhonenumbers()); - $this->assertFalse($users[0]->getPhonenumbers()->isInitialized()); - $this->assertInstanceOf(CmsAddress::class, $users[0]->getAddress()); - $this->assertTrue($users[0]->getAddress()->getUser() == $users[0]); - $this->assertEquals('germany', $users[0]->getAddress()->getCountry()); - $this->assertEquals(10827, $users[0]->getAddress()->getZipCode()); - $this->assertEquals('Berlin', $users[0]->getAddress()->getCity()); + self::assertEquals(1, count($users)); + self::assertInstanceOf(CmsUser::class, $users[0]); + self::assertEquals('Roman', $users[0]->name); + self::assertInstanceOf(PersistentCollection::class, $users[0]->getPhonenumbers()); + self::assertFalse($users[0]->getPhonenumbers()->isInitialized()); + self::assertInstanceOf(CmsAddress::class, $users[0]->getAddress()); + self::assertTrue($users[0]->getAddress()->getUser() == $users[0]); + self::assertEquals('germany', $users[0]->getAddress()->getCountry()); + self::assertEquals(10827, $users[0]->getAddress()->getZipCode()); + self::assertEquals('Berlin', $users[0]->getAddress()->getCity()); + + $this->em->clear(); - $this->_em->clear(); + $rsm = new ResultSetMappingBuilder($this->em); - $rsm = new ResultSetMappingBuilder($this->_em); $rsm->addRootEntityFromClassMetadata(CmsAddress::class, 'a'); - $query = $this->_em->createNativeQuery('SELECT a.* FROM cms_addresses a WHERE a.id = ?', $rsm); + + $query = $this->em->createNativeQuery('SELECT a.* FROM cms_addresses a WHERE a.id = ?', $rsm); + $query->setParameter(1, $addr->getId()); + $address = $query->getSingleResult(); - $this->assertNotNull($address->getUser()); - $this->assertEquals($user->name, $address->getUser()->getName()); + self::assertNotNull($address->getUser()); + self::assertEquals($user->name, $address->getUser()->getName()); } /** @@ -323,7 +354,8 @@ public function testJoinedOneToOneNativeQueryWithRSMBuilder() */ public function testConcreteClassInSingleTableInheritanceSchemaWithRSMBuilderIsFine() { - $rsm = new ResultSetMappingBuilder($this->_em); + $rsm = new ResultSetMappingBuilder($this->em); + $rsm->addRootEntityFromClassMetadata(CompanyFixContract::class, 'c'); self::assertSame(CompanyFixContract::class, $rsm->getClassName('c')); @@ -337,7 +369,8 @@ public function testAbstractClassInSingleTableInheritanceSchemaWithRSMBuilderThr $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('ResultSetMapping builder does not currently support your inheritance scheme.'); - $rsm = new ResultSetMappingBuilder($this->_em); + $rsm = new ResultSetMappingBuilder($this->em); + $rsm->addRootEntityFromClassMetadata(CompanyContract::class, 'c'); } @@ -346,7 +379,8 @@ public function testAbstractClassInSingleTableInheritanceSchemaWithRSMBuilderThr */ public function testRSMBuilderThrowsExceptionOnColumnConflict() { - $rsm = new ResultSetMappingBuilder($this->_em); + $rsm = new ResultSetMappingBuilder($this->em); + $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); $rsm->addJoinedEntityFromClassMetadata(CmsAddress::class, 'a', 'u', 'address'); } @@ -356,18 +390,19 @@ public function testRSMBuilderThrowsExceptionOnColumnConflict() */ public function testUnknownParentAliasThrowsException() { - $rsm = new ResultSetMappingBuilder($this->_em); + $rsm = new ResultSetMappingBuilder($this->em); + $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); - $rsm->addJoinedEntityFromClassMetadata(CmsAddress::class, 'a', 'un', 'address', ['id' => 'a_id'] - ); + $rsm->addJoinedEntityFromClassMetadata(CmsAddress::class, 'a', 'un', 'address', ['id' => 'a_id']); + + $query = $this->em->createNativeQuery('SELECT u.*, a.*, a.id AS a_id FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id WHERE u.username = ?', $rsm); - $query = $this->_em->createNativeQuery('SELECT u.*, a.*, a.id AS a_id FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id WHERE u.username = ?', $rsm); $query->setParameter(1, 'romanb'); $this->expectException(HydrationException::class); $this->expectExceptionMessage("The parent object of entity result with alias 'a' was not found. The parent alias is 'un'."); - $users = $query->getResult(); + $query->getResult(); } @@ -376,34 +411,34 @@ public function testUnknownParentAliasThrowsException() */ public function testBasicNativeNamedQueryWithSqlResultSetMapping() { - $user = new CmsUser; + $user = new CmsUser; + $user->name = 'Fabio B. Silva'; $user->username = 'FabioBatSilva'; $user->status = 'dev'; - $addr = new CmsAddress; + $addr = new CmsAddress; + $addr->country = 'Brazil'; $addr->zip = 10827; $addr->city = 'São Paulo'; $user->setAddress($addr); - $this->_em->clear(); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $this->_em->clear(); - - - $repository = $this->_em->getRepository(CmsAddress::class); + $repository = $this->em->getRepository(CmsAddress::class); $query = $repository->createNativeNamedQuery('find-all'); $result = $query->getResult(); - $this->assertCount(1, $result); - $this->assertInstanceOf(CmsAddress::class, $result[0]); - $this->assertEquals($addr->id, $result[0]->id); - $this->assertEquals($addr->city, $result[0]->city); - $this->assertEquals($addr->country, $result[0]->country); + self::assertCount(1, $result); + self::assertInstanceOf(CmsAddress::class, $result[0]); + self::assertEquals($addr->id, $result[0]->id); + self::assertEquals($addr->city, $result[0]->city); + self::assertEquals($addr->country, $result[0]->country); } /** @@ -411,51 +446,52 @@ public function testBasicNativeNamedQueryWithSqlResultSetMapping() */ public function testBasicNativeNamedQueryWithResultClass() { - $user = new CmsUser; + $user = new CmsUser; + $user->name = 'Fabio B. Silva'; $user->username = 'FabioBatSilva'; $user->status = 'dev'; - $email = new CmsEmail(); + $email = new CmsEmail(); + $email->email = 'fabio.bat.silva@gmail.com'; $user->setEmail($email); - $this->_em->clear(); - $this->_em->persist($user); - $this->_em->flush(); - - $this->_em->clear(); - - $repository = $this->_em->getRepository(CmsUser::class); - - $result = $repository->createNativeNamedQuery('fetchIdAndUsernameWithResultClass') - ->setParameter(1, 'FabioBatSilva') - ->getResult(); - - $this->assertEquals(1, count($result)); - $this->assertInstanceOf(CmsUser::class, $result[0]); - $this->assertNull($result[0]->name); - $this->assertNull($result[0]->email); - $this->assertEquals($user->id, $result[0]->id); - $this->assertEquals('FabioBatSilva', $result[0]->username); - - $this->_em->clear(); - - $result = $repository->createNativeNamedQuery('fetchAllColumns') - ->setParameter(1, 'FabioBatSilva') - ->getResult(); - - $this->assertEquals(1, count($result)); - $this->assertInstanceOf(CmsUser::class, $result[0]); - $this->assertEquals($user->id, $result[0]->id); - $this->assertEquals('Fabio B. Silva', $result[0]->name); - $this->assertEquals('FabioBatSilva', $result[0]->username); - $this->assertEquals('dev', $result[0]->status); - $this->assertInstanceOf(CmsEmail::class, $result[0]->email); + $this->em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); + + $repository = $this->em->getRepository(CmsUser::class); + $result = $repository + ->createNativeNamedQuery('fetchIdAndUsernameWithResultClass') + ->setParameter(1, 'FabioBatSilva') + ->getResult(); + + self::assertEquals(1, count($result)); + self::assertInstanceOf(CmsUser::class, $result[0]); + self::assertNull($result[0]->name); + self::assertNull($result[0]->email); + self::assertEquals($user->id, $result[0]->id); + self::assertEquals('FabioBatSilva', $result[0]->username); + + $this->em->clear(); + + $result = $repository + ->createNativeNamedQuery('fetchAllColumns') + ->setParameter(1, 'FabioBatSilva') + ->getResult(); + + self::assertEquals(1, count($result)); + self::assertInstanceOf(CmsUser::class, $result[0]); + self::assertEquals($user->id, $result[0]->id); + self::assertEquals('Fabio B. Silva', $result[0]->name); + self::assertEquals('FabioBatSilva', $result[0]->username); + self::assertEquals('dev', $result[0]->status); + self::assertInstanceOf(CmsEmail::class, $result[0]->email); } - /** * @group DDC-1663 */ @@ -473,25 +509,27 @@ public function testJoinedOneToOneNativeNamedQueryWithResultSetMapping() $user->setAddress($addr); - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); - - $result = $this->_em->getRepository(CmsUser::class) - ->createNativeNamedQuery('fetchJoinedAddress') - ->setParameter(1, 'FabioBatSilva') - ->getResult(); - - $this->assertEquals(1, count($result)); - $this->assertInstanceOf(CmsUser::class, $result[0]); - $this->assertEquals('Fabio B. Silva', $result[0]->name); - $this->assertInstanceOf(PersistentCollection::class, $result[0]->getPhonenumbers()); - $this->assertFalse($result[0]->getPhonenumbers()->isInitialized()); - $this->assertInstanceOf(CmsAddress::class, $result[0]->getAddress()); - $this->assertTrue($result[0]->getAddress()->getUser() == $result[0]); - $this->assertEquals('Brazil', $result[0]->getAddress()->getCountry()); - $this->assertEquals(10827, $result[0]->getAddress()->getZipCode()); - $this->assertEquals('São Paulo', $result[0]->getAddress()->getCity()); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); + + $repository = $this->em->getRepository(CmsUser::class); + + $result = $repository + ->createNativeNamedQuery('fetchJoinedAddress') + ->setParameter(1, 'FabioBatSilva') + ->getResult(); + + self::assertEquals(1, count($result)); + self::assertInstanceOf(CmsUser::class, $result[0]); + self::assertEquals('Fabio B. Silva', $result[0]->name); + self::assertInstanceOf(PersistentCollection::class, $result[0]->getPhonenumbers()); + self::assertFalse($result[0]->getPhonenumbers()->isInitialized()); + self::assertInstanceOf(CmsAddress::class, $result[0]->getAddress()); + self::assertTrue($result[0]->getAddress()->getUser() == $result[0]); + self::assertEquals('Brazil', $result[0]->getAddress()->getCountry()); + self::assertEquals(10827, $result[0]->getAddress()->getZipCode()); + self::assertEquals('São Paulo', $result[0]->getAddress()->getCity()); } /** @@ -509,25 +547,25 @@ public function testJoinedOneToManyNativeNamedQueryWithResultSetMapping() $user->addPhonenumber($phone); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $result = $repository->createNativeNamedQuery('fetchJoinedPhonenumber') ->setParameter(1, 'FabioBatSilva')->getResult(); - $this->assertEquals(1, count($result)); - $this->assertInstanceOf(CmsUser::class, $result[0]); - $this->assertEquals('Fabio B. Silva', $result[0]->name); - $this->assertInstanceOf(PersistentCollection::class, $result[0]->getPhonenumbers()); - $this->assertTrue($result[0]->getPhonenumbers()->isInitialized()); - $this->assertEquals(1, count($result[0]->getPhonenumbers())); + self::assertEquals(1, count($result)); + self::assertInstanceOf(CmsUser::class, $result[0]); + self::assertEquals('Fabio B. Silva', $result[0]->name); + self::assertInstanceOf(PersistentCollection::class, $result[0]->getPhonenumbers()); + self::assertTrue($result[0]->getPhonenumbers()->isInitialized()); + self::assertEquals(1, count($result[0]->getPhonenumbers())); $phones = $result[0]->getPhonenumbers(); - $this->assertEquals(424242, $phones[0]->phonenumber); - $this->assertTrue($phones[0]->getUser() === $result[0]); + self::assertEquals(424242, $phones[0]->phonenumber); + self::assertTrue($phones[0]->getUser() === $result[0]); } /** @@ -535,19 +573,22 @@ public function testJoinedOneToManyNativeNamedQueryWithResultSetMapping() */ public function testMixedNativeNamedQueryNormalJoin() { - $user1 = new CmsUser; + $user1 = new CmsUser; + $user1->name = 'Fabio B. Silva'; $user1->username = 'FabioBatSilva'; $user1->status = 'dev'; - $user2 = new CmsUser; + $user2 = new CmsUser; + $user2->name = 'test tester'; $user2->username = 'test'; $user2->status = 'tester'; - $phone1 = new CmsPhonenumber; - $phone2 = new CmsPhonenumber; - $phone3 = new CmsPhonenumber; + $phone1 = new CmsPhonenumber; + $phone2 = new CmsPhonenumber; + $phone3 = new CmsPhonenumber; + $phone1->phonenumber = 11111111; $phone2->phonenumber = 22222222; $phone3->phonenumber = 33333333; @@ -556,30 +597,29 @@ public function testMixedNativeNamedQueryNormalJoin() $user1->addPhonenumber($phone2); $user2->addPhonenumber($phone3); - $this->_em->persist($user1); - $this->_em->persist($user2); - $this->_em->flush(); - - $this->_em->clear(); - - $repository = $this->_em->getRepository(CmsUser::class); + $this->em->persist($user1); + $this->em->persist($user2); + $this->em->flush(); + $this->em->clear(); - $result = $repository->createNativeNamedQuery('fetchUserPhonenumberCount') - ->setParameter(1, ['test','FabioBatSilva'])->getResult(); + $repository = $this->em->getRepository(CmsUser::class); + $result = $repository + ->createNativeNamedQuery('fetchUserPhonenumberCount') + ->setParameter(1, ['test','FabioBatSilva'])->getResult(); - $this->assertEquals(2, count($result)); - $this->assertTrue(is_array($result[0])); - $this->assertTrue(is_array($result[1])); + self::assertEquals(2, count($result)); + self::assertTrue(is_array($result[0])); + self::assertTrue(is_array($result[1])); // first user => 2 phonenumbers - $this->assertInstanceOf(CmsUser::class, $result[0][0]); - $this->assertEquals('Fabio B. Silva', $result[0][0]->name); - $this->assertEquals(2, $result[0]['numphones']); + self::assertInstanceOf(CmsUser::class, $result[0][0]); + self::assertEquals('Fabio B. Silva', $result[0][0]->name); + self::assertEquals(2, $result[0]['numphones']); // second user => 1 phonenumbers - $this->assertInstanceOf(CmsUser::class, $result[1][0]); - $this->assertEquals('test tester', $result[1][0]->name); - $this->assertEquals(1, $result[1]['numphones']); + self::assertInstanceOf(CmsUser::class, $result[1][0]); + self::assertEquals('test tester', $result[1][0]->name); + self::assertEquals(1, $result[1]['numphones']); } /** @@ -588,46 +628,46 @@ public function testMixedNativeNamedQueryNormalJoin() public function testNativeNamedQueryInheritance() { $person = new CompanyPerson; + $person->setName('Fabio B. Silva'); $employee = new CompanyEmployee; + $employee->setName('Fabio Silva'); $employee->setSalary(100000); $employee->setDepartment('IT'); - $this->_em->persist($person); - $this->_em->persist($employee); - - $this->_em->flush(); - $this->_em->clear(); - - $repository = $this->_em->getRepository(CompanyPerson::class); - - $result = $repository->createNativeNamedQuery('fetchAllWithSqlResultSetMapping') - ->getResult(); - - $this->assertEquals(2, count($result)); - $this->assertInstanceOf(CompanyPerson::class, $result[0]); - $this->assertInstanceOf(CompanyEmployee::class, $result[1]); - $this->assertTrue(is_numeric($result[0]->getId())); - $this->assertTrue(is_numeric($result[1]->getId())); - $this->assertEquals('Fabio B. Silva', $result[0]->getName()); - $this->assertEquals('Fabio Silva', $result[1]->getName()); - - - $this->_em->clear(); - - - $result = $repository->createNativeNamedQuery('fetchAllWithResultClass') - ->getResult(); - - $this->assertEquals(2, count($result)); - $this->assertInstanceOf(CompanyPerson::class, $result[0]); - $this->assertInstanceOf(CompanyEmployee::class, $result[1]); - $this->assertTrue(is_numeric($result[0]->getId())); - $this->assertTrue(is_numeric($result[1]->getId())); - $this->assertEquals('Fabio B. Silva', $result[0]->getName()); - $this->assertEquals('Fabio Silva', $result[1]->getName()); + $this->em->persist($person); + $this->em->persist($employee); + $this->em->flush(); + $this->em->clear(); + + $repository = $this->em->getRepository(CompanyPerson::class); + $result = $repository + ->createNativeNamedQuery('fetchAllWithSqlResultSetMapping') + ->getResult(); + + self::assertEquals(2, count($result)); + self::assertInstanceOf(CompanyPerson::class, $result[0]); + self::assertInstanceOf(CompanyEmployee::class, $result[1]); + self::assertTrue(is_numeric($result[0]->getId())); + self::assertTrue(is_numeric($result[1]->getId())); + self::assertEquals('Fabio B. Silva', $result[0]->getName()); + self::assertEquals('Fabio Silva', $result[1]->getName()); + + $this->em->clear(); + + $result = $repository + ->createNativeNamedQuery('fetchAllWithResultClass') + ->getResult(); + + self::assertEquals(2, count($result)); + self::assertInstanceOf(CompanyPerson::class, $result[0]); + self::assertInstanceOf(CompanyEmployee::class, $result[1]); + self::assertTrue(is_numeric($result[0]->getId())); + self::assertTrue(is_numeric($result[1]->getId())); + self::assertEquals('Fabio B. Silva', $result[0]->getName()); + self::assertEquals('Fabio Silva', $result[1]->getName()); } /** @@ -636,102 +676,88 @@ public function testNativeNamedQueryInheritance() */ public function testMultipleEntityResults() { + $user = new CmsUser; - $user = new CmsUser; $user->name = 'Fabio B. Silva'; $user->username = 'FabioBatSilva'; $user->status = 'dev'; - $addr = new CmsAddress; + $addr = new CmsAddress; + $addr->country = 'Brazil'; $addr->zip = 10827; $addr->city = 'São Paulo'; - $phone = new CmsPhonenumber; - $phone->phonenumber = 424242; + $phone = new CmsPhonenumber; + $phone->phonenumber = 424242; $user->setAddress($addr); $user->addPhonenumber($phone); + $this->em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $this->_em->clear(); - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); - - - $repository = $this->_em->getRepository(CmsUser::class); + $repository = $this->em->getRepository(CmsUser::class); $query = $repository->createNativeNamedQuery('fetchMultipleJoinsEntityResults'); $result = $query->getResult(); + self::assertEquals(1, count($result)); + self::assertTrue(is_array($result[0])); + self::assertInstanceOf(CmsUser::class, $result[0][0]); + self::assertEquals('Fabio B. Silva', $result[0][0]->name); + self::assertInstanceOf(CmsAddress::class, $result[0][0]->getAddress()); + self::assertTrue($result[0][0]->getAddress()->getUser() == $result[0][0]); + self::assertEquals('Brazil', $result[0][0]->getAddress()->getCountry()); + self::assertEquals(10827, $result[0][0]->getAddress()->getZipCode()); - $this->assertEquals(1, count($result)); - $this->assertTrue(is_array($result[0])); - - $this->assertInstanceOf(CmsUser::class, $result[0][0]); - $this->assertEquals('Fabio B. Silva', $result[0][0]->name); - $this->assertInstanceOf(CmsAddress::class, $result[0][0]->getAddress()); - $this->assertTrue($result[0][0]->getAddress()->getUser() == $result[0][0]); - $this->assertEquals('Brazil', $result[0][0]->getAddress()->getCountry()); - $this->assertEquals(10827, $result[0][0]->getAddress()->getZipCode()); - - $this->assertEquals(1, $result[0]['numphones']); - + self::assertEquals(1, $result[0]['numphones']); } /** * @group DDC-1663 + * @dataProvider provideDataForNamedNativeQueryInheritance + * + * @param $className */ - public function testNamedNativeQueryInheritance() + public function testNamedNativeQueryInheritance($className) { - $contractMetadata = $this->_em->getClassMetadata(CompanyContract::class); - $flexMetadata = $this->_em->getClassMetadata(CompanyFlexContract::class); - - $contractQueries = $contractMetadata->getNamedNativeQueries(); - $flexQueries = $flexMetadata->getNamedNativeQueries(); - - $contractMappings = $contractMetadata->getSqlResultSetMappings(); - $flexMappings = $flexMetadata->getSqlResultSetMappings(); - - - // contract queries - $this->assertEquals('all-contracts', $contractQueries['all-contracts']['name']); - $this->assertEquals(CompanyContract::class, $contractQueries['all-contracts']['resultClass']); - - $this->assertEquals('all', $contractQueries['all']['name']); - $this->assertEquals(CompanyContract::class, $contractQueries['all']['resultClass']); - + $classMetadata = $this->em->getClassMetadata($className); + $repository = $this->em->getRepository($className); + $namedNativeQueries = $classMetadata->getNamedNativeQueries(); + $sqlResultSetMappings = $classMetadata->getSqlResultSetMappings(); - // flex contract queries - $this->assertEquals('all-contracts', $flexQueries['all-contracts']['name']); - $this->assertEquals(CompanyFlexContract::class, $flexQueries['all-contracts']['resultClass']); + // Native Query Mappings + self::assertArrayHasKey('all-contracts', $namedNativeQueries); + self::assertEquals('__CLASS__', $namedNativeQueries['all-contracts']['resultClass']); - $this->assertEquals('all-flex', $flexQueries['all-flex']['name']); - $this->assertEquals(CompanyFlexContract::class, $flexQueries['all-flex']['resultClass']); + self::assertArrayHasKey('all', $namedNativeQueries); + self::assertEquals('__CLASS__', $namedNativeQueries['all']['resultClass']); - $this->assertEquals('all', $flexQueries['all']['name']); - $this->assertEquals(CompanyFlexContract::class, $flexQueries['all']['resultClass']); + // SQL ResultSet Mappings + self::assertArrayHasKey('mapping-all-contracts', $sqlResultSetMappings); + self::assertEquals('__CLASS__', $sqlResultSetMappings['mapping-all-contracts']['entities'][0]['entityClass']); + self::assertArrayHasKey('mapping-all', $sqlResultSetMappings); + self::assertEquals('__CLASS__', $sqlResultSetMappings['mapping-all']['entities'][0]['entityClass']); - // contract result mapping - $this->assertEquals('mapping-all-contracts', $contractMappings['mapping-all-contracts']['name']); - $this->assertEquals(CompanyContract::class, $contractMappings['mapping-all-contracts']['entities'][0]['entityClass']); + // Resolved Native Query Mappings + $allContractsNativeNamedQuery = $repository->createNativeNamedQuery('all-contracts'); + $allNativeNamedQuery = $repository->createNativeNamedQuery('all'); - $this->assertEquals('mapping-all', $contractMappings['mapping-all']['name']); - $this->assertEquals(CompanyContract::class, $contractMappings['mapping-all-contracts']['entities'][0]['entityClass']); - - // flex contract result mapping - $this->assertEquals('mapping-all-contracts', $flexMappings['mapping-all-contracts']['name']); - $this->assertEquals(CompanyFlexContract::class, $flexMappings['mapping-all-contracts']['entities'][0]['entityClass']); - - $this->assertEquals('mapping-all', $flexMappings['mapping-all']['name']); - $this->assertEquals(CompanyFlexContract::class, $flexMappings['mapping-all']['entities'][0]['entityClass']); - - $this->assertEquals('mapping-all-flex', $flexMappings['mapping-all-flex']['name']); - $this->assertEquals(CompanyFlexContract::class, $flexMappings['mapping-all-flex']['entities'][0]['entityClass']); + self::assertEquals($className, $this->getResultSetMapping($allContractsNativeNamedQuery)->getClassName('e0')); + self::assertEquals($className, $this->getResultSetMapping($allNativeNamedQuery)->getClassName('e0')); + } + public function provideDataForNamedNativeQueryInheritance() + { + return [ + [CompanyContract::class], + [CompanyFlexContract::class], + ]; } /** @@ -739,12 +765,13 @@ public function testNamedNativeQueryInheritance() */ public function testGenerateSelectClauseNoRenameSingleEntity() { - $rsm = new ResultSetMappingBuilder($this->_em); + $rsm = new ResultSetMappingBuilder($this->em); + $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); $selectClause = $rsm->generateSelectClause(); - $this->assertSQLEquals('u.id AS id, u.status AS status, u.username AS username, u.name AS name, u.email_id AS email_id', $selectClause); + self::assertSQLEquals('u.id AS id, u.status AS status, u.username AS username, u.name AS name, u.email_id AS email_id', $selectClause); } /** @@ -752,16 +779,20 @@ public function testGenerateSelectClauseNoRenameSingleEntity() */ public function testGenerateSelectClauseCustomRenames() { - $rsm = new ResultSetMappingBuilder($this->_em); - $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u', [ - 'id' => 'id1', - 'username' => 'username2' - ] + $rsm = new ResultSetMappingBuilder($this->em); + + $rsm->addRootEntityFromClassMetadata( + CmsUser::class, + 'u', + [ + 'id' => 'id1', + 'username' => 'username2' + ] ); $selectClause = $rsm->generateSelectClause(); - $this->assertSQLEquals('u.id AS id1, u.status AS status, u.username AS username2, u.name AS name, u.email_id AS email_id', $selectClause); + self::assertSQLEquals('u.id AS id1, u.status AS status, u.username AS username2, u.name AS name, u.email_id AS email_id', $selectClause); } /** @@ -769,12 +800,13 @@ public function testGenerateSelectClauseCustomRenames() */ public function testGenerateSelectClauseRenameTableAlias() { - $rsm = new ResultSetMappingBuilder($this->_em); + $rsm = new ResultSetMappingBuilder($this->em); + $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); $selectClause = $rsm->generateSelectClause(['u' => 'u1']); - $this->assertSQLEquals('u1.id AS id, u1.status AS status, u1.username AS username, u1.name AS name, u1.email_id AS email_id', $selectClause); + self::assertSQLEquals('u1.id AS id, u1.status AS status, u1.username AS username, u1.name AS name, u1.email_id AS email_id', $selectClause); } /** @@ -782,12 +814,13 @@ public function testGenerateSelectClauseRenameTableAlias() */ public function testGenerateSelectClauseIncrement() { - $rsm = new ResultSetMappingBuilder($this->_em, ResultSetMappingBuilder::COLUMN_RENAMING_INCREMENT); + $rsm = new ResultSetMappingBuilder($this->em, ResultSetMappingBuilder::COLUMN_RENAMING_INCREMENT); + $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); $selectClause = $rsm->generateSelectClause(); - $this->assertSQLEquals('u.id AS id0, u.status AS status1, u.username AS username2, u.name AS name3, u.email_id AS email_id4', $selectClause); + self::assertSQLEquals('u.id AS id0, u.status AS status1, u.username AS username2, u.name AS name3, u.email_id AS email_id4', $selectClause); } /** @@ -795,10 +828,11 @@ public function testGenerateSelectClauseIncrement() */ public function testGenerateSelectClauseToString() { - $rsm = new ResultSetMappingBuilder($this->_em, ResultSetMappingBuilder::COLUMN_RENAMING_INCREMENT); + $rsm = new ResultSetMappingBuilder($this->em, ResultSetMappingBuilder::COLUMN_RENAMING_INCREMENT); + $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); - $this->assertSQLEquals('u.id AS id0, u.status AS status1, u.username AS username2, u.name AS name3, u.email_id AS email_id4', (string)$rsm); + self::assertSQLEquals('u.id AS id0, u.status AS status1, u.username AS username2, u.name AS name3, u.email_id AS email_id4', (string)$rsm); } /** @@ -806,7 +840,8 @@ public function testGenerateSelectClauseToString() */ public function testGenerateSelectClauseWithDiscriminatorColumn() { - $rsm = new ResultSetMappingBuilder($this->_em, ResultSetMappingBuilder::COLUMN_RENAMING_INCREMENT); + $rsm = new ResultSetMappingBuilder($this->em, ResultSetMappingBuilder::COLUMN_RENAMING_INCREMENT); + $rsm->addEntityResult(DDC3899User::class, 'u'); $rsm->addJoinedEntityResult(DDC3899FixContract::class, 'c', 'u', 'contracts'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('id'), 'id'); @@ -814,6 +849,16 @@ public function testGenerateSelectClauseWithDiscriminatorColumn() $selectClause = $rsm->generateSelectClause(['u' => 'u1', 'c' => 'c1']); - $this->assertSQLEquals('u1.id as id, c1.discr as discr', $selectClause); + self::assertSQLEquals('u1.id as id, c1.discr as discr', $selectClause); + } + + protected function getResultSetMapping(AbstractQuery $query) : ResultSetMapping + { + $reflClass = new \ReflectionClass($query); + $reflMethod = $reflClass->getMethod('getResultSetMapping'); + + $reflMethod->setAccessible(true); + + return $reflMethod->invoke($query); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/NewOperatorTest.php b/tests/Doctrine/Tests/ORM/Functional/NewOperatorTest.php index 1422dcd9a2c..79482c8efbf 100644 --- a/tests/Doctrine/Tests/ORM/Functional/NewOperatorTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/NewOperatorTest.php @@ -1,5 +1,7 @@ phonenumbers[1]->phonenumber = "(33) 2222-2222"; $u3->phonenumbers[2]->phonenumber = "(33) 3333-3333"; - $this->_em->persist($u1); - $this->_em->persist($u2); - $this->_em->persist($u3); + $this->em->persist($u1); + $this->em->persist($u2); + $this->em->persist($u3); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $this->fixtures = [$u1, $u2, $u3]; } @@ -119,26 +121,26 @@ public function testShouldSupportsBasicUsage($hydrationMode) ORDER BY u.name"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult($hydrationMode); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0]); - $this->assertInstanceOf(CmsUserDTO::class, $result[1]); - $this->assertInstanceOf(CmsUserDTO::class, $result[2]); + self::assertInstanceOf(CmsUserDTO::class, $result[0]); + self::assertInstanceOf(CmsUserDTO::class, $result[1]); + self::assertInstanceOf(CmsUserDTO::class, $result[2]); - $this->assertEquals($this->fixtures[0]->name, $result[0]->name); - $this->assertEquals($this->fixtures[1]->name, $result[1]->name); - $this->assertEquals($this->fixtures[2]->name, $result[2]->name); + self::assertEquals($this->fixtures[0]->name, $result[0]->name); + self::assertEquals($this->fixtures[1]->name, $result[1]->name); + self::assertEquals($this->fixtures[2]->name, $result[2]->name); - $this->assertEquals($this->fixtures[0]->email->email, $result[0]->email); - $this->assertEquals($this->fixtures[1]->email->email, $result[1]->email); - $this->assertEquals($this->fixtures[2]->email->email, $result[2]->email); + self::assertEquals($this->fixtures[0]->email->email, $result[0]->email); + self::assertEquals($this->fixtures[1]->email->email, $result[1]->email); + self::assertEquals($this->fixtures[2]->email->email, $result[2]->email); - $this->assertEquals($this->fixtures[0]->address->city, $result[0]->address); - $this->assertEquals($this->fixtures[1]->address->city, $result[1]->address); - $this->assertEquals($this->fixtures[2]->address->city, $result[2]->address); + self::assertEquals($this->fixtures[0]->address->city, $result[0]->address); + self::assertEquals($this->fixtures[1]->address->city, $result[1]->address); + self::assertEquals($this->fixtures[2]->address->city, $result[2]->address); } /** @@ -162,26 +164,26 @@ public function testShouldIgnoreAliasesForSingleObject($hydrationMode) ORDER BY u.name"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult($hydrationMode); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0]); - $this->assertInstanceOf(CmsUserDTO::class, $result[1]); - $this->assertInstanceOf(CmsUserDTO::class, $result[2]); + self::assertInstanceOf(CmsUserDTO::class, $result[0]); + self::assertInstanceOf(CmsUserDTO::class, $result[1]); + self::assertInstanceOf(CmsUserDTO::class, $result[2]); - $this->assertEquals($this->fixtures[0]->name, $result[0]->name); - $this->assertEquals($this->fixtures[1]->name, $result[1]->name); - $this->assertEquals($this->fixtures[2]->name, $result[2]->name); + self::assertEquals($this->fixtures[0]->name, $result[0]->name); + self::assertEquals($this->fixtures[1]->name, $result[1]->name); + self::assertEquals($this->fixtures[2]->name, $result[2]->name); - $this->assertEquals($this->fixtures[0]->email->email, $result[0]->email); - $this->assertEquals($this->fixtures[1]->email->email, $result[1]->email); - $this->assertEquals($this->fixtures[2]->email->email, $result[2]->email); + self::assertEquals($this->fixtures[0]->email->email, $result[0]->email); + self::assertEquals($this->fixtures[1]->email->email, $result[1]->email); + self::assertEquals($this->fixtures[2]->email->email, $result[2]->email); - $this->assertEquals($this->fixtures[0]->address->city, $result[0]->address); - $this->assertEquals($this->fixtures[1]->address->city, $result[1]->address); - $this->assertEquals($this->fixtures[2]->address->city, $result[2]->address); + self::assertEquals($this->fixtures[0]->address->city, $result[0]->address); + self::assertEquals($this->fixtures[1]->address->city, $result[1]->address); + self::assertEquals($this->fixtures[2]->address->city, $result[2]->address); } public function testShouldAssumeFromEntityNamespaceWhenNotGiven() @@ -198,14 +200,14 @@ public function testShouldAssumeFromEntityNamespaceWhenNotGiven() ORDER BY u.name"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0]); - $this->assertInstanceOf(CmsUserDTO::class, $result[1]); - $this->assertInstanceOf(CmsUserDTO::class, $result[2]); + self::assertInstanceOf(CmsUserDTO::class, $result[0]); + self::assertInstanceOf(CmsUserDTO::class, $result[1]); + self::assertInstanceOf(CmsUserDTO::class, $result[2]); } public function testShouldSupportFromEntityNamespaceAlias() @@ -223,17 +225,17 @@ public function testShouldSupportFromEntityNamespaceAlias() u.name"; - $this->_em->getConfiguration() + $this->em->getConfiguration() ->addEntityNamespace('cms', 'Doctrine\Tests\Models\CMS'); - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0]); - $this->assertInstanceOf(CmsUserDTO::class, $result[1]); - $this->assertInstanceOf(CmsUserDTO::class, $result[2]); + self::assertInstanceOf(CmsUserDTO::class, $result[0]); + self::assertInstanceOf(CmsUserDTO::class, $result[1]); + self::assertInstanceOf(CmsUserDTO::class, $result[2]); } public function testShouldSupportValueObjectNamespaceAlias() @@ -251,17 +253,17 @@ public function testShouldSupportValueObjectNamespaceAlias() u.name"; - $this->_em->getConfiguration() + $this->em->getConfiguration() ->addEntityNamespace('cms', 'Doctrine\Tests\Models\CMS'); - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0]); - $this->assertInstanceOf(CmsUserDTO::class, $result[1]); - $this->assertInstanceOf(CmsUserDTO::class, $result[2]); + self::assertInstanceOf(CmsUserDTO::class, $result[0]); + self::assertInstanceOf(CmsUserDTO::class, $result[1]); + self::assertInstanceOf(CmsUserDTO::class, $result[2]); } public function testShouldSupportLiteralExpression() @@ -287,31 +289,31 @@ public function testShouldSupportLiteralExpression() ORDER BY u.name"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0]); - $this->assertInstanceOf(CmsUserDTO::class, $result[1]); - $this->assertInstanceOf(CmsUserDTO::class, $result[2]); + self::assertInstanceOf(CmsUserDTO::class, $result[0]); + self::assertInstanceOf(CmsUserDTO::class, $result[1]); + self::assertInstanceOf(CmsUserDTO::class, $result[2]); - $this->assertEquals($this->fixtures[0]->name, $result[0]->name); - $this->assertEquals($this->fixtures[1]->name, $result[1]->name); - $this->assertEquals($this->fixtures[2]->name, $result[2]->name); + self::assertEquals($this->fixtures[0]->name, $result[0]->name); + self::assertEquals($this->fixtures[1]->name, $result[1]->name); + self::assertEquals($this->fixtures[2]->name, $result[2]->name); - $this->assertEquals('fabio.bat.silva@gmail.com', $result[0]->email); - $this->assertEquals('fabio.bat.silva@gmail.com', $result[1]->email); - $this->assertEquals('fabio.bat.silva@gmail.com', $result[2]->email); + self::assertEquals('fabio.bat.silva@gmail.com', $result[0]->email); + self::assertEquals('fabio.bat.silva@gmail.com', $result[1]->email); + self::assertEquals('fabio.bat.silva@gmail.com', $result[2]->email); - $this->assertEquals(false, $result[0]->address); - $this->assertEquals(false, $result[1]->address); - $this->assertEquals(false, $result[2]->address); + self::assertEquals(false, $result[0]->address); + self::assertEquals(false, $result[1]->address); + self::assertEquals(false, $result[2]->address); - $this->assertEquals(123, $result[0]->phonenumbers); - $this->assertEquals(123, $result[1]->phonenumbers); - $this->assertEquals(123, $result[2]->phonenumbers); + self::assertEquals(123, $result[0]->phonenumbers); + self::assertEquals(123, $result[1]->phonenumbers); + self::assertEquals(123, $result[2]->phonenumbers); } public function testShouldSupportCaseExpression() @@ -335,23 +337,23 @@ public function testShouldSupportCaseExpression() ORDER BY u.name"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0]); - $this->assertInstanceOf(CmsUserDTO::class, $result[1]); - $this->assertInstanceOf(CmsUserDTO::class, $result[2]); + self::assertInstanceOf(CmsUserDTO::class, $result[0]); + self::assertInstanceOf(CmsUserDTO::class, $result[1]); + self::assertInstanceOf(CmsUserDTO::class, $result[2]); - $this->assertEquals($this->fixtures[0]->name, $result[0]->name); - $this->assertEquals($this->fixtures[1]->name, $result[1]->name); - $this->assertEquals($this->fixtures[2]->name, $result[2]->name); + self::assertEquals($this->fixtures[0]->name, $result[0]->name); + self::assertEquals($this->fixtures[1]->name, $result[1]->name); + self::assertEquals($this->fixtures[2]->name, $result[2]->name); - $this->assertEquals('TEST1', $result[0]->email); - $this->assertEquals('OTHER_TEST', $result[1]->email); - $this->assertEquals('OTHER_TEST', $result[2]->email); + self::assertEquals('TEST1', $result[0]->email); + self::assertEquals('OTHER_TEST', $result[1]->email); + self::assertEquals('OTHER_TEST', $result[2]->email); } public function testShouldSupportSimpleArithmeticExpression() @@ -377,38 +379,38 @@ public function testShouldSupportSimpleArithmeticExpression() ORDER BY u.name"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0]); - $this->assertInstanceOf(CmsUserDTO::class, $result[1]); - $this->assertInstanceOf(CmsUserDTO::class, $result[2]); + self::assertInstanceOf(CmsUserDTO::class, $result[0]); + self::assertInstanceOf(CmsUserDTO::class, $result[1]); + self::assertInstanceOf(CmsUserDTO::class, $result[2]); - $this->assertEquals($this->fixtures[0]->name, $result[0]->name); - $this->assertEquals($this->fixtures[1]->name, $result[1]->name); - $this->assertEquals($this->fixtures[2]->name, $result[2]->name); + self::assertEquals($this->fixtures[0]->name, $result[0]->name); + self::assertEquals($this->fixtures[1]->name, $result[1]->name); + self::assertEquals($this->fixtures[2]->name, $result[2]->name); - $this->assertEquals($this->fixtures[0]->email->email, $result[0]->email); - $this->assertEquals($this->fixtures[1]->email->email, $result[1]->email); - $this->assertEquals($this->fixtures[2]->email->email, $result[2]->email); + self::assertEquals($this->fixtures[0]->email->email, $result[0]->email); + self::assertEquals($this->fixtures[1]->email->email, $result[1]->email); + self::assertEquals($this->fixtures[2]->email->email, $result[2]->email); - $this->assertEquals($this->fixtures[0]->address->city, $result[0]->address); - $this->assertEquals($this->fixtures[1]->address->city, $result[1]->address); - $this->assertEquals($this->fixtures[2]->address->city, $result[2]->address); + self::assertEquals($this->fixtures[0]->address->city, $result[0]->address); + self::assertEquals($this->fixtures[1]->address->city, $result[1]->address); + self::assertEquals($this->fixtures[2]->address->city, $result[2]->address); - $this->assertEquals( + self::assertEquals( ($this->fixtures[0]->address->id + $this->fixtures[0]->id), $result[0]->phonenumbers ); - $this->assertEquals( + self::assertEquals( ($this->fixtures[1]->address->id + $this->fixtures[1]->id), $result[1]->phonenumbers ); - $this->assertEquals( + self::assertEquals( ($this->fixtures[2]->address->id + $this->fixtures[2]->id), $result[2]->phonenumbers ); @@ -437,38 +439,38 @@ public function testShouldSupportAggregateFunctions() ORDER BY u.name"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0]); - $this->assertInstanceOf(CmsUserDTO::class, $result[1]); - $this->assertInstanceOf(CmsUserDTO::class, $result[2]); + self::assertInstanceOf(CmsUserDTO::class, $result[0]); + self::assertInstanceOf(CmsUserDTO::class, $result[1]); + self::assertInstanceOf(CmsUserDTO::class, $result[2]); - $this->assertEquals($this->fixtures[0]->name, $result[0]->name); - $this->assertEquals($this->fixtures[1]->name, $result[1]->name); - $this->assertEquals($this->fixtures[2]->name, $result[2]->name); + self::assertEquals($this->fixtures[0]->name, $result[0]->name); + self::assertEquals($this->fixtures[1]->name, $result[1]->name); + self::assertEquals($this->fixtures[2]->name, $result[2]->name); - $this->assertEquals($this->fixtures[0]->email->email, $result[0]->email); - $this->assertEquals($this->fixtures[1]->email->email, $result[1]->email); - $this->assertEquals($this->fixtures[2]->email->email, $result[2]->email); + self::assertEquals($this->fixtures[0]->email->email, $result[0]->email); + self::assertEquals($this->fixtures[1]->email->email, $result[1]->email); + self::assertEquals($this->fixtures[2]->email->email, $result[2]->email); - $this->assertEquals($this->fixtures[0]->address->city, $result[0]->address); - $this->assertEquals($this->fixtures[1]->address->city, $result[1]->address); - $this->assertEquals($this->fixtures[2]->address->city, $result[2]->address); + self::assertEquals($this->fixtures[0]->address->city, $result[0]->address); + self::assertEquals($this->fixtures[1]->address->city, $result[1]->address); + self::assertEquals($this->fixtures[2]->address->city, $result[2]->address); - $this->assertEquals( + self::assertEquals( (count($this->fixtures[0]->phonenumbers)), $result[0]->phonenumbers ); - $this->assertEquals( + self::assertEquals( (count($this->fixtures[1]->phonenumbers)), $result[1]->phonenumbers ); - $this->assertEquals( + self::assertEquals( (count($this->fixtures[2]->phonenumbers)), $result[2]->phonenumbers ); @@ -497,38 +499,38 @@ public function testShouldSupportArithmeticExpression() ORDER BY u.name"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0]); - $this->assertInstanceOf(CmsUserDTO::class, $result[1]); - $this->assertInstanceOf(CmsUserDTO::class, $result[2]); + self::assertInstanceOf(CmsUserDTO::class, $result[0]); + self::assertInstanceOf(CmsUserDTO::class, $result[1]); + self::assertInstanceOf(CmsUserDTO::class, $result[2]); - $this->assertEquals($this->fixtures[0]->name, $result[0]->name); - $this->assertEquals($this->fixtures[1]->name, $result[1]->name); - $this->assertEquals($this->fixtures[2]->name, $result[2]->name); + self::assertEquals($this->fixtures[0]->name, $result[0]->name); + self::assertEquals($this->fixtures[1]->name, $result[1]->name); + self::assertEquals($this->fixtures[2]->name, $result[2]->name); - $this->assertEquals($this->fixtures[0]->email->email, $result[0]->email); - $this->assertEquals($this->fixtures[1]->email->email, $result[1]->email); - $this->assertEquals($this->fixtures[2]->email->email, $result[2]->email); + self::assertEquals($this->fixtures[0]->email->email, $result[0]->email); + self::assertEquals($this->fixtures[1]->email->email, $result[1]->email); + self::assertEquals($this->fixtures[2]->email->email, $result[2]->email); - $this->assertEquals($this->fixtures[0]->address->city, $result[0]->address); - $this->assertEquals($this->fixtures[1]->address->city, $result[1]->address); - $this->assertEquals($this->fixtures[2]->address->city, $result[2]->address); + self::assertEquals($this->fixtures[0]->address->city, $result[0]->address); + self::assertEquals($this->fixtures[1]->address->city, $result[1]->address); + self::assertEquals($this->fixtures[2]->address->city, $result[2]->address); - $this->assertEquals( + self::assertEquals( (count($this->fixtures[0]->phonenumbers) + $this->fixtures[0]->id), $result[0]->phonenumbers ); - $this->assertEquals( + self::assertEquals( (count($this->fixtures[1]->phonenumbers) + $this->fixtures[1]->id), $result[1]->phonenumbers ); - $this->assertEquals( + self::assertEquals( (count($this->fixtures[2]->phonenumbers) + $this->fixtures[2]->id), $result[2]->phonenumbers ); @@ -555,35 +557,35 @@ public function testShouldSupportMultipleNewOperators() ORDER BY u.name"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0][0]); - $this->assertInstanceOf(CmsUserDTO::class, $result[1][0]); - $this->assertInstanceOf(CmsUserDTO::class, $result[2][0]); + self::assertInstanceOf(CmsUserDTO::class, $result[0][0]); + self::assertInstanceOf(CmsUserDTO::class, $result[1][0]); + self::assertInstanceOf(CmsUserDTO::class, $result[2][0]); - $this->assertInstanceOf(CmsAddressDTO::class, $result[0][1]); - $this->assertInstanceOf(CmsAddressDTO::class, $result[1][1]); - $this->assertInstanceOf(CmsAddressDTO::class, $result[2][1]); + self::assertInstanceOf(CmsAddressDTO::class, $result[0][1]); + self::assertInstanceOf(CmsAddressDTO::class, $result[1][1]); + self::assertInstanceOf(CmsAddressDTO::class, $result[2][1]); - $this->assertEquals($this->fixtures[0]->name, $result[0][0]->name); - $this->assertEquals($this->fixtures[1]->name, $result[1][0]->name); - $this->assertEquals($this->fixtures[2]->name, $result[2][0]->name); + self::assertEquals($this->fixtures[0]->name, $result[0][0]->name); + self::assertEquals($this->fixtures[1]->name, $result[1][0]->name); + self::assertEquals($this->fixtures[2]->name, $result[2][0]->name); - $this->assertEquals($this->fixtures[0]->email->email, $result[0][0]->email); - $this->assertEquals($this->fixtures[1]->email->email, $result[1][0]->email); - $this->assertEquals($this->fixtures[2]->email->email, $result[2][0]->email); + self::assertEquals($this->fixtures[0]->email->email, $result[0][0]->email); + self::assertEquals($this->fixtures[1]->email->email, $result[1][0]->email); + self::assertEquals($this->fixtures[2]->email->email, $result[2][0]->email); - $this->assertEquals($this->fixtures[0]->address->city, $result[0][1]->city); - $this->assertEquals($this->fixtures[1]->address->city, $result[1][1]->city); - $this->assertEquals($this->fixtures[2]->address->city, $result[2][1]->city); + self::assertEquals($this->fixtures[0]->address->city, $result[0][1]->city); + self::assertEquals($this->fixtures[1]->address->city, $result[1][1]->city); + self::assertEquals($this->fixtures[2]->address->city, $result[2][1]->city); - $this->assertEquals($this->fixtures[0]->address->country, $result[0][1]->country); - $this->assertEquals($this->fixtures[1]->address->country, $result[1][1]->country); - $this->assertEquals($this->fixtures[2]->address->country, $result[2][1]->country); + self::assertEquals($this->fixtures[0]->address->country, $result[0][1]->country); + self::assertEquals($this->fixtures[1]->address->country, $result[1][1]->country); + self::assertEquals($this->fixtures[2]->address->country, $result[2][1]->country); } public function testShouldSupportMultipleNewOperatorsWithAliases() @@ -607,35 +609,35 @@ public function testShouldSupportMultipleNewOperatorsWithAliases() ORDER BY u.name"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); - $this->assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); - $this->assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); - $this->assertInstanceOf(CmsAddressDTO::class, $result[0]['cmsAddress']); - $this->assertInstanceOf(CmsAddressDTO::class, $result[1]['cmsAddress']); - $this->assertInstanceOf(CmsAddressDTO::class, $result[2]['cmsAddress']); + self::assertInstanceOf(CmsAddressDTO::class, $result[0]['cmsAddress']); + self::assertInstanceOf(CmsAddressDTO::class, $result[1]['cmsAddress']); + self::assertInstanceOf(CmsAddressDTO::class, $result[2]['cmsAddress']); - $this->assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); - $this->assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); - $this->assertEquals($this->fixtures[2]->name, $result[2]['cmsUser']->name); + self::assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); + self::assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); + self::assertEquals($this->fixtures[2]->name, $result[2]['cmsUser']->name); - $this->assertEquals($this->fixtures[0]->email->email, $result[0]['cmsUser']->email); - $this->assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); - $this->assertEquals($this->fixtures[2]->email->email, $result[2]['cmsUser']->email); + self::assertEquals($this->fixtures[0]->email->email, $result[0]['cmsUser']->email); + self::assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); + self::assertEquals($this->fixtures[2]->email->email, $result[2]['cmsUser']->email); - $this->assertEquals($this->fixtures[0]->address->city, $result[0]['cmsAddress']->city); - $this->assertEquals($this->fixtures[1]->address->city, $result[1]['cmsAddress']->city); - $this->assertEquals($this->fixtures[2]->address->city, $result[2]['cmsAddress']->city); + self::assertEquals($this->fixtures[0]->address->city, $result[0]['cmsAddress']->city); + self::assertEquals($this->fixtures[1]->address->city, $result[1]['cmsAddress']->city); + self::assertEquals($this->fixtures[2]->address->city, $result[2]['cmsAddress']->city); - $this->assertEquals($this->fixtures[0]->address->country, $result[0]['cmsAddress']->country); - $this->assertEquals($this->fixtures[1]->address->country, $result[1]['cmsAddress']->country); - $this->assertEquals($this->fixtures[2]->address->country, $result[2]['cmsAddress']->country); + self::assertEquals($this->fixtures[0]->address->country, $result[0]['cmsAddress']->country); + self::assertEquals($this->fixtures[1]->address->country, $result[1]['cmsAddress']->country); + self::assertEquals($this->fixtures[2]->address->country, $result[2]['cmsAddress']->country); } public function testShouldSupportMultipleNewOperatorsWithAndWithoutAliases() @@ -659,35 +661,35 @@ public function testShouldSupportMultipleNewOperatorsWithAndWithoutAliases() ORDER BY u.name"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); - $this->assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); - $this->assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); - $this->assertInstanceOf(CmsAddressDTO::class, $result[0][0]); - $this->assertInstanceOf(CmsAddressDTO::class, $result[1][0]); - $this->assertInstanceOf(CmsAddressDTO::class, $result[2][0]); + self::assertInstanceOf(CmsAddressDTO::class, $result[0][0]); + self::assertInstanceOf(CmsAddressDTO::class, $result[1][0]); + self::assertInstanceOf(CmsAddressDTO::class, $result[2][0]); - $this->assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); - $this->assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); - $this->assertEquals($this->fixtures[2]->name, $result[2]['cmsUser']->name); + self::assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); + self::assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); + self::assertEquals($this->fixtures[2]->name, $result[2]['cmsUser']->name); - $this->assertEquals($this->fixtures[0]->email->email, $result[0]['cmsUser']->email); - $this->assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); - $this->assertEquals($this->fixtures[2]->email->email, $result[2]['cmsUser']->email); + self::assertEquals($this->fixtures[0]->email->email, $result[0]['cmsUser']->email); + self::assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); + self::assertEquals($this->fixtures[2]->email->email, $result[2]['cmsUser']->email); - $this->assertEquals($this->fixtures[0]->address->city, $result[0][0]->city); - $this->assertEquals($this->fixtures[1]->address->city, $result[1][0]->city); - $this->assertEquals($this->fixtures[2]->address->city, $result[2][0]->city); + self::assertEquals($this->fixtures[0]->address->city, $result[0][0]->city); + self::assertEquals($this->fixtures[1]->address->city, $result[1][0]->city); + self::assertEquals($this->fixtures[2]->address->city, $result[2][0]->city); - $this->assertEquals($this->fixtures[0]->address->country, $result[0][0]->country); - $this->assertEquals($this->fixtures[1]->address->country, $result[1][0]->country); - $this->assertEquals($this->fixtures[2]->address->country, $result[2][0]->country); + self::assertEquals($this->fixtures[0]->address->country, $result[0][0]->country); + self::assertEquals($this->fixtures[1]->address->country, $result[1][0]->country); + self::assertEquals($this->fixtures[2]->address->country, $result[2][0]->country); } public function testShouldSupportMultipleNewOperatorsAndSingleScalar() @@ -712,39 +714,39 @@ public function testShouldSupportMultipleNewOperatorsAndSingleScalar() ORDER BY u.name"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0][0]); - $this->assertInstanceOf(CmsUserDTO::class, $result[1][0]); - $this->assertInstanceOf(CmsUserDTO::class, $result[2][0]); + self::assertInstanceOf(CmsUserDTO::class, $result[0][0]); + self::assertInstanceOf(CmsUserDTO::class, $result[1][0]); + self::assertInstanceOf(CmsUserDTO::class, $result[2][0]); - $this->assertInstanceOf(CmsAddressDTO::class, $result[0][1]); - $this->assertInstanceOf(CmsAddressDTO::class, $result[1][1]); - $this->assertInstanceOf(CmsAddressDTO::class, $result[2][1]); + self::assertInstanceOf(CmsAddressDTO::class, $result[0][1]); + self::assertInstanceOf(CmsAddressDTO::class, $result[1][1]); + self::assertInstanceOf(CmsAddressDTO::class, $result[2][1]); - $this->assertEquals($this->fixtures[0]->name, $result[0][0]->name); - $this->assertEquals($this->fixtures[1]->name, $result[1][0]->name); - $this->assertEquals($this->fixtures[2]->name, $result[2][0]->name); + self::assertEquals($this->fixtures[0]->name, $result[0][0]->name); + self::assertEquals($this->fixtures[1]->name, $result[1][0]->name); + self::assertEquals($this->fixtures[2]->name, $result[2][0]->name); - $this->assertEquals($this->fixtures[0]->email->email, $result[0][0]->email); - $this->assertEquals($this->fixtures[1]->email->email, $result[1][0]->email); - $this->assertEquals($this->fixtures[2]->email->email, $result[2][0]->email); + self::assertEquals($this->fixtures[0]->email->email, $result[0][0]->email); + self::assertEquals($this->fixtures[1]->email->email, $result[1][0]->email); + self::assertEquals($this->fixtures[2]->email->email, $result[2][0]->email); - $this->assertEquals($this->fixtures[0]->address->city, $result[0][1]->city); - $this->assertEquals($this->fixtures[1]->address->city, $result[1][1]->city); - $this->assertEquals($this->fixtures[2]->address->city, $result[2][1]->city); + self::assertEquals($this->fixtures[0]->address->city, $result[0][1]->city); + self::assertEquals($this->fixtures[1]->address->city, $result[1][1]->city); + self::assertEquals($this->fixtures[2]->address->city, $result[2][1]->city); - $this->assertEquals($this->fixtures[0]->address->country, $result[0][1]->country); - $this->assertEquals($this->fixtures[1]->address->country, $result[1][1]->country); - $this->assertEquals($this->fixtures[2]->address->country, $result[2][1]->country); + self::assertEquals($this->fixtures[0]->address->country, $result[0][1]->country); + self::assertEquals($this->fixtures[1]->address->country, $result[1][1]->country); + self::assertEquals($this->fixtures[2]->address->country, $result[2][1]->country); - $this->assertEquals($this->fixtures[0]->status,$result[0]['status']); - $this->assertEquals($this->fixtures[1]->status,$result[1]['status']); - $this->assertEquals($this->fixtures[2]->status,$result[2]['status']); + self::assertEquals($this->fixtures[0]->status,$result[0]['status']); + self::assertEquals($this->fixtures[1]->status,$result[1]['status']); + self::assertEquals($this->fixtures[2]->status,$result[2]['status']); } public function testShouldSupportMultipleNewOperatorsAndSingleScalarWithAliases() @@ -769,39 +771,39 @@ public function testShouldSupportMultipleNewOperatorsAndSingleScalarWithAliases( ORDER BY u.name"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); - $this->assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); - $this->assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); - $this->assertInstanceOf(CmsAddressDTO::class, $result[0]['cmsAddress']); - $this->assertInstanceOf(CmsAddressDTO::class, $result[1]['cmsAddress']); - $this->assertInstanceOf(CmsAddressDTO::class, $result[2]['cmsAddress']); + self::assertInstanceOf(CmsAddressDTO::class, $result[0]['cmsAddress']); + self::assertInstanceOf(CmsAddressDTO::class, $result[1]['cmsAddress']); + self::assertInstanceOf(CmsAddressDTO::class, $result[2]['cmsAddress']); - $this->assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); - $this->assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); - $this->assertEquals($this->fixtures[2]->name, $result[2]['cmsUser']->name); + self::assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); + self::assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); + self::assertEquals($this->fixtures[2]->name, $result[2]['cmsUser']->name); - $this->assertEquals($this->fixtures[0]->email->email, $result[0]['cmsUser']->email); - $this->assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); - $this->assertEquals($this->fixtures[2]->email->email, $result[2]['cmsUser']->email); + self::assertEquals($this->fixtures[0]->email->email, $result[0]['cmsUser']->email); + self::assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); + self::assertEquals($this->fixtures[2]->email->email, $result[2]['cmsUser']->email); - $this->assertEquals($this->fixtures[0]->address->city, $result[0]['cmsAddress']->city); - $this->assertEquals($this->fixtures[1]->address->city, $result[1]['cmsAddress']->city); - $this->assertEquals($this->fixtures[2]->address->city, $result[2]['cmsAddress']->city); + self::assertEquals($this->fixtures[0]->address->city, $result[0]['cmsAddress']->city); + self::assertEquals($this->fixtures[1]->address->city, $result[1]['cmsAddress']->city); + self::assertEquals($this->fixtures[2]->address->city, $result[2]['cmsAddress']->city); - $this->assertEquals($this->fixtures[0]->address->country, $result[0]['cmsAddress']->country); - $this->assertEquals($this->fixtures[1]->address->country, $result[1]['cmsAddress']->country); - $this->assertEquals($this->fixtures[2]->address->country, $result[2]['cmsAddress']->country); + self::assertEquals($this->fixtures[0]->address->country, $result[0]['cmsAddress']->country); + self::assertEquals($this->fixtures[1]->address->country, $result[1]['cmsAddress']->country); + self::assertEquals($this->fixtures[2]->address->country, $result[2]['cmsAddress']->country); - $this->assertEquals($this->fixtures[0]->status,$result[0]['cmsUserStatus']); - $this->assertEquals($this->fixtures[1]->status,$result[1]['cmsUserStatus']); - $this->assertEquals($this->fixtures[2]->status,$result[2]['cmsUserStatus']); + self::assertEquals($this->fixtures[0]->status,$result[0]['cmsUserStatus']); + self::assertEquals($this->fixtures[1]->status,$result[1]['cmsUserStatus']); + self::assertEquals($this->fixtures[2]->status,$result[2]['cmsUserStatus']); } public function testShouldSupportMultipleNewOperatorsAndSingleScalarWithAndWithoutAliases() @@ -826,39 +828,39 @@ public function testShouldSupportMultipleNewOperatorsAndSingleScalarWithAndWitho ORDER BY u.name"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); - $this->assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); - $this->assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); - $this->assertInstanceOf(CmsAddressDTO::class, $result[0][0]); - $this->assertInstanceOf(CmsAddressDTO::class, $result[1][0]); - $this->assertInstanceOf(CmsAddressDTO::class, $result[2][0]); + self::assertInstanceOf(CmsAddressDTO::class, $result[0][0]); + self::assertInstanceOf(CmsAddressDTO::class, $result[1][0]); + self::assertInstanceOf(CmsAddressDTO::class, $result[2][0]); - $this->assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); - $this->assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); - $this->assertEquals($this->fixtures[2]->name, $result[2]['cmsUser']->name); + self::assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); + self::assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); + self::assertEquals($this->fixtures[2]->name, $result[2]['cmsUser']->name); - $this->assertEquals($this->fixtures[0]->email->email, $result[0]['cmsUser']->email); - $this->assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); - $this->assertEquals($this->fixtures[2]->email->email, $result[2]['cmsUser']->email); + self::assertEquals($this->fixtures[0]->email->email, $result[0]['cmsUser']->email); + self::assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); + self::assertEquals($this->fixtures[2]->email->email, $result[2]['cmsUser']->email); - $this->assertEquals($this->fixtures[0]->address->city, $result[0][0]->city); - $this->assertEquals($this->fixtures[1]->address->city, $result[1][0]->city); - $this->assertEquals($this->fixtures[2]->address->city, $result[2][0]->city); + self::assertEquals($this->fixtures[0]->address->city, $result[0][0]->city); + self::assertEquals($this->fixtures[1]->address->city, $result[1][0]->city); + self::assertEquals($this->fixtures[2]->address->city, $result[2][0]->city); - $this->assertEquals($this->fixtures[0]->address->country, $result[0][0]->country); - $this->assertEquals($this->fixtures[1]->address->country, $result[1][0]->country); - $this->assertEquals($this->fixtures[2]->address->country, $result[2][0]->country); + self::assertEquals($this->fixtures[0]->address->country, $result[0][0]->country); + self::assertEquals($this->fixtures[1]->address->country, $result[1][0]->country); + self::assertEquals($this->fixtures[2]->address->country, $result[2][0]->country); - $this->assertEquals($this->fixtures[0]->status,$result[0]['status']); - $this->assertEquals($this->fixtures[1]->status,$result[1]['status']); - $this->assertEquals($this->fixtures[2]->status,$result[2]['status']); + self::assertEquals($this->fixtures[0]->status,$result[0]['status']); + self::assertEquals($this->fixtures[1]->status,$result[1]['status']); + self::assertEquals($this->fixtures[2]->status,$result[2]['status']); } public function testShouldSupportMultipleNewOperatorsAndMultipleScalars() @@ -884,43 +886,43 @@ public function testShouldSupportMultipleNewOperatorsAndMultipleScalars() ORDER BY u.name"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0][0]); - $this->assertInstanceOf(CmsUserDTO::class, $result[1][0]); - $this->assertInstanceOf(CmsUserDTO::class, $result[2][0]); + self::assertInstanceOf(CmsUserDTO::class, $result[0][0]); + self::assertInstanceOf(CmsUserDTO::class, $result[1][0]); + self::assertInstanceOf(CmsUserDTO::class, $result[2][0]); - $this->assertInstanceOf(CmsAddressDTO::class, $result[0][1]); - $this->assertInstanceOf(CmsAddressDTO::class, $result[1][1]); - $this->assertInstanceOf(CmsAddressDTO::class, $result[2][1]); + self::assertInstanceOf(CmsAddressDTO::class, $result[0][1]); + self::assertInstanceOf(CmsAddressDTO::class, $result[1][1]); + self::assertInstanceOf(CmsAddressDTO::class, $result[2][1]); - $this->assertEquals($this->fixtures[0]->name, $result[0][0]->name); - $this->assertEquals($this->fixtures[1]->name, $result[1][0]->name); - $this->assertEquals($this->fixtures[2]->name, $result[2][0]->name); + self::assertEquals($this->fixtures[0]->name, $result[0][0]->name); + self::assertEquals($this->fixtures[1]->name, $result[1][0]->name); + self::assertEquals($this->fixtures[2]->name, $result[2][0]->name); - $this->assertEquals($this->fixtures[0]->email->email, $result[0][0]->email); - $this->assertEquals($this->fixtures[1]->email->email, $result[1][0]->email); - $this->assertEquals($this->fixtures[2]->email->email, $result[2][0]->email); + self::assertEquals($this->fixtures[0]->email->email, $result[0][0]->email); + self::assertEquals($this->fixtures[1]->email->email, $result[1][0]->email); + self::assertEquals($this->fixtures[2]->email->email, $result[2][0]->email); - $this->assertEquals($this->fixtures[0]->address->city, $result[0][1]->city); - $this->assertEquals($this->fixtures[1]->address->city, $result[1][1]->city); - $this->assertEquals($this->fixtures[2]->address->city, $result[2][1]->city); + self::assertEquals($this->fixtures[0]->address->city, $result[0][1]->city); + self::assertEquals($this->fixtures[1]->address->city, $result[1][1]->city); + self::assertEquals($this->fixtures[2]->address->city, $result[2][1]->city); - $this->assertEquals($this->fixtures[0]->address->country, $result[0][1]->country); - $this->assertEquals($this->fixtures[1]->address->country, $result[1][1]->country); - $this->assertEquals($this->fixtures[2]->address->country, $result[2][1]->country); + self::assertEquals($this->fixtures[0]->address->country, $result[0][1]->country); + self::assertEquals($this->fixtures[1]->address->country, $result[1][1]->country); + self::assertEquals($this->fixtures[2]->address->country, $result[2][1]->country); - $this->assertEquals($this->fixtures[0]->status,$result[0]['status']); - $this->assertEquals($this->fixtures[1]->status,$result[1]['status']); - $this->assertEquals($this->fixtures[2]->status,$result[2]['status']); + self::assertEquals($this->fixtures[0]->status,$result[0]['status']); + self::assertEquals($this->fixtures[1]->status,$result[1]['status']); + self::assertEquals($this->fixtures[2]->status,$result[2]['status']); - $this->assertEquals($this->fixtures[0]->username,$result[0]['username']); - $this->assertEquals($this->fixtures[1]->username,$result[1]['username']); - $this->assertEquals($this->fixtures[2]->username,$result[2]['username']); + self::assertEquals($this->fixtures[0]->username,$result[0]['username']); + self::assertEquals($this->fixtures[1]->username,$result[1]['username']); + self::assertEquals($this->fixtures[2]->username,$result[2]['username']); } public function testShouldSupportMultipleNewOperatorsAndMultipleScalarsWithAliases() @@ -946,43 +948,43 @@ public function testShouldSupportMultipleNewOperatorsAndMultipleScalarsWithAlias ORDER BY u.name"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); - $this->assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); - $this->assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); - $this->assertInstanceOf(CmsAddressDTO::class, $result[0]['cmsAddress']); - $this->assertInstanceOf(CmsAddressDTO::class, $result[1]['cmsAddress']); - $this->assertInstanceOf(CmsAddressDTO::class, $result[2]['cmsAddress']); + self::assertInstanceOf(CmsAddressDTO::class, $result[0]['cmsAddress']); + self::assertInstanceOf(CmsAddressDTO::class, $result[1]['cmsAddress']); + self::assertInstanceOf(CmsAddressDTO::class, $result[2]['cmsAddress']); - $this->assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); - $this->assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); - $this->assertEquals($this->fixtures[2]->name, $result[2]['cmsUser']->name); + self::assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); + self::assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); + self::assertEquals($this->fixtures[2]->name, $result[2]['cmsUser']->name); - $this->assertEquals($this->fixtures[0]->email->email, $result[0]['cmsUser']->email); - $this->assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); - $this->assertEquals($this->fixtures[2]->email->email, $result[2]['cmsUser']->email); + self::assertEquals($this->fixtures[0]->email->email, $result[0]['cmsUser']->email); + self::assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); + self::assertEquals($this->fixtures[2]->email->email, $result[2]['cmsUser']->email); - $this->assertEquals($this->fixtures[0]->address->city, $result[0]['cmsAddress']->city); - $this->assertEquals($this->fixtures[1]->address->city, $result[1]['cmsAddress']->city); - $this->assertEquals($this->fixtures[2]->address->city, $result[2]['cmsAddress']->city); + self::assertEquals($this->fixtures[0]->address->city, $result[0]['cmsAddress']->city); + self::assertEquals($this->fixtures[1]->address->city, $result[1]['cmsAddress']->city); + self::assertEquals($this->fixtures[2]->address->city, $result[2]['cmsAddress']->city); - $this->assertEquals($this->fixtures[0]->address->country, $result[0]['cmsAddress']->country); - $this->assertEquals($this->fixtures[1]->address->country, $result[1]['cmsAddress']->country); - $this->assertEquals($this->fixtures[2]->address->country, $result[2]['cmsAddress']->country); + self::assertEquals($this->fixtures[0]->address->country, $result[0]['cmsAddress']->country); + self::assertEquals($this->fixtures[1]->address->country, $result[1]['cmsAddress']->country); + self::assertEquals($this->fixtures[2]->address->country, $result[2]['cmsAddress']->country); - $this->assertEquals($this->fixtures[0]->status,$result[0]['cmsUserStatus']); - $this->assertEquals($this->fixtures[1]->status,$result[1]['cmsUserStatus']); - $this->assertEquals($this->fixtures[2]->status,$result[2]['cmsUserStatus']); + self::assertEquals($this->fixtures[0]->status,$result[0]['cmsUserStatus']); + self::assertEquals($this->fixtures[1]->status,$result[1]['cmsUserStatus']); + self::assertEquals($this->fixtures[2]->status,$result[2]['cmsUserStatus']); - $this->assertEquals($this->fixtures[0]->username,$result[0]['cmsUserUsername']); - $this->assertEquals($this->fixtures[1]->username,$result[1]['cmsUserUsername']); - $this->assertEquals($this->fixtures[2]->username,$result[2]['cmsUserUsername']); + self::assertEquals($this->fixtures[0]->username,$result[0]['cmsUserUsername']); + self::assertEquals($this->fixtures[1]->username,$result[1]['cmsUserUsername']); + self::assertEquals($this->fixtures[2]->username,$result[2]['cmsUserUsername']); } public function testShouldSupportMultipleNewOperatorsAndMultipleScalarsWithAndWithoutAliases() @@ -1008,43 +1010,43 @@ public function testShouldSupportMultipleNewOperatorsAndMultipleScalarsWithAndWi ORDER BY u.name"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertCount(3, $result); + self::assertCount(3, $result); - $this->assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); - $this->assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); - $this->assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); + self::assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); - $this->assertInstanceOf(CmsAddressDTO::class, $result[0][0]); - $this->assertInstanceOf(CmsAddressDTO::class, $result[1][0]); - $this->assertInstanceOf(CmsAddressDTO::class, $result[2][0]); + self::assertInstanceOf(CmsAddressDTO::class, $result[0][0]); + self::assertInstanceOf(CmsAddressDTO::class, $result[1][0]); + self::assertInstanceOf(CmsAddressDTO::class, $result[2][0]); - $this->assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); - $this->assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); - $this->assertEquals($this->fixtures[2]->name, $result[2]['cmsUser']->name); + self::assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); + self::assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); + self::assertEquals($this->fixtures[2]->name, $result[2]['cmsUser']->name); - $this->assertEquals($this->fixtures[0]->email->email, $result[0]['cmsUser']->email); - $this->assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); - $this->assertEquals($this->fixtures[2]->email->email, $result[2]['cmsUser']->email); + self::assertEquals($this->fixtures[0]->email->email, $result[0]['cmsUser']->email); + self::assertEquals($this->fixtures[1]->email->email, $result[1]['cmsUser']->email); + self::assertEquals($this->fixtures[2]->email->email, $result[2]['cmsUser']->email); - $this->assertEquals($this->fixtures[0]->address->city, $result[0][0]->city); - $this->assertEquals($this->fixtures[1]->address->city, $result[1][0]->city); - $this->assertEquals($this->fixtures[2]->address->city, $result[2][0]->city); + self::assertEquals($this->fixtures[0]->address->city, $result[0][0]->city); + self::assertEquals($this->fixtures[1]->address->city, $result[1][0]->city); + self::assertEquals($this->fixtures[2]->address->city, $result[2][0]->city); - $this->assertEquals($this->fixtures[0]->address->country, $result[0][0]->country); - $this->assertEquals($this->fixtures[1]->address->country, $result[1][0]->country); - $this->assertEquals($this->fixtures[2]->address->country, $result[2][0]->country); + self::assertEquals($this->fixtures[0]->address->country, $result[0][0]->country); + self::assertEquals($this->fixtures[1]->address->country, $result[1][0]->country); + self::assertEquals($this->fixtures[2]->address->country, $result[2][0]->country); - $this->assertEquals($this->fixtures[0]->status,$result[0]['status']); - $this->assertEquals($this->fixtures[1]->status,$result[1]['status']); - $this->assertEquals($this->fixtures[2]->status,$result[2]['status']); + self::assertEquals($this->fixtures[0]->status,$result[0]['status']); + self::assertEquals($this->fixtures[1]->status,$result[1]['status']); + self::assertEquals($this->fixtures[2]->status,$result[2]['status']); - $this->assertEquals($this->fixtures[0]->username,$result[0]['cmsUserUsername']); - $this->assertEquals($this->fixtures[1]->username,$result[1]['cmsUserUsername']); - $this->assertEquals($this->fixtures[2]->username,$result[2]['cmsUserUsername']); + self::assertEquals($this->fixtures[0]->username,$result[0]['cmsUserUsername']); + self::assertEquals($this->fixtures[1]->username,$result[1]['cmsUserUsername']); + self::assertEquals($this->fixtures[2]->username,$result[2]['cmsUserUsername']); } /** @@ -1054,7 +1056,7 @@ public function testShouldSupportMultipleNewOperatorsAndMultipleScalarsWithAndWi public function testInvalidClassException() { $dql = "SELECT new \InvalidClass(u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u"; - $this->_em->createQuery($dql)->getResult(); + $this->em->createQuery($dql)->getResult(); } /** @@ -1064,7 +1066,7 @@ public function testInvalidClassException() public function testInvalidClassConstructorException() { $dql = "SELECT new \stdClass(u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u"; - $this->_em->createQuery($dql)->getResult(); + $this->em->createQuery($dql)->getResult(); } /** @@ -1074,7 +1076,7 @@ public function testInvalidClassConstructorException() public function testInvalidClassWithoutConstructorException() { $dql = "SELECT new Doctrine\Tests\ORM\Functional\ClassWithTooMuchArgs(u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u"; - $this->_em->createQuery($dql)->getResult(); + $this->em->createQuery($dql)->getResult(); } /** @@ -1084,7 +1086,7 @@ public function testInvalidClassWithoutConstructorException() public function testClassCantBeInstantiatedException() { $dql = "SELECT new Doctrine\Tests\ORM\Functional\ClassWithPrivateConstructor(u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u"; - $this->_em->createQuery($dql)->getResult(); + $this->em->createQuery($dql)->getResult(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/NotifyPolicyTest.php b/tests/Doctrine/Tests/ORM/Functional/NotifyPolicyTest.php index 5444af6710e..28b329e11aa 100644 --- a/tests/Doctrine/Tests/ORM/Functional/NotifyPolicyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/NotifyPolicyTest.php @@ -1,10 +1,13 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(NotifyUser::class), - $this->_em->getClassMetadata(NotifyGroup::class) + $this->em->getClassMetadata(NotifyUser::class), + $this->em->getClassMetadata(NotifyGroup::class) ] ); } catch (\Exception $e) { @@ -39,54 +42,54 @@ public function testChangeTracking() $user->getGroups()->add($group); $group->getUsers()->add($user); - $this->_em->persist($user); - $this->_em->persist($group); + $this->em->persist($user); + $this->em->persist($group); - $this->assertEquals(1, count($user->listeners)); - $this->assertEquals(1, count($group->listeners)); + self::assertEquals(1, count($user->listeners)); + self::assertEquals(1, count($group->listeners)); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $this->assertEquals(1, count($user->listeners)); - $this->assertEquals(1, count($group->listeners)); + self::assertEquals(1, count($user->listeners)); + self::assertEquals(1, count($group->listeners)); $userId = $user->getId(); $groupId = $group->getId(); unset($user, $group); - $user = $this->_em->find(NotifyUser::class, $userId); - $this->assertEquals(1, $user->getGroups()->count()); - $group = $this->_em->find(NotifyGroup::class, $groupId); - $this->assertEquals(1, $group->getUsers()->count()); + $user = $this->em->find(NotifyUser::class, $userId); + self::assertEquals(1, $user->getGroups()->count()); + $group = $this->em->find(NotifyGroup::class, $groupId); + self::assertEquals(1, $group->getUsers()->count()); - $this->assertEquals(1, count($user->listeners)); - $this->assertEquals(1, count($group->listeners)); + self::assertEquals(1, count($user->listeners)); + self::assertEquals(1, count($group->listeners)); $group2 = new NotifyGroup(); $group2->setName('nerds'); - $this->_em->persist($group2); + $this->em->persist($group2); $user->getGroups()->add($group2); $group2->getUsers()->add($user); $group->setName('geeks'); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $this->assertEquals(1, count($user->listeners)); - $this->assertEquals(1, count($group->listeners)); + self::assertEquals(1, count($user->listeners)); + self::assertEquals(1, count($group->listeners)); $group2Id = $group2->getId(); unset($group2, $user); - $user = $this->_em->find(NotifyUser::class, $userId); - $this->assertEquals(2, $user->getGroups()->count()); - $group2 = $this->_em->find(NotifyGroup::class, $group2Id); - $this->assertEquals(1, $group2->getUsers()->count()); - $group = $this->_em->find(NotifyGroup::class, $groupId); - $this->assertEquals(1, $group->getUsers()->count()); - $this->assertEquals('geeks', $group->getName()); + $user = $this->em->find(NotifyUser::class, $userId); + self::assertEquals(2, $user->getGroups()->count()); + $group2 = $this->em->find(NotifyGroup::class, $group2Id); + self::assertEquals(1, $group2->getUsers()->count()); + $group = $this->em->find(NotifyGroup::class, $groupId); + self::assertEquals(1, $group->getUsers()->count()); + self::assertEquals('geeks', $group->getName()); } } @@ -106,68 +109,68 @@ protected function onPropertyChanged($propName, $oldValue, $newValue) { } } -/** @Entity @ChangeTrackingPolicy("NOTIFY") */ +/** @ORM\Entity @ORM\ChangeTrackingPolicy("NOTIFY") */ class NotifyUser extends NotifyBaseEntity { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ private $id; - /** @Column */ + /** @ORM\Column */ private $name; - /** @ManyToMany(targetEntity="NotifyGroup") */ + /** @ORM\ManyToMany(targetEntity="NotifyGroup") */ private $groups; - function __construct() { + public function __construct() { $this->groups = new ArrayCollection; } - function getId() { + public function getId() { return $this->id; } - function getName() { + public function getName() { return $this->name; } - function setName($name) { + public function setName($name) { $this->onPropertyChanged('name', $this->name, $name); $this->name = $name; } - function getGroups() { + public function getGroups() { return $this->groups; } } -/** @Entity */ +/** @ORM\Entity */ class NotifyGroup extends NotifyBaseEntity { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ private $id; - /** @Column */ + /** @ORM\Column */ private $name; - /** @ManyToMany(targetEntity="NotifyUser", mappedBy="groups") */ + /** @ORM\ManyToMany(targetEntity="NotifyUser", mappedBy="groups") */ private $users; - function __construct() { + public function __construct() { $this->users = new ArrayCollection; } - function getId() { + public function getId() { return $this->id; } - function getName() { + public function getName() { return $this->name; } - function setName($name) { + public function setName($name) { $this->onPropertyChanged('name', $this->name, $name); $this->name = $name; } - function getUsers() { + public function getUsers() { return $this->users; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToManyBidirectionalAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToManyBidirectionalAssociationTest.php index 95309c60579..b46de79e8dc 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToManyBidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToManyBidirectionalAssociationTest.php @@ -1,5 +1,7 @@ product->addFeature($this->firstFeature); $this->product->addFeature($this->secondFeature); - $this->_em->persist($this->product); - $this->_em->flush(); + $this->em->persist($this->product); + $this->em->flush(); - $this->assertFeatureForeignKeyIs($this->product->getId(), $this->firstFeature); - $this->assertFeatureForeignKeyIs($this->product->getId(), $this->secondFeature); + self::assertFeatureForeignKeyIs($this->product->getId(), $this->firstFeature); + self::assertFeatureForeignKeyIs($this->product->getId(), $this->secondFeature); } public function testSavesAnEmptyCollection() { - $this->_em->persist($this->product); - $this->_em->flush(); + $this->em->persist($this->product); + $this->em->flush(); - $this->assertEquals(0, count($this->product->getFeatures())); + self::assertEquals(0, count($this->product->getFeatures())); } public function testDoesNotSaveAnInverseSideSet() { $this->product->brokenAddFeature($this->firstFeature); - $this->_em->persist($this->product); - $this->_em->flush(); + $this->em->persist($this->product); + $this->em->flush(); - $this->assertFeatureForeignKeyIs(null, $this->firstFeature); + self::assertFeatureForeignKeyIs(null, $this->firstFeature); } public function testRemovesOneToOneAssociation() { $this->product->addFeature($this->firstFeature); $this->product->addFeature($this->secondFeature); - $this->_em->persist($this->product); + $this->em->persist($this->product); $this->product->removeFeature($this->firstFeature); - $this->_em->flush(); + $this->em->flush(); - $this->assertFeatureForeignKeyIs(null, $this->firstFeature); - $this->assertFeatureForeignKeyIs($this->product->getId(), $this->secondFeature); + self::assertFeatureForeignKeyIs(null, $this->firstFeature); + self::assertFeatureForeignKeyIs($this->product->getId(), $this->secondFeature); } public function testEagerLoadsOneToManyAssociation() { - $this->_createFixture(); - $query = $this->_em->createQuery('select p, f from Doctrine\Tests\Models\ECommerce\ECommerceProduct p join p.features f'); + $this->createFixture(); + $query = $this->em->createQuery('select p, f from Doctrine\Tests\Models\ECommerce\ECommerceProduct p join p.features f'); $result = $query->getResult(); $product = $result[0]; $features = $product->getFeatures(); - $this->assertInstanceOf(ECommerceFeature::class, $features[0]); - $this->assertNotInstanceOf(Proxy::class, $features[0]->getProduct()); - $this->assertSame($product, $features[0]->getProduct()); - $this->assertEquals('Model writing tutorial', $features[0]->getDescription()); - $this->assertInstanceOf(ECommerceFeature::class, $features[1]); - $this->assertSame($product, $features[1]->getProduct()); - $this->assertNotInstanceOf(Proxy::class, $features[1]->getProduct()); - $this->assertEquals('Annotations examples', $features[1]->getDescription()); + self::assertInstanceOf(ECommerceFeature::class, $features[0]); + self::assertNotInstanceOf(Proxy::class, $features[0]->getProduct()); + self::assertSame($product, $features[0]->getProduct()); + self::assertEquals('Model writing tutorial', $features[0]->getDescription()); + self::assertInstanceOf(ECommerceFeature::class, $features[1]); + self::assertSame($product, $features[1]->getProduct()); + self::assertNotInstanceOf(Proxy::class, $features[1]->getProduct()); + self::assertEquals('Annotations examples', $features[1]->getDescription()); } public function testLazyLoadsObjectsOnTheOwningSide() { - $this->_createFixture(); + $this->createFixture(); - $query = $this->_em->createQuery('select p from Doctrine\Tests\Models\ECommerce\ECommerceProduct p'); + $query = $this->em->createQuery('select p from Doctrine\Tests\Models\ECommerce\ECommerceProduct p'); $result = $query->getResult(); $product = $result[0]; $features = $product->getFeatures(); - $this->assertFalse($features->isInitialized()); - $this->assertInstanceOf(ECommerceFeature::class, $features[0]); - $this->assertTrue($features->isInitialized()); - $this->assertSame($product, $features[0]->getProduct()); - $this->assertEquals('Model writing tutorial', $features[0]->getDescription()); - $this->assertInstanceOf(ECommerceFeature::class, $features[1]); - $this->assertSame($product, $features[1]->getProduct()); - $this->assertEquals('Annotations examples', $features[1]->getDescription()); + self::assertFalse($features->isInitialized()); + self::assertInstanceOf(ECommerceFeature::class, $features[0]); + self::assertTrue($features->isInitialized()); + self::assertSame($product, $features[0]->getProduct()); + self::assertEquals('Model writing tutorial', $features[0]->getDescription()); + self::assertInstanceOf(ECommerceFeature::class, $features[1]); + self::assertSame($product, $features[1]->getProduct()); + self::assertEquals('Annotations examples', $features[1]->getDescription()); } public function testLazyLoadsObjectsOnTheInverseSide() { - $this->_createFixture(); + $this->createFixture(); - $query = $this->_em->createQuery('select f from Doctrine\Tests\Models\ECommerce\ECommerceFeature f'); + $query = $this->em->createQuery('select f from Doctrine\Tests\Models\ECommerce\ECommerceFeature f'); $features = $query->getResult(); $product = $features[0]->getProduct(); - $this->assertInstanceOf(Proxy::class, $product); - $this->assertInstanceOf(ECommerceProduct::class, $product); - $this->assertFalse($product->__isInitialized__); - $this->assertSame('Doctrine Cookbook', $product->getName()); - $this->assertTrue($product->__isInitialized__); + self::assertInstanceOf(Proxy::class, $product); + self::assertInstanceOf(ECommerceProduct::class, $product); + self::assertFalse($product->__isInitialized()); + self::assertSame('Doctrine Cookbook', $product->getName()); + self::assertTrue($product->__isInitialized()); } public function testLazyLoadsObjectsOnTheInverseSide2() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_createFixture(); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + $this->createFixture(); - $query = $this->_em->createQuery('select f,p from Doctrine\Tests\Models\ECommerce\ECommerceFeature f join f.product p'); + $query = $this->em->createQuery('select f,p from Doctrine\Tests\Models\ECommerce\ECommerceFeature f join f.product p'); $features = $query->getResult(); $product = $features[0]->getProduct(); - $this->assertNotInstanceOf(Proxy::class, $product); - $this->assertInstanceOf(ECommerceProduct::class, $product); - $this->assertSame('Doctrine Cookbook', $product->getName()); + self::assertNotInstanceOf(Proxy::class, $product); + self::assertInstanceOf(ECommerceProduct::class, $product); + self::assertSame('Doctrine Cookbook', $product->getName()); - $this->assertFalse($product->getFeatures()->isInitialized()); + self::assertFalse($product->getFeatures()->isInitialized()); // This would trigger lazy-load - //$this->assertEquals(2, $product->getFeatures()->count()); - //$this->assertTrue($product->getFeatures()->contains($features[0])); - //$this->assertTrue($product->getFeatures()->contains($features[1])); + //self::assertEquals(2, $product->getFeatures()->count()); + //self::assertTrue($product->getFeatures()->contains($features[0])); + //self::assertTrue($product->getFeatures()->contains($features[1])); - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(null); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(null); } public function testJoinFromOwningSide() { - $query = $this->_em->createQuery('select f,p from Doctrine\Tests\Models\ECommerce\ECommerceFeature f join f.product p'); + $query = $this->em->createQuery('select f,p from Doctrine\Tests\Models\ECommerce\ECommerceFeature f join f.product p'); $features = $query->getResult(); - $this->assertEquals(0, count($features)); + self::assertEquals(0, count($features)); } /** @@ -157,22 +159,22 @@ public function testJoinFromOwningSide() */ public function testMatching() { - $this->_createFixture(); + $this->createFixture(); - $product = $this->_em->find(ECommerceProduct::class, $this->product->getId()); + $product = $this->em->find(ECommerceProduct::class, $this->product->getId()); $features = $product->getFeatures(); $results = $features->matching(new Criteria( Criteria::expr()->eq('description', 'Model writing tutorial') )); - $this->assertInstanceOf(Collection::class, $results); - $this->assertEquals(1, count($results)); + self::assertInstanceOf(Collection::class, $results); + self::assertEquals(1, count($results)); $results = $features->matching(new Criteria()); - $this->assertInstanceOf(Collection::class, $results); - $this->assertEquals(2, count($results)); + self::assertInstanceOf(Collection::class, $results); + self::assertEquals(2, count($results)); } /** @@ -180,9 +182,9 @@ public function testMatching() */ public function testMatchingOnDirtyCollection() { - $this->_createFixture(); + $this->createFixture(); - $product = $this->_em->find(ECommerceProduct::class, $this->product->getId()); + $product = $this->em->find(ECommerceProduct::class, $this->product->getId()); $thirdFeature = new ECommerceFeature(); $thirdFeature->setDescription('Model writing tutorial'); @@ -194,14 +196,14 @@ public function testMatchingOnDirtyCollection() Criteria::expr()->eq('description', 'Model writing tutorial') )); - $this->assertEquals(2, count($results)); + self::assertEquals(2, count($results)); } public function testMatchingBis() { - $this->_createFixture(); + $this->createFixture(); - $product = $this->_em->find(ECommerceProduct::class, $this->product->getId()); + $product = $this->em->find(ECommerceProduct::class, $this->product->getId()); $features = $product->getFeatures(); $thirdFeature = new ECommerceFeature(); @@ -212,30 +214,30 @@ public function testMatchingBis() Criteria::expr()->eq('description', 'Third feature') )); - $this->assertInstanceOf(Collection::class, $results); - $this->assertCount(1, $results); + self::assertInstanceOf(Collection::class, $results); + self::assertCount(1, $results); $results = $features->matching(new Criteria()); - $this->assertInstanceOf(Collection::class, $results); - $this->assertCount(3, $results); + self::assertInstanceOf(Collection::class, $results); + self::assertCount(3, $results); } - private function _createFixture() + private function createFixture() { $this->product->addFeature($this->firstFeature); $this->product->addFeature($this->secondFeature); - $this->_em->persist($this->product); + $this->em->persist($this->product); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); } public function assertFeatureForeignKeyIs($value, ECommerceFeature $feature) { - $foreignKey = $this->_em->getConnection()->executeQuery( + $foreignKey = $this->em->getConnection()->executeQuery( 'SELECT product_id FROM ecommerce_features WHERE id=?', [$feature->getId()] )->fetchColumn(); - $this->assertEquals($value, $foreignKey); + self::assertEquals($value, $foreignKey); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToManyOrphanRemovalTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToManyOrphanRemovalTest.php index da70672b6d2..b1b404e9c70 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToManyOrphanRemovalTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToManyOrphanRemovalTest.php @@ -1,5 +1,7 @@ addPhonenumber($phone1); $user->addPhonenumber($phone2); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); $this->userId = $user->getId(); - $this->_em->clear(); + $this->em->clear(); } public function testOrphanRemoval() { - $userProxy = $this->_em->getReference(CmsUser::class, $this->userId); + $userProxy = $this->em->getReference(CmsUser::class, $this->userId); - $this->_em->remove($userProxy); - $this->_em->flush(); - $this->_em->clear(); + $this->em->remove($userProxy); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'); + $query = $this->em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'); $result = $query->getResult(); - $this->assertEquals(0, count($result), 'CmsUser should be removed by EntityManager'); + self::assertEquals(0, count($result), 'CmsUser should be removed by EntityManager'); - $query = $this->_em->createQuery('SELECT p FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p'); + $query = $this->em->createQuery('SELECT p FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p'); $result = $query->getResult(); - $this->assertEquals(0, count($result), 'CmsPhonenumber should be removed by orphanRemoval'); + self::assertEquals(0, count($result), 'CmsPhonenumber should be removed by orphanRemoval'); } /** @@ -64,17 +66,17 @@ public function testOrphanRemoval() */ public function testOrphanRemovalRemoveFromCollection() { - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); $phonenumber = $user->getPhonenumbers()->remove(0); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery('SELECT p FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p'); + $query = $this->em->createQuery('SELECT p FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p'); $result = $query->getResult(); - $this->assertEquals(1, count($result), 'CmsPhonenumber should be removed by orphanRemoval'); + self::assertEquals(1, count($result), 'CmsPhonenumber should be removed by orphanRemoval'); } /** @@ -82,19 +84,19 @@ public function testOrphanRemovalRemoveFromCollection() */ public function testOrphanRemovalClearCollectionAndReAdd() { - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); $phone1 = $user->getPhonenumbers()->first(); $user->getPhonenumbers()->clear(); $user->addPhonenumber($phone1); - $this->_em->flush(); + $this->em->flush(); - $query = $this->_em->createQuery('SELECT p FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p'); + $query = $this->em->createQuery('SELECT p FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p'); $result = $query->getResult(); - $this->assertEquals(1, count($result), 'CmsPhonenumber should be removed by orphanRemoval'); + self::assertEquals(1, count($result), 'CmsPhonenumber should be removed by orphanRemoval'); } /** @@ -102,7 +104,7 @@ public function testOrphanRemovalClearCollectionAndReAdd() */ public function testOrphanRemovalClearCollectionAndAddNew() { - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); $newPhone = new CmsPhonenumber(); $newPhone->phonenumber = '654321'; @@ -110,12 +112,12 @@ public function testOrphanRemovalClearCollectionAndAddNew() $user->getPhonenumbers()->clear(); $user->addPhonenumber($newPhone); - $this->_em->flush(); + $this->em->flush(); - $query = $this->_em->createQuery('SELECT p FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p'); + $query = $this->em->createQuery('SELECT p FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p'); $result = $query->getResult(); - $this->assertEquals(1, count($result), 'Old CmsPhonenumbers should be removed by orphanRemoval and new one added'); + self::assertEquals(1, count($result), 'Old CmsPhonenumbers should be removed by orphanRemoval and new one added'); } /** @@ -123,14 +125,14 @@ public function testOrphanRemovalClearCollectionAndAddNew() */ public function testOrphanRemovalUnitializedCollection() { - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); $user->phonenumbers->clear(); - $this->_em->flush(); + $this->em->flush(); - $query = $this->_em->createQuery('SELECT p FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p'); + $query = $this->em->createQuery('SELECT p FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p'); $result = $query->getResult(); - $this->assertEquals(0, count($result), 'CmsPhonenumber should be removed by orphanRemoval'); + self::assertEquals(0, count($result), 'CmsPhonenumber should be removed by orphanRemoval'); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToManySelfReferentialAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToManySelfReferentialAssociationTest.php index c9f42237d19..edea9519208 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToManySelfReferentialAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToManySelfReferentialAssociationTest.php @@ -1,9 +1,12 @@ parent->addChild($this->firstChild); $this->parent->addChild($this->secondChild); - $this->_em->persist($this->parent); + $this->em->persist($this->parent); - $this->_em->flush(); + $this->em->flush(); - $this->assertForeignKeyIs($this->parent->getId(), $this->firstChild); - $this->assertForeignKeyIs($this->parent->getId(), $this->secondChild); + self::assertForeignKeyIs($this->parent->getId(), $this->firstChild); + self::assertForeignKeyIs($this->parent->getId(), $this->secondChild); } public function testSavesAnEmptyCollection() { - $this->_em->persist($this->parent); - $this->_em->flush(); + $this->em->persist($this->parent); + $this->em->flush(); - $this->assertEquals(0, count($this->parent->getChildren())); + self::assertEquals(0, count($this->parent->getChildren())); } public function testDoesNotSaveAnInverseSideSet() { $this->parent->brokenAddChild($this->firstChild); - $this->_em->persist($this->parent); - $this->_em->flush(); + $this->em->persist($this->parent); + $this->em->flush(); - $this->assertForeignKeyIs(null, $this->firstChild); + self::assertForeignKeyIs(null, $this->firstChild); } public function testRemovesOneToManyAssociation() { $this->parent->addChild($this->firstChild); $this->parent->addChild($this->secondChild); - $this->_em->persist($this->parent); + $this->em->persist($this->parent); $this->parent->removeChild($this->firstChild); - $this->_em->flush(); + $this->em->flush(); - $this->assertForeignKeyIs(null, $this->firstChild); - $this->assertForeignKeyIs($this->parent->getId(), $this->secondChild); + self::assertForeignKeyIs(null, $this->firstChild); + self::assertForeignKeyIs($this->parent->getId(), $this->secondChild); } public function testEagerLoadsOneToManyAssociation() { - $this->_createFixture(); + $this->createFixture(); - $query = $this->_em->createQuery('select c1, c2 from Doctrine\Tests\Models\ECommerce\ECommerceCategory c1 join c1.children c2'); + $query = $this->em->createQuery('select c1, c2 from Doctrine\Tests\Models\ECommerce\ECommerceCategory c1 join c1.children c2'); $result = $query->getResult(); - $this->assertEquals(1, count($result)); + self::assertEquals(1, count($result)); $parent = $result[0]; $children = $parent->getChildren(); - $this->assertInstanceOf(ECommerceCategory::class, $children[0]); - $this->assertSame($parent, $children[0]->getParent()); - $this->assertEquals(' books', strstr($children[0]->getName(), ' books')); - $this->assertInstanceOf(ECommerceCategory::class, $children[1]); - $this->assertSame($parent, $children[1]->getParent()); - $this->assertEquals(' books', strstr($children[1]->getName(), ' books')); + self::assertInstanceOf(ECommerceCategory::class, $children[0]); + self::assertSame($parent, $children[0]->getParent()); + self::assertEquals(' books', strstr($children[0]->getName(), ' books')); + self::assertInstanceOf(ECommerceCategory::class, $children[1]); + self::assertSame($parent, $children[1]->getParent()); + self::assertEquals(' books', strstr($children[1]->getName(), ' books')); } public function testLazyLoadsOneToManyAssociation() { - $this->_createFixture(); - $metadata = $this->_em->getClassMetadata(ECommerceCategory::class); - $metadata->associationMappings['children']['fetch'] = ClassMetadata::FETCH_LAZY; + $this->createFixture(); + $metadata = $this->em->getClassMetadata(ECommerceCategory::class); + $metadata->getProperty('children')->setFetchMode(FetchMode::LAZY); - $query = $this->_em->createQuery('select c from Doctrine\Tests\Models\ECommerce\ECommerceCategory c order by c.id asc'); + $query = $this->em->createQuery('select c from Doctrine\Tests\Models\ECommerce\ECommerceCategory c order by c.id asc'); $result = $query->getResult(); $parent = $result[0]; $children = $parent->getChildren(); - $this->assertInstanceOf(ECommerceCategory::class, $children[0]); - $this->assertSame($parent, $children[0]->getParent()); - $this->assertEquals(' books', strstr($children[0]->getName(), ' books')); - $this->assertInstanceOf(ECommerceCategory::class, $children[1]); - $this->assertSame($parent, $children[1]->getParent()); - $this->assertEquals(' books', strstr($children[1]->getName(), ' books')); + self::assertInstanceOf(ECommerceCategory::class, $children[0]); + self::assertSame($parent, $children[0]->getParent()); + self::assertEquals(' books', strstr($children[0]->getName(), ' books')); + self::assertInstanceOf(ECommerceCategory::class, $children[1]); + self::assertSame($parent, $children[1]->getParent()); + self::assertEquals(' books', strstr($children[1]->getName(), ' books')); } - private function _createFixture() + private function createFixture() { $this->parent->addChild($this->firstChild); $this->parent->addChild($this->secondChild); - $this->_em->persist($this->parent); + $this->em->persist($this->parent); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); } public function assertForeignKeyIs($value, ECommerceCategory $child) { - $foreignKey = $this->_em->getConnection()->executeQuery('SELECT parent_id FROM ecommerce_categories WHERE id=?', [$child->getId()] - )->fetchColumn(); - $this->assertEquals($value, $foreignKey); + $foreignKey = $this->em->getConnection()->executeQuery('SELECT parent_id FROM ecommerce_categories WHERE id=?', [$child->getId()])->fetchColumn(); + self::assertEquals($value, $foreignKey); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToManyUnidirectionalAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToManyUnidirectionalAssociationTest.php index c13a6fe9971..b2f649cafcc 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToManyUnidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToManyUnidirectionalAssociationTest.php @@ -1,5 +1,7 @@ name = $locationName; - $this->_em->persist($location); + $this->em->persist($location); $this->locations[$locationName] = $location; } - $this->_em->flush(); + $this->em->flush(); } public function testPersistOwning_InverseCascade() @@ -41,18 +43,18 @@ public function testPersistOwning_InverseCascade() $route = new RoutingRoute(); $route->legs[] = $leg; - $this->_em->persist($route); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($route); + $this->em->flush(); + $this->em->clear(); - $routes = $this->_em->createQuery( + $routes = $this->em->createQuery( "SELECT r, l, f, t FROM Doctrine\Tests\Models\Routing\RoutingRoute r ". "JOIN r.legs l JOIN l.fromLocation f JOIN l.toLocation t" )->getSingleResult(); - $this->assertEquals(1, count($routes->legs)); - $this->assertEquals("Berlin", $routes->legs[0]->fromLocation->name); - $this->assertEquals("Bonn", $routes->legs[0]->toLocation->name); + self::assertEquals(1, count($routes->legs)); + self::assertEquals("Berlin", $routes->legs[0]->fromLocation->name); + self::assertEquals("Bonn", $routes->legs[0]->toLocation->name); } public function testLegsAreUniqueToRoutes() @@ -69,17 +71,17 @@ public function testLegsAreUniqueToRoutes() $routeB = new RoutingRoute(); $routeB->legs[] = $leg; - $this->_em->persist($routeA); - $this->_em->persist($routeB); + $this->em->persist($routeA); + $this->em->persist($routeB); $exceptionThrown = false; try { // exception depending on the underlying Database Driver - $this->_em->flush(); + $this->em->flush(); } catch(\Exception $e) { $exceptionThrown = true; } - $this->assertTrue($exceptionThrown, "The underlying database driver throws an exception."); + self::assertTrue($exceptionThrown, "The underlying database driver throws an exception."); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneBidirectionalAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneBidirectionalAssociationTest.php index c989e126c44..2f585382ea7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneBidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneBidirectionalAssociationTest.php @@ -1,9 +1,12 @@ customer->setCart($this->cart); - $this->_em->persist($this->customer); - $this->_em->flush(); + $this->em->persist($this->customer); + $this->em->flush(); - $this->assertCartForeignKeyIs($this->customer->getId()); + self::assertCartForeignKeyIs($this->customer->getId()); } public function testDoesNotSaveAnInverseSideSet() { $this->customer->brokenSetCart($this->cart); - $this->_em->persist($this->customer); - $this->_em->flush(); + $this->em->persist($this->customer); + $this->em->flush(); - $this->assertCartForeignKeyIs(null); + self::assertCartForeignKeyIs(null); } public function testRemovesOneToOneAssociation() { $this->customer->setCart($this->cart); - $this->_em->persist($this->customer); + $this->em->persist($this->customer); $this->customer->removeCart(); - $this->_em->flush(); + $this->em->flush(); - $this->assertCartForeignKeyIs(null); + self::assertCartForeignKeyIs(null); } public function testEagerLoad() { - $this->_createFixture(); + $this->createFixture(); - $query = $this->_em->createQuery('select c, ca from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c join c.cart ca'); + $query = $this->em->createQuery('select c, ca from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c join c.cart ca'); $result = $query->getResult(); $customer = $result[0]; - $this->assertInstanceOf(ECommerceCart::class, $customer->getCart()); - $this->assertEquals('paypal', $customer->getCart()->getPayment()); + self::assertInstanceOf(ECommerceCart::class, $customer->getCart()); + self::assertEquals('paypal', $customer->getCart()->getPayment()); } public function testLazyLoadsObjectsOnTheOwningSide() { - $this->_createFixture(); - $metadata = $this->_em->getClassMetadata(ECommerceCart::class); - $metadata->associationMappings['customer']['fetchMode'] = ClassMetadata::FETCH_LAZY; + $this->createFixture(); + $metadata = $this->em->getClassMetadata(ECommerceCart::class); + $metadata->getProperty('customer')->setFetchMode(FetchMode::LAZY); - $query = $this->_em->createQuery('select c from Doctrine\Tests\Models\ECommerce\ECommerceCart c'); + $query = $this->em->createQuery('select c from Doctrine\Tests\Models\ECommerce\ECommerceCart c'); $result = $query->getResult(); $cart = $result[0]; - $this->assertInstanceOf(ECommerceCustomer::class, $cart->getCustomer()); - $this->assertEquals('Giorgio', $cart->getCustomer()->getName()); + self::assertInstanceOf(ECommerceCustomer::class, $cart->getCustomer()); + self::assertEquals('Giorgio', $cart->getCustomer()->getName()); } public function testInverseSideIsNeverLazy() { - $this->_createFixture(); - $metadata = $this->_em->getClassMetadata(ECommerceCustomer::class); - $metadata->associationMappings['mentor']['fetch'] = ClassMetadata::FETCH_EAGER; + $this->createFixture(); + $metadata = $this->em->getClassMetadata(ECommerceCustomer::class); + $metadata->getProperty('mentor')->setFetchMode(FetchMode::EAGER); - $query = $this->_em->createQuery('select c from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c'); + $query = $this->em->createQuery('select c from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c'); $result = $query->getResult(); $customer = $result[0]; - $this->assertNull($customer->getMentor()); - $this->assertInstanceOf(ECommerceCart::class, $customer->getCart()); - $this->assertNotInstanceOf(Proxy::class, $customer->getCart()); - $this->assertEquals('paypal', $customer->getCart()->getPayment()); + self::assertNull($customer->getMentor()); + self::assertInstanceOf(ECommerceCart::class, $customer->getCart()); + self::assertNotInstanceOf(Proxy::class, $customer->getCart()); + self::assertEquals('paypal', $customer->getCart()->getPayment()); } public function testUpdateWithProxyObject() @@ -103,34 +106,34 @@ public function testUpdateWithProxyObject() $cart->setPayment('CARD'); $cust->setCart($cart); - $this->_em->persist($cust); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($cust); + $this->em->flush(); + $this->em->clear(); - $this->assertInstanceOf(ECommerceCart::class, $cust->getCart()); - $this->assertEquals('Roman', $cust->getName()); - $this->assertSame($cust, $cart->getCustomer()); + self::assertInstanceOf(ECommerceCart::class, $cust->getCart()); + self::assertEquals('Roman', $cust->getName()); + self::assertSame($cust, $cart->getCustomer()); - $query = $this->_em->createQuery('select ca from Doctrine\Tests\Models\ECommerce\ECommerceCart ca where ca.id =?1'); + $query = $this->em->createQuery('select ca from Doctrine\Tests\Models\ECommerce\ECommerceCart ca where ca.id =?1'); $query->setParameter(1, $cart->getId()); $cart2 = $query->getSingleResult(); $cart2->setPayment('CHEQUE'); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $query2 = $this->_em->createQuery('select ca, c from Doctrine\Tests\Models\ECommerce\ECommerceCart ca left join ca.customer c where ca.id =?1'); + $query2 = $this->em->createQuery('select ca, c from Doctrine\Tests\Models\ECommerce\ECommerceCart ca left join ca.customer c where ca.id =?1'); $query2->setParameter(1, $cart->getId()); $cart3 = $query2->getSingleResult(); - $this->assertInstanceOf(ECommerceCustomer::class, $cart3->getCustomer()); - $this->assertEquals('Roman', $cart3->getCustomer()->getName()); + self::assertInstanceOf(ECommerceCustomer::class, $cart3->getCustomer()); + self::assertEquals('Roman', $cart3->getCustomer()->getName()); } - protected function _createFixture() + protected function createFixture() { $customer = new ECommerceCustomer; $customer->setName('Giorgio'); @@ -138,15 +141,14 @@ protected function _createFixture() $cart->setPayment('paypal'); $customer->setCart($cart); - $this->_em->persist($customer); + $this->em->persist($customer); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); } public function assertCartForeignKeyIs($value) { - $foreignKey = $this->_em->getConnection()->executeQuery('SELECT customer_id FROM ecommerce_carts WHERE id=?', [$this->cart->getId()] - )->fetchColumn(); - $this->assertEquals($value, $foreignKey); + $foreignKey = $this->em->getConnection()->executeQuery('SELECT customer_id FROM ecommerce_carts WHERE id=?', [$this->cart->getId()])->fetchColumn(); + self::assertEquals($value, $foreignKey); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneEagerLoadingTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneEagerLoadingTest.php index 5b4cdffdfe5..63e4a9be36c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneEagerLoadingTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneEagerLoadingTest.php @@ -1,7 +1,11 @@ _em); + $schemaTool = new SchemaTool($this->em); try { $schemaTool->createSchema( [ - $this->_em->getClassMetadata(Train::class), - $this->_em->getClassMetadata(TrainDriver::class), - $this->_em->getClassMetadata(TrainOwner::class), - $this->_em->getClassMetadata(Waggon::class), - $this->_em->getClassMetadata(TrainOrder::class), + $this->em->getClassMetadata(Train::class), + $this->em->getClassMetadata(TrainDriver::class), + $this->em->getClassMetadata(TrainOwner::class), + $this->em->getClassMetadata(Waggon::class), + $this->em->getClassMetadata(TrainOrder::class), ] ); } catch(\Exception $e) {} @@ -40,17 +44,17 @@ public function testEagerLoadOneToOneOwningSide() $train->setDriver($driver); $train->addWaggon($waggon); - $this->_em->persist($train); // cascades - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($train); // cascades + $this->em->flush(); + $this->em->clear(); - $sqlCount = count($this->_sqlLoggerStack->queries); + $sqlCount = count($this->sqlLoggerStack->queries); - $train = $this->_em->find(get_class($train), $train->id); - $this->assertNotInstanceOf(Proxy::class, $train->driver); - $this->assertEquals("Benjamin", $train->driver->name); + $train = $this->em->find(get_class($train), $train->id); + self::assertNotInstanceOf(Proxy::class, $train->driver); + self::assertEquals("Benjamin", $train->driver->name); - $this->assertEquals($sqlCount + 1, count($this->_sqlLoggerStack->queries)); + self::assertEquals($sqlCount + 1, count($this->sqlLoggerStack->queries)); } /** @@ -60,17 +64,17 @@ public function testEagerLoadOneToOneNullOwningSide() { $train = new Train(new TrainOwner("Alexander")); - $this->_em->persist($train); // cascades - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($train); // cascades + $this->em->flush(); + $this->em->clear(); - $sqlCount = count($this->_sqlLoggerStack->queries); + $sqlCount = count($this->sqlLoggerStack->queries); - $train = $this->_em->find(get_class($train), $train->id); - $this->assertNotInstanceOf(Proxy::class, $train->driver); - $this->assertNull($train->driver); + $train = $this->em->find(get_class($train), $train->id); + self::assertNotInstanceOf(Proxy::class, $train->driver); + self::assertNull($train->driver); - $this->assertEquals($sqlCount + 1, count($this->_sqlLoggerStack->queries)); + self::assertEquals($sqlCount + 1, count($this->sqlLoggerStack->queries)); } /** @@ -81,17 +85,17 @@ public function testEagerLoadOneToOneInverseSide() $owner = new TrainOwner("Alexander"); $train = new Train($owner); - $this->_em->persist($train); // cascades - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($train); // cascades + $this->em->flush(); + $this->em->clear(); - $sqlCount = count($this->_sqlLoggerStack->queries); + $sqlCount = count($this->sqlLoggerStack->queries); - $driver = $this->_em->find(get_class($owner), $owner->id); - $this->assertNotInstanceOf(Proxy::class, $owner->train); - $this->assertNotNull($owner->train); + $driver = $this->em->find(get_class($owner), $owner->id); + self::assertNotInstanceOf(Proxy::class, $owner->train); + self::assertNotNull($owner->train); - $this->assertEquals($sqlCount + 1, count($this->_sqlLoggerStack->queries)); + self::assertEquals($sqlCount + 1, count($this->sqlLoggerStack->queries)); } /** @@ -101,19 +105,19 @@ public function testEagerLoadOneToOneNullInverseSide() { $driver = new TrainDriver("Dagny Taggert"); - $this->_em->persist($driver); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($driver); + $this->em->flush(); + $this->em->clear(); - $this->assertNull($driver->train); + self::assertNull($driver->train); - $sqlCount = count($this->_sqlLoggerStack->queries); + $sqlCount = count($this->sqlLoggerStack->queries); - $driver = $this->_em->find(get_class($driver), $driver->id); - $this->assertNotInstanceOf(Proxy::class, $driver->train); - $this->assertNull($driver->train); + $driver = $this->em->find(get_class($driver), $driver->id); + self::assertNotInstanceOf(Proxy::class, $driver->train); + self::assertNull($driver->train); - $this->assertEquals($sqlCount + 1, count($this->_sqlLoggerStack->queries)); + self::assertEquals($sqlCount + 1, count($this->sqlLoggerStack->queries)); } public function testEagerLoadManyToOne() @@ -122,13 +126,13 @@ public function testEagerLoadManyToOne() $waggon = new Waggon(); $train->addWaggon($waggon); - $this->_em->persist($train); // cascades - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($train); // cascades + $this->em->flush(); + $this->em->clear(); - $waggon = $this->_em->find(get_class($waggon), $waggon->id); - $this->assertNotInstanceOf(Proxy::class, $waggon->train); - $this->assertNotNull($waggon->train); + $waggon = $this->em->find(get_class($waggon), $waggon->id); + self::assertNotInstanceOf(Proxy::class, $waggon->train); + self::assertNotNull($waggon->train); } /** @@ -140,21 +144,24 @@ public function testEagerLoadWithNullableColumnsGeneratesLeftJoinOnBothSides() $driver = new TrainDriver("Benjamin"); $train->setDriver($driver); - $this->_em->persist($train); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($train); + $this->em->flush(); + $this->em->clear(); + + $this->em->find(get_class($train), $train->id); - $train = $this->_em->find(get_class($train), $train->id); - $this->assertSQLEquals( - "SELECT t0.id AS id_1, t0.driver_id AS driver_id_2, t3.id AS id_4, t3.name AS name_5, t0.owner_id AS owner_id_6, t7.id AS id_8, t7.name AS name_9 FROM Train t0 LEFT JOIN TrainDriver t3 ON t0.driver_id = t3.id INNER JOIN TrainOwner t7 ON t0.owner_id = t7.id WHERE t0.id = ?", - $this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['sql'] + self::assertSQLEquals( + 'SELECT t0."id" AS c1, t0."driver_id" AS c2, t4."id" AS c3, t4."name" AS c5, t0."owner_id" AS c6, t8."id" AS c7, t8."name" AS c9 FROM "Train" t0 LEFT JOIN "TrainDriver" t4 ON t0."driver_id" = t4."id" INNER JOIN "TrainOwner" t8 ON t0."owner_id" = t8."id" WHERE t0."id" = ?', + $this->sqlLoggerStack->queries[$this->sqlLoggerStack->currentQuery]['sql'] ); - $this->_em->clear(); - $driver = $this->_em->find(get_class($driver), $driver->id); - $this->assertSQLEquals( - "SELECT t0.id AS id_1, t0.name AS name_2, t3.id AS id_4, t3.driver_id AS driver_id_5, t3.owner_id AS owner_id_6 FROM TrainOwner t0 LEFT JOIN Train t3 ON t3.owner_id = t0.id WHERE t0.id IN (?)", - $this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['sql'] + $this->em->clear(); + + $this->em->find(get_class($driver), $driver->id); + + self::assertSQLEquals( + 'SELECT t0."id" AS c1, t0."name" AS c2, t4."id" AS c3, t4."driver_id" AS c5, t4."owner_id" AS c6 FROM "TrainOwner" t0 LEFT JOIN "Train" t4 ON t4."owner_id" = t0."id" WHERE t0."id" IN (?)', + $this->sqlLoggerStack->queries[$this->sqlLoggerStack->currentQuery]['sql'] ); } @@ -169,22 +176,22 @@ public function testEagerLoadWithNonNullableColumnsGeneratesInnerJoinOnOwningSid $train = new Train(new TrainOwner("Alexander")); $train->addWaggon($waggon); - $this->_em->persist($train); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($train); + $this->em->flush(); + $this->em->clear(); - $waggon = $this->_em->find(get_class($waggon), $waggon->id); + $this->em->find(get_class($waggon), $waggon->id); // The last query is the eager loading of the owner of the train - $this->assertSQLEquals( - "SELECT t0.id AS id_1, t0.name AS name_2, t3.id AS id_4, t3.driver_id AS driver_id_5, t3.owner_id AS owner_id_6 FROM TrainOwner t0 LEFT JOIN Train t3 ON t3.owner_id = t0.id WHERE t0.id IN (?)", - $this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['sql'] + self::assertSQLEquals( + 'SELECT t0."id" AS c1, t0."name" AS c2, t4."id" AS c3, t4."driver_id" AS c5, t4."owner_id" AS c6 FROM "TrainOwner" t0 LEFT JOIN "Train" t4 ON t4."owner_id" = t0."id" WHERE t0."id" IN (?)', + $this->sqlLoggerStack->queries[$this->sqlLoggerStack->currentQuery]['sql'] ); // The one before is the fetching of the waggon and train - $this->assertSQLEquals( - "SELECT t0.id AS id_1, t0.train_id AS train_id_2, t3.id AS id_4, t3.driver_id AS driver_id_5, t3.owner_id AS owner_id_6 FROM Waggon t0 INNER JOIN Train t3 ON t0.train_id = t3.id WHERE t0.id = ?", - $this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery - 1]['sql'] + self::assertSQLEquals( + 'SELECT t0."id" AS c1, t0."train_id" AS c2, t4."id" AS c3, t4."driver_id" AS c5, t4."owner_id" AS c6 FROM "Waggon" t0 INNER JOIN "Train" t4 ON t0."train_id" = t4."id" WHERE t0."id" = ?', + $this->sqlLoggerStack->queries[$this->sqlLoggerStack->currentQuery - 1]['sql'] ); } @@ -195,14 +202,16 @@ public function testEagerLoadWithNonNullableColumnsGeneratesLeftJoinOnNonOwningS { $owner = new TrainOwner('Alexander'); $train = new Train($owner); - $this->_em->persist($train); - $this->_em->flush(); - $this->_em->clear(); - - $waggon = $this->_em->find(get_class($owner), $owner->id); - $this->assertSQLEquals( - "SELECT t0.id AS id_1, t0.name AS name_2, t3.id AS id_4, t3.driver_id AS driver_id_5, t3.owner_id AS owner_id_6 FROM TrainOwner t0 LEFT JOIN Train t3 ON t3.owner_id = t0.id WHERE t0.id = ?", - $this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['sql'] + + $this->em->persist($train); + $this->em->flush(); + $this->em->clear(); + + $this->em->find(get_class($owner), $owner->id); + + self::assertSQLEquals( + 'SELECT t0."id" AS c1, t0."name" AS c2, t4."id" AS c3, t4."driver_id" AS c5, t4."owner_id" AS c6 FROM "TrainOwner" t0 LEFT JOIN "Train" t4 ON t4."owner_id" = t0."id" WHERE t0."id" = ?', + $this->sqlLoggerStack->queries[$this->sqlLoggerStack->currentQuery]['sql'] ); } @@ -213,42 +222,45 @@ public function testEagerLoadingDoesNotBreakRefresh() { $train = new Train(new TrainOwner('Johannes')); $order = new TrainOrder($train); - $this->_em->persist($train); - $this->_em->persist($order); - $this->_em->flush(); - $this->_em->getConnection()->exec("UPDATE TrainOrder SET train_id = NULL"); + $this->em->persist($train); + $this->em->persist($order); + $this->em->flush(); + + $this->em->getConnection()->exec("UPDATE TrainOrder SET train_id = NULL"); + + self::assertSame($train, $order->train); + + $this->em->refresh($order); - $this->assertSame($train, $order->train); - $this->_em->refresh($order); - $this->assertTrue($order->train === null, "Train reference was not refreshed to NULL."); + self::assertTrue($order->train === null, "Train reference was not refreshed to NULL."); } } /** - * @Entity + * @ORM\Entity */ class Train { /** - * @id @column(type="integer") @generatedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue * @var int */ public $id; /** * Owning side - * @OneToOne(targetEntity="TrainDriver", inversedBy="train", fetch="EAGER", cascade={"persist"}) - * @JoinColumn(nullable=true) + * @ORM\OneToOne(targetEntity="TrainDriver", inversedBy="train", fetch="EAGER", cascade={"persist"}) + * @ORM\JoinColumn(nullable=true) */ public $driver; /** * Owning side - * @OneToOne(targetEntity="TrainOwner", inversedBy="train", fetch="EAGER", cascade={"persist"}) - * @JoinColumn(nullable=false) + * @ORM\OneToOne(targetEntity="TrainOwner", inversedBy="train", fetch="EAGER", cascade={"persist"}) + * @ORM\JoinColumn(nullable=false) */ public $owner; /** - * @oneToMany(targetEntity="Waggon", mappedBy="train", cascade={"persist"}) + * @ORM\OneToMany(targetEntity="Waggon", mappedBy="train", cascade={"persist"}) */ public $waggons; @@ -278,17 +290,17 @@ public function addWaggon(Waggon $w) } /** - * @Entity + * @ORM\Entity */ class TrainDriver { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @column(type="string") */ + /** @ORM\Column(type="string") */ public $name; /** * Inverse side - * @OneToOne(targetEntity="Train", mappedBy="driver", fetch="EAGER") + * @ORM\OneToOne(targetEntity="Train", mappedBy="driver", fetch="EAGER") */ public $train; @@ -304,17 +316,17 @@ public function setTrain(Train $t) } /** - * @Entity + * @ORM\Entity */ class TrainOwner { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @column(type="string") */ + /** @ORM\Column(type="string") */ public $name; /** * Inverse side - * @OneToOne(targetEntity="Train", mappedBy="owner", fetch="EAGER") + * @ORM\OneToOne(targetEntity="Train", mappedBy="owner", fetch="EAGER") */ public $train; @@ -330,15 +342,15 @@ public function setTrain(Train $t) } /** - * @Entity + * @ORM\Entity */ class Waggon { - /** @id @generatedValue @column(type="integer") */ + /** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ public $id; /** - * @ManyToOne(targetEntity="Train", inversedBy="waggons", fetch="EAGER") - * @JoinColumn(nullable=false) + * @ORM\ManyToOne(targetEntity="Train", inversedBy="waggons", fetch="EAGER") + * @ORM\JoinColumn(nullable=false) */ public $train; @@ -349,14 +361,14 @@ public function setTrain($train) } /** - * @Entity + * @ORM\Entity */ class TrainOrder { - /** @id @generatedValue @column(type="integer") */ + /** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ public $id; - /** @OneToOne(targetEntity = "Train", fetch = "EAGER") */ + /** @ORM\OneToOne(targetEntity = "Train", fetch = "EAGER") */ public $train; public function __construct(Train $train) diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneOrphanRemovalTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneOrphanRemovalTest.php index 09ef64e021f..b89c376f733 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneOrphanRemovalTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneOrphanRemovalTest.php @@ -1,5 +1,7 @@ setAddress($address); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); $userId = $user->getId(); - $this->_em->clear(); + $this->em->clear(); - $userProxy = $this->_em->getReference(CmsUser::class, $userId); + $userProxy = $this->em->getReference(CmsUser::class, $userId); - $this->_em->remove($userProxy); - $this->_em->flush(); - $this->_em->clear(); + $this->em->remove($userProxy); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'); + $query = $this->em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'); $result = $query->getResult(); - $this->assertEquals(0, count($result), 'CmsUser should be removed by EntityManager'); + self::assertEquals(0, count($result), 'CmsUser should be removed by EntityManager'); - $query = $this->_em->createQuery('SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a'); + $query = $this->em->createQuery('SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a'); $result = $query->getResult(); - $this->assertEquals(0, count($result), 'CmsAddress should be removed by orphanRemoval'); + self::assertEquals(0, count($result), 'CmsAddress should be removed by orphanRemoval'); } public function testOrphanRemovalWhenUnlink() @@ -69,24 +71,24 @@ public function testOrphanRemovalWhenUnlink() $user->setEmail($email); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); $userId = $user->getId(); - $this->_em->clear(); + $this->em->clear(); - $user = $this->_em->find(CmsUser::class, $userId); + $user = $this->em->find(CmsUser::class, $userId); $user->setEmail(null); - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery('SELECT e FROM Doctrine\Tests\Models\CMS\CmsEmail e'); + $query = $this->em->createQuery('SELECT e FROM Doctrine\Tests\Models\CMS\CmsEmail e'); $result = $query->getResult(); - $this->assertEquals(0, count($result), 'CmsEmail should be removed by orphanRemoval'); + self::assertEquals(0, count($result), 'CmsEmail should be removed by orphanRemoval'); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneSelfReferentialAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneSelfReferentialAssociationTest.php index 0011e8c8c40..cbf0cb3f7e6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneSelfReferentialAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneSelfReferentialAssociationTest.php @@ -1,9 +1,11 @@ customer->setMentor($this->mentor); - $this->_em->persist($this->customer); - $this->_em->flush(); + $this->em->persist($this->customer); + $this->em->flush(); - $this->assertForeignKeyIs($this->mentor->getId()); + self::assertForeignKeyIs($this->mentor->getId()); } public function testRemovesOneToOneAssociation() { $this->customer->setMentor($this->mentor); - $this->_em->persist($this->customer); + $this->em->persist($this->customer); $this->customer->removeMentor(); - $this->_em->flush(); + $this->em->flush(); - $this->assertForeignKeyIs(null); + self::assertForeignKeyIs(null); } public function testFind() { - $id = $this->_createFixture(); + $id = $this->createFixture(); - $customer = $this->_em->find(ECommerceCustomer::class, $id); - $this->assertNotInstanceOf(Proxy::class, $customer->getMentor()); + $customer = $this->em->find(ECommerceCustomer::class, $id); + self::assertNotInstanceOf(Proxy::class, $customer->getMentor()); } public function testEagerLoadsAssociation() { - $this->_createFixture(); + $this->createFixture(); - $query = $this->_em->createQuery('select c, m from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c left join c.mentor m order by c.id asc'); + $query = $this->em->createQuery('select c, m from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c left join c.mentor m order by c.id asc'); $result = $query->getResult(); $customer = $result[0]; - $this->assertLoadingOfAssociation($customer); + self::assertLoadingOfAssociation($customer); } /** * @group mine - * @return unknown_type */ public function testLazyLoadsAssociation() { - $this->_createFixture(); + $this->createFixture(); - $metadata = $this->_em->getClassMetadata(ECommerceCustomer::class); - $metadata->associationMappings['mentor']['fetch'] = ClassMetadata::FETCH_LAZY; + $metadata = $this->em->getClassMetadata(ECommerceCustomer::class); + $metadata->getProperty('mentor')->setFetchMode(FetchMode::LAZY); - $query = $this->_em->createQuery("select c from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c where c.name='Luke Skywalker'"); + $query = $this->em->createQuery("select c from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c where c.name='Luke Skywalker'"); $result = $query->getResult(); $customer = $result[0]; - $this->assertLoadingOfAssociation($customer); + + self::assertLoadingOfAssociation($customer); } public function testMultiSelfReference() { try { - $this->_schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(MultiSelfReference::class) + $this->em->getClassMetadata(MultiSelfReference::class) ] ); } catch (\Exception $e) { @@ -97,36 +99,35 @@ public function testMultiSelfReference() } $entity1 = new MultiSelfReference(); - $this->_em->persist($entity1); + $this->em->persist($entity1); $entity1->setOther1($entity2 = new MultiSelfReference); $entity1->setOther2($entity3 = new MultiSelfReference); - $this->_em->flush(); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); - $entity2 = $this->_em->find(get_class($entity1), $entity1->getId()); + $entity2 = $this->em->find(get_class($entity1), $entity1->getId()); - $this->assertInstanceOf(MultiSelfReference::class, $entity2->getOther1()); - $this->assertInstanceOf(MultiSelfReference::class, $entity2->getOther2()); - $this->assertNull($entity2->getOther1()->getOther1()); - $this->assertNull($entity2->getOther1()->getOther2()); - $this->assertNull($entity2->getOther2()->getOther1()); - $this->assertNull($entity2->getOther2()->getOther2()); + self::assertInstanceOf(MultiSelfReference::class, $entity2->getOther1()); + self::assertInstanceOf(MultiSelfReference::class, $entity2->getOther2()); + self::assertNull($entity2->getOther1()->getOther1()); + self::assertNull($entity2->getOther1()->getOther2()); + self::assertNull($entity2->getOther2()->getOther1()); + self::assertNull($entity2->getOther2()->getOther2()); } public function assertLoadingOfAssociation($customer) { - $this->assertInstanceOf(ECommerceCustomer::class, $customer->getMentor()); - $this->assertEquals('Obi-wan Kenobi', $customer->getMentor()->getName()); + self::assertInstanceOf(ECommerceCustomer::class, $customer->getMentor()); + self::assertEquals('Obi-wan Kenobi', $customer->getMentor()->getName()); } public function assertForeignKeyIs($value) { - $foreignKey = $this->_em->getConnection()->executeQuery('SELECT mentor_id FROM ecommerce_customers WHERE id=?', [$this->customer->getId()] - )->fetchColumn(); - $this->assertEquals($value, $foreignKey); + $foreignKey = $this->em->getConnection()->executeQuery('SELECT mentor_id FROM ecommerce_customers WHERE id=?', [$this->customer->getId()])->fetchColumn(); + self::assertEquals($value, $foreignKey); } - private function _createFixture() + private function createFixture() { $customer = new ECommerceCustomer; $customer->setName('Luke Skywalker'); @@ -134,29 +135,29 @@ private function _createFixture() $mentor->setName('Obi-wan Kenobi'); $customer->setMentor($mentor); - $this->_em->persist($customer); + $this->em->persist($customer); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); return $customer->getId(); } } /** - * @Entity + * @ORM\Entity */ class MultiSelfReference { - /** @Id @GeneratedValue(strategy="AUTO") @Column(type="integer") */ + /** @ORM\Id @ORM\GeneratedValue(strategy="AUTO") @ORM\Column(type="integer") */ private $id; /** - * @OneToOne(targetEntity="MultiSelfReference", cascade={"persist"}) - * @JoinColumn(name="other1", referencedColumnName="id") + * @ORM\OneToOne(targetEntity="MultiSelfReference", cascade={"persist"}) + * @ORM\JoinColumn(name="other1", referencedColumnName="id") */ private $other1; /** - * @OneToOne(targetEntity="MultiSelfReference", cascade={"persist"}) - * @JoinColumn(name="other2", referencedColumnName="id") + * @ORM\OneToOne(targetEntity="MultiSelfReference", cascade={"persist"}) + * @ORM\JoinColumn(name="other2", referencedColumnName="id") */ private $other2; diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneSingleTableInheritanceTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneSingleTableInheritanceTest.php index 3e9a291f00b..7b833bb82b1 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneSingleTableInheritanceTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneSingleTableInheritanceTest.php @@ -1,5 +1,7 @@ _schemaTool->createSchema([ - $this->_em->getClassMetadata(Pet::class), - $this->_em->getClassMetadata(Cat::class), - $this->_em->getClassMetadata(LitterBox::class), + $this->schemaTool->createSchema([ + $this->em->getClassMetadata(Pet::class), + $this->em->getClassMetadata(Cat::class), + $this->em->getClassMetadata(LitterBox::class), ]); } @@ -32,17 +34,17 @@ public function testFindFromOneToOneOwningSideJoinedTableInheritance() $cat = new Cat(); $cat->litterBox = new LitterBox(); - $this->_em->persist($cat); - $this->_em->persist($cat->litterBox); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($cat); + $this->em->persist($cat->litterBox); + $this->em->flush(); + $this->em->clear(); /* @var $foundCat Cat */ - $foundCat = $this->_em->find(Pet::class, $cat->id); + $foundCat = $this->em->find(Pet::class, $cat->id); - $this->assertInstanceOf(Cat::class, $foundCat); - $this->assertSame($cat->id, $foundCat->id); - $this->assertInstanceOf(LitterBox::class, $foundCat->litterBox); - $this->assertSame($cat->litterBox->id, $foundCat->litterBox->id); + self::assertInstanceOf(Cat::class, $foundCat); + self::assertSame($cat->id, $foundCat->id); + self::assertInstanceOf(LitterBox::class, $foundCat->litterBox); + self::assertSame($cat->litterBox->id, $foundCat->litterBox->id); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneUnidirectionalAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneUnidirectionalAssociationTest.php index 797a38517d0..dd3727c06dd 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneUnidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneUnidirectionalAssociationTest.php @@ -1,9 +1,12 @@ product->setShipping($this->shipping); - $this->_em->persist($this->product); - $this->_em->flush(); + $this->em->persist($this->product); + $this->em->flush(); - $this->assertForeignKeyIs($this->shipping->getId()); + self::assertForeignKeyIs($this->shipping->getId()); } public function testRemovesOneToOneAssociation() { $this->product->setShipping($this->shipping); - $this->_em->persist($this->product); + $this->em->persist($this->product); $this->product->removeShipping(); - $this->_em->flush(); + $this->em->flush(); - $this->assertForeignKeyIs(null); + self::assertForeignKeyIs(null); } public function _testEagerLoad() { - $this->_createFixture(); + $this->createFixture(); - $query = $this->_em->createQuery('select p, s from Doctrine\Tests\Models\ECommerce\ECommerceProduct p left join p.shipping s'); + $query = $this->em->createQuery('select p, s from Doctrine\Tests\Models\ECommerce\ECommerceProduct p left join p.shipping s'); $result = $query->getResult(); $product = $result[0]; - $this->assertInstanceOf(ECommerceShipping::class, $product->getShipping()); - $this->assertEquals(1, $product->getShipping()->getDays()); + self::assertInstanceOf(ECommerceShipping::class, $product->getShipping()); + self::assertEquals(1, $product->getShipping()->getDays()); } public function testLazyLoadsObjects() { - $this->_createFixture(); - $metadata = $this->_em->getClassMetadata(ECommerceProduct::class); - $metadata->associationMappings['shipping']['fetch'] = ClassMetadata::FETCH_LAZY; + $this->createFixture(); + $metadata = $this->em->getClassMetadata(ECommerceProduct::class); + $metadata->getProperty('shipping')->setFetchMode(FetchMode::LAZY); - $query = $this->_em->createQuery('select p from Doctrine\Tests\Models\ECommerce\ECommerceProduct p'); + $query = $this->em->createQuery('select p from Doctrine\Tests\Models\ECommerce\ECommerceProduct p'); $result = $query->getResult(); $product = $result[0]; - $this->assertInstanceOf(ECommerceShipping::class, $product->getShipping()); - $this->assertEquals(1, $product->getShipping()->getDays()); + self::assertInstanceOf(ECommerceShipping::class, $product->getShipping()); + self::assertEquals(1, $product->getShipping()->getDays()); } public function testDoesNotLazyLoadObjectsIfConfigurationDoesNotAllowIt() { - $this->_createFixture(); + $this->createFixture(); - $query = $this->_em->createQuery('select p from Doctrine\Tests\Models\ECommerce\ECommerceProduct p'); + $query = $this->em->createQuery('select p from Doctrine\Tests\Models\ECommerce\ECommerceProduct p'); $query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true); $result = $query->getResult(); $product = $result[0]; - $this->assertNull($product->getShipping()); + self::assertNull($product->getShipping()); } - protected function _createFixture() + protected function createFixture() { $product = new ECommerceProduct; $product->setName('Php manual'); @@ -92,18 +95,18 @@ protected function _createFixture() $shipping->setDays('1'); $product->setShipping($shipping); - $this->_em->persist($product); + $this->em->persist($product); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); } public function assertForeignKeyIs($value) { - $foreignKey = $this->_em->getConnection()->executeQuery( + $foreignKey = $this->em->getConnection()->executeQuery( 'SELECT shipping_id FROM ecommerce_products WHERE id=?', [$this->product->getId()] )->fetchColumn(); - $this->assertEquals($value, $foreignKey); + self::assertEquals($value, $foreignKey); } /** @@ -114,11 +117,11 @@ public function testNullForeignKey() $product = new ECommerceProduct(); $product->setName('Doctrine 2 Manual'); - $this->_em->persist($product); - $this->_em->flush(); + $this->em->persist($product); + $this->em->flush(); - $product = $this->_em->find(get_class($product), $product->getId()); + $product = $this->em->find(get_class($product), $product->getId()); - $this->assertNull($product->getShipping()); + self::assertNull($product->getShipping()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/OrderedCollectionTest.php b/tests/Doctrine/Tests/ORM/Functional/OrderedCollectionTest.php index aa4fb1da0f6..73aa0e049b6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OrderedCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OrderedCollectionTest.php @@ -1,5 +1,7 @@ name = $locationName; - $this->_em->persist($location); + $this->em->persist($location); $this->locations[$locationName] = $location; } - $this->_em->flush(); + $this->em->flush(); } public function createPersistedRouteWithLegs() @@ -47,10 +49,10 @@ public function createPersistedRouteWithLegs() $route->legs[] = $leg2; $route->legs[] = $leg1; - $this->_em->persist($route); - $this->_em->flush(); + $this->em->persist($route); + $this->em->flush(); $routeId = $route->id; - $this->_em->clear(); + $this->em->clear(); return $routeId; } @@ -59,19 +61,19 @@ public function testLazyManyToManyCollection_IsRetrievedWithOrderByClause() { $routeId = $this->createPersistedRouteWithLegs(); - $route = $this->_em->find(RoutingRoute::class, $routeId); + $route = $this->em->find(RoutingRoute::class, $routeId); - $this->assertEquals(2, count($route->legs)); - $this->assertEquals("Berlin", $route->legs[0]->fromLocation->getName()); - $this->assertEquals("Bonn", $route->legs[1]->fromLocation->getName()); + self::assertEquals(2, count($route->legs)); + self::assertEquals("Berlin", $route->legs[0]->fromLocation->getName()); + self::assertEquals("Bonn", $route->legs[1]->fromLocation->getName()); } public function testLazyOneToManyCollection_IsRetrievedWithOrderByClause() { $route = new RoutingRoute(); - $this->_em->persist($route); - $this->_em->flush(); + $this->em->persist($route); + $this->em->flush(); $routeId = $route->id; $booking1 = new RoutingRouteBooking(); @@ -84,29 +86,29 @@ public function testLazyOneToManyCollection_IsRetrievedWithOrderByClause() $route->bookings[] = $booking2; $booking2->route = $route; - $this->_em->persist($booking1); - $this->_em->persist($booking2); + $this->em->persist($booking1); + $this->em->persist($booking2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $route = $this->_em->find(RoutingRoute::class, $routeId); + $route = $this->em->find(RoutingRoute::class, $routeId); - $this->assertEquals(2, count($route->bookings)); - $this->assertEquals('Benjamin', $route->bookings[0]->getPassengerName()); - $this->assertEquals('Guilherme', $route->bookings[1]->getPassengerName()); + self::assertEquals(2, count($route->bookings)); + self::assertEquals('Benjamin', $route->bookings[0]->getPassengerName()); + self::assertEquals('Guilherme', $route->bookings[1]->getPassengerName()); } public function testOrderedResultFromDqlQuery() { $routeId = $this->createPersistedRouteWithLegs(); - $route = $this->_em->createQuery("SELECT r, l FROM Doctrine\Tests\Models\Routing\RoutingRoute r JOIN r.legs l WHERE r.id = ?1") + $route = $this->em->createQuery("SELECT r, l FROM Doctrine\Tests\Models\Routing\RoutingRoute r JOIN r.legs l WHERE r.id = ?1") ->setParameter(1, $routeId) ->getSingleResult(); - $this->assertEquals(2, count($route->legs)); - $this->assertEquals("Berlin", $route->legs[0]->fromLocation->getName()); - $this->assertEquals("Bonn", $route->legs[1]->fromLocation->getName()); + self::assertEquals(2, count($route->legs)); + self::assertEquals("Berlin", $route->legs[0]->fromLocation->getName()); + self::assertEquals("Bonn", $route->legs[1]->fromLocation->getName()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/OrderedJoinedTableInheritanceCollectionTest.php b/tests/Doctrine/Tests/ORM/Functional/OrderedJoinedTableInheritanceCollectionTest.php index 30531bae98d..8ba3ca234dc 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OrderedJoinedTableInheritanceCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OrderedJoinedTableInheritanceCollectionTest.php @@ -1,8 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(OJTIC_Pet::class), - $this->_em->getClassMetadata(OJTIC_Cat::class), - $this->_em->getClassMetadata(OJTIC_Dog::class), + $this->em->getClassMetadata(OJTIC_Pet::class), + $this->em->getClassMetadata(OJTIC_Cat::class), + $this->em->getClassMetadata(OJTIC_Dog::class), ] ); } catch (\Exception $e) { @@ -41,74 +43,74 @@ protected function setUp() $dog->children[] = $dog1; $dog->children[] = $dog2; - $this->_em->persist($dog); - $this->_em->persist($dog1); - $this->_em->persist($dog2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($dog); + $this->em->persist($dog1); + $this->em->persist($dog2); + $this->em->flush(); + $this->em->clear(); } public function testOrderdOneToManyCollection() { - $poofy = $this->_em->createQuery("SELECT p FROM Doctrine\Tests\ORM\Functional\OJTIC_Pet p WHERE p.name = 'Poofy'")->getSingleResult(); + $poofy = $this->em->createQuery("SELECT p FROM Doctrine\Tests\ORM\Functional\OJTIC_Pet p WHERE p.name = 'Poofy'")->getSingleResult(); - $this->assertEquals('Aari', $poofy->children[0]->getName()); - $this->assertEquals('Zampa', $poofy->children[1]->getName()); + self::assertEquals('Aari', $poofy->children[0]->getName()); + self::assertEquals('Zampa', $poofy->children[1]->getName()); - $this->_em->clear(); + $this->em->clear(); - $result = $this->_em->createQuery( + $result = $this->em->createQuery( "SELECT p, c FROM Doctrine\Tests\ORM\Functional\OJTIC_Pet p JOIN p.children c WHERE p.name = 'Poofy'") ->getResult(); - $this->assertEquals(1, count($result)); + self::assertEquals(1, count($result)); $poofy = $result[0]; - $this->assertEquals('Aari', $poofy->children[0]->getName()); - $this->assertEquals('Zampa', $poofy->children[1]->getName()); + self::assertEquals('Aari', $poofy->children[0]->getName()); + self::assertEquals('Zampa', $poofy->children[1]->getName()); } } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="discr", type="string") - * @DiscriminatorMap({ + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="discr", type="string") + * @ORM\DiscriminatorMap({ * "cat" = "OJTIC_Cat", * "dog" = "OJTIC_Dog"}) */ abstract class OJTIC_Pet { /** - * @Id - * @column(type="integer") - * @generatedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** * - * @Column + * @ORM\Column */ public $name; /** - * @ManyToOne(targetEntity="OJTIC_PET") + * @ORM\ManyToOne(targetEntity="OJTIC_PET") */ public $mother; /** - * @OneToMany(targetEntity="OJTIC_Pet", mappedBy="mother") - * @OrderBy({"name" = "ASC"}) + * @ORM\OneToMany(targetEntity="OJTIC_Pet", mappedBy="mother") + * @ORM\OrderBy({"name" = "ASC"}) */ public $children; /** - * @ManyToMany(targetEntity="OJTIC_Pet") - * @JoinTable(name="OTJIC_Pet_Friends", - * joinColumns={@JoinColumn(name="pet_id", referencedColumnName="id")}, - * inverseJoinColumns={@JoinColumn(name="friend_id", referencedColumnName="id")}) - * @OrderBy({"name" = "ASC"}) + * @ORM\ManyToMany(targetEntity="OJTIC_Pet") + * @ORM\JoinTable(name="OTJIC_Pet_Friends", + * joinColumns={@ORM\JoinColumn(name="pet_id", referencedColumnName="id")}, + * inverseJoinColumns={@ORM\JoinColumn(name="friend_id", referencedColumnName="id")}) + * @ORM\OrderBy({"name" = "ASC"}) */ public $friends; @@ -119,7 +121,7 @@ public function getName() } /** - * @Entity + * @ORM\Entity */ class OJTIC_Cat extends OJTIC_Pet { @@ -127,7 +129,7 @@ class OJTIC_Cat extends OJTIC_Pet } /** - * @Entity + * @ORM\Entity */ class OJTIC_Dog extends OJTIC_Pet { diff --git a/tests/Doctrine/Tests/ORM/Functional/PaginationTest.php b/tests/Doctrine/Tests/ORM/Functional/PaginationTest.php index 58a88dbd764..cc8ae212518 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PaginationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PaginationTest.php @@ -1,5 +1,7 @@ _em->createQuery($dql); + $query = $this->em->createQuery($dql); $paginator = new Paginator($query); $paginator->setUseOutputWalkers($useOutputWalkers); - $this->assertCount(9, $paginator); + self::assertCount(9, $paginator); } /** @@ -49,27 +51,27 @@ public function testCountSimpleWithoutJoin($useOutputWalkers) public function testCountWithFetchJoin($useOutputWalkers) { $dql = 'SELECT u,g FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $paginator = new Paginator($query); $paginator->setUseOutputWalkers($useOutputWalkers); - $this->assertCount(9, $paginator); + self::assertCount(9, $paginator); } public function testCountComplexWithOutputWalker() { $dql = 'SELECT g, COUNT(u.id) AS userCount FROM Doctrine\Tests\Models\CMS\CmsGroup g LEFT JOIN g.users u GROUP BY g HAVING COUNT(u.id) > 0'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $paginator = new Paginator($query); $paginator->setUseOutputWalkers(true); - $this->assertCount(3, $paginator); + self::assertCount(3, $paginator); } public function testCountComplexWithoutOutputWalker() { $dql = 'SELECT g, COUNT(u.id) AS userCount FROM Doctrine\Tests\Models\CMS\CmsGroup g LEFT JOIN g.users u GROUP BY g HAVING COUNT(u.id) > 0'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $paginator = new Paginator($query); $paginator->setUseOutputWalkers(false); @@ -77,7 +79,7 @@ public function testCountComplexWithoutOutputWalker() $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Cannot count query that uses a HAVING clause. Use the output walkers for pagination'); - $this->assertCount(3, $paginator); + self::assertCount(3, $paginator); } /** @@ -86,11 +88,11 @@ public function testCountComplexWithoutOutputWalker() public function testCountWithComplexScalarOrderBy($useOutputWalkers) { $dql = 'SELECT l FROM Doctrine\Tests\Models\Pagination\Logo l ORDER BY l.image_width * l.image_height DESC'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $paginator = new Paginator($query); $paginator->setUseOutputWalkers($useOutputWalkers); - $this->assertCount(9, $paginator); + self::assertCount(9, $paginator); } /** @@ -99,112 +101,112 @@ public function testCountWithComplexScalarOrderBy($useOutputWalkers) public function testIterateSimpleWithoutJoin($useOutputWalkers, $fetchJoinCollection) { $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $paginator = new Paginator($query, $fetchJoinCollection); $paginator->setUseOutputWalkers($useOutputWalkers); - $this->assertCount(9, $paginator->getIterator()); + self::assertCount(9, $paginator->getIterator()); // Test with limit $query->setMaxResults(3); $paginator = new Paginator($query, $fetchJoinCollection); $paginator->setUseOutputWalkers($useOutputWalkers); - $this->assertCount(3, $paginator->getIterator()); + self::assertCount(3, $paginator->getIterator()); // Test with limit and offset $query->setMaxResults(3)->setFirstResult(4); $paginator = new Paginator($query, $fetchJoinCollection); $paginator->setUseOutputWalkers($useOutputWalkers); - $this->assertCount(3, $paginator->getIterator()); + self::assertCount(3, $paginator->getIterator()); } private function iterateWithOrderAsc($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField) { // Ascending $dql = "$baseDql ASC"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $paginator = new Paginator($query, $fetchJoinCollection); $paginator->setUseOutputWalkers($useOutputWalkers); $iter = $paginator->getIterator(); - $this->assertCount(9, $iter); + self::assertCount(9, $iter); $result = iterator_to_array($iter); - $this->assertEquals($checkField . "0", $result[0]->$checkField); + self::assertEquals($checkField . "0", $result[0]->$checkField); } private function iterateWithOrderAscWithLimit($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField) { // Ascending $dql = "$baseDql ASC"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); // With limit $query->setMaxResults(3); $paginator = new Paginator($query, $fetchJoinCollection); $paginator->setUseOutputWalkers($useOutputWalkers); $iter = $paginator->getIterator(); - $this->assertCount(3, $iter); + self::assertCount(3, $iter); $result = iterator_to_array($iter); - $this->assertEquals($checkField . "0", $result[0]->$checkField); + self::assertEquals($checkField . "0", $result[0]->$checkField); } private function iterateWithOrderAscWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField) { // Ascending $dql = "$baseDql ASC"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); // With offset $query->setMaxResults(3)->setFirstResult(3); $paginator = new Paginator($query, $fetchJoinCollection); $paginator->setUseOutputWalkers($useOutputWalkers); $iter = $paginator->getIterator(); - $this->assertCount(3, $iter); + self::assertCount(3, $iter); $result = iterator_to_array($iter); - $this->assertEquals($checkField . "3", $result[0]->$checkField); + self::assertEquals($checkField . "3", $result[0]->$checkField); } private function iterateWithOrderDesc($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField) { $dql = "$baseDql DESC"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $paginator = new Paginator($query, $fetchJoinCollection); $paginator->setUseOutputWalkers($useOutputWalkers); $iter = $paginator->getIterator(); - $this->assertCount(9, $iter); + self::assertCount(9, $iter); $result = iterator_to_array($iter); - $this->assertEquals($checkField . "8", $result[0]->$checkField); + self::assertEquals($checkField . "8", $result[0]->$checkField); } private function iterateWithOrderDescWithLimit($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField) { $dql = "$baseDql DESC"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); // With limit $query->setMaxResults(3); $paginator = new Paginator($query, $fetchJoinCollection); $paginator->setUseOutputWalkers($useOutputWalkers); $iter = $paginator->getIterator(); - $this->assertCount(3, $iter); + self::assertCount(3, $iter); $result = iterator_to_array($iter); - $this->assertEquals($checkField . "8", $result[0]->$checkField); + self::assertEquals($checkField . "8", $result[0]->$checkField); } private function iterateWithOrderDescWithLimitAndOffset($useOutputWalkers, $fetchJoinCollection, $baseDql, $checkField) { $dql = "$baseDql DESC"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); // With offset $query->setMaxResults(3)->setFirstResult(3); $paginator = new Paginator($query, $fetchJoinCollection); $paginator->setUseOutputWalkers($useOutputWalkers); $iter = $paginator->getIterator(); - $this->assertCount(3, $iter); + self::assertCount(3, $iter); $result = iterator_to_array($iter); - $this->assertEquals($checkField . "5", $result[0]->$checkField); + self::assertEquals($checkField . "5", $result[0]->$checkField); } /** @@ -279,11 +281,11 @@ public function testIterateSimpleWithOutputWalkerWithoutJoinWithComplexOrderAndL public function testIterateWithFetchJoin($useOutputWalkers) { $dql = 'SELECT u,g FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $paginator = new Paginator($query, true); $paginator->setUseOutputWalkers($useOutputWalkers); - $this->assertCount(9, $paginator->getIterator()); + self::assertCount(9, $paginator->getIterator()); } /** @@ -455,20 +457,20 @@ public function testIterateWithOutputWalkersWithFetchJoinWithComplexOrderByRefer public function testIterateComplexWithOutputWalker() { $dql = 'SELECT g, COUNT(u.id) AS userCount FROM Doctrine\Tests\Models\CMS\CmsGroup g LEFT JOIN g.users u GROUP BY g HAVING COUNT(u.id) > 0'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $paginator = new Paginator($query); $paginator->setUseOutputWalkers(true); - $this->assertCount(3, $paginator->getIterator()); + self::assertCount(3, $paginator->getIterator()); } public function testJoinedClassTableInheritance() { $dql = 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyManager c ORDER BY c.startDate'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $paginator = new Paginator($query); - $this->assertCount(1, $paginator->getIterator()); + self::assertCount(1, $paginator->getIterator()); } /** @@ -565,25 +567,25 @@ public function testIterateWithFetchJoinOneToManyWithOrderByColumnFromJoinedWith public function testCountWithCountSubqueryInWhereClauseWithOutputWalker() { $dql = "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE ((SELECT COUNT(s.id) FROM Doctrine\Tests\Models\CMS\CmsUser s) = 9) ORDER BY u.id desc"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $paginator = new Paginator($query, true); $paginator->setUseOutputWalkers(true); - $this->assertCount(9, $paginator); + self::assertCount(9, $paginator); } public function testIterateWithCountSubqueryInWhereClause() { $dql = "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE ((SELECT COUNT(s.id) FROM Doctrine\Tests\Models\CMS\CmsUser s) = 9) ORDER BY u.id desc"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $paginator = new Paginator($query, true); $paginator->setUseOutputWalkers(true); $users = iterator_to_array($paginator->getIterator()); - $this->assertCount(9, $users); + self::assertCount(9, $users); foreach ($users as $i => $user) { - $this->assertEquals("username" . (8 - $i), $user->username); + self::assertEquals("username" . (8 - $i), $user->username); } } @@ -591,7 +593,7 @@ public function testDetectOutputWalker() { // This query works using the output walkers but causes an exception using the TreeWalker $dql = 'SELECT g, COUNT(u.id) AS userCount FROM Doctrine\Tests\Models\CMS\CmsGroup g LEFT JOIN g.users u GROUP BY g HAVING COUNT(u.id) > 0'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); // If the Paginator detects the custom output walker it should fall back to using the // Tree walkers for pagination, which leads to an exception. If the query works, the output walkers were used @@ -610,40 +612,40 @@ public function testDetectOutputWalker() public function testPaginationWithColumnAttributeNameDifference() { $dql = 'SELECT c FROM Doctrine\Tests\Models\Pagination\Company c ORDER BY c.id'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $paginator = new Paginator($query); $paginator->getIterator(); - $this->assertCount(9, $paginator->getIterator()); + self::assertCount(9, $paginator->getIterator()); } public function testCloneQuery() { $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $paginator = new Paginator($query); $paginator->getIterator(); - $this->assertTrue($query->getParameters()->isEmpty()); + self::assertTrue($query->getParameters()->isEmpty()); } public function testQueryWalkerIsKept() { $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CustomPaginationTestTreeWalker::class]); $paginator = new Paginator($query, true); $paginator->setUseOutputWalkers(false); - $this->assertCount(1, $paginator->getIterator()); - $this->assertEquals(1, $paginator->count()); + self::assertCount(1, $paginator->getIterator()); + self::assertEquals(1, $paginator->count()); } public function testCountQueryStripsParametersInSelect() { - $query = $this->_em->createQuery( + $query = $this->em->createQuery( 'SELECT u, (CASE WHEN u.id < :vipMaxId THEN 1 ELSE 0 END) AS hidden promotedFirst FROM Doctrine\\Tests\\Models\\CMS\\CmsUser u WHERE u.id < :id or 1=1' @@ -658,8 +660,8 @@ public function testCountQueryStripsParametersInSelect() $getCountQuery->setAccessible(true); - $this->assertCount(2, $getCountQuery->invoke($paginator)->getParameters()); - $this->assertCount(9, $paginator); + self::assertCount(2, $getCountQuery->invoke($paginator)->getParameters()); + self::assertCount(9, $paginator); $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, Query\SqlWalker::class); @@ -667,8 +669,8 @@ public function testCountQueryStripsParametersInSelect() // if select part of query is replaced with count(...) paginator should remove // parameters from query object not used in new query. - $this->assertCount(1, $getCountQuery->invoke($paginator)->getParameters()); - $this->assertCount(9, $paginator); + self::assertCount(1, $getCountQuery->invoke($paginator)->getParameters()); + self::assertCount(9, $paginator); } /** @@ -676,7 +678,7 @@ public function testCountQueryStripsParametersInSelect() */ public function testPaginationWithSubSelectOrderByExpression($useOutputWalker, $fetchJoinCollection) { - $query = $this->_em->createQuery( + $query = $this->em->createQuery( "SELECT u, ( SELECT MAX(a.version) @@ -690,7 +692,7 @@ public function testPaginationWithSubSelectOrderByExpression($useOutputWalker, $ $paginator = new Paginator($query, $fetchJoinCollection); $paginator->setUseOutputWalkers($useOutputWalker); - $this->assertCount(9, $paginator->getIterator()); + self::assertCount(9, $paginator->getIterator()); } public function populate() @@ -700,7 +702,7 @@ public function populate() $group = new CmsGroup(); $group->name = "group$j"; $groups[] = $group; - $this->_em->persist($group); + $this->em->persist($group); } for ($i = 0; $i < 9; $i++) { @@ -714,14 +716,14 @@ public function populate() for ($j = 0; $j < 3; $j++) { $user->addGroup($groups[$j]); } - $this->_em->persist($user); + $this->em->persist($user); for ($j = 0; $j < $i + 1; $j++) { $article = new CmsArticle(); $article->topic = "topic$i$j"; $article->text = "text$i$j"; $article->setAuthor($user); $article->version = 0; - $this->_em->persist($article); + $this->em->persist($article); } } @@ -739,14 +741,14 @@ public function populate() $department->company = $company; $company->departments[] = $department; } - $this->_em->persist($company); + $this->em->persist($company); } for ($i = 0; $i < 9; $i++) { $user = new User1(); $user->name = "name$i"; $user->email = "email$i"; - $this->_em->persist($user); + $this->em->persist($user); } $manager = new CompanyManager(); @@ -755,9 +757,9 @@ public function populate() $manager->setDepartment('IT'); $manager->setSalary(100000); - $this->_em->persist($manager); + $this->em->persist($manager); - $this->_em->flush(); + $this->em->flush(); } public function useOutputWalkers() diff --git a/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionCriteriaTest.php b/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionCriteriaTest.php index 4e0f442d84a..65fd3088e78 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionCriteriaTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionCriteriaTest.php @@ -1,5 +1,7 @@ useModelSet('tweet'); $this->useModelSet('quote'); + parent::setUp(); } public function tearDown() { - if ($this->_em) { - $this->_em->getConfiguration()->setEntityNamespaces([]); + if ($this->em) { + $this->em->getConfiguration()->setEntityNamespaces([]); } parent::tearDown(); } @@ -35,7 +38,7 @@ public function loadTweetFixture() { $author = new TweetUser(); $author->name = 'ngal'; - $this->_em->persist($author); + $this->em->persist($author); $tweet1 = new Tweet(); $tweet1->content = 'Foo'; @@ -45,20 +48,20 @@ public function loadTweetFixture() $tweet2->content = 'Bar'; $author->addTweet($tweet2); - $this->_em->flush(); + $this->em->flush(); unset($author); unset($tweet1); unset($tweet2); - $this->_em->clear(); + $this->em->clear(); } public function loadQuoteFixture() { $user = new QuoteUser(); $user->name = 'mgal'; - $this->_em->persist($user); + $this->em->persist($user); $quote1 = new Group('quote1'); $user->groups->add($quote1); @@ -66,33 +69,33 @@ public function loadQuoteFixture() $quote2 = new Group('quote2'); $user->groups->add($quote2); - $this->_em->flush(); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); } public function testCanCountWithoutLoadingPersistentCollection() { $this->loadTweetFixture(); - $repository = $this->_em->getRepository(User::class); + $repository = $this->em->getRepository(User::class); $user = $repository->findOneBy(['name' => 'ngal']); $tweets = $user->tweets->matching(new Criteria()); - $this->assertInstanceOf(LazyCriteriaCollection::class, $tweets); - $this->assertFalse($tweets->isInitialized()); - $this->assertCount(2, $tweets); - $this->assertFalse($tweets->isInitialized()); + self::assertInstanceOf(LazyCriteriaCollection::class, $tweets); + self::assertFalse($tweets->isInitialized()); + self::assertCount(2, $tweets); + self::assertFalse($tweets->isInitialized()); // Make sure it works with constraints $tweets = $user->tweets->matching(new Criteria( Criteria::expr()->eq('content', 'Foo') )); - $this->assertInstanceOf(LazyCriteriaCollection::class, $tweets); - $this->assertFalse($tweets->isInitialized()); - $this->assertCount(1, $tweets); - $this->assertFalse($tweets->isInitialized()); + self::assertInstanceOf(LazyCriteriaCollection::class, $tweets); + self::assertFalse($tweets->isInitialized()); + self::assertCount(1, $tweets); + self::assertFalse($tweets->isInitialized()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionTest.php b/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionTest.php index b1751455f34..c986b721e48 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionTest.php @@ -1,10 +1,13 @@ _schemaTool->createSchema( - [ - $this->_em->getClassMetadata(PersistentCollectionHolder::class), - $this->_em->getClassMetadata(PersistentCollectionContent::class), - ] - ); + $this->schemaTool->createSchema([ + $this->em->getClassMetadata(PersistentCollectionHolder::class), + $this->em->getClassMetadata(PersistentCollectionContent::class), + ]); } catch (\Exception $e) { } - PersistentObject::setObjectManager($this->_em); + + PersistentObject::setEntityManager($this->em); } public function testPersist() @@ -31,46 +34,46 @@ public function testPersist() $content = new PersistentCollectionContent('first element'); $collectionHolder->addElement($content); - $this->_em->persist($collectionHolder); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($collectionHolder); + $this->em->flush(); + $this->em->clear(); - $collectionHolder = $this->_em->find(PersistentCollectionHolder::class, $collectionHolder->getId()); + $collectionHolder = $this->em->find(PersistentCollectionHolder::class, $collectionHolder->getId()); $collectionHolder->getCollection(); $content = new PersistentCollectionContent('second element'); $collectionHolder->addElement($content); - $this->assertEquals(2, $collectionHolder->getCollection()->count()); + self::assertEquals(2, $collectionHolder->getCollection()->count()); } /** - * Tests that PersistentCollection::isEmpty() does not initialize the collection when FETCH_EXTRA_LAZY is used. + * Tests that PersistentCollection::isEmpty() does not initialize the collection when FetchMode::EXTRA_LAZY is used. */ public function testExtraLazyIsEmptyDoesNotInitializeCollection() { $collectionHolder = new PersistentCollectionHolder(); - $this->_em->persist($collectionHolder); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($collectionHolder); + $this->em->flush(); + $this->em->clear(); - $collectionHolder = $this->_em->find(PersistentCollectionHolder::class, $collectionHolder->getId()); + $collectionHolder = $this->em->find(PersistentCollectionHolder::class, $collectionHolder->getId()); $collection = $collectionHolder->getRawCollection(); - $this->assertTrue($collection->isEmpty()); - $this->assertFalse($collection->isInitialized()); + self::assertTrue($collection->isEmpty()); + self::assertFalse($collection->isInitialized()); $collectionHolder->addElement(new PersistentCollectionContent()); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $collectionHolder = $this->_em->find(PersistentCollectionHolder::class, $collectionHolder->getId()); + $collectionHolder = $this->em->find(PersistentCollectionHolder::class, $collectionHolder->getId()); $collection = $collectionHolder->getRawCollection(); - $this->assertFalse($collection->isEmpty()); - $this->assertFalse($collection->isInitialized()); + self::assertFalse($collection->isEmpty()); + self::assertFalse($collection->isInitialized()); } /** @@ -81,36 +84,36 @@ public function testMatchingDoesNotModifyTheGivenCriteria() { $collectionHolder = new PersistentCollectionHolder(); - $this->_em->persist($collectionHolder); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($collectionHolder); + $this->em->flush(); + $this->em->clear(); $criteria = new Criteria(); - $collectionHolder = $this->_em->find(PersistentCollectionHolder::class, $collectionHolder->getId()); + $collectionHolder = $this->em->find(PersistentCollectionHolder::class, $collectionHolder->getId()); $collectionHolder->getCollection()->matching($criteria); - $this->assertEmpty($criteria->getWhereExpression()); - $this->assertEmpty($criteria->getFirstResult()); - $this->assertEmpty($criteria->getMaxResults()); - $this->assertEmpty($criteria->getOrderings()); + self::assertEmpty($criteria->getWhereExpression()); + self::assertEmpty($criteria->getFirstResult()); + self::assertEmpty($criteria->getMaxResults()); + self::assertEmpty($criteria->getOrderings()); } } /** - * @Entity + * @ORM\Entity */ class PersistentCollectionHolder extends PersistentObject { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue * @var int */ protected $id; /** * @var \Doctrine\Common\Collections\Collection - * @ManyToMany(targetEntity="PersistentCollectionContent", cascade={"all"}, fetch="EXTRA_LAZY") + * @ORM\ManyToMany(targetEntity="PersistentCollectionContent", cascade={"all"}, fetch="EXTRA_LAZY") */ protected $collection; @@ -145,12 +148,12 @@ public function getRawCollection() } /** - * @Entity + * @ORM\Entity */ class PersistentCollectionContent extends PersistentObject { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue * @var int */ protected $id; diff --git a/tests/Doctrine/Tests/ORM/Functional/PersistentObjectTest.php b/tests/Doctrine/Tests/ORM/Functional/PersistentObjectTest.php index 0fd2b47455c..45ad198a259 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PersistentObjectTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PersistentObjectTest.php @@ -1,8 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(PersistentEntity::class), + $this->em->getClassMetadata(PersistentEntity::class), ] ); } catch (\Exception $e) { } - PersistentObject::setObjectManager($this->_em); + PersistentObject::setEntityManager($this->em); } public function testPersist() @@ -34,8 +37,8 @@ public function testPersist() $entity = new PersistentEntity(); $entity->setName("test"); - $this->_em->persist($entity); - $this->_em->flush(); + $this->em->persist($entity); + $this->em->flush(); $this->addToAssertionCount(1); } @@ -45,16 +48,16 @@ public function testFind() $entity = new PersistentEntity(); $entity->setName("test"); - $this->_em->persist($entity); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($entity); + $this->em->flush(); + $this->em->clear(); - $entity = $this->_em->find(PersistentEntity::class, $entity->getId()); + $entity = $this->em->find(PersistentEntity::class, $entity->getId()); - $this->assertEquals('test', $entity->getName()); + self::assertEquals('test', $entity->getName()); $entity->setName('foobar'); - $this->_em->flush(); + $this->em->flush(); } public function testGetReference() @@ -62,13 +65,13 @@ public function testGetReference() $entity = new PersistentEntity(); $entity->setName("test"); - $this->_em->persist($entity); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($entity); + $this->em->flush(); + $this->em->clear(); - $entity = $this->_em->getReference(PersistentEntity::class, $entity->getId()); + $entity = $this->em->getReference(PersistentEntity::class, $entity->getId()); - $this->assertEquals('test', $entity->getName()); + self::assertEquals('test', $entity->getName()); } public function testSetAssociation() @@ -77,34 +80,34 @@ public function testSetAssociation() $entity->setName("test"); $entity->setParent($entity); - $this->_em->persist($entity); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($entity); + $this->em->flush(); + $this->em->clear(); - $entity = $this->_em->getReference(PersistentEntity::class, $entity->getId()); - $this->assertSame($entity, $entity->getParent()); + $entity = $this->em->getReference(PersistentEntity::class, $entity->getId()); + self::assertSame($entity, $entity->getParent()); } } /** - * @Entity + * @ORM\Entity */ class PersistentEntity extends PersistentObject { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue * @var int */ protected $id; /** - * @Column(type="string") + * @ORM\Column(type="string") * @var string */ protected $name; /** - * @ManyToOne(targetEntity="PersistentEntity") + * @ORM\ManyToOne(targetEntity="PersistentEntity") * @var PersistentEntity */ protected $parent; diff --git a/tests/Doctrine/Tests/ORM/Functional/PostFlushEventTest.php b/tests/Doctrine/Tests/ORM/Functional/PostFlushEventTest.php index 12e2c40809d..1471a6e6517 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PostFlushEventTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PostFlushEventTest.php @@ -1,5 +1,7 @@ useModelSet('cms'); parent::setUp(); $this->listener = new PostFlushListener(); - $evm = $this->_em->getEventManager(); + $evm = $this->em->getEventManager(); $evm->addEventListener(Events::postFlush, $this->listener); } public function testListenerShouldBeNotified() { - $this->_em->persist($this->createNewValidUser()); - $this->_em->flush(); - $this->assertTrue($this->listener->wasNotified); + $this->em->persist($this->createNewValidUser()); + $this->em->flush(); + self::assertTrue($this->listener->wasNotified); } public function testListenerShouldNotBeNotifiedWhenFlushThrowsException() { $user = new CmsUser(); $user->username = 'dfreudenberger'; - $this->_em->persist($user); + $this->em->persist($user); $exceptionRaised = false; try { - $this->_em->flush(); + $this->em->flush(); } catch (\Exception $ex) { $exceptionRaised = true; } - $this->assertTrue($exceptionRaised); - $this->assertFalse($this->listener->wasNotified); + self::assertTrue($exceptionRaised); + self::assertFalse($this->listener->wasNotified); } public function testListenerShouldReceiveEntityManagerThroughArgs() { - $this->_em->persist($this->createNewValidUser()); - $this->_em->flush(); + $this->em->persist($this->createNewValidUser()); + $this->em->flush(); $receivedEm = $this->listener->receivedArgs->getEntityManager(); - $this->assertSame($this->_em, $receivedEm); + self::assertSame($this->em, $receivedEm); } /** diff --git a/tests/Doctrine/Tests/ORM/Functional/PostLoadEventTest.php b/tests/Doctrine/Tests/ORM/Functional/PostLoadEventTest.php index 02a08666673..8f8406ed03a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PostLoadEventTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PostLoadEventTest.php @@ -1,4 +1,6 @@ method('postLoad') ->will($this->returnValue(true)); - $eventManager = $this->_em->getEventManager(); + $eventManager = $this->em->getEventManager(); $eventManager->addEventListener([Events::postLoad], $mockListener); - $this->_em->find(CmsUser::class, $this->userId); + $this->em->find(CmsUser::class, $this->userId); } public function testLoadedEntityUsingQueryShouldTriggerEvent() @@ -61,11 +63,11 @@ public function testLoadedEntityUsingQueryShouldTriggerEvent() ->method('postLoad') ->will($this->returnValue(true)); - $eventManager = $this->_em->getEventManager(); + $eventManager = $this->em->getEventManager(); $eventManager->addEventListener([Events::postLoad], $mockListener); - $query = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :id'); + $query = $this->em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :id'); $query->setParameter('id', $this->userId); $query->getResult(); @@ -81,11 +83,11 @@ public function testLoadedAssociationToOneShouldTriggerEvent() ->method('postLoad') ->will($this->returnValue(true)); - $eventManager = $this->_em->getEventManager(); + $eventManager = $this->em->getEventManager(); $eventManager->addEventListener([Events::postLoad], $mockListener); - $query = $this->_em->createQuery('SELECT u, e FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e WHERE u.id = :id'); + $query = $this->em->createQuery('SELECT u, e FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e WHERE u.id = :id'); $query->setParameter('id', $this->userId); $query->getResult(); @@ -101,11 +103,11 @@ public function testLoadedAssociationToManyShouldTriggerEvent() ->method('postLoad') ->will($this->returnValue(true)); - $eventManager = $this->_em->getEventManager(); + $eventManager = $this->em->getEventManager(); $eventManager->addEventListener([Events::postLoad], $mockListener); - $query = $this->_em->createQuery('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.phonenumbers p WHERE u.id = :id'); + $query = $this->em->createQuery('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.phonenumbers p WHERE u.id = :id'); $query->setParameter('id', $this->userId); $query->getResult(); @@ -113,7 +115,7 @@ public function testLoadedAssociationToManyShouldTriggerEvent() public function testLoadedProxyEntityShouldTriggerEvent() { - $eventManager = $this->_em->getEventManager(); + $eventManager = $this->em->getEventManager(); // Should not be invoked during getReference call $mockListener = $this->createMock(PostLoadListener::class); @@ -125,7 +127,7 @@ public function testLoadedProxyEntityShouldTriggerEvent() $eventManager->addEventListener([Events::postLoad], $mockListener); - $userProxy = $this->_em->getReference(CmsUser::class, $this->userId); + $userProxy = $this->em->getReference(CmsUser::class, $this->userId); // Now deactivate original listener and attach new one $eventManager->removeEventListener([Events::postLoad], $mockListener); @@ -144,7 +146,7 @@ public function testLoadedProxyEntityShouldTriggerEvent() public function testLoadedProxyPartialShouldTriggerEvent() { - $eventManager = $this->_em->getEventManager(); + $eventManager = $this->em->getEventManager(); // Should not be invoked during getReference call $mockListener = $this->createMock(PostLoadListener::class); @@ -157,7 +159,7 @@ public function testLoadedProxyPartialShouldTriggerEvent() $eventManager->addEventListener([Events::postLoad], $mockListener); - $query = $this->_em->createQuery('SELECT PARTIAL u.{id, name}, p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.phonenumbers p WHERE u.id = :id'); + $query = $this->em->createQuery('SELECT PARTIAL u.{id, name}, p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.phonenumbers p WHERE u.id = :id'); $query->setParameter('id', $this->userId); $query->getResult(); @@ -165,7 +167,7 @@ public function testLoadedProxyPartialShouldTriggerEvent() public function testLoadedProxyAssociationToOneShouldTriggerEvent() { - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); $mockListener = $this->createMock(PostLoadListener::class); @@ -175,7 +177,7 @@ public function testLoadedProxyAssociationToOneShouldTriggerEvent() ->method('postLoad') ->will($this->returnValue(true)); - $eventManager = $this->_em->getEventManager(); + $eventManager = $this->em->getEventManager(); $eventManager->addEventListener([Events::postLoad], $mockListener); @@ -186,7 +188,7 @@ public function testLoadedProxyAssociationToOneShouldTriggerEvent() public function testLoadedProxyAssociationToManyShouldTriggerEvent() { - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); $mockListener = $this->createMock(PostLoadListener::class); @@ -196,7 +198,7 @@ public function testLoadedProxyAssociationToManyShouldTriggerEvent() ->method('postLoad') ->will($this->returnValue(true)); - $eventManager = $this->_em->getEventManager(); + $eventManager = $this->em->getEventManager(); $eventManager->addEventListener([Events::postLoad], $mockListener); @@ -211,15 +213,15 @@ public function testLoadedProxyAssociationToManyShouldTriggerEvent() public function testAssociationsArePopulatedWhenEventIsFired() { $checkerListener = new PostLoadListenerCheckAssociationsArePopulated(); - $this->_em->getEventManager()->addEventListener([Events::postLoad], $checkerListener); + $this->em->getEventManager()->addEventListener([Events::postLoad], $checkerListener); - $qb = $this->_em->getRepository(CmsUser::class)->createQueryBuilder('u'); + $qb = $this->em->getRepository(CmsUser::class)->createQueryBuilder('u'); $qb->leftJoin('u.email', 'email'); $qb->addSelect('email'); $qb->getQuery()->getSingleResult(); - $this->assertTrue($checkerListener->checked, 'postLoad event is not invoked'); - $this->assertTrue($checkerListener->populated, 'Association of email is not populated in postLoad event'); + self::assertTrue($checkerListener->checked, 'postLoad event is not invoked'); + self::assertTrue($checkerListener->populated, 'Association of email is not populated in postLoad event'); } /** @@ -227,13 +229,13 @@ public function testAssociationsArePopulatedWhenEventIsFired() */ public function testEventRaisedCorrectTimesWhenOtherEntityLoadedInEventHandler() { - $eventManager = $this->_em->getEventManager(); + $eventManager = $this->em->getEventManager(); $listener = new PostLoadListenerLoadEntityInEventHandler(); $eventManager->addEventListener([Events::postLoad], $listener); - $this->_em->find(CmsUser::class, $this->userId); - $this->assertSame(1, $listener->countHandledEvents(CmsUser::class), CmsUser::class . ' should be handled once!'); - $this->assertSame(1, $listener->countHandledEvents(CmsEmail::class), CmsEmail::class . ' should be handled once!'); + $this->em->find(CmsUser::class, $this->userId); + self::assertSame(1, $listener->countHandledEvents(CmsUser::class), CmsUser::class . ' should be handled once!'); + self::assertSame(1, $listener->countHandledEvents(CmsEmail::class), CmsEmail::class . ' should be handled once!'); } private function loadFixture() @@ -264,12 +266,12 @@ private function loadFixture() $user->addPhonenumber($ph1); $user->addPhonenumber($ph2); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); $this->userId = $user->getId(); - $this->_em->clear(); + $this->em->clear(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ProxiesLikeEntitiesTest.php b/tests/Doctrine/Tests/ORM/Functional/ProxiesLikeEntitiesTest.php index c88eff4ab70..68acb41e822 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ProxiesLikeEntitiesTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ProxiesLikeEntitiesTest.php @@ -1,5 +1,7 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(CmsUser::class), - $this->_em->getClassMetadata(CmsTag::class), - $this->_em->getClassMetadata(CmsPhonenumber::class), - $this->_em->getClassMetadata(CmsArticle::class), - $this->_em->getClassMetadata(CmsAddress::class), - $this->_em->getClassMetadata(CmsEmail::class), - $this->_em->getClassMetadata(CmsGroup::class), + $this->em->getClassMetadata(CmsUser::class), + $this->em->getClassMetadata(CmsTag::class), + $this->em->getClassMetadata(CmsPhonenumber::class), + $this->em->getClassMetadata(CmsArticle::class), + $this->em->getClassMetadata(CmsAddress::class), + $this->em->getClassMetadata(CmsEmail::class), + $this->em->getClassMetadata(CmsGroup::class), ] ); } catch (\Exception $e) { @@ -47,9 +49,9 @@ protected function setUp() $this->user = new CmsUser(); $this->user->username = 'ocramius'; $this->user->name = 'Marco'; - $this->_em->persist($this->user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($this->user); + $this->em->flush(); + $this->em->clear(); } /** @@ -58,36 +60,42 @@ protected function setUp() public function testPersistUpdate() { // Considering case (a) - $proxy = $this->_em->getProxyFactory()->getProxy(CmsUser::class, ['id' => 123]); - $proxy->__isInitialized__ = true; + $proxy = $this->em->getProxyFactory()->getProxy(CmsUser::class, ['id' => 123]); + + $proxy->__setInitialized(true); $proxy->id = null; $proxy->username = 'ocra'; $proxy->name = 'Marco'; - $this->_em->persist($proxy); - $this->_em->flush(); - $this->assertNotNull($proxy->getId()); + + $this->em->persist($proxy); + $this->em->flush(); + + self::assertNotNull($proxy->getId()); + $proxy->name = 'Marco Pivetta'; - $this->_em->getUnitOfWork() - ->computeChangeSet($this->_em->getClassMetadata(CmsUser::class), $proxy); - $this->assertNotEmpty($this->_em->getUnitOfWork()->getEntityChangeSet($proxy)); - $this->assertEquals('Marco Pivetta', $this->_em->find(CmsUser::class, $proxy->getId())->name); - $this->_em->remove($proxy); - $this->_em->flush(); + + $this->em->getUnitOfWork() + ->computeChangeSet($this->em->getClassMetadata(CmsUser::class), $proxy); + self::assertNotEmpty($this->em->getUnitOfWork()->getEntityChangeSet($proxy)); + self::assertEquals('Marco Pivetta', $this->em->find(CmsUser::class, $proxy->getId())->name); + + $this->em->remove($proxy); + $this->em->flush(); } public function testEntityWithIdentifier() { $userId = $this->user->getId(); /* @var $uninitializedProxy CmsUserProxy */ - $uninitializedProxy = $this->_em->getReference(CmsUser::class, $userId); - $this->assertInstanceOf(CmsUserProxy::class, $uninitializedProxy); - - $this->_em->persist($uninitializedProxy); - $this->_em->flush($uninitializedProxy); - $this->assertFalse($uninitializedProxy->__isInitialized(), 'Proxy didn\'t get initialized during flush operations'); - $this->assertEquals($userId, $uninitializedProxy->getId()); - $this->_em->remove($uninitializedProxy); - $this->_em->flush(); + $uninitializedProxy = $this->em->getReference(CmsUser::class, $userId); + self::assertInstanceOf(CmsUserProxy::class, $uninitializedProxy); + + $this->em->persist($uninitializedProxy); + $this->em->flush(); + self::assertFalse($uninitializedProxy->__isInitialized(), 'Proxy didn\'t get initialized during flush operations'); + self::assertEquals($userId, $uninitializedProxy->getId()); + $this->em->remove($uninitializedProxy); + $this->em->flush(); } /** @@ -95,17 +103,20 @@ public function testEntityWithIdentifier() */ public function testProxyAsDqlParameterPersist() { - $proxy = $this->_em->getProxyFactory()->getProxy(CmsUser::class, ['id' => $this->user->getId()] - ); + $proxy = $this->em->getProxyFactory()->getProxy(CmsUser::class, ['id' => $this->user->getId()]); + $proxy->id = $this->user->getId(); + $result = $this - ->_em + ->em ->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u = ?1') ->setParameter(1, $proxy) ->getSingleResult(); - $this->assertSame($this->user->getId(), $result->getId()); - $this->_em->remove($proxy); - $this->_em->flush(); + + self::assertSame($this->user->getId(), $result->getId()); + + $this->em->remove($proxy); + $this->em->flush(); } /** @@ -113,29 +124,38 @@ public function testProxyAsDqlParameterPersist() */ public function testFindWithProxyName() { - $result = $this->_em->find(CmsUserProxy::class, $this->user->getId()); - $this->assertSame($this->user->getId(), $result->getId()); - $this->_em->clear(); + $result = $this->em->find(CmsUserProxy::class, $this->user->getId()); + + self::assertSame($this->user->getId(), $result->getId()); + + $this->em->clear(); + + $result = $this->em->getReference(CmsUserProxy::class, $this->user->getId()); - $result = $this->_em->getReference(CmsUserProxy::class, $this->user->getId()); - $this->assertSame($this->user->getId(), $result->getId()); - $this->_em->clear(); + self::assertSame($this->user->getId(), $result->getId()); - $result = $this->_em->getRepository(CmsUserProxy::class)->findOneBy(['username' => $this->user->username]); - $this->assertSame($this->user->getId(), $result->getId()); - $this->_em->clear(); + $this->em->clear(); - $result = $this->_em + $result = $this->em->getRepository(CmsUserProxy::class)->findOneBy([ + 'username' => $this->user->username + ]); + + self::assertSame($this->user->getId(), $result->getId()); + + $this->em->clear(); + + $result = $this->em ->createQuery('SELECT u FROM Doctrine\Tests\Proxies\__CG__\Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1') ->setParameter(1, $this->user->getId()) ->getSingleResult(); - $this->assertSame($this->user->getId(), $result->getId()); - $this->_em->clear(); + self::assertSame($this->user->getId(), $result->getId()); + + $this->em->clear(); } protected function tearDown() { - $this->_em->createQuery('DELETE FROM Doctrine\Tests\Models\CMS\CmsUser u')->execute(); + $this->em->createQuery('DELETE FROM Doctrine\Tests\Models\CMS\CmsUser u')->execute(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/QueryCacheTest.php b/tests/Doctrine/Tests/ORM/Functional/QueryCacheTest.php index a307ad13786..f175ca8903e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/QueryCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/QueryCacheTest.php @@ -1,5 +1,7 @@ _em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); + $query = $this->em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); $cache = new ArrayCache(); $query->setQueryCacheDriver($cache); $query->getResult(); - $this->assertEquals(1, $this->getCacheSize($cache)); + self::assertEquals(1, $this->getCacheSize($cache)); $query->setHint('foo', 'bar'); $query->getResult(); - $this->assertEquals(2, $this->getCacheSize($cache)); + self::assertEquals(2, $this->getCacheSize($cache)); return $query; } @@ -72,7 +74,7 @@ public function testQueryCache_DependsOnFirstResult($query) $query->setMaxResults(9999); $query->getResult(); - $this->assertEquals($cacheCount + 1, $this->getCacheSize($cache)); + self::assertEquals($cacheCount + 1, $this->getCacheSize($cache)); } /** @@ -87,7 +89,7 @@ public function testQueryCache_DependsOnMaxResults($query) $query->setMaxResults(10); $query->getResult(); - $this->assertEquals($cacheCount + 1, $this->getCacheSize($cache)); + self::assertEquals($cacheCount + 1, $this->getCacheSize($cache)); } /** @@ -100,14 +102,14 @@ public function testQueryCache_DependsOnHydrationMode($query) $cacheCount = $this->getCacheSize($cache); $query->getArrayResult(); - $this->assertEquals($cacheCount + 1, $this->getCacheSize($cache)); + self::assertEquals($cacheCount + 1, $this->getCacheSize($cache)); } public function testQueryCache_NoHitSaveParserResult() { - $this->_em->getConfiguration()->setQueryCacheImpl(new ArrayCache()); + $this->em->getConfiguration()->setQueryCacheImpl(new ArrayCache()); - $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); + $query = $this->em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); $cache = $this->createMock(Cache::class); @@ -123,9 +125,9 @@ public function testQueryCache_NoHitSaveParserResult() public function testQueryCache_HitDoesNotSaveParserResult() { - $this->_em->getConfiguration()->setQueryCacheImpl(new ArrayCache()); + $this->em->getConfiguration()->setQueryCacheImpl(new ArrayCache()); - $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); + $query = $this->em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); $sqlExecMock = $this->getMockBuilder(AbstractSqlExecutor::class) ->setMethods(['execute']) diff --git a/tests/Doctrine/Tests/ORM/Functional/QueryDqlFunctionTest.php b/tests/Doctrine/Tests/ORM/Functional/QueryDqlFunctionTest.php index 764b213dde2..ca409cf04c0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/QueryDqlFunctionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/QueryDqlFunctionTest.php @@ -1,5 +1,7 @@ _em->createQuery('SELECT SUM(m.salary) AS salary FROM Doctrine\Tests\Models\Company\CompanyManager m') + $salarySum = $this->em->createQuery('SELECT SUM(m.salary) AS salary FROM Doctrine\Tests\Models\Company\CompanyManager m') ->getSingleResult(); - $this->assertEquals(1500000, $salarySum['salary']); + self::assertEquals(1500000, $salarySum['salary']); } public function testAggregateAvg() { - $salaryAvg = $this->_em->createQuery('SELECT AVG(m.salary) AS salary FROM Doctrine\Tests\Models\Company\CompanyManager m') + $salaryAvg = $this->em->createQuery('SELECT AVG(m.salary) AS salary FROM Doctrine\Tests\Models\Company\CompanyManager m') ->getSingleResult(); - $this->assertEquals(375000, round($salaryAvg['salary'], 0)); + self::assertEquals(375000, round($salaryAvg['salary'], 0)); } public function testAggregateMin() { - $salary = $this->_em->createQuery('SELECT MIN(m.salary) AS salary FROM Doctrine\Tests\Models\Company\CompanyManager m') + $salary = $this->em->createQuery('SELECT MIN(m.salary) AS salary FROM Doctrine\Tests\Models\Company\CompanyManager m') ->getSingleResult(); - $this->assertEquals(100000, $salary['salary']); + self::assertEquals(100000, $salary['salary']); } public function testAggregateMax() { - $salary = $this->_em->createQuery('SELECT MAX(m.salary) AS salary FROM Doctrine\Tests\Models\Company\CompanyManager m') + $salary = $this->em->createQuery('SELECT MAX(m.salary) AS salary FROM Doctrine\Tests\Models\Company\CompanyManager m') ->getSingleResult(); - $this->assertEquals(800000, $salary['salary']); + self::assertEquals(800000, $salary['salary']); } public function testAggregateCount() { - $managerCount = $this->_em->createQuery('SELECT COUNT(m.id) AS managers FROM Doctrine\Tests\Models\Company\CompanyManager m') + $managerCount = $this->em->createQuery('SELECT COUNT(m.id) AS managers FROM Doctrine\Tests\Models\Company\CompanyManager m') ->getSingleResult(); - $this->assertEquals(4, $managerCount['managers']); + self::assertEquals(4, $managerCount['managers']); } public function testFunctionAbs() { - $result = $this->_em->createQuery('SELECT m, ABS(m.salary * -1) AS abs FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC') + $result = $this->em->createQuery('SELECT m, ABS(m.salary * -1) AS abs FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC') ->getResult(); - $this->assertEquals(4, count($result)); - $this->assertEquals(100000, $result[0]['abs']); - $this->assertEquals(200000, $result[1]['abs']); - $this->assertEquals(400000, $result[2]['abs']); - $this->assertEquals(800000, $result[3]['abs']); + self::assertEquals(4, count($result)); + self::assertEquals(100000, $result[0]['abs']); + self::assertEquals(200000, $result[1]['abs']); + self::assertEquals(400000, $result[2]['abs']); + self::assertEquals(800000, $result[3]['abs']); } public function testFunctionConcat() { - $arg = $this->_em->createQuery('SELECT m, CONCAT(m.name, m.department) AS namedep FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC') + $arg = $this->em->createQuery('SELECT m, CONCAT(m.name, m.department) AS namedep FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC') ->getArrayResult(); - $this->assertEquals(4, count($arg)); - $this->assertEquals('Roman B.IT', $arg[0]['namedep']); - $this->assertEquals('Benjamin E.HR', $arg[1]['namedep']); - $this->assertEquals('Guilherme B.Complaint Department', $arg[2]['namedep']); - $this->assertEquals('Jonathan W.Administration', $arg[3]['namedep']); + self::assertEquals(4, count($arg)); + self::assertEquals('Roman B.IT', $arg[0]['namedep']); + self::assertEquals('Benjamin E.HR', $arg[1]['namedep']); + self::assertEquals('Guilherme B.Complaint Department', $arg[2]['namedep']); + self::assertEquals('Jonathan W.Administration', $arg[3]['namedep']); } public function testFunctionLength() { - $result = $this->_em->createQuery('SELECT m, LENGTH(CONCAT(m.name, m.department)) AS namedeplength FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC') + $result = $this->em->createQuery('SELECT m, LENGTH(CONCAT(m.name, m.department)) AS namedeplength FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC') ->getArrayResult(); - $this->assertEquals(4, count($result)); - $this->assertEquals(10, $result[0]['namedeplength']); - $this->assertEquals(13, $result[1]['namedeplength']); - $this->assertEquals(32, $result[2]['namedeplength']); - $this->assertEquals(25, $result[3]['namedeplength']); + self::assertEquals(4, count($result)); + self::assertEquals(10, $result[0]['namedeplength']); + self::assertEquals(13, $result[1]['namedeplength']); + self::assertEquals(32, $result[2]['namedeplength']); + self::assertEquals(25, $result[3]['namedeplength']); } public function testFunctionLocate() @@ -101,66 +103,66 @@ public function testFunctionLocate() $dql = "SELECT m, LOCATE('e', LOWER(m.name)) AS loc, LOCATE('e', LOWER(m.name), 7) AS loc2 ". "FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC"; - $result = $this->_em->createQuery($dql) + $result = $this->em->createQuery($dql) ->getArrayResult(); - $this->assertEquals(4, count($result)); - $this->assertEquals(0, $result[0]['loc']); - $this->assertEquals(2, $result[1]['loc']); - $this->assertEquals(6, $result[2]['loc']); - $this->assertEquals(0, $result[3]['loc']); - $this->assertEquals(0, $result[0]['loc2']); - $this->assertEquals(10, $result[1]['loc2']); - $this->assertEquals(9, $result[2]['loc2']); - $this->assertEquals(0, $result[3]['loc2']); + self::assertEquals(4, count($result)); + self::assertEquals(0, $result[0]['loc']); + self::assertEquals(2, $result[1]['loc']); + self::assertEquals(6, $result[2]['loc']); + self::assertEquals(0, $result[3]['loc']); + self::assertEquals(0, $result[0]['loc2']); + self::assertEquals(10, $result[1]['loc2']); + self::assertEquals(9, $result[2]['loc2']); + self::assertEquals(0, $result[3]['loc2']); } public function testFunctionLower() { - $result = $this->_em->createQuery("SELECT m, LOWER(m.name) AS lowername FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC") + $result = $this->em->createQuery("SELECT m, LOWER(m.name) AS lowername FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC") ->getArrayResult(); - $this->assertEquals(4, count($result)); - $this->assertEquals('roman b.', $result[0]['lowername']); - $this->assertEquals('benjamin e.', $result[1]['lowername']); - $this->assertEquals('guilherme b.', $result[2]['lowername']); - $this->assertEquals('jonathan w.', $result[3]['lowername']); + self::assertEquals(4, count($result)); + self::assertEquals('roman b.', $result[0]['lowername']); + self::assertEquals('benjamin e.', $result[1]['lowername']); + self::assertEquals('guilherme b.', $result[2]['lowername']); + self::assertEquals('jonathan w.', $result[3]['lowername']); } public function testFunctionMod() { - $result = $this->_em->createQuery("SELECT m, MOD(m.salary, 3500) AS amod FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC") + $result = $this->em->createQuery("SELECT m, MOD(m.salary, 3500) AS amod FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC") ->getArrayResult(); - $this->assertEquals(4, count($result)); - $this->assertEquals(2000, $result[0]['amod']); - $this->assertEquals(500, $result[1]['amod']); - $this->assertEquals(1000, $result[2]['amod']); - $this->assertEquals(2000, $result[3]['amod']); + self::assertEquals(4, count($result)); + self::assertEquals(2000, $result[0]['amod']); + self::assertEquals(500, $result[1]['amod']); + self::assertEquals(1000, $result[2]['amod']); + self::assertEquals(2000, $result[3]['amod']); } public function testFunctionSqrt() { - $result = $this->_em->createQuery("SELECT m, SQRT(m.salary) AS sqrtsalary FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC") + $result = $this->em->createQuery("SELECT m, SQRT(m.salary) AS sqrtsalary FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC") ->getArrayResult(); - $this->assertEquals(4, count($result)); - $this->assertEquals(316, round($result[0]['sqrtsalary'])); - $this->assertEquals(447, round($result[1]['sqrtsalary'])); - $this->assertEquals(632, round($result[2]['sqrtsalary'])); - $this->assertEquals(894, round($result[3]['sqrtsalary'])); + self::assertEquals(4, count($result)); + self::assertEquals(316, round($result[0]['sqrtsalary'])); + self::assertEquals(447, round($result[1]['sqrtsalary'])); + self::assertEquals(632, round($result[2]['sqrtsalary'])); + self::assertEquals(894, round($result[3]['sqrtsalary'])); } public function testFunctionUpper() { - $result = $this->_em->createQuery("SELECT m, UPPER(m.name) AS uppername FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC") + $result = $this->em->createQuery("SELECT m, UPPER(m.name) AS uppername FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC") ->getArrayResult(); - $this->assertEquals(4, count($result)); - $this->assertEquals('ROMAN B.', $result[0]['uppername']); - $this->assertEquals('BENJAMIN E.', $result[1]['uppername']); - $this->assertEquals('GUILHERME B.', $result[2]['uppername']); - $this->assertEquals('JONATHAN W.', $result[3]['uppername']); + self::assertEquals(4, count($result)); + self::assertEquals('ROMAN B.', $result[0]['uppername']); + self::assertEquals('BENJAMIN E.', $result[1]['uppername']); + self::assertEquals('GUILHERME B.', $result[2]['uppername']); + self::assertEquals('JONATHAN W.', $result[3]['uppername']); } public function testFunctionSubstring() @@ -168,19 +170,19 @@ public function testFunctionSubstring() $dql = "SELECT m, SUBSTRING(m.name, 1, 3) AS str1, SUBSTRING(m.name, 5) AS str2 ". "FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.name"; - $result = $this->_em->createQuery($dql) + $result = $this->em->createQuery($dql) ->getArrayResult(); - $this->assertEquals(4, count($result)); - $this->assertEquals('Ben', $result[0]['str1']); - $this->assertEquals('Gui', $result[1]['str1']); - $this->assertEquals('Jon', $result[2]['str1']); - $this->assertEquals('Rom', $result[3]['str1']); + self::assertEquals(4, count($result)); + self::assertEquals('Ben', $result[0]['str1']); + self::assertEquals('Gui', $result[1]['str1']); + self::assertEquals('Jon', $result[2]['str1']); + self::assertEquals('Rom', $result[3]['str1']); - $this->assertEquals('amin E.', $result[0]['str2']); - $this->assertEquals('herme B.', $result[1]['str2']); - $this->assertEquals('than W.', $result[2]['str2']); - $this->assertEquals('n B.', $result[3]['str2']); + self::assertEquals('amin E.', $result[0]['str2']); + self::assertEquals('herme B.', $result[1]['str2']); + self::assertEquals('than W.', $result[2]['str2']); + self::assertEquals('n B.', $result[3]['str2']); } public function testFunctionTrim() @@ -189,57 +191,57 @@ public function testFunctionTrim() " TRIM(LEADING '.' FROM m.name) AS str2, TRIM(CONCAT(' ', CONCAT(m.name, ' '))) AS str3 ". "FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC"; - $result = $this->_em->createQuery($dql)->getArrayResult(); - - $this->assertEquals(4, count($result)); - $this->assertEquals('Roman B', $result[0]['str1']); - $this->assertEquals('Benjamin E', $result[1]['str1']); - $this->assertEquals('Guilherme B', $result[2]['str1']); - $this->assertEquals('Jonathan W', $result[3]['str1']); - $this->assertEquals('Roman B.', $result[0]['str2']); - $this->assertEquals('Benjamin E.', $result[1]['str2']); - $this->assertEquals('Guilherme B.', $result[2]['str2']); - $this->assertEquals('Jonathan W.', $result[3]['str2']); - $this->assertEquals('Roman B.', $result[0]['str3']); - $this->assertEquals('Benjamin E.', $result[1]['str3']); - $this->assertEquals('Guilherme B.', $result[2]['str3']); - $this->assertEquals('Jonathan W.', $result[3]['str3']); + $result = $this->em->createQuery($dql)->getArrayResult(); + + self::assertEquals(4, count($result)); + self::assertEquals('Roman B', $result[0]['str1']); + self::assertEquals('Benjamin E', $result[1]['str1']); + self::assertEquals('Guilherme B', $result[2]['str1']); + self::assertEquals('Jonathan W', $result[3]['str1']); + self::assertEquals('Roman B.', $result[0]['str2']); + self::assertEquals('Benjamin E.', $result[1]['str2']); + self::assertEquals('Guilherme B.', $result[2]['str2']); + self::assertEquals('Jonathan W.', $result[3]['str2']); + self::assertEquals('Roman B.', $result[0]['str3']); + self::assertEquals('Benjamin E.', $result[1]['str3']); + self::assertEquals('Guilherme B.', $result[2]['str3']); + self::assertEquals('Jonathan W.', $result[3]['str3']); } public function testOperatorAdd() { - $result = $this->_em->createQuery('SELECT m, m.salary+2500 AS add FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC') + $result = $this->em->createQuery('SELECT m, m.salary+2500 AS add FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC') ->getResult(); - $this->assertEquals(4, count($result)); - $this->assertEquals(102500, $result[0]['add']); - $this->assertEquals(202500, $result[1]['add']); - $this->assertEquals(402500, $result[2]['add']); - $this->assertEquals(802500, $result[3]['add']); + self::assertEquals(4, count($result)); + self::assertEquals(102500, $result[0]['add']); + self::assertEquals(202500, $result[1]['add']); + self::assertEquals(402500, $result[2]['add']); + self::assertEquals(802500, $result[3]['add']); } public function testOperatorSub() { - $result = $this->_em->createQuery('SELECT m, m.salary-2500 AS sub FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC') + $result = $this->em->createQuery('SELECT m, m.salary-2500 AS sub FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC') ->getResult(); - $this->assertEquals(4, count($result)); - $this->assertEquals(97500, $result[0]['sub']); - $this->assertEquals(197500, $result[1]['sub']); - $this->assertEquals(397500, $result[2]['sub']); - $this->assertEquals(797500, $result[3]['sub']); + self::assertEquals(4, count($result)); + self::assertEquals(97500, $result[0]['sub']); + self::assertEquals(197500, $result[1]['sub']); + self::assertEquals(397500, $result[2]['sub']); + self::assertEquals(797500, $result[3]['sub']); } public function testOperatorMultiply() { - $result = $this->_em->createQuery('SELECT m, m.salary*2 AS op FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC') + $result = $this->em->createQuery('SELECT m, m.salary*2 AS op FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC') ->getResult(); - $this->assertEquals(4, count($result)); - $this->assertEquals(200000, $result[0]['op']); - $this->assertEquals(400000, $result[1]['op']); - $this->assertEquals(800000, $result[2]['op']); - $this->assertEquals(1600000, $result[3]['op']); + self::assertEquals(4, count($result)); + self::assertEquals(200000, $result[0]['op']); + self::assertEquals(400000, $result[1]['op']); + self::assertEquals(800000, $result[2]['op']); + self::assertEquals(1600000, $result[3]['op']); } /** @@ -247,26 +249,26 @@ public function testOperatorMultiply() */ public function testOperatorDiv() { - $result = $this->_em->createQuery('SELECT m, (m.salary/0.5) AS op FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC') + $result = $this->em->createQuery('SELECT m, (m.salary/0.5) AS op FROM Doctrine\Tests\Models\Company\CompanyManager m ORDER BY m.salary ASC') ->getResult(); - $this->assertEquals(4, count($result)); - $this->assertEquals(200000, $result[0]['op']); - $this->assertEquals(400000, $result[1]['op']); - $this->assertEquals(800000, $result[2]['op']); - $this->assertEquals(1600000, $result[3]['op']); + self::assertEquals(4, count($result)); + self::assertEquals(200000, $result[0]['op']); + self::assertEquals(400000, $result[1]['op']); + self::assertEquals(800000, $result[2]['op']); + self::assertEquals(1600000, $result[3]['op']); } public function testConcatFunction() { - $arg = $this->_em->createQuery('SELECT CONCAT(m.name, m.department) AS namedep FROM Doctrine\Tests\Models\Company\CompanyManager m order by namedep desc') + $arg = $this->em->createQuery('SELECT CONCAT(m.name, m.department) AS namedep FROM Doctrine\Tests\Models\Company\CompanyManager m order by namedep desc') ->getArrayResult(); - $this->assertEquals(4, count($arg)); - $this->assertEquals('Roman B.IT', $arg[0]['namedep']); - $this->assertEquals('Jonathan W.Administration', $arg[1]['namedep']); - $this->assertEquals('Guilherme B.Complaint Department', $arg[2]['namedep']); - $this->assertEquals('Benjamin E.HR', $arg[3]['namedep']); + self::assertEquals(4, count($arg)); + self::assertEquals('Roman B.IT', $arg[0]['namedep']); + self::assertEquals('Jonathan W.Administration', $arg[1]['namedep']); + self::assertEquals('Guilherme B.Complaint Department', $arg[2]['namedep']); + self::assertEquals('Benjamin E.HR', $arg[3]['namedep']); } /** @@ -274,15 +276,15 @@ public function testConcatFunction() */ public function testDateDiff() { - $query = $this->_em->createQuery("SELECT DATE_DIFF(CURRENT_TIMESTAMP(), DATE_ADD(CURRENT_TIMESTAMP(), 10, 'day')) AS diff FROM Doctrine\Tests\Models\Company\CompanyManager m"); + $query = $this->em->createQuery("SELECT DATE_DIFF(CURRENT_TIMESTAMP(), DATE_ADD(CURRENT_TIMESTAMP(), 10, 'day')) AS diff FROM Doctrine\Tests\Models\Company\CompanyManager m"); $arg = $query->getArrayResult(); - $this->assertEquals(-10, $arg[0]['diff'], "Should be roughly -10 (or -9)", 1); + self::assertEquals(-10, $arg[0]['diff'], "Should be roughly -10 (or -9)", 1); - $query = $this->_em->createQuery("SELECT DATE_DIFF(DATE_ADD(CURRENT_TIMESTAMP(), 10, 'day'), CURRENT_TIMESTAMP()) AS diff FROM Doctrine\Tests\Models\Company\CompanyManager m"); + $query = $this->em->createQuery("SELECT DATE_DIFF(DATE_ADD(CURRENT_TIMESTAMP(), 10, 'day'), CURRENT_TIMESTAMP()) AS diff FROM Doctrine\Tests\Models\Company\CompanyManager m"); $arg = $query->getArrayResult(); - $this->assertEquals(10, $arg[0]['diff'], "Should be roughly 10 (or 9)", 1); + self::assertEquals(10, $arg[0]['diff'], "Should be roughly 10 (or 9)", 1); } /** @@ -290,32 +292,32 @@ public function testDateDiff() */ public function testDateAdd() { - $arg = $this->_em->createQuery("SELECT DATE_ADD(CURRENT_TIMESTAMP(), 10, 'day') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m") + $arg = $this->em->createQuery("SELECT DATE_ADD(CURRENT_TIMESTAMP(), 10, 'day') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m") ->getArrayResult(); - $this->assertTrue(strtotime($arg[0]['add']) > 0); + self::assertTrue(strtotime($arg[0]['add']) > 0); - $arg = $this->_em->createQuery("SELECT DATE_ADD(CURRENT_TIMESTAMP(), 10, 'month') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m") + $arg = $this->em->createQuery("SELECT DATE_ADD(CURRENT_TIMESTAMP(), 10, 'month') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m") ->getArrayResult(); - $this->assertTrue(strtotime($arg[0]['add']) > 0); + self::assertTrue(strtotime($arg[0]['add']) > 0); } public function testDateAddSecond() { $dql = "SELECT CURRENT_TIMESTAMP() now, DATE_ADD(CURRENT_TIMESTAMP(), 10, 'second') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m"; - $query = $this->_em->createQuery($dql)->setMaxResults(1); + $query = $this->em->createQuery($dql)->setMaxResults(1); $result = $query->getArrayResult(); - $this->assertCount(1, $result); - $this->assertArrayHasKey('now', $result[0]); - $this->assertArrayHasKey('add', $result[0]); + self::assertCount(1, $result); + self::assertArrayHasKey('now', $result[0]); + self::assertArrayHasKey('add', $result[0]); $now = strtotime($result[0]['now']); $add = strtotime($result[0]['add']); $diff = $add - $now; - $this->assertSQLEquals(10, $diff); + self::assertSQLEquals(10, $diff); } /** @@ -323,15 +325,15 @@ public function testDateAddSecond() */ public function testDateSub() { - $arg = $this->_em->createQuery("SELECT DATE_SUB(CURRENT_TIMESTAMP(), 10, 'day') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m") + $arg = $this->em->createQuery("SELECT DATE_SUB(CURRENT_TIMESTAMP(), 10, 'day') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m") ->getArrayResult(); - $this->assertTrue(strtotime($arg[0]['add']) > 0); + self::assertTrue(strtotime($arg[0]['add']) > 0); - $arg = $this->_em->createQuery("SELECT DATE_SUB(CURRENT_TIMESTAMP(), 10, 'month') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m") + $arg = $this->em->createQuery("SELECT DATE_SUB(CURRENT_TIMESTAMP(), 10, 'month') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m") ->getArrayResult(); - $this->assertTrue(strtotime($arg[0]['add']) > 0); + self::assertTrue(strtotime($arg[0]['add']) > 0); } /** @@ -345,17 +347,17 @@ public function testBitOrComparison() 'FROM Doctrine\Tests\Models\Company\CompanyManager m ' . 'ORDER BY ' . 'm.id ' ; - $result = $this->_em->createQuery($dql)->getArrayResult(); + $result = $this->em->createQuery($dql)->getArrayResult(); - $this->assertEquals(4 | 2, $result[0]['bit_or']); - $this->assertEquals(4 | 2, $result[1]['bit_or']); - $this->assertEquals(4 | 2, $result[2]['bit_or']); - $this->assertEquals(4 | 2, $result[3]['bit_or']); + self::assertEquals(4 | 2, $result[0]['bit_or']); + self::assertEquals(4 | 2, $result[1]['bit_or']); + self::assertEquals(4 | 2, $result[2]['bit_or']); + self::assertEquals(4 | 2, $result[3]['bit_or']); - $this->assertEquals(($result[0][0]['salary']/100000) | 2, $result[0]['salary_bit_or']); - $this->assertEquals(($result[1][0]['salary']/100000) | 2, $result[1]['salary_bit_or']); - $this->assertEquals(($result[2][0]['salary']/100000) | 2, $result[2]['salary_bit_or']); - $this->assertEquals(($result[3][0]['salary']/100000) | 2, $result[3]['salary_bit_or']); + self::assertEquals(($result[0][0]['salary']/100000) | 2, $result[0]['salary_bit_or']); + self::assertEquals(($result[1][0]['salary']/100000) | 2, $result[1]['salary_bit_or']); + self::assertEquals(($result[2][0]['salary']/100000) | 2, $result[2]['salary_bit_or']); + self::assertEquals(($result[3][0]['salary']/100000) | 2, $result[3]['salary_bit_or']); } /** @@ -369,17 +371,17 @@ public function testBitAndComparison() 'FROM Doctrine\Tests\Models\Company\CompanyManager m ' . 'ORDER BY ' . 'm.id ' ; - $result = $this->_em->createQuery($dql)->getArrayResult(); + $result = $this->em->createQuery($dql)->getArrayResult(); - $this->assertEquals(4 & 2, $result[0]['bit_and']); - $this->assertEquals(4 & 2, $result[1]['bit_and']); - $this->assertEquals(4 & 2, $result[2]['bit_and']); - $this->assertEquals(4 & 2, $result[3]['bit_and']); + self::assertEquals(4 & 2, $result[0]['bit_and']); + self::assertEquals(4 & 2, $result[1]['bit_and']); + self::assertEquals(4 & 2, $result[2]['bit_and']); + self::assertEquals(4 & 2, $result[3]['bit_and']); - $this->assertEquals(($result[0][0]['salary']/100000) & 2, $result[0]['salary_bit_and']); - $this->assertEquals(($result[1][0]['salary']/100000) & 2, $result[1]['salary_bit_and']); - $this->assertEquals(($result[2][0]['salary']/100000) & 2, $result[2]['salary_bit_and']); - $this->assertEquals(($result[3][0]['salary']/100000) & 2, $result[3]['salary_bit_and']); + self::assertEquals(($result[0][0]['salary']/100000) & 2, $result[0]['salary_bit_and']); + self::assertEquals(($result[1][0]['salary']/100000) & 2, $result[1]['salary_bit_and']); + self::assertEquals(($result[2][0]['salary']/100000) & 2, $result[2]['salary_bit_and']); + self::assertEquals(($result[3][0]['salary']/100000) & 2, $result[3]['salary_bit_and']); } protected function generateFixture() @@ -408,11 +410,11 @@ protected function generateFixture() $manager4->setDepartment('Administration'); $manager4->setSalary(800000); - $this->_em->persist($manager1); - $this->_em->persist($manager2); - $this->_em->persist($manager3); - $this->_em->persist($manager4); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($manager1); + $this->em->persist($manager2); + $this->em->persist($manager3); + $this->em->persist($manager4); + $this->em->flush(); + $this->em->clear(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/QueryTest.php b/tests/Doctrine/Tests/ORM/Functional/QueryTest.php index f25cd33faaa..9a827bd777d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/QueryTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/QueryTest.php @@ -1,9 +1,12 @@ name = 'Guilherme'; $user->username = 'gblanco'; $user->status = 'developer'; - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery("select u, upper(u.name) from Doctrine\Tests\Models\CMS\CmsUser u where u.username = 'gblanco'"); + $query = $this->em->createQuery("select u, upper(u.name) from Doctrine\Tests\Models\CMS\CmsUser u where u.username = 'gblanco'"); $result = $query->getResult(); - $this->assertEquals(1, count($result)); - $this->assertInstanceOf(CmsUser::class, $result[0][0]); - $this->assertEquals('Guilherme', $result[0][0]->name); - $this->assertEquals('gblanco', $result[0][0]->username); - $this->assertEquals('developer', $result[0][0]->status); - $this->assertEquals('GUILHERME', $result[0][1]); + self::assertEquals(1, count($result)); + self::assertInstanceOf(CmsUser::class, $result[0][0]); + self::assertEquals('Guilherme', $result[0][0]->name); + self::assertEquals('gblanco', $result[0][0]->username); + self::assertEquals('developer', $result[0][0]->status); + self::assertEquals('GUILHERME', $result[0][1]); $resultArray = $query->getArrayResult(); - $this->assertEquals(1, count($resultArray)); - $this->assertTrue(is_array($resultArray[0][0])); - $this->assertEquals('Guilherme', $resultArray[0][0]['name']); - $this->assertEquals('gblanco', $resultArray[0][0]['username']); - $this->assertEquals('developer', $resultArray[0][0]['status']); - $this->assertEquals('GUILHERME', $resultArray[0][1]); + self::assertEquals(1, count($resultArray)); + self::assertTrue(is_array($resultArray[0][0])); + self::assertEquals('Guilherme', $resultArray[0][0]['name']); + self::assertEquals('gblanco', $resultArray[0][0]['username']); + self::assertEquals('developer', $resultArray[0][0]['status']); + self::assertEquals('GUILHERME', $resultArray[0][1]); $scalarResult = $query->getScalarResult(); - $this->assertEquals(1, count($scalarResult)); - $this->assertEquals('Guilherme', $scalarResult[0]['u_name']); - $this->assertEquals('gblanco', $scalarResult[0]['u_username']); - $this->assertEquals('developer', $scalarResult[0]['u_status']); - $this->assertEquals('GUILHERME', $scalarResult[0][1]); + self::assertEquals(1, count($scalarResult)); + self::assertEquals('Guilherme', $scalarResult[0]['u_name']); + self::assertEquals('gblanco', $scalarResult[0]['u_username']); + self::assertEquals('developer', $scalarResult[0]['u_status']); + self::assertEquals('GUILHERME', $scalarResult[0][1]); - $query = $this->_em->createQuery("select upper(u.name) from Doctrine\Tests\Models\CMS\CmsUser u where u.username = 'gblanco'"); - $this->assertEquals('GUILHERME', $query->getSingleScalarResult()); + $query = $this->em->createQuery("select upper(u.name) from Doctrine\Tests\Models\CMS\CmsUser u where u.username = 'gblanco'"); + self::assertEquals('GUILHERME', $query->getSingleScalarResult()); } public function testJoinQueries() @@ -87,20 +90,21 @@ public function testJoinQueries() $article2->text = "This is an introduction to Symfony 2."; $user->addArticle($article2); - $this->_em->persist($user); - $this->_em->persist($article1); - $this->_em->persist($article2); + $this->em->persist($user); + $this->em->persist($article1); + $this->em->persist($article2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery('select u, a from ' . CmsUser::class . ' u join u.articles a ORDER BY a.topic'); + $query = $this->em->createQuery('select u, a from ' . CmsUser::class . ' u join u.articles a ORDER BY a.topic'); $users = $query->getResult(); - $this->assertEquals(1, count($users)); - $this->assertInstanceOf(CmsUser::class, $users[0]); - $this->assertEquals(2, count($users[0]->articles)); - $this->assertEquals('Doctrine 2', $users[0]->articles[0]->topic); - $this->assertEquals('Symfony 2', $users[0]->articles[1]->topic); + + self::assertEquals(1, count($users)); + self::assertInstanceOf(CmsUser::class, $users[0]); + self::assertEquals(2, count($users[0]->articles)); + self::assertEquals('Doctrine 2', $users[0]->articles[0]->topic); + self::assertEquals('Symfony 2', $users[0]->articles[1]->topic); } public function testUsingZeroBasedQueryParameterShouldWork() @@ -109,15 +113,15 @@ public function testUsingZeroBasedQueryParameterShouldWork() $user->name = 'Jonathan'; $user->username = 'jwage'; $user->status = 'developer'; - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $q = $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.username = ?0'); + $q = $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.username = ?0'); $q->setParameter(0, 'jwage'); $user = $q->getSingleResult(); - $this->assertNotNull($user); + self::assertNotNull($user); } public function testUsingUnknownQueryParameterShouldThrowException() @@ -125,7 +129,7 @@ public function testUsingUnknownQueryParameterShouldThrowException() $this->expectException(QueryException::class); $this->expectExceptionMessage('Invalid parameter: token 2 is not defined in the query.'); - $q = $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1'); + $q = $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1'); $q->setParameter(2, 'jwage'); $user = $q->getSingleResult(); } @@ -135,7 +139,7 @@ public function testTooManyParametersShouldThrowException() $this->expectException(QueryException::class); $this->expectExceptionMessage('Too many parameters: the query defines 1 parameters and you bound 2'); - $q = $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1'); + $q = $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1'); $q->setParameter(1, 'jwage'); $q->setParameter(2, 'jwage'); @@ -147,7 +151,7 @@ public function testTooFewParametersShouldThrowException() $this->expectException(QueryException::class); $this->expectExceptionMessage('Too few parameters: the query defines 1 parameters but you only bound 0'); - $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1') + $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1') ->getSingleResult(); } @@ -155,7 +159,7 @@ public function testInvalidInputParameterThrowsException() { $this->expectException(QueryException::class); - $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?') + $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?') ->setParameter(1, 'jwage') ->getSingleResult(); } @@ -166,7 +170,7 @@ public function testSetParameters() $parameters->add(new Parameter(1, 'jwage')); $parameters->add(new Parameter(2, 'active')); - $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1 AND u.status = ?2') + $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1 AND u.status = ?2') ->setParameters($parameters) ->getResult(); @@ -176,7 +180,7 @@ public function testSetParameters() self::assertSame( $parameters->map($extractValue)->toArray(), - $this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['params'] + $this->sqlLoggerStack->queries[$this->sqlLoggerStack->currentQuery]['params'] ); } @@ -184,13 +188,13 @@ public function testSetParametersBackwardsCompatible() { $parameters = [1 => 'jwage', 2 => 'active']; - $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1 AND u.status = ?2') + $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1 AND u.status = ?2') ->setParameters($parameters) ->getResult(); self::assertSame( array_values($parameters), - $this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['params'] + $this->sqlLoggerStack->queries[$this->sqlLoggerStack->currentQuery]['params'] ); } @@ -207,14 +211,14 @@ public function testIterateResultAsArrayAndParams() $article2->topic = "Symfony 2"; $article2->text = "This is an introduction to Symfony 2."; - $this->_em->persist($article1); - $this->_em->persist($article2); + $this->em->persist($article1); + $this->em->persist($article2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $articleId = $article1->id; - $query = $this->_em->createQuery('select a from ' . CmsArticle::class . ' a WHERE a.topic = ?1'); + $query = $this->em->createQuery('select a from ' . CmsArticle::class . ' a WHERE a.topic = ?1'); $articles = $query->iterate(new ArrayCollection([new Parameter(1, 'Doctrine 2')]), Query::HYDRATE_ARRAY); $found = []; @@ -223,17 +227,17 @@ public function testIterateResultAsArrayAndParams() $found[] = $article; } - $this->assertEquals(1, count($found)); - $this->assertSame( + self::assertEquals(1, count($found)); + self::assertEquals( [ [ [ 'id' => $articleId, 'topic' => 'Doctrine 2', 'text' => 'This is an introduction to Doctrine 2.', - 'version' => 1, - ], - ], + 'version' => 1 + ] + ] ], $found ); @@ -249,13 +253,13 @@ public function testIterateResult_IterativelyBuildUpUnitOfWork() $article2->topic = "Symfony 2"; $article2->text = "This is an introduction to Symfony 2."; - $this->_em->persist($article1); - $this->_em->persist($article2); + $this->em->persist($article1); + $this->em->persist($article2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery('select a from ' . CmsArticle::class . ' a'); + $query = $this->em->createQuery('select a from ' . CmsArticle::class . ' a'); $articles = $query->iterate(); $iteratedCount = 0; @@ -265,18 +269,18 @@ public function testIterateResult_IterativelyBuildUpUnitOfWork() $article = $row[0]; $topics[] = $article->topic; - $identityMap = $this->_em->getUnitOfWork()->getIdentityMap(); + $identityMap = $this->em->getUnitOfWork()->getIdentityMap(); $identityMapCount = count($identityMap[CmsArticle::class]); - $this->assertTrue($identityMapCount>$iteratedCount); + self::assertTrue($identityMapCount>$iteratedCount); $iteratedCount++; } - $this->assertSame(["Doctrine 2", "Symfony 2"], $topics); - $this->assertSame(2, $iteratedCount); + self::assertSame(["Doctrine 2", "Symfony 2"], $topics); + self::assertSame(2, $iteratedCount); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); } public function testIterateResultClearEveryCycle() @@ -289,13 +293,13 @@ public function testIterateResultClearEveryCycle() $article2->topic = "Symfony 2"; $article2->text = "This is an introduction to Symfony 2."; - $this->_em->persist($article1); - $this->_em->persist($article2); + $this->em->persist($article1); + $this->em->persist($article2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a"); + $query = $this->em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a"); $articles = $query->iterate(); $iteratedCount = 0; @@ -304,15 +308,15 @@ public function testIterateResultClearEveryCycle() $article = $row[0]; $topics[] = $article->topic; - $this->_em->clear(); + $this->em->clear(); $iteratedCount++; } - $this->assertSame(["Doctrine 2", "Symfony 2"], $topics); - $this->assertSame(2, $iteratedCount); + self::assertSame(["Doctrine 2", "Symfony 2"], $topics); + self::assertSame(2, $iteratedCount); - $this->_em->flush(); + $this->em->flush(); } /** @@ -320,7 +324,7 @@ public function testIterateResultClearEveryCycle() */ public function testIterateResult_FetchJoinedCollection_ThrowsException() { - $query = $this->_em->createQuery("SELECT u, a FROM ' . CmsUser::class . ' u JOIN u.articles a"); + $query = $this->em->createQuery("SELECT u, a FROM ' . CmsUser::class . ' u JOIN u.articles a"); $articles = $query->iterate(); } @@ -329,7 +333,7 @@ public function testIterateResult_FetchJoinedCollection_ThrowsException() */ public function testGetSingleResultThrowsExceptionOnNoResult() { - $this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a") + $this->em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a") ->getSingleResult(); } @@ -338,7 +342,7 @@ public function testGetSingleResultThrowsExceptionOnNoResult() */ public function testGetSingleScalarResultThrowsExceptionOnNoResult() { - $this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a") + $this->em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a") ->getSingleScalarResult(); } @@ -362,14 +366,14 @@ public function testGetSingleScalarResultThrowsExceptionOnNonUniqueResult() $article2->text = "This is an introduction to Symfony 2."; $user->addArticle($article2); - $this->_em->persist($user); - $this->_em->persist($article1); - $this->_em->persist($article2); + $this->em->persist($user); + $this->em->persist($article1); + $this->em->persist($article2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a") + $this->em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a") ->getSingleScalarResult(); } @@ -380,31 +384,31 @@ public function testModifiedLimitQuery() $user->name = 'Guilherme' . $i; $user->username = 'gblanco' . $i; $user->status = 'developer'; - $this->_em->persist($user); + $this->em->persist($user); } - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $data = $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u') + $data = $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u') ->setFirstResult(1) ->setMaxResults(2) ->getResult(); - $this->assertEquals(2, count($data)); - $this->assertEquals('gblanco1', $data[0]->username); - $this->assertEquals('gblanco2', $data[1]->username); + self::assertEquals(2, count($data)); + self::assertEquals('gblanco1', $data[0]->username); + self::assertEquals('gblanco2', $data[1]->username); - $data = $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u') + $data = $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u') ->setFirstResult(3) ->setMaxResults(2) ->getResult(); - $this->assertEquals(2, count($data)); - $this->assertEquals('gblanco3', $data[0]->username); - $this->assertEquals('gblanco4', $data[1]->username); + self::assertEquals(2, count($data)); + self::assertEquals('gblanco3', $data[0]->username); + self::assertEquals('gblanco4', $data[1]->username); - $data = $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u') + $data = $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u') ->setFirstResult(3) ->setMaxResults(2) ->getScalarResult(); @@ -412,17 +416,19 @@ public function testModifiedLimitQuery() public function testSupportsQueriesWithEntityNamespaces() { - $this->_em->getConfiguration()->addEntityNamespace('CMS', 'Doctrine\Tests\Models\CMS'); + $this->em->getConfiguration()->addEntityNamespace('CMS', 'Doctrine\Tests\Models\CMS'); try { - $query = $this->_em->createQuery('UPDATE CMS:CmsUser u SET u.name = ?1'); - $this->assertEquals('UPDATE cms_users SET name = ?', $query->getSQL()); + $query = $this->em->createQuery('UPDATE CMS:CmsUser u SET u.name = ?1'); + + self::assertEquals('UPDATE "cms_users" SET "name" = ?', $query->getSQL()); + $query->free(); } catch (\Exception $e) { $this->fail($e->getMessage()); } - $this->_em->getConfiguration()->setEntityNamespaces([]); + $this->em->getConfiguration()->setEntityNamespaces([]); } /** @@ -438,21 +444,21 @@ public function testEntityParameters() $author->username = "anon"; $author->status = "here"; $article->user = $author; - $this->_em->persist($author); - $this->_em->persist($article); - $this->_em->flush(); - $this->_em->clear(); - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $q = $this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a where a.topic = :topic and a.user = :user") - ->setParameter("user", $this->_em->getReference(CmsUser::class, $author->id)) + $this->em->persist($author); + $this->em->persist($article); + $this->em->flush(); + $this->em->clear(); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + $q = $this->em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a where a.topic = :topic and a.user = :user") + ->setParameter("user", $this->em->getReference(CmsUser::class, $author->id)) ->setParameter("topic", "dr. dolittle"); $result = $q->getResult(); - $this->assertEquals(1, count($result)); - $this->assertInstanceOf(CmsArticle::class, $result[0]); - $this->assertEquals("dr. dolittle", $result[0]->topic); - $this->assertInstanceOf(Proxy::class, $result[0]->user); - $this->assertFalse($result[0]->user->__isInitialized__); + self::assertEquals(1, count($result)); + self::assertInstanceOf(CmsArticle::class, $result[0]); + self::assertEquals("dr. dolittle", $result[0]->topic); + self::assertInstanceOf(Proxy::class, $result[0]->user); + self::assertFalse($result[0]->user->__isInitialized()); } /** @@ -462,26 +468,33 @@ public function testEnableFetchEagerMode() { for ($i = 0; $i < 10; $i++) { $article = new CmsArticle; + $article->topic = "dr. dolittle"; $article->text = "Once upon a time ..."; + $author = new CmsUser; + $author->name = "anonymous"; $author->username = "anon".$i; $author->status = "here"; $article->user = $author; - $this->_em->persist($author); - $this->_em->persist($article); + + $this->em->persist($author); + $this->em->persist($article); } - $this->_em->flush(); - $this->_em->clear(); - $articles = $this->_em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a') - ->setFetchMode(CmsArticle::class, 'user', ClassMetadata::FETCH_EAGER) - ->getResult(); + $this->em->flush(); + $this->em->clear(); + + $articles = $this->em + ->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a') + ->setFetchMode(CmsArticle::class, 'user', FetchMode::EAGER) + ->getResult(); + + self::assertEquals(10, count($articles)); - $this->assertEquals(10, count($articles)); foreach ($articles AS $article) { - $this->assertNotInstanceOf(Proxy::class, $article); + self::assertNotInstanceOf(Proxy::class, $article); } } @@ -494,19 +507,20 @@ public function testgetOneOrNullResult() $user->name = 'Guilherme'; $user->username = 'gblanco'; $user->status = 'developer'; - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); - - $query = $this->_em->createQuery("select u from " . CmsUser::class . " u where u.username = 'gblanco'"); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); + $query = $this->em->createQuery("select u from " . CmsUser::class . " u where u.username = 'gblanco'"); $fetchedUser = $query->getOneOrNullResult(); - $this->assertInstanceOf(CmsUser::class, $fetchedUser); - $this->assertEquals('gblanco', $fetchedUser->username); - $query = $this->_em->createQuery("select u.username from " . CmsUser::class . " u where u.username = 'gblanco'"); + self::assertInstanceOf(CmsUser::class, $fetchedUser); + self::assertEquals('gblanco', $fetchedUser->username); + + $query = $this->em->createQuery("select u.username from " . CmsUser::class . " u where u.username = 'gblanco'"); $fetchedUsername = $query->getOneOrNullResult(Query::HYDRATE_SINGLE_SCALAR); - $this->assertEquals('gblanco', $fetchedUsername); + + self::assertEquals('gblanco', $fetchedUsername); } /** @@ -518,16 +532,16 @@ public function testgetOneOrNullResultSeveralRows() $user->name = 'Guilherme'; $user->username = 'gblanco'; $user->status = 'developer'; - $this->_em->persist($user); + $this->em->persist($user); $user = new CmsUser; $user->name = 'Roman'; $user->username = 'romanb'; $user->status = 'developer'; - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u"); + $query = $this->em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u"); $this->expectException(NonUniqueResultException::class); @@ -539,11 +553,11 @@ public function testgetOneOrNullResultSeveralRows() */ public function testgetOneOrNullResultNoRows() { - $query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u"); - $this->assertNull($query->getOneOrNullResult()); + $query = $this->em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u"); + self::assertNull($query->getOneOrNullResult()); - $query = $this->_em->createQuery("select u.username from Doctrine\Tests\Models\CMS\CmsUser u where u.username = 'gblanco'"); - $this->assertNull($query->getOneOrNullResult(Query::HYDRATE_SCALAR)); + $query = $this->em->createQuery("select u.username from Doctrine\Tests\Models\CMS\CmsUser u where u.username = 'gblanco'"); + self::assertNull($query->getOneOrNullResult(Query::HYDRATE_SCALAR)); } /** @@ -555,24 +569,24 @@ public function testParameterOrder() $user1->name = 'Benjamin'; $user1->username = 'beberlei'; $user1->status = 'developer'; - $this->_em->persist($user1); + $this->em->persist($user1); $user2 = new CmsUser; $user2->name = 'Roman'; $user2->username = 'romanb'; $user2->status = 'developer'; - $this->_em->persist($user2); + $this->em->persist($user2); $user3 = new CmsUser; $user3->name = 'Jonathan'; $user3->username = 'jwage'; $user3->status = 'developer'; - $this->_em->persist($user3); + $this->em->persist($user3); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.status = :a AND u.id IN (:b)"); + $query = $this->em->createQuery("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.status = :a AND u.id IN (:b)"); $query->setParameters(new ArrayCollection( [ new Parameter('b', [$user1->id, $user2->id, $user3->id]), @@ -581,7 +595,7 @@ public function testParameterOrder() )); $result = $query->getResult(); - $this->assertEquals(3, count($result)); + self::assertEquals(3, count($result)); } public function testDqlWithAutoInferOfParameters() @@ -590,34 +604,34 @@ public function testDqlWithAutoInferOfParameters() $user->name = 'Benjamin'; $user->username = 'beberlei'; $user->status = 'developer'; - $this->_em->persist($user); + $this->em->persist($user); $user = new CmsUser; $user->name = 'Roman'; $user->username = 'romanb'; $user->status = 'developer'; - $this->_em->persist($user); + $this->em->persist($user); $user = new CmsUser; $user->name = 'Jonathan'; $user->username = 'jwage'; $user->status = 'developer'; - $this->_em->persist($user); + $this->em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username IN (?0)"); + $query = $this->em->createQuery("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username IN (?0)"); $query->setParameter(0, ['beberlei', 'jwage']); $users = $query->execute(); - $this->assertEquals(2, count($users)); + self::assertEquals(2, count($users)); } public function testQueryBuilderWithStringWhereClauseContainingOrAndConditionalPrimary() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') ->innerJoin('u.articles', 'a') @@ -626,7 +640,7 @@ public function testQueryBuilderWithStringWhereClauseContainingOrAndConditionalP $query = $qb->getQuery(); $users = $query->execute(); - $this->assertEquals(0, count($users)); + self::assertEquals(0, count($users)); } public function testQueryWithArrayOfEntitiesAsParameter() @@ -635,30 +649,30 @@ public function testQueryWithArrayOfEntitiesAsParameter() $userA->name = 'Benjamin'; $userA->username = 'beberlei'; $userA->status = 'developer'; - $this->_em->persist($userA); + $this->em->persist($userA); $userB = new CmsUser; $userB->name = 'Roman'; $userB->username = 'romanb'; $userB->status = 'developer'; - $this->_em->persist($userB); + $this->em->persist($userB); $userC = new CmsUser; $userC->name = 'Jonathan'; $userC->username = 'jwage'; $userC->status = 'developer'; - $this->_em->persist($userC); + $this->em->persist($userC); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u IN (?0) OR u.username = ?1"); + $query = $this->em->createQuery("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u IN (?0) OR u.username = ?1"); $query->setParameter(0, [$userA, $userC]); $query->setParameter(1, 'beberlei'); $users = $query->execute(); - $this->assertEquals(2, count($users)); + self::assertEquals(2, count($users)); } public function testQueryWithHiddenAsSelectExpression() @@ -667,28 +681,28 @@ public function testQueryWithHiddenAsSelectExpression() $userA->name = 'Benjamin'; $userA->username = 'beberlei'; $userA->status = 'developer'; - $this->_em->persist($userA); + $this->em->persist($userA); $userB = new CmsUser; $userB->name = 'Roman'; $userB->username = 'romanb'; $userB->status = 'developer'; - $this->_em->persist($userB); + $this->em->persist($userB); $userC = new CmsUser; $userC->name = 'Jonathan'; $userC->username = 'jwage'; $userC->status = 'developer'; - $this->_em->persist($userC); + $this->em->persist($userC); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery("SELECT u, (SELECT COUNT(u2.id) FROM Doctrine\Tests\Models\CMS\CmsUser u2) AS HIDDEN total FROM Doctrine\Tests\Models\CMS\CmsUser u"); + $query = $this->em->createQuery("SELECT u, (SELECT COUNT(u2.id) FROM Doctrine\Tests\Models\CMS\CmsUser u2) AS HIDDEN total FROM Doctrine\Tests\Models\CMS\CmsUser u"); $users = $query->execute(); - $this->assertEquals(3, count($users)); - $this->assertInstanceOf(CmsUser::class, $users[0]); + self::assertEquals(3, count($users)); + self::assertInstanceOf(CmsUser::class, $users[0]); } /** @@ -700,15 +714,15 @@ public function testSetParameterBindingSingleIdentifierObject() $userC->name = 'Jonathan'; $userC->username = 'jwage'; $userC->status = 'developer'; - $this->_em->persist($userC); + $this->em->persist($userC); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $q = $this->_em->createQuery("SELECT DISTINCT u from Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1"); + $q = $this->em->createQuery("SELECT DISTINCT u from Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1"); $q->setParameter(1, $userC); - $this->assertEquals($userC, $q->getParameter(1)->getValue()); + self::assertEquals($userC, $q->getParameter(1)->getValue()); // Parameter is not converted before, but it should be converted during execution. Test should not fail here $q->getResult(); @@ -723,22 +737,22 @@ public function testSetCollectionParameterBindingSingleIdentifierObject() $u1->name = 'Name1'; $u1->username = 'username1'; $u1->status = 'developer'; - $this->_em->persist($u1); + $this->em->persist($u1); $u2 = new CmsUser; $u2->name = 'Name2'; $u2->username = 'username2'; $u2->status = 'tester'; - $this->_em->persist($u2); + $this->em->persist($u2); $u3 = new CmsUser; $u3->name = 'Name3'; $u3->username = 'username3'; $u3->status = 'tester'; - $this->_em->persist($u3); + $this->em->persist($u3); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $userCollection = new ArrayCollection(); @@ -746,22 +760,22 @@ public function testSetCollectionParameterBindingSingleIdentifierObject() $userCollection->add($u2); $userCollection->add($u3->getId()); - $q = $this->_em->createQuery("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u IN (:users) ORDER BY u.id"); + $q = $this->em->createQuery("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u IN (:users) ORDER BY u.id"); $q->setParameter('users', $userCollection); $users = $q->execute(); - $this->assertEquals(3, count($users)); - $this->assertInstanceOf(CmsUser::class, $users[0]); - $this->assertInstanceOf(CmsUser::class, $users[1]); - $this->assertInstanceOf(CmsUser::class, $users[2]); + self::assertEquals(3, count($users)); + self::assertInstanceOf(CmsUser::class, $users[0]); + self::assertInstanceOf(CmsUser::class, $users[1]); + self::assertInstanceOf(CmsUser::class, $users[2]); $resultUser1 = $users[0]; $resultUser2 = $users[1]; $resultUser3 = $users[2]; - $this->assertEquals($u1->username, $resultUser1->username); - $this->assertEquals($u2->username, $resultUser2->username); - $this->assertEquals($u3->username, $resultUser3->username); + self::assertEquals($u1->username, $resultUser1->username); + self::assertEquals($u2->username, $resultUser2->username); + self::assertEquals($u3->username, $resultUser3->username); } /** @@ -780,23 +794,23 @@ public function testUnexpectedResultException() $u2->status = 'tester'; try { - $this->_em->createQuery($dql)->getSingleResult(); + $this->em->createQuery($dql)->getSingleResult(); $this->fail('Expected exception "\Doctrine\ORM\NoResultException".'); } catch (UnexpectedResultException $exc) { - $this->assertInstanceOf('\Doctrine\ORM\NoResultException', $exc); + self::assertInstanceOf('\Doctrine\ORM\NoResultException', $exc); } - $this->_em->persist($u1); - $this->_em->persist($u2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($u1); + $this->em->persist($u2); + $this->em->flush(); + $this->em->clear(); try { - $this->_em->createQuery($dql)->getSingleResult(); + $this->em->createQuery($dql)->getSingleResult(); $this->fail('Expected exception "\Doctrine\ORM\NonUniqueResultException".'); } catch (UnexpectedResultException $exc) { - $this->assertInstanceOf('\Doctrine\ORM\NonUniqueResultException', $exc); + self::assertInstanceOf('\Doctrine\ORM\NonUniqueResultException', $exc); } } @@ -816,21 +830,21 @@ public function testMultipleJoinComponentsUsingInnerJoin() $userB->username = 'asm89'; $userB->status = 'developer'; - $this->_em->persist($userA); - $this->_em->persist($userB); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($userA); + $this->em->persist($userB); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery(" + $query = $this->em->createQuery(" SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN Doctrine\Tests\Models\CMS\CmsPhonenumber p WITH u = p.user "); $users = $query->execute(); - $this->assertEquals(2, count($users)); - $this->assertInstanceOf(CmsUser::class, $users[0]); - $this->assertInstanceOf(CmsPhonenumber::class, $users[1]); + self::assertEquals(2, count($users)); + self::assertInstanceOf(CmsUser::class, $users[0]); + self::assertInstanceOf(CmsPhonenumber::class, $users[1]); } public function testMultipleJoinComponentsUsingLeftJoin() @@ -849,22 +863,22 @@ public function testMultipleJoinComponentsUsingLeftJoin() $userB->username = 'asm89'; $userB->status = 'developer'; - $this->_em->persist($userA); - $this->_em->persist($userB); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($userA); + $this->em->persist($userB); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery(" + $query = $this->em->createQuery(" SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN Doctrine\Tests\Models\CMS\CmsPhonenumber p WITH u = p.user "); $users = $query->execute(); - $this->assertEquals(4, count($users)); - $this->assertInstanceOf(CmsUser::class, $users[0]); - $this->assertInstanceOf(CmsPhonenumber::class, $users[1]); - $this->assertInstanceOf(CmsUser::class, $users[2]); - $this->assertNull($users[3]); + self::assertEquals(4, count($users)); + self::assertInstanceOf(CmsUser::class, $users[0]); + self::assertInstanceOf(CmsPhonenumber::class, $users[1]); + self::assertInstanceOf(CmsUser::class, $users[2]); + self::assertNull($users[3]); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ReadOnlyTest.php b/tests/Doctrine/Tests/ORM/Functional/ReadOnlyTest.php index a664a4df252..80440290019 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ReadOnlyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ReadOnlyTest.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(ReadOnlyEntity::class), + $this->em->getClassMetadata(ReadOnlyEntity::class), ] ); } catch(\Exception $e) { @@ -28,18 +31,18 @@ protected function setUp() public function testReadOnlyEntityNeverChangeTracked() { $readOnly = new ReadOnlyEntity("Test1", 1234); - $this->_em->persist($readOnly); - $this->_em->flush(); + $this->em->persist($readOnly); + $this->em->flush(); $readOnly->name = "Test2"; $readOnly->numericValue = 4321; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $dbReadOnly = $this->_em->find(ReadOnlyEntity::class, $readOnly->id); - $this->assertEquals("Test1", $dbReadOnly->name); - $this->assertEquals(1234, $dbReadOnly->numericValue); + $dbReadOnly = $this->em->find(ReadOnlyEntity::class, $readOnly->id); + self::assertEquals("Test1", $dbReadOnly->name); + self::assertEquals(1234, $dbReadOnly->numericValue); } /** @@ -48,13 +51,13 @@ public function testReadOnlyEntityNeverChangeTracked() public function testClearReadOnly() { $readOnly = new ReadOnlyEntity("Test1", 1234); - $this->_em->persist($readOnly); - $this->_em->flush(); - $this->_em->getUnitOfWork()->markReadOnly($readOnly); + $this->em->persist($readOnly); + $this->em->flush(); + $this->em->getUnitOfWork()->markReadOnly($readOnly); - $this->_em->clear(); + $this->em->clear(); - $this->assertFalse($this->_em->getUnitOfWork()->isReadOnly($readOnly)); + self::assertFalse($this->em->getUnitOfWork()->isReadOnly($readOnly)); } /** @@ -63,29 +66,29 @@ public function testClearReadOnly() public function testClearEntitiesReadOnly() { $readOnly = new ReadOnlyEntity("Test1", 1234); - $this->_em->persist($readOnly); - $this->_em->flush(); - $this->_em->getUnitOfWork()->markReadOnly($readOnly); + $this->em->persist($readOnly); + $this->em->flush(); + $this->em->getUnitOfWork()->markReadOnly($readOnly); - $this->_em->clear(get_class($readOnly)); + $this->em->clear(get_class($readOnly)); - $this->assertFalse($this->_em->getUnitOfWork()->isReadOnly($readOnly)); + self::assertFalse($this->em->getUnitOfWork()->isReadOnly($readOnly)); } } /** - * @Entity(readOnly=true) + * @ORM\Entity(readOnly=true) */ class ReadOnlyEntity { /** - * @Id @GeneratedValue @Column(type="integer") + * @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") * @var int */ public $id; - /** @column(type="string") */ + /** @ORM\Column(type="string") */ public $name; - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ public $numericValue; public function __construct($name, $number) diff --git a/tests/Doctrine/Tests/ORM/Functional/ReferenceProxyTest.php b/tests/Doctrine/Tests/ORM/Functional/ReferenceProxyTest.php index 5e1cb2fb223..c7e68f6fdec 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ReferenceProxyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ReferenceProxyTest.php @@ -1,10 +1,16 @@ * @author Benjamin Eberlei */ class ReferenceProxyTest extends OrmFunctionalTestCase { + /** + * @var ProxyResolver + */ + private $resolver; + + /** + * @var ProxyFactory + */ + private $factory; + protected function setUp() { $this->useModelSet('ecommerce'); $this->useModelSet('company'); + parent::setUp(); - $this->_factory = new ProxyFactory( - $this->_em, - __DIR__ . '/../../Proxies', - 'Doctrine\Tests\Proxies', - true); + + $namespace = 'Doctrine\Tests\Proxies'; + $directory = __DIR__ . '/../../Proxies'; + + $this->resolver = new DefaultProxyResolver($namespace, $directory); + + $proxyConfiguration = new ProxyConfiguration(); + + $proxyConfiguration->setDirectory($directory); + $proxyConfiguration->setNamespace($namespace); + $proxyConfiguration->setAutoGenerate(ProxyFactory::AUTOGENERATE_ALWAYS); + $proxyConfiguration->setResolver($this->resolver); + + $this->factory = new StaticProxyFactory($this->em, $proxyConfiguration); } public function createProduct() { $product = new ECommerceProduct(); $product->setName('Doctrine Cookbook'); - $this->_em->persist($product); + $this->em->persist($product); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); return $product->getId(); } @@ -45,10 +72,10 @@ public function createAuction() { $event = new CompanyAuction(); $event->setData('Doctrine Cookbook'); - $this->_em->persist($event); + $this->em->persist($event); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); return $event->getId(); } @@ -57,8 +84,9 @@ public function testLazyLoadsFieldValuesFromDatabase() { $id = $this->createProduct(); - $productProxy = $this->_em->getReference(ECommerceProduct::class, ['id' => $id]); - $this->assertEquals('Doctrine Cookbook', $productProxy->getName()); + $productProxy = $this->em->getReference(ECommerceProduct::class, ['id' => $id]); + + self::assertEquals('Doctrine Cookbook', $productProxy->getName()); } /** @@ -68,10 +96,10 @@ public function testAccessMetatadaForProxy() { $id = $this->createProduct(); - $entity = $this->_em->getReference(ECommerceProduct::class , $id); - $class = $this->_em->getClassMetadata(get_class($entity)); + $entity = $this->em->getReference(ECommerceProduct::class , $id); + $class = $this->em->getClassMetadata(get_class($entity)); - $this->assertEquals(ECommerceProduct::class, $class->name); + self::assertEquals(ECommerceProduct::class, $class->getClassName()); } /** @@ -81,11 +109,11 @@ public function testReferenceFind() { $id = $this->createProduct(); - $entity = $this->_em->getReference(ECommerceProduct::class , $id); - $entity2 = $this->_em->find(ECommerceProduct::class , $id); + $entity = $this->em->getReference(ECommerceProduct::class , $id); + $entity2 = $this->em->find(ECommerceProduct::class , $id); - $this->assertSame($entity, $entity2); - $this->assertEquals('Doctrine Cookbook', $entity2->getName()); + self::assertSame($entity, $entity2); + self::assertEquals('Doctrine Cookbook', $entity2->getName()); } /** @@ -96,21 +124,21 @@ public function testCloneProxy() $id = $this->createProduct(); /* @var $entity ECommerceProduct */ - $entity = $this->_em->getReference(ECommerceProduct::class , $id); + $entity = $this->em->getReference(ECommerceProduct::class , $id); /* @var $clone ECommerceProduct */ $clone = clone $entity; - $this->assertEquals($id, $entity->getId()); - $this->assertEquals('Doctrine Cookbook', $entity->getName()); + self::assertEquals($id, $entity->getId()); + self::assertEquals('Doctrine Cookbook', $entity->getName()); - $this->assertFalse($this->_em->contains($clone), "Cloning a reference proxy should return an unmanaged/detached entity."); - $this->assertEquals($id, $clone->getId(), "Cloning a reference proxy should return same id."); - $this->assertEquals('Doctrine Cookbook', $clone->getName(), "Cloning a reference proxy should return same product name."); + self::assertFalse($this->em->contains($clone), "Cloning a reference proxy should return an unmanaged/detached entity."); + self::assertEquals($id, $clone->getId(), "Cloning a reference proxy should return same id."); + self::assertEquals('Doctrine Cookbook', $clone->getName(), "Cloning a reference proxy should return same product name."); // domain logic, Product::__clone sets isCloned public property - $this->assertTrue($clone->isCloned); - $this->assertFalse($entity->isCloned); + self::assertTrue($clone->isCloned); + self::assertFalse($entity->isCloned); } /** @@ -121,11 +149,13 @@ public function testInitializeProxy() $id = $this->createProduct(); /* @var $entity ECommerceProduct */ - $entity = $this->_em->getReference(ECommerceProduct::class , $id); + $entity = $this->em->getReference(ECommerceProduct::class , $id); + + self::assertFalse($entity->__isInitialized(), "Pre-Condition: Object is unitialized proxy."); - $this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy."); - $this->_em->getUnitOfWork()->initializeObject($entity); - $this->assertTrue($entity->__isInitialized__, "Should be initialized after called UnitOfWork::initializeObject()"); + $this->em->getUnitOfWork()->initializeObject($entity); + + self::assertTrue($entity->__isInitialized(), "Should be initialized after called UnitOfWork::initializeObject()"); } /** @@ -136,14 +166,16 @@ public function testInitializeChangeAndFlushProxy() $id = $this->createProduct(); /* @var $entity ECommerceProduct */ - $entity = $this->_em->getReference(ECommerceProduct::class , $id); + $entity = $this->em->getReference(ECommerceProduct::class , $id); + $entity->setName('Doctrine 2 Cookbook'); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); + + $entity = $this->em->getReference(ECommerceProduct::class , $id); - $entity = $this->_em->getReference(ECommerceProduct::class , $id); - $this->assertEquals('Doctrine 2 Cookbook', $entity->getName()); + self::assertEquals('Doctrine 2 Cookbook', $entity->getName()); } /** @@ -154,13 +186,13 @@ public function testWakeupCalledOnProxy() $id = $this->createProduct(); /* @var $entity ECommerceProduct */ - $entity = $this->_em->getReference(ECommerceProduct::class , $id); + $entity = $this->em->getReference(ECommerceProduct::class , $id); - $this->assertFalse($entity->wakeUp); + self::assertFalse($entity->wakeUp); $entity->setName('Doctrine 2 Cookbook'); - $this->assertTrue($entity->wakeUp, "Loading the proxy should call __wakeup()."); + self::assertTrue($entity->wakeUp, "Loading the proxy should call __wakeup()."); } public function testDoNotInitializeProxyOnGettingTheIdentifier() @@ -168,11 +200,11 @@ public function testDoNotInitializeProxyOnGettingTheIdentifier() $id = $this->createProduct(); /* @var $entity ECommerceProduct */ - $entity = $this->_em->getReference(ECommerceProduct::class , $id); + $entity = $this->em->getReference(ECommerceProduct::class , $id); - $this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy."); - $this->assertEquals($id, $entity->getId()); - $this->assertFalse($entity->__isInitialized__, "Getting the identifier doesn't initialize the proxy."); + self::assertFalse($entity->__isInitialized(), "Pre-Condition: Object is unitialized proxy."); + self::assertEquals($id, $entity->getId()); + self::assertFalse($entity->__isInitialized(), "Getting the identifier doesn't initialize the proxy."); } /** @@ -183,11 +215,11 @@ public function testDoNotInitializeProxyOnGettingTheIdentifier_DDC_1625() $id = $this->createAuction(); /* @var $entity CompanyAuction */ - $entity = $this->_em->getReference(CompanyAuction::class , $id); + $entity = $this->em->getReference(CompanyAuction::class , $id); - $this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy."); - $this->assertEquals($id, $entity->getId()); - $this->assertFalse($entity->__isInitialized__, "Getting the identifier doesn't initialize the proxy when extending."); + self::assertFalse($entity->__isInitialized(), "Pre-Condition: Object is unitialized proxy."); + self::assertEquals($id, $entity->getId()); + self::assertFalse($entity->__isInitialized(), "Getting the identifier doesn't initialize the proxy when extending."); } public function testDoNotInitializeProxyOnGettingTheIdentifierAndReturnTheRightType() @@ -198,19 +230,21 @@ public function testDoNotInitializeProxyOnGettingTheIdentifierAndReturnTheRightT $shipping = new ECommerceShipping(); $shipping->setDays(1); $product->setShipping($shipping); - $this->_em->persist($product); - $this->_em->flush(); - $this->_em->clear(); + + $this->em->persist($product); + $this->em->flush(); + $this->em->clear(); $id = $shipping->getId(); - $product = $this->_em->getRepository(ECommerceProduct::class)->find($product->getId()); + $product = $this->em->getRepository(ECommerceProduct::class)->find($product->getId()); $entity = $product->getShipping(); - $this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy."); - $this->assertEquals($id, $entity->getId()); - $this->assertSame($id, $entity->getId(), "Check that the id's are the same value, and type."); - $this->assertFalse($entity->__isInitialized__, "Getting the identifier doesn't initialize the proxy."); + + self::assertFalse($entity->__isInitialized(), "Pre-Condition: Object is unitialized proxy."); + self::assertEquals($id, $entity->getId()); + self::assertSame($id, $entity->getId(), "Check that the id's are the same value, and type."); + self::assertFalse($entity->__isInitialized(), "Getting the identifier doesn't initialize the proxy."); } public function testInitializeProxyOnGettingSomethingOtherThanTheIdentifier() @@ -218,11 +252,11 @@ public function testInitializeProxyOnGettingSomethingOtherThanTheIdentifier() $id = $this->createProduct(); /* @var $entity ECommerceProduct */ - $entity = $this->_em->getReference(ECommerceProduct::class , $id); + $entity = $this->em->getReference(ECommerceProduct::class , $id); - $this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy."); - $this->assertEquals('Doctrine Cookbook', $entity->getName()); - $this->assertTrue($entity->__isInitialized__, "Getting something other than the identifier initializes the proxy."); + self::assertFalse($entity->__isInitialized(), "Pre-Condition: Object is unitialized proxy."); + self::assertEquals('Doctrine Cookbook', $entity->getName()); + self::assertTrue($entity->__isInitialized(), "Getting something other than the identifier initializes the proxy."); } /** @@ -233,19 +267,20 @@ public function testCommonPersistenceProxy() $id = $this->createProduct(); /* @var $entity ECommerceProduct */ - $entity = $this->_em->getReference(ECommerceProduct::class , $id); + $entity = $this->em->getReference(ECommerceProduct::class , $id); + $className = ClassUtils::getClass($entity); - $this->assertInstanceOf(Proxy::class, $entity); - $this->assertFalse($entity->__isInitialized()); - $this->assertEquals(ECommerceProduct::class, $className); + self::assertInstanceOf(Proxy::class, $entity); + self::assertFalse($entity->__isInitialized()); + self::assertEquals(ECommerceProduct::class, $className); - $restName = str_replace($this->_em->getConfiguration()->getProxyNamespace(), "", get_class($entity)); - $restName = substr(get_class($entity), strlen($this->_em->getConfiguration()->getProxyNamespace()) +1); - $proxyFileName = $this->_em->getConfiguration()->getProxyDir() . DIRECTORY_SEPARATOR . str_replace("\\", "", $restName) . ".php"; - $this->assertTrue(file_exists($proxyFileName), "Proxy file name cannot be found generically."); + $proxyFileName = $this->resolver->resolveProxyClassPath(ECommerceProduct::class ); + + self::assertTrue(file_exists($proxyFileName), "Proxy file name cannot be found generically."); $entity->__load(); - $this->assertTrue($entity->__isInitialized()); + + self::assertTrue($entity->__isInitialized()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ResultCacheTest.php b/tests/Doctrine/Tests/ORM/Functional/ResultCacheTest.php index bfadf2c2543..7ef9c3479b0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ResultCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ResultCacheTest.php @@ -1,12 +1,15 @@ cacheDataReflection = new \ReflectionProperty(ArrayCache::class, "data"); $this->cacheDataReflection->setAccessible(true); + $this->useModelSet('cms'); + parent::setUp(); } @@ -45,63 +50,63 @@ public function testResultCache() $user->username = 'romanb'; $user->status = 'dev'; - $this->_em->persist($user); - $this->_em->flush(); - - $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); + $this->em->persist($user); + $this->em->flush(); + $query = $this->em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); $cache = new ArrayCache(); $query->setResultCacheDriver($cache)->setResultCacheId('my_cache_id'); - $this->assertFalse($cache->contains('my_cache_id')); + self::assertFalse($cache->contains('my_cache_id')); $users = $query->getResult(); - $this->assertTrue($cache->contains('my_cache_id')); - $this->assertEquals(1, count($users)); - $this->assertEquals('Roman', $users[0]->name); + self::assertTrue($cache->contains('my_cache_id')); + self::assertEquals(1, count($users)); + self::assertEquals('Roman', $users[0]->name); - $this->_em->clear(); + $this->em->clear(); - $query2 = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); + $query2 = $this->em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); $query2->setResultCacheDriver($cache)->setResultCacheId('my_cache_id'); $users = $query2->getResult(); - $this->assertTrue($cache->contains('my_cache_id')); - $this->assertEquals(1, count($users)); - $this->assertEquals('Roman', $users[0]->name); + self::assertTrue($cache->contains('my_cache_id')); + self::assertEquals(1, count($users)); + self::assertEquals('Roman', $users[0]->name); } public function testSetResultCacheId() { $cache = new ArrayCache; - $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); + $query = $this->em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); $query->setResultCacheDriver($cache); $query->setResultCacheId('testing_result_cache_id'); - $this->assertFalse($cache->contains('testing_result_cache_id')); + self::assertFalse($cache->contains('testing_result_cache_id')); $users = $query->getResult(); - $this->assertTrue($cache->contains('testing_result_cache_id')); + self::assertTrue($cache->contains('testing_result_cache_id')); } public function testUseResultCache() { $cache = new ArrayCache(); - $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); + $query = $this->em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); $query->useResultCache(true); $query->setResultCacheDriver($cache); $query->setResultCacheId('testing_result_cache_id'); + $users = $query->getResult(); - $this->assertTrue($cache->contains('testing_result_cache_id')); + self::assertTrue($cache->contains('testing_result_cache_id')); - $this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache()); + $this->em->getConfiguration()->setResultCacheImpl(new ArrayCache()); } /** @@ -110,8 +115,8 @@ public function testUseResultCache() public function testUseResultCacheParams() { $cache = new ArrayCache(); - $sqlCount = count($this->_sqlLoggerStack->queries); - $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux WHERE ux.id = ?1'); + $sqlCount = count($this->sqlLoggerStack->queries); + $query = $this->em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux WHERE ux.id = ?1'); $query->setParameter(1, 1); $query->setResultCacheDriver($cache); @@ -121,7 +126,7 @@ public function testUseResultCacheParams() $query->setParameter(1, 2); $query->getResult(); - $this->assertEquals($sqlCount + 2, count($this->_sqlLoggerStack->queries), "Two non-cached queries."); + self::assertEquals($sqlCount + 2, count($this->sqlLoggerStack->queries), "Two non-cached queries."); $query->setParameter(1, 1); $query->useResultCache(true); @@ -130,26 +135,31 @@ public function testUseResultCacheParams() $query->setParameter(1, 2); $query->getResult(); - $this->assertEquals($sqlCount + 2, count($this->_sqlLoggerStack->queries), "The next two sql should have been cached, but were not."); + self::assertEquals($sqlCount + 2, count($this->sqlLoggerStack->queries), "The next two sql should have been cached, but were not."); } + /** + * @return \Doctrine\ORM\NativeQuery + * + * @throws \Doctrine\ORM\ORMException + */ public function testNativeQueryResultCaching() { $cache = new ArrayCache(); $rsm = new ResultSetMapping(); - $rsm->addScalarResult('id', 'u', 'integer'); + $rsm->addScalarResult('id', 'u', DBALType::getType('integer')); - $query = $this->_em->createNativeQuery('select u.id FROM cms_users u WHERE u.id = ?', $rsm); + $query = $this->em->createNativeQuery('select u.id FROM cms_users u WHERE u.id = ?', $rsm); $query->setParameter(1, 10); $query->setResultCacheDriver($cache)->useResultCache(true); - $this->assertEquals(0, $this->getCacheSize($cache)); + self::assertEquals(0, $this->getCacheSize($cache)); $query->getResult(); - $this->assertEquals(1, $this->getCacheSize($cache)); + self::assertEquals(1, $this->getCacheSize($cache)); return $query; } @@ -160,13 +170,13 @@ public function testNativeQueryResultCaching() */ public function testResultCacheNotDependsOnQueryHints($query) { - $cache = $query->getResultCacheDriver(); + $cache = $query->getResultCacheDriver(); $cacheCount = $this->getCacheSize($cache); $query->setHint('foo', 'bar'); $query->getResult(); - $this->assertEquals($cacheCount, $this->getCacheSize($cache)); + self::assertEquals($cacheCount, $this->getCacheSize($cache)); } /** @@ -181,7 +191,7 @@ public function testResultCacheDependsOnParameters($query) $query->setParameter(1, 50); $query->getResult(); - $this->assertEquals($cacheCount + 1, $this->getCacheSize($cache)); + self::assertEquals($cacheCount + 1, $this->getCacheSize($cache)); } /** @@ -193,10 +203,10 @@ public function testResultCacheNotDependsOnHydrationMode($query) $cache = $query->getResultCacheDriver(); $cacheCount = $this->getCacheSize($cache); - $this->assertNotEquals(Query::HYDRATE_ARRAY, $query->getHydrationMode()); + self::assertNotEquals(Query::HYDRATE_ARRAY, $query->getHydrationMode()); $query->getArrayResult(); - $this->assertEquals($cacheCount, $this->getCacheSize($cache)); + self::assertEquals($cacheCount, $this->getCacheSize($cache)); } /** @@ -219,12 +229,12 @@ public function testResultCacheWithObjectParameter() $article->topic = "baz"; $article->user = $user1; - $this->_em->persist($article); - $this->_em->persist($user1); - $this->_em->persist($user2); - $this->_em->flush(); + $this->em->persist($article); + $this->em->persist($user1); + $this->em->persist($user2); + $this->em->flush(); - $query = $this->_em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = ?1'); + $query = $this->em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = ?1'); $query->setParameter(1, $user1); $cache = new ArrayCache(); @@ -233,28 +243,28 @@ public function testResultCacheWithObjectParameter() $articles = $query->getResult(); - $this->assertEquals(1, count($articles)); - $this->assertEquals('baz', $articles[0]->topic); + self::assertEquals(1, count($articles)); + self::assertEquals('baz', $articles[0]->topic); - $this->_em->clear(); + $this->em->clear(); - $query2 = $this->_em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = ?1'); + $query2 = $this->em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = ?1'); $query2->setParameter(1, $user1); $query2->setResultCacheDriver($cache)->useResultCache(true); $articles = $query2->getResult(); - $this->assertEquals(1, count($articles)); - $this->assertEquals('baz', $articles[0]->topic); + self::assertEquals(1, count($articles)); + self::assertEquals('baz', $articles[0]->topic); - $query3 = $this->_em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = ?1'); + $query3 = $this->em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = ?1'); $query3->setParameter(1, $user2); $query3->setResultCacheDriver($cache)->useResultCache(true); $articles = $query3->getResult(); - $this->assertEquals(0, count($articles)); + self::assertEquals(0, count($articles)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SQLFilterTest.php b/tests/Doctrine/Tests/ORM/Functional/SQLFilterTest.php index c35036b6e3c..074db749a4b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SQLFilterTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SQLFilterTest.php @@ -1,16 +1,21 @@ useModelSet('cms'); $this->useModelSet('company'); + parent::setUp(); } @@ -50,9 +56,9 @@ public function tearDown() { parent::tearDown(); - $class = $this->_em->getClassMetadata(CmsUser::class); - $class->associationMappings['groups']['fetch'] = ClassMetadataInfo::FETCH_LAZY; - $class->associationMappings['articles']['fetch'] = ClassMetadataInfo::FETCH_LAZY; + $class = $this->em->getClassMetadata(CmsUser::class); + $class->getProperty('groups')->setFetchMode(FetchMode::LAZY); + $class->getProperty('articles')->setFetchMode(FetchMode::LAZY); } public function testConfigureFilter() @@ -61,22 +67,22 @@ public function testConfigureFilter() $config->addFilter("locale", "\Doctrine\Tests\ORM\Functional\MyLocaleFilter"); - $this->assertEquals("\Doctrine\Tests\ORM\Functional\MyLocaleFilter", $config->getFilterClassName("locale")); - $this->assertNull($config->getFilterClassName("foo")); + self::assertEquals("\Doctrine\Tests\ORM\Functional\MyLocaleFilter", $config->getFilterClassName("locale")); + self::assertNull($config->getFilterClassName("foo")); } public function testEntityManagerEnableFilter() { - $em = $this->_getEntityManager(); + $em = $this->getEntityManager(); $this->configureFilters($em); // Enable an existing filter $filter = $em->getFilters()->enable("locale"); - $this->assertTrue($filter instanceof MyLocaleFilter); + self::assertTrue($filter instanceof MyLocaleFilter); // Enable the filter again $filter2 = $em->getFilters()->enable("locale"); - $this->assertEquals($filter, $filter2); + self::assertEquals($filter, $filter2); // Enable a non-existing filter $exceptionThrown = false; @@ -85,36 +91,37 @@ public function testEntityManagerEnableFilter() } catch (\InvalidArgumentException $e) { $exceptionThrown = true; } - $this->assertTrue($exceptionThrown); + self::assertTrue($exceptionThrown); } public function testEntityManagerEnabledFilters() { - $em = $this->_getEntityManager(); + $em = $this->getEntityManager(); // No enabled filters - $this->assertEquals([], $em->getFilters()->getEnabledFilters()); + self::assertEquals([], $em->getFilters()->getEnabledFilters()); $this->configureFilters($em); - $filter = $em->getFilters()->enable("locale"); - $filter = $em->getFilters()->enable("soft_delete"); + + $em->getFilters()->enable("locale"); + $em->getFilters()->enable("soft_delete"); // Two enabled filters - $this->assertEquals(2, count($em->getFilters()->getEnabledFilters())); + self::assertEquals(2, count($em->getFilters()->getEnabledFilters())); } public function testEntityManagerDisableFilter() { - $em = $this->_getEntityManager(); + $em = $this->getEntityManager(); $this->configureFilters($em); // Enable the filter $filter = $em->getFilters()->enable("locale"); // Disable it - $this->assertEquals($filter, $em->getFilters()->disable("locale")); - $this->assertEquals(0, count($em->getFilters()->getEnabledFilters())); + self::assertEquals($filter, $em->getFilters()->disable("locale")); + self::assertEquals(0, count($em->getFilters()->getEnabledFilters())); // Disable a non-existing filter $exceptionThrown = false; @@ -123,7 +130,7 @@ public function testEntityManagerDisableFilter() } catch (\InvalidArgumentException $e) { $exceptionThrown = true; } - $this->assertTrue($exceptionThrown); + self::assertTrue($exceptionThrown); // Disable a non-enabled filter $exceptionThrown = false; @@ -132,19 +139,19 @@ public function testEntityManagerDisableFilter() } catch (\InvalidArgumentException $e) { $exceptionThrown = true; } - $this->assertTrue($exceptionThrown); + self::assertTrue($exceptionThrown); } public function testEntityManagerGetFilter() { - $em = $this->_getEntityManager(); + $em = $this->getEntityManager(); $this->configureFilters($em); // Enable the filter $filter = $em->getFilters()->enable("locale"); // Get the filter - $this->assertEquals($filter, $em->getFilters()->getFilter("locale")); + self::assertEquals($filter, $em->getFilters()->getFilter("locale")); // Get a non-enabled filter $exceptionThrown = false; @@ -153,7 +160,7 @@ public function testEntityManagerGetFilter() } catch (\InvalidArgumentException $e) { $exceptionThrown = true; } - $this->assertTrue($exceptionThrown); + self::assertTrue($exceptionThrown); } /** @@ -161,19 +168,19 @@ public function testEntityManagerGetFilter() */ public function testEntityManagerIsFilterEnabled() { - $em = $this->_getEntityManager(); + $em = $this->getEntityManager(); $this->configureFilters($em); // Check for an enabled filter $em->getFilters()->enable("locale"); - $this->assertTrue($em->getFilters()->isEnabled("locale")); + self::assertTrue($em->getFilters()->isEnabled("locale")); // Check for a disabled filter $em->getFilters()->disable("locale"); - $this->assertFalse($em->getFilters()->isEnabled("locale")); + self::assertFalse($em->getFilters()->isEnabled("locale")); // Check a non-existing filter - $this->assertFalse($em->getFilters()->isEnabled("foo_filter")); + self::assertFalse($em->getFilters()->isEnabled("foo_filter")); } protected function configureFilters($em) @@ -197,7 +204,7 @@ protected function getMockConnection() protected function getMockEntityManager() { // Setup connection mock - $em = $this->getMockBuilder(EntityManager::class) + $em = $this->getMockBuilder(EntityManagerInterface::class) ->disableOriginalConstructor() ->getMock(); @@ -240,7 +247,7 @@ public function testSQLFilterGetSetParameter() $filter->setParameter('locale', 'en', DBALType::STRING); - $this->assertEquals("'en'", $filter->getParameter('locale')); + self::assertEquals("'en'", $filter->getParameter('locale')); } /** @@ -262,7 +269,7 @@ public function testSQLFilterGetConnection() $reflMethod = new \ReflectionMethod(SQLFilter::class, 'getConnection'); $reflMethod->setAccessible(true); - $this->assertSame($conn, $reflMethod->invoke($filter)); + self::assertSame($conn, $reflMethod->invoke($filter)); } public function testSQLFilterSetParameterInfersType() @@ -288,25 +295,27 @@ public function testSQLFilterSetParameterInfersType() $filter->setParameter('locale', 'en'); - $this->assertEquals("'en'", $filter->getParameter('locale')); + self::assertEquals("'en'", $filter->getParameter('locale')); } public function testSQLFilterAddConstraint() { - // Set up metadata mock - $targetEntity = $this->getMockBuilder(ClassMetadata::class) - ->disableOriginalConstructor() - ->getMock(); + $metadataBuildingContext = new ClassMetadataBuildingContext( + $this->createMock(ClassMetadataFactory::class), + $this->createMock(ReflectionService::class) + ); $filter = new MySoftDeleteFilter($this->getMockEntityManager()); // Test for an entity that gets extra filter data - $targetEntity->name = 'MyEntity\SoftDeleteNewsItem'; - $this->assertEquals('t1_.deleted = 0', $filter->addFilterConstraint($targetEntity, 't1_')); + $metadata = new ClassMetadata('MyEntity\SoftDeleteNewsItem', $metadataBuildingContext); + + self::assertEquals('t1_.deleted = 0', $filter->addFilterConstraint($metadata, 't1_')); // Test for an entity that doesn't get extra filter data - $targetEntity->name = 'MyEntity\NoSoftDeleteNewsItem'; - $this->assertEquals('', $filter->addFilterConstraint($targetEntity, 't1_')); + $metadata = new ClassMetadata('MyEntity\NoSoftDeleteNewsItem', $metadataBuildingContext); + + self::assertEquals('', $filter->addFilterConstraint($metadata, 't1_')); } @@ -328,8 +337,8 @@ public function testSQLFilterToString() 'locale' => ['value' => 'en', 'type' => DBALType::STRING], ]; - $this->assertEquals(serialize($parameters), ''.$filter); - $this->assertEquals(''.$filter, ''.$filter2); + self::assertEquals(serialize($parameters), ''.$filter); + self::assertEquals(''.$filter, ''.$filter2); } public function testQueryCache_DependsOnFilters() @@ -337,77 +346,77 @@ public function testQueryCache_DependsOnFilters() $cacheDataReflection = new \ReflectionProperty(ArrayCache::class, "data"); $cacheDataReflection->setAccessible(true); - $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); + $query = $this->em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); $cache = new ArrayCache(); $query->setQueryCacheDriver($cache); $query->getResult(); - $this->assertEquals(1, sizeof($cacheDataReflection->getValue($cache))); + self::assertEquals(1, sizeof($cacheDataReflection->getValue($cache))); - $conf = $this->_em->getConfiguration(); + $conf = $this->em->getConfiguration(); $conf->addFilter("locale", "\Doctrine\Tests\ORM\Functional\MyLocaleFilter"); - $this->_em->getFilters()->enable("locale"); + $this->em->getFilters()->enable("locale"); $query->getResult(); - $this->assertEquals(2, sizeof($cacheDataReflection->getValue($cache))); + self::assertEquals(2, sizeof($cacheDataReflection->getValue($cache))); // Another time doesn't add another cache entry $query->getResult(); - $this->assertEquals(2, sizeof($cacheDataReflection->getValue($cache))); + self::assertEquals(2, sizeof($cacheDataReflection->getValue($cache))); } public function testQueryGeneration_DependsOnFilters() { - $query = $this->_em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsAddress a'); + $query = $this->em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsAddress a'); $firstSQLQuery = $query->getSQL(); - $conf = $this->_em->getConfiguration(); + $conf = $this->em->getConfiguration(); $conf->addFilter("country", "\Doctrine\Tests\ORM\Functional\CMSCountryFilter"); - $this->_em->getFilters()->enable("country") + $this->em->getFilters()->enable("country") ->setParameter("country", "en", DBALType::STRING); - $this->assertNotEquals($firstSQLQuery, $query->getSQL()); + self::assertNotEquals($firstSQLQuery, $query->getSQL()); } public function testRepositoryFind() { $this->loadFixtureData(); - $this->assertNotNull($this->_em->getRepository(CmsGroup::class)->find($this->groupId)); - $this->assertNotNull($this->_em->getRepository(CmsGroup::class)->find($this->groupId2)); + self::assertNotNull($this->em->getRepository(CmsGroup::class)->find($this->groupId)); + self::assertNotNull($this->em->getRepository(CmsGroup::class)->find($this->groupId2)); $this->useCMSGroupPrefixFilter(); - $this->_em->clear(); + $this->em->clear(); - $this->assertNotNull($this->_em->getRepository(CmsGroup::class)->find($this->groupId)); - $this->assertNull($this->_em->getRepository(CmsGroup::class)->find($this->groupId2)); + self::assertNotNull($this->em->getRepository(CmsGroup::class)->find($this->groupId)); + self::assertNull($this->em->getRepository(CmsGroup::class)->find($this->groupId2)); } public function testRepositoryFindAll() { $this->loadFixtureData(); - $this->assertCount(2, $this->_em->getRepository(CmsGroup::class)->findAll()); + self::assertCount(2, $this->em->getRepository(CmsGroup::class)->findAll()); $this->useCMSGroupPrefixFilter(); - $this->_em->clear(); + $this->em->clear(); - $this->assertCount(1, $this->_em->getRepository(CmsGroup::class)->findAll()); + self::assertCount(1, $this->em->getRepository(CmsGroup::class)->findAll()); } public function testRepositoryFindBy() { $this->loadFixtureData(); - $this->assertCount(1, $this->_em->getRepository(CmsGroup::class)->findBy( + self::assertCount(1, $this->em->getRepository(CmsGroup::class)->findBy( ['id' => $this->groupId2] )); $this->useCMSGroupPrefixFilter(); - $this->_em->clear(); + $this->em->clear(); - $this->assertCount(0, $this->_em->getRepository(CmsGroup::class)->findBy( + self::assertCount(0, $this->em->getRepository(CmsGroup::class)->findBy( ['id' => $this->groupId2] )); } @@ -416,26 +425,26 @@ public function testRepositoryFindByX() { $this->loadFixtureData(); - $this->assertCount(1, $this->_em->getRepository(CmsGroup::class)->findById($this->groupId2)); + self::assertCount(1, $this->em->getRepository(CmsGroup::class)->findById($this->groupId2)); $this->useCMSGroupPrefixFilter(); - $this->_em->clear(); + $this->em->clear(); - $this->assertCount(0, $this->_em->getRepository(CmsGroup::class)->findById($this->groupId2)); + self::assertCount(0, $this->em->getRepository(CmsGroup::class)->findById($this->groupId2)); } public function testRepositoryFindOneBy() { $this->loadFixtureData(); - $this->assertNotNull($this->_em->getRepository(CmsGroup::class)->findOneBy( + self::assertNotNull($this->em->getRepository(CmsGroup::class)->findOneBy( ['id' => $this->groupId2] )); $this->useCMSGroupPrefixFilter(); - $this->_em->clear(); + $this->em->clear(); - $this->assertNull($this->_em->getRepository(CmsGroup::class)->findOneBy( + self::assertNull($this->em->getRepository(CmsGroup::class)->findOneBy( ['id' => $this->groupId2] )); } @@ -444,183 +453,183 @@ public function testRepositoryFindOneByX() { $this->loadFixtureData(); - $this->assertNotNull($this->_em->getRepository(CmsGroup::class)->findOneById($this->groupId2)); + self::assertNotNull($this->em->getRepository(CmsGroup::class)->findOneById($this->groupId2)); $this->useCMSGroupPrefixFilter(); - $this->_em->clear(); + $this->em->clear(); - $this->assertNull($this->_em->getRepository(CmsGroup::class)->findOneById($this->groupId2)); + self::assertNull($this->em->getRepository(CmsGroup::class)->findOneById($this->groupId2)); } public function testToOneFilter() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $this->loadFixtureData(); - $query = $this->_em->createQuery('select ux, ua from Doctrine\Tests\Models\CMS\CmsUser ux JOIN ux.address ua'); + $query = $this->em->createQuery('select ux, ua from Doctrine\Tests\Models\CMS\CmsUser ux JOIN ux.address ua'); // We get two users before enabling the filter - $this->assertEquals(2, count($query->getResult())); + self::assertEquals(2, count($query->getResult())); - $conf = $this->_em->getConfiguration(); + $conf = $this->em->getConfiguration(); $conf->addFilter("country", "\Doctrine\Tests\ORM\Functional\CMSCountryFilter"); - $this->_em->getFilters()->enable("country")->setParameter("country", "Germany", DBALType::STRING); + $this->em->getFilters()->enable("country")->setParameter("country", "Germany", DBALType::STRING); // We get one user after enabling the filter - $this->assertEquals(1, count($query->getResult())); + self::assertEquals(1, count($query->getResult())); } public function testManyToManyFilter() { $this->loadFixtureData(); - $query = $this->_em->createQuery('select ux, ug from Doctrine\Tests\Models\CMS\CmsUser ux JOIN ux.groups ug'); + $query = $this->em->createQuery('select ux, ug from Doctrine\Tests\Models\CMS\CmsUser ux JOIN ux.groups ug'); // We get two users before enabling the filter - $this->assertEquals(2, count($query->getResult())); + self::assertEquals(2, count($query->getResult())); - $conf = $this->_em->getConfiguration(); + $conf = $this->em->getConfiguration(); $conf->addFilter("group_prefix", "\Doctrine\Tests\ORM\Functional\CMSGroupPrefixFilter"); - $this->_em->getFilters()->enable("group_prefix")->setParameter("prefix", "bar_%", DBALType::STRING); + $this->em->getFilters()->enable("group_prefix")->setParameter("prefix", "bar_%", DBALType::STRING); // We get one user after enabling the filter - $this->assertEquals(1, count($query->getResult())); + self::assertEquals(1, count($query->getResult())); } public function testWhereFilter() { $this->loadFixtureData(); - $query = $this->_em->createQuery('select ug from Doctrine\Tests\Models\CMS\CmsGroup ug WHERE 1=1'); + $query = $this->em->createQuery('select ug from Doctrine\Tests\Models\CMS\CmsGroup ug WHERE 1=1'); // We get two users before enabling the filter - $this->assertEquals(2, count($query->getResult())); + self::assertEquals(2, count($query->getResult())); - $conf = $this->_em->getConfiguration(); + $conf = $this->em->getConfiguration(); $conf->addFilter("group_prefix", "\Doctrine\Tests\ORM\Functional\CMSGroupPrefixFilter"); - $this->_em->getFilters()->enable("group_prefix")->setParameter("prefix", "bar_%", DBALType::STRING); + $this->em->getFilters()->enable("group_prefix")->setParameter("prefix", "bar_%", DBALType::STRING); // We get one user after enabling the filter - $this->assertEquals(1, count($query->getResult())); + self::assertEquals(1, count($query->getResult())); } public function testWhereOrFilter() { $this->loadFixtureData(); - $query = $this->_em->createQuery('select ug from Doctrine\Tests\Models\CMS\CmsGroup ug WHERE 1=1 OR 1=1'); + $query = $this->em->createQuery('select ug from Doctrine\Tests\Models\CMS\CmsGroup ug WHERE 1=1 OR 1=1'); // We get two users before enabling the filter - $this->assertEquals(2, count($query->getResult())); + self::assertEquals(2, count($query->getResult())); - $conf = $this->_em->getConfiguration(); + $conf = $this->em->getConfiguration(); $conf->addFilter("group_prefix", "\Doctrine\Tests\ORM\Functional\CMSGroupPrefixFilter"); - $this->_em->getFilters()->enable("group_prefix")->setParameter("prefix", "bar_%", DBALType::STRING); + $this->em->getFilters()->enable("group_prefix")->setParameter("prefix", "bar_%", DBALType::STRING); // We get one user after enabling the filter - $this->assertEquals(1, count($query->getResult())); + self::assertEquals(1, count($query->getResult())); } private function loadLazyFixtureData() { - $class = $this->_em->getClassMetadata(CmsUser::class); - $class->associationMappings['articles']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; - $class->associationMappings['groups']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; + $class = $this->em->getClassMetadata(CmsUser::class); + $class->getProperty('articles')->setFetchMode(FetchMode::EXTRA_LAZY); + $class->getProperty('groups')->setFetchMode(FetchMode::EXTRA_LAZY); $this->loadFixtureData(); } private function useCMSArticleTopicFilter() { - $conf = $this->_em->getConfiguration(); + $conf = $this->em->getConfiguration(); $conf->addFilter("article_topic", "\Doctrine\Tests\ORM\Functional\CMSArticleTopicFilter"); - $this->_em->getFilters()->enable("article_topic")->setParameter("topic", "Test1", DBALType::STRING); + $this->em->getFilters()->enable("article_topic")->setParameter("topic", "Test1", DBALType::STRING); } public function testOneToMany_ExtraLazyCountWithFilter() { $this->loadLazyFixtureData(); - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); - $this->assertFalse($user->articles->isInitialized()); - $this->assertEquals(2, count($user->articles)); + self::assertFalse($user->articles->isInitialized()); + self::assertEquals(2, count($user->articles)); $this->useCMSArticleTopicFilter(); - $this->assertEquals(1, count($user->articles)); + self::assertEquals(1, count($user->articles)); } public function testOneToMany_ExtraLazyContainsWithFilter() { $this->loadLazyFixtureData(); - $user = $this->_em->find(CmsUser::class, $this->userId); - $filteredArticle = $this->_em->find(CmsArticle::class, $this->articleId2); + $user = $this->em->find(CmsUser::class, $this->userId); + $filteredArticle = $this->em->find(CmsArticle::class, $this->articleId2); - $this->assertFalse($user->articles->isInitialized()); - $this->assertTrue($user->articles->contains($filteredArticle)); + self::assertFalse($user->articles->isInitialized()); + self::assertTrue($user->articles->contains($filteredArticle)); $this->useCMSArticleTopicFilter(); - $this->assertFalse($user->articles->contains($filteredArticle)); + self::assertFalse($user->articles->contains($filteredArticle)); } public function testOneToMany_ExtraLazySliceWithFilter() { $this->loadLazyFixtureData(); - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); - $this->assertFalse($user->articles->isInitialized()); - $this->assertEquals(2, count($user->articles->slice(0,10))); + self::assertFalse($user->articles->isInitialized()); + self::assertEquals(2, count($user->articles->slice(0,10))); $this->useCMSArticleTopicFilter(); - $this->assertEquals(1, count($user->articles->slice(0,10))); + self::assertEquals(1, count($user->articles->slice(0,10))); } private function useCMSGroupPrefixFilter() { - $conf = $this->_em->getConfiguration(); + $conf = $this->em->getConfiguration(); $conf->addFilter("group_prefix", "\Doctrine\Tests\ORM\Functional\CMSGroupPrefixFilter"); - $this->_em->getFilters()->enable("group_prefix")->setParameter("prefix", "foo%", DBALType::STRING); + $this->em->getFilters()->enable("group_prefix")->setParameter("prefix", "foo%", DBALType::STRING); } public function testManyToMany_ExtraLazyCountWithFilter() { $this->loadLazyFixtureData(); - $user = $this->_em->find(CmsUser::class, $this->userId2); + $user = $this->em->find(CmsUser::class, $this->userId2); - $this->assertFalse($user->groups->isInitialized()); - $this->assertEquals(2, count($user->groups)); + self::assertFalse($user->groups->isInitialized()); + self::assertEquals(2, count($user->groups)); $this->useCMSGroupPrefixFilter(); - $this->assertEquals(1, count($user->groups)); + self::assertEquals(1, count($user->groups)); } public function testManyToMany_ExtraLazyContainsWithFilter() { $this->loadLazyFixtureData(); - $user = $this->_em->find(CmsUser::class, $this->userId2); - $filteredArticle = $this->_em->find(CmsGroup::class, $this->groupId2); + $user = $this->em->find(CmsUser::class, $this->userId2); + $filteredArticle = $this->em->find(CmsGroup::class, $this->groupId2); - $this->assertFalse($user->groups->isInitialized()); - $this->assertTrue($user->groups->contains($filteredArticle)); + self::assertFalse($user->groups->isInitialized()); + self::assertTrue($user->groups->contains($filteredArticle)); $this->useCMSGroupPrefixFilter(); - $this->assertFalse($user->groups->contains($filteredArticle)); + self::assertFalse($user->groups->contains($filteredArticle)); } public function testManyToMany_ExtraLazySliceWithFilter() { $this->loadLazyFixtureData(); - $user = $this->_em->find(CmsUser::class, $this->userId2); + $user = $this->em->find(CmsUser::class, $this->userId2); - $this->assertFalse($user->groups->isInitialized()); - $this->assertEquals(2, count($user->groups->slice(0,10))); + self::assertFalse($user->groups->isInitialized()); + self::assertEquals(2, count($user->groups->slice(0,10))); $this->useCMSGroupPrefixFilter(); - $this->assertEquals(1, count($user->groups->slice(0,10))); + self::assertEquals(1, count($user->groups->slice(0,10))); } private function loadFixtureData() @@ -652,10 +661,10 @@ private function loadFixtureData() $article2->text = "Test"; $article2->setAuthor($user); - $this->_em->persist($article1); - $this->_em->persist($article2); + $this->em->persist($article1); + $this->em->persist($article2); - $this->_em->persist($user); + $this->em->persist($user); $user2 = new CmsUser; $user2->name = 'Guilherme'; @@ -675,9 +684,9 @@ private function loadFixtureData() $group2->name = 'bar_group'; $user2->addGroup($group2); - $this->_em->persist($user2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user2); + $this->em->flush(); + $this->em->clear(); $this->userId = $user->getId(); $this->userId2 = $user2->getId(); @@ -691,34 +700,34 @@ public function testJoinSubclassPersister_FilterOnlyOnRootTableWhenFetchingSubEn { $this->loadCompanyJoinedSubclassFixtureData(); // Persister - $this->assertEquals(2, count($this->_em->getRepository(CompanyManager::class)->findAll())); + self::assertEquals(2, count($this->em->getRepository(CompanyManager::class)->findAll())); // SQLWalker - $this->assertEquals(2, count($this->_em->createQuery("SELECT cm FROM Doctrine\Tests\Models\Company\CompanyManager cm")->getResult())); + self::assertEquals(2, count($this->em->createQuery("SELECT cm FROM Doctrine\Tests\Models\Company\CompanyManager cm")->getResult())); // Enable the filter $this->usePersonNameFilter('Guilh%'); - $managers = $this->_em->getRepository(CompanyManager::class)->findAll(); - $this->assertEquals(1, count($managers)); - $this->assertEquals("Guilherme", $managers[0]->getName()); + $managers = $this->em->getRepository(CompanyManager::class)->findAll(); + self::assertEquals(1, count($managers)); + self::assertEquals("Guilherme", $managers[0]->getName()); - $this->assertEquals(1, count($this->_em->createQuery("SELECT cm FROM Doctrine\Tests\Models\Company\CompanyManager cm")->getResult())); + self::assertEquals(1, count($this->em->createQuery("SELECT cm FROM Doctrine\Tests\Models\Company\CompanyManager cm")->getResult())); } public function testJoinSubclassPersister_FilterOnlyOnRootTableWhenFetchingRootEntity() { $this->loadCompanyJoinedSubclassFixtureData(); - $this->assertEquals(3, count($this->_em->getRepository(CompanyPerson::class)->findAll())); - $this->assertEquals(3, count($this->_em->createQuery("SELECT cp FROM Doctrine\Tests\Models\Company\CompanyPerson cp")->getResult())); + self::assertEquals(3, count($this->em->getRepository(CompanyPerson::class)->findAll())); + self::assertEquals(3, count($this->em->createQuery("SELECT cp FROM Doctrine\Tests\Models\Company\CompanyPerson cp")->getResult())); // Enable the filter $this->usePersonNameFilter('Guilh%'); - $persons = $this->_em->getRepository(CompanyPerson::class)->findAll(); - $this->assertEquals(1, count($persons)); - $this->assertEquals("Guilherme", $persons[0]->getName()); + $persons = $this->em->getRepository(CompanyPerson::class)->findAll(); + self::assertEquals(1, count($persons)); + self::assertEquals("Guilherme", $persons[0]->getName()); - $this->assertEquals(1, count($this->_em->createQuery("SELECT cp FROM Doctrine\Tests\Models\Company\CompanyPerson cp")->getResult())); + self::assertEquals(1, count($this->em->createQuery("SELECT cp FROM Doctrine\Tests\Models\Company\CompanyPerson cp")->getResult())); } private function loadCompanyJoinedSubclassFixtureData() @@ -738,47 +747,47 @@ private function loadCompanyJoinedSubclassFixtureData() $person = new CompanyPerson; $person->setName('Benjamin'); - $this->_em->persist($manager); - $this->_em->persist($manager2); - $this->_em->persist($person); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($manager); + $this->em->persist($manager2); + $this->em->persist($person); + $this->em->flush(); + $this->em->clear(); } public function testSingleTableInheritance_FilterOnlyOnRootTableWhenFetchingSubEntity() { $this->loadCompanySingleTableInheritanceFixtureData(); // Persister - $this->assertEquals(2, count($this->_em->getRepository(CompanyFlexUltraContract::class)->findAll())); + self::assertEquals(2, count($this->em->getRepository(CompanyFlexUltraContract::class)->findAll())); // SQLWalker - $this->assertEquals(2, count($this->_em->createQuery("SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract cfc")->getResult())); + self::assertEquals(2, count($this->em->createQuery("SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract cfc")->getResult())); // Enable the filter - $conf = $this->_em->getConfiguration(); + $conf = $this->em->getConfiguration(); $conf->addFilter("completed_contract", "\Doctrine\Tests\ORM\Functional\CompletedContractFilter"); - $this->_em->getFilters() + $this->em->getFilters() ->enable("completed_contract") ->setParameter("completed", true, DBALType::BOOLEAN); - $this->assertEquals(1, count($this->_em->getRepository(CompanyFlexUltraContract::class)->findAll())); - $this->assertEquals(1, count($this->_em->createQuery("SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract cfc")->getResult())); + self::assertEquals(1, count($this->em->getRepository(CompanyFlexUltraContract::class)->findAll())); + self::assertEquals(1, count($this->em->createQuery("SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract cfc")->getResult())); } public function testSingleTableInheritance_FilterOnlyOnRootTableWhenFetchingRootEntity() { $this->loadCompanySingleTableInheritanceFixtureData(); - $this->assertEquals(4, count($this->_em->getRepository(CompanyFlexContract::class)->findAll())); - $this->assertEquals(4, count($this->_em->createQuery("SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexContract cfc")->getResult())); + self::assertEquals(4, count($this->em->getRepository(CompanyFlexContract::class)->findAll())); + self::assertEquals(4, count($this->em->createQuery("SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexContract cfc")->getResult())); // Enable the filter - $conf = $this->_em->getConfiguration(); + $conf = $this->em->getConfiguration(); $conf->addFilter("completed_contract", "\Doctrine\Tests\ORM\Functional\CompletedContractFilter"); - $this->_em->getFilters() + $this->em->getFilters() ->enable("completed_contract") ->setParameter("completed", true, DBALType::BOOLEAN); - $this->assertEquals(2, count($this->_em->getRepository(CompanyFlexContract::class)->findAll())); - $this->assertEquals(2, count($this->_em->createQuery("SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexContract cfc")->getResult())); + self::assertEquals(2, count($this->em->getRepository(CompanyFlexContract::class)->findAll())); + self::assertEquals(2, count($this->em->createQuery("SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexContract cfc")->getResult())); } private function loadCompanySingleTableInheritanceFixtureData() @@ -813,14 +822,14 @@ private function loadCompanySingleTableInheritanceFixtureData() $contract1->setSalesPerson($manager); $contract2->setSalesPerson($manager); - $this->_em->persist($manager); - $this->_em->persist($manager2); - $this->_em->persist($contract1); - $this->_em->persist($contract2); - $this->_em->persist($contract3); - $this->_em->persist($contract4); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($manager); + $this->em->persist($manager2); + $this->em->persist($contract1); + $this->em->persist($contract2); + $this->em->persist($contract3); + $this->em->persist($contract4); + $this->em->flush(); + $this->em->clear(); $this->managerId = $manager->getId(); $this->managerId2 = $manager2->getId(); @@ -830,71 +839,75 @@ private function loadCompanySingleTableInheritanceFixtureData() private function useCompletedContractFilter() { - $conf = $this->_em->getConfiguration(); - $conf->addFilter("completed_contract", "\Doctrine\Tests\ORM\Functional\CompletedContractFilter"); - $this->_em->getFilters() + $conf = $this->em->getConfiguration(); + + $conf->addFilter("completed_contract", CompletedContractFilter::class); + + $this->em + ->getFilters() ->enable("completed_contract") - ->setParameter("completed", true, DBALType::BOOLEAN); + ->setParameter("completed", true, DBALType::BOOLEAN) + ; } public function testManyToMany_ExtraLazyCountWithFilterOnSTI() { $this->loadCompanySingleTableInheritanceFixtureData(); - $manager = $this->_em->find(CompanyManager::class, $this->managerId); + $manager = $this->em->find(CompanyManager::class, $this->managerId); - $this->assertFalse($manager->managedContracts->isInitialized()); - $this->assertEquals(4, count($manager->managedContracts)); + self::assertFalse($manager->managedContracts->isInitialized()); + self::assertEquals(4, count($manager->managedContracts)); // Enable the filter $this->useCompletedContractFilter(); - $this->assertFalse($manager->managedContracts->isInitialized()); - $this->assertEquals(2, count($manager->managedContracts)); + self::assertFalse($manager->managedContracts->isInitialized()); + self::assertEquals(2, count($manager->managedContracts)); } public function testManyToMany_ExtraLazyContainsWithFilterOnSTI() { $this->loadCompanySingleTableInheritanceFixtureData(); - $manager = $this->_em->find(CompanyManager::class, $this->managerId); - $contract1 = $this->_em->find(CompanyContract::class, $this->contractId1); - $contract2 = $this->_em->find(CompanyContract::class, $this->contractId2); + $manager = $this->em->find(CompanyManager::class, $this->managerId); + $contract1 = $this->em->find(CompanyContract::class, $this->contractId1); + $contract2 = $this->em->find(CompanyContract::class, $this->contractId2); - $this->assertFalse($manager->managedContracts->isInitialized()); - $this->assertTrue($manager->managedContracts->contains($contract1)); - $this->assertTrue($manager->managedContracts->contains($contract2)); + self::assertFalse($manager->managedContracts->isInitialized()); + self::assertTrue($manager->managedContracts->contains($contract1)); + self::assertTrue($manager->managedContracts->contains($contract2)); // Enable the filter $this->useCompletedContractFilter(); - $this->assertFalse($manager->managedContracts->isInitialized()); - $this->assertFalse($manager->managedContracts->contains($contract1)); - $this->assertTrue($manager->managedContracts->contains($contract2)); + self::assertFalse($manager->managedContracts->isInitialized()); + self::assertFalse($manager->managedContracts->contains($contract1)); + self::assertTrue($manager->managedContracts->contains($contract2)); } public function testManyToMany_ExtraLazySliceWithFilterOnSTI() { $this->loadCompanySingleTableInheritanceFixtureData(); - $manager = $this->_em->find(CompanyManager::class, $this->managerId); + $manager = $this->em->find(CompanyManager::class, $this->managerId); - $this->assertFalse($manager->managedContracts->isInitialized()); - $this->assertEquals(4, count($manager->managedContracts->slice(0, 10))); + self::assertFalse($manager->managedContracts->isInitialized()); + self::assertEquals(4, count($manager->managedContracts->slice(0, 10))); // Enable the filter $this->useCompletedContractFilter(); - $this->assertFalse($manager->managedContracts->isInitialized()); - $this->assertEquals(2, count($manager->managedContracts->slice(0, 10))); + self::assertFalse($manager->managedContracts->isInitialized()); + self::assertEquals(2, count($manager->managedContracts->slice(0, 10))); } private function usePersonNameFilter($name) { // Enable the filter - $conf = $this->_em->getConfiguration(); + $conf = $this->em->getConfiguration(); $conf->addFilter("person_name", "\Doctrine\Tests\ORM\Functional\CompanyPersonNameFilter"); - $this->_em->getFilters() + $this->em->getFilters() ->enable("person_name") ->setParameter("name", $name, DBALType::STRING); } @@ -903,88 +916,88 @@ public function testManyToMany_ExtraLazyCountWithFilterOnCTI() { $this->loadCompanySingleTableInheritanceFixtureData(); - $contract = $this->_em->find(CompanyFlexUltraContract::class, $this->contractId1); + $contract = $this->em->find(CompanyFlexUltraContract::class, $this->contractId1); - $this->assertFalse($contract->managers->isInitialized()); - $this->assertEquals(2, count($contract->managers)); + self::assertFalse($contract->managers->isInitialized()); + self::assertEquals(2, count($contract->managers)); // Enable the filter $this->usePersonNameFilter('Benjamin'); - $this->assertFalse($contract->managers->isInitialized()); - $this->assertEquals(1, count($contract->managers)); + self::assertFalse($contract->managers->isInitialized()); + self::assertEquals(1, count($contract->managers)); } public function testManyToMany_ExtraLazyContainsWithFilterOnCTI() { $this->loadCompanySingleTableInheritanceFixtureData(); - $contract = $this->_em->find(CompanyFlexUltraContract::class, $this->contractId1); - $manager1 = $this->_em->find(CompanyManager::class, $this->managerId); - $manager2 = $this->_em->find(CompanyManager::class, $this->managerId2); + $contract = $this->em->find(CompanyFlexUltraContract::class, $this->contractId1); + $manager1 = $this->em->find(CompanyManager::class, $this->managerId); + $manager2 = $this->em->find(CompanyManager::class, $this->managerId2); - $this->assertFalse($contract->managers->isInitialized()); - $this->assertTrue($contract->managers->contains($manager1)); - $this->assertTrue($contract->managers->contains($manager2)); + self::assertFalse($contract->managers->isInitialized()); + self::assertTrue($contract->managers->contains($manager1)); + self::assertTrue($contract->managers->contains($manager2)); // Enable the filter $this->usePersonNameFilter('Benjamin'); - $this->assertFalse($contract->managers->isInitialized()); - $this->assertFalse($contract->managers->contains($manager1)); - $this->assertTrue($contract->managers->contains($manager2)); + self::assertFalse($contract->managers->isInitialized()); + self::assertFalse($contract->managers->contains($manager1)); + self::assertTrue($contract->managers->contains($manager2)); } public function testManyToMany_ExtraLazySliceWithFilterOnCTI() { $this->loadCompanySingleTableInheritanceFixtureData(); - $contract = $this->_em->find(CompanyFlexUltraContract::class, $this->contractId1); + $contract = $this->em->find(CompanyFlexUltraContract::class, $this->contractId1); - $this->assertFalse($contract->managers->isInitialized()); - $this->assertEquals(2, count($contract->managers->slice(0, 10))); + self::assertFalse($contract->managers->isInitialized()); + self::assertEquals(2, count($contract->managers->slice(0, 10))); // Enable the filter $this->usePersonNameFilter('Benjamin'); - $this->assertFalse($contract->managers->isInitialized()); - $this->assertEquals(1, count($contract->managers->slice(0, 10))); + self::assertFalse($contract->managers->isInitialized()); + self::assertEquals(1, count($contract->managers->slice(0, 10))); } public function testOneToMany_ExtraLazyCountWithFilterOnSTI() { $this->loadCompanySingleTableInheritanceFixtureData(); - $manager = $this->_em->find(CompanyManager::class, $this->managerId); + $manager = $this->em->find(CompanyManager::class, $this->managerId); - $this->assertFalse($manager->soldContracts->isInitialized()); - $this->assertEquals(2, count($manager->soldContracts)); + self::assertFalse($manager->soldContracts->isInitialized()); + self::assertEquals(2, count($manager->soldContracts)); // Enable the filter $this->useCompletedContractFilter(); - $this->assertFalse($manager->soldContracts->isInitialized()); - $this->assertEquals(1, count($manager->soldContracts)); + self::assertFalse($manager->soldContracts->isInitialized()); + self::assertEquals(1, count($manager->soldContracts)); } public function testOneToMany_ExtraLazyContainsWithFilterOnSTI() { $this->loadCompanySingleTableInheritanceFixtureData(); - $manager = $this->_em->find(CompanyManager::class, $this->managerId); - $contract1 = $this->_em->find(CompanyContract::class, $this->contractId1); - $contract2 = $this->_em->find(CompanyContract::class, $this->contractId2); + $manager = $this->em->find(CompanyManager::class, $this->managerId); + $contract1 = $this->em->find(CompanyContract::class, $this->contractId1); + $contract2 = $this->em->find(CompanyContract::class, $this->contractId2); - $this->assertFalse($manager->soldContracts->isInitialized()); - $this->assertTrue($manager->soldContracts->contains($contract1)); - $this->assertTrue($manager->soldContracts->contains($contract2)); + self::assertFalse($manager->soldContracts->isInitialized()); + self::assertTrue($manager->soldContracts->contains($contract1)); + self::assertTrue($manager->soldContracts->contains($contract2)); // Enable the filter $this->useCompletedContractFilter(); - $this->assertFalse($manager->soldContracts->isInitialized()); - $this->assertFalse($manager->soldContracts->contains($contract1)); - $this->assertTrue($manager->soldContracts->contains($contract2)); + self::assertFalse($manager->soldContracts->isInitialized()); + self::assertFalse($manager->soldContracts->contains($contract1)); + self::assertTrue($manager->soldContracts->contains($contract2)); } public function testOneToMany_ExtraLazySliceWithFilterOnSTI() @@ -992,16 +1005,16 @@ public function testOneToMany_ExtraLazySliceWithFilterOnSTI() $this->loadCompanySingleTableInheritanceFixtureData(); - $manager = $this->_em->find(CompanyManager::class, $this->managerId); + $manager = $this->em->find(CompanyManager::class, $this->managerId); - $this->assertFalse($manager->soldContracts->isInitialized()); - $this->assertEquals(2, count($manager->soldContracts->slice(0, 10))); + self::assertFalse($manager->soldContracts->isInitialized()); + self::assertEquals(2, count($manager->soldContracts->slice(0, 10))); // Enable the filter $this->useCompletedContractFilter(); - $this->assertFalse($manager->soldContracts->isInitialized()); - $this->assertEquals(1, count($manager->soldContracts->slice(0, 10))); + self::assertFalse($manager->soldContracts->isInitialized()); + self::assertEquals(1, count($manager->soldContracts->slice(0, 10))); } private function loadCompanyOrganizationEventJoinedSubclassFixtureData() { @@ -1016,9 +1029,9 @@ private function loadCompanyOrganizationEventJoinedSubclassFixtureData() $organization->addEvent($event1); $organization->addEvent($event2); - $this->_em->persist($organization); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($organization); + $this->em->flush(); + $this->em->clear(); $this->organizationId = $organization->getId(); $this->eventId1 = $event1->getId(); @@ -1028,9 +1041,9 @@ private function loadCompanyOrganizationEventJoinedSubclassFixtureData() private function useCompanyEventIdFilter() { // Enable the filter - $conf = $this->_em->getConfiguration(); + $conf = $this->em->getConfiguration(); $conf->addFilter("event_id", CompanyEventFilter::class); - $this->_em->getFilters() + $this->em->getFilters() ->enable("event_id") ->setParameter("id", $this->eventId2); } @@ -1040,53 +1053,53 @@ public function testOneToMany_ExtraLazyCountWithFilterOnCTI() { $this->loadCompanyOrganizationEventJoinedSubclassFixtureData(); - $organization = $this->_em->find(CompanyOrganization::class, $this->organizationId); + $organization = $this->em->find(CompanyOrganization::class, $this->organizationId); - $this->assertFalse($organization->events->isInitialized()); - $this->assertEquals(2, count($organization->events)); + self::assertFalse($organization->events->isInitialized()); + self::assertEquals(2, count($organization->events)); // Enable the filter $this->useCompanyEventIdFilter(); - $this->assertFalse($organization->events->isInitialized()); - $this->assertEquals(1, count($organization->events)); + self::assertFalse($organization->events->isInitialized()); + self::assertEquals(1, count($organization->events)); } public function testOneToMany_ExtraLazyContainsWithFilterOnCTI() { $this->loadCompanyOrganizationEventJoinedSubclassFixtureData(); - $organization = $this->_em->find(CompanyOrganization::class, $this->organizationId); + $organization = $this->em->find(CompanyOrganization::class, $this->organizationId); - $event1 = $this->_em->find(CompanyEvent::class, $this->eventId1); - $event2 = $this->_em->find(CompanyEvent::class, $this->eventId2); + $event1 = $this->em->find(CompanyEvent::class, $this->eventId1); + $event2 = $this->em->find(CompanyEvent::class, $this->eventId2); - $this->assertFalse($organization->events->isInitialized()); - $this->assertTrue($organization->events->contains($event1)); - $this->assertTrue($organization->events->contains($event2)); + self::assertFalse($organization->events->isInitialized()); + self::assertTrue($organization->events->contains($event1)); + self::assertTrue($organization->events->contains($event2)); // Enable the filter $this->useCompanyEventIdFilter(); - $this->assertFalse($organization->events->isInitialized()); - $this->assertFalse($organization->events->contains($event1)); - $this->assertTrue($organization->events->contains($event2)); + self::assertFalse($organization->events->isInitialized()); + self::assertFalse($organization->events->contains($event1)); + self::assertTrue($organization->events->contains($event2)); } public function testOneToMany_ExtraLazySliceWithFilterOnCTI() { $this->loadCompanyOrganizationEventJoinedSubclassFixtureData(); - $organization = $this->_em->find(CompanyOrganization::class, $this->organizationId); + $organization = $this->em->find(CompanyOrganization::class, $this->organizationId); - $this->assertFalse($organization->events->isInitialized()); - $this->assertEquals(2, count($organization->events->slice(0, 10))); + self::assertFalse($organization->events->isInitialized()); + self::assertEquals(2, count($organization->events->slice(0, 10))); // Enable the filter $this->useCompanyEventIdFilter(); - $this->assertFalse($organization->events->isInitialized()); - $this->assertEquals(1, count($organization->events->slice(0, 10))); + self::assertFalse($organization->events->isInitialized()); + self::assertEquals(1, count($organization->events->slice(0, 10))); } } @@ -1094,7 +1107,7 @@ class MySoftDeleteFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) { - if ($targetEntity->name != "MyEntity\SoftDeleteNewsItem") { + if ($targetEntity->getClassName() !== "MyEntity\SoftDeleteNewsItem") { return ""; } @@ -1106,7 +1119,7 @@ class MyLocaleFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) { - if (!in_array("LocaleAware", $targetEntity->reflClass->getInterfaceNames())) { + if (!in_array("LocaleAware", $targetEntity->getReflectionClass()->getInterfaceNames())) { return ""; } @@ -1118,7 +1131,7 @@ class CMSCountryFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) { - if ($targetEntity->name != CmsAddress::class) { + if ($targetEntity->getClassName() !== CmsAddress::class) { return ""; } @@ -1130,7 +1143,7 @@ class CMSGroupPrefixFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) { - if ($targetEntity->name != CmsGroup::class) { + if ($targetEntity->getClassName() !== CmsGroup::class) { return ""; } @@ -1142,7 +1155,7 @@ class CMSArticleTopicFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) { - if ($targetEntity->name != CmsArticle::class) { + if ($targetEntity->getClassName() !== CmsArticle::class) { return ""; } @@ -1154,7 +1167,7 @@ class CompanyPersonNameFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias, $targetTable = '') { - if ($targetEntity->name != CompanyPerson::class) { + if ($targetEntity->getClassName() !== CompanyPerson::class) { return ""; } @@ -1166,11 +1179,11 @@ class CompletedContractFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias, $targetTable = '') { - if ($targetEntity->name != CompanyContract::class) { + if ($targetEntity->getClassName() !== CompanyContract::class) { return ""; } - return $targetTableAlias.'.completed = ' . $this->getParameter('completed'); + return $targetTableAlias.'."completed" = ' . $this->getParameter('completed'); } } @@ -1178,7 +1191,7 @@ class CompanyEventFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias, $targetTable = '') { - if ($targetEntity->name != CompanyEvent::class) { + if ($targetEntity->getClassName() !== CompanyEvent::class) { return ""; } diff --git a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/CompanySchemaTest.php b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/CompanySchemaTest.php index 1a36591cf53..6b38fc9d9ff 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/CompanySchemaTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/CompanySchemaTest.php @@ -1,5 +1,7 @@ _em->getConnection()->getSchemaManager()->createSchema(); + $schema = $this->em->getConnection()->getSchemaManager()->createSchema(); - $this->assertTrue($schema->hasTable('company_contracts')); + self::assertTrue($schema->hasTable('company_contracts')); return $schema; } @@ -41,14 +43,14 @@ public function testSingleTableInheritance(Schema $schema) $table = $schema->getTable('company_contracts'); // Check nullability constraints - $this->assertTrue($table->getColumn('id')->getNotnull()); - $this->assertTrue($table->getColumn('completed')->getNotnull()); - $this->assertFalse($table->getColumn('salesPerson_id')->getNotnull()); - $this->assertTrue($table->getColumn('discr')->getNotnull()); - $this->assertFalse($table->getColumn('fixPrice')->getNotnull()); - $this->assertFalse($table->getColumn('hoursWorked')->getNotnull()); - $this->assertFalse($table->getColumn('pricePerHour')->getNotnull()); - $this->assertFalse($table->getColumn('maxPrice')->getNotnull()); + self::assertTrue($table->getColumn('id')->getNotnull()); + self::assertTrue($table->getColumn('completed')->getNotnull()); + self::assertFalse($table->getColumn('salesPerson_id')->getNotnull()); + self::assertTrue($table->getColumn('discr')->getNotnull()); + self::assertFalse($table->getColumn('fixPrice')->getNotnull()); + self::assertFalse($table->getColumn('hoursWorked')->getNotnull()); + self::assertFalse($table->getColumn('pricePerHour')->getNotnull()); + self::assertFalse($table->getColumn('maxPrice')->getNotnull()); } /** @@ -56,15 +58,15 @@ public function testSingleTableInheritance(Schema $schema) */ public function testDropPartSchemaWithForeignKeys() { - if (!$this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { + if (!$this->em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { $this->markTestSkipped("Foreign Key test"); } - $sql = $this->_schemaTool->getDropSchemaSQL( + $sql = $this->schemaTool->getDropSchemaSQL( [ - $this->_em->getClassMetadata(CompanyManager::class), + $this->em->getClassMetadata(CompanyManager::class), ] ); - $this->assertEquals(4, count($sql)); + self::assertEquals(4, count($sql)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DBAL483Test.php b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DBAL483Test.php index 8a874c478a7..9d5db939338 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DBAL483Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DBAL483Test.php @@ -1,7 +1,10 @@ _em->getConnection(); + $this->em->getConnection(); - $this->schemaTool = new Tools\SchemaTool($this->_em); + $this->schemaTool = new Tools\SchemaTool($this->em); } /** @@ -21,7 +24,7 @@ public function setUp() */ public function testDefaultValueIsComparedCorrectly() { - $class = $this->_em->getClassMetadata(DBAL483Default::class); + $class = $this->em->getClassMetadata(DBAL483Default::class); $this->schemaTool->createSchema([$class]); @@ -31,27 +34,27 @@ public function testDefaultValueIsComparedCorrectly() return strpos($sql, 'DBAL483') !== false; }); - $this->assertEquals(0, count($updateSql)); + self::assertEquals(0, count($updateSql)); } } /** - * @Entity + * @ORM\Entity */ class DBAL483Default { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; /** - * @Column(type="integer", options={"default": 0}) + * @ORM\Column(type="integer", options={"default": 0}) */ public $num; /** - * @Column(type="string", options={"default": "foo"}) + * @ORM\Column(type="string", options={"default": "foo"}) */ public $str = "foo"; } diff --git a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DDC214Test.php b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DDC214Test.php index 8c414b119a3..cab7c60e8a2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DDC214Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DDC214Test.php @@ -1,5 +1,7 @@ _em->getConnection(); + $conn = $this->em->getConnection(); if (strpos($conn->getDriver()->getName(), "sqlite") !== false) { $this->markTestSkipped('SQLite does not support ALTER TABLE statements.'); } - $this->schemaTool = new Tools\SchemaTool($this->_em); } /** @@ -41,7 +41,7 @@ public function testCmsAddressModel() Models\CMS\CmsEmail::class, ]; - $this->assertCreatedSchemaNeedsNoUpdates($this->classes); + self::assertCreatedSchemaNeedsNoUpdates($this->classes); } /** @@ -60,14 +60,14 @@ public function testCompanyModel() Models\Company\CompanyCar::class ]; - $this->assertCreatedSchemaNeedsNoUpdates($this->classes); + self::assertCreatedSchemaNeedsNoUpdates($this->classes); } public function assertCreatedSchemaNeedsNoUpdates($classes) { $classMetadata = []; foreach ($classes AS $class) { - $classMetadata[] = $this->_em->getClassMetadata($class); + $classMetadata[] = $this->em->getClassMetadata($class); } try { @@ -76,7 +76,7 @@ public function assertCreatedSchemaNeedsNoUpdates($classes) // was already created } - $sm = $this->_em->getConnection()->getSchemaManager(); + $sm = $this->em->getConnection()->getSchemaManager(); $fromSchema = $sm->createSchema(); $toSchema = $this->schemaTool->getSchemaFromMetadata($classMetadata); @@ -84,9 +84,9 @@ public function assertCreatedSchemaNeedsNoUpdates($classes) $comparator = new Comparator(); $schemaDiff = $comparator->compare($fromSchema, $toSchema); - $sql = $schemaDiff->toSql($this->_em->getConnection()->getDatabasePlatform()); + $sql = $schemaDiff->toSql($this->em->getConnection()->getDatabasePlatform()); $sql = array_filter($sql, function($sql) { return strpos($sql, 'DROP') === false; }); - $this->assertEquals(0, count($sql), "SQL: " . implode(PHP_EOL, $sql)); + self::assertEquals(0, count($sql), "SQL: " . implode(PHP_EOL, $sql)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/MySqlSchemaToolTest.php b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/MySqlSchemaToolTest.php index 2deedb37aa6..b6aa22715c5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/MySqlSchemaToolTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/MySqlSchemaToolTest.php @@ -1,7 +1,10 @@ _em->getConnection()->getDatabasePlatform()->getName() !== 'mysql') { + if ($this->em->getConnection()->getDatabasePlatform()->getName() !== 'mysql') { $this->markTestSkipped('The ' . __CLASS__ .' requires the use of mysql.'); } } @@ -18,60 +21,60 @@ protected function setUp() { public function testGetCreateSchemaSql() { $classes = [ - $this->_em->getClassMetadata(Models\CMS\CmsGroup::class), - $this->_em->getClassMetadata(Models\CMS\CmsUser::class), - $this->_em->getClassMetadata(Models\CMS\CmsTag::class), - $this->_em->getClassMetadata(Models\CMS\CmsAddress::class), - $this->_em->getClassMetadata(Models\CMS\CmsEmail::class), - $this->_em->getClassMetadata(Models\CMS\CmsPhonenumber::class), + $this->em->getClassMetadata(Models\CMS\CmsGroup::class), + $this->em->getClassMetadata(Models\CMS\CmsUser::class), + $this->em->getClassMetadata(Models\CMS\CmsTag::class), + $this->em->getClassMetadata(Models\CMS\CmsAddress::class), + $this->em->getClassMetadata(Models\CMS\CmsEmail::class), + $this->em->getClassMetadata(Models\CMS\CmsPhonenumber::class), ]; - $tool = new SchemaTool($this->_em); + $tool = new SchemaTool($this->em); $sql = $tool->getCreateSchemaSql($classes); - $this->assertEquals("CREATE TABLE cms_groups (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[0]); - $this->assertEquals("CREATE TABLE cms_users (id INT AUTO_INCREMENT NOT NULL, email_id INT DEFAULT NULL, status VARCHAR(50) DEFAULT NULL, username VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, UNIQUE INDEX UNIQ_3AF03EC5F85E0677 (username), UNIQUE INDEX UNIQ_3AF03EC5A832C1C9 (email_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[1]); - $this->assertEquals("CREATE TABLE cms_users_groups (user_id INT NOT NULL, group_id INT NOT NULL, INDEX IDX_7EA9409AA76ED395 (user_id), INDEX IDX_7EA9409AFE54D947 (group_id), PRIMARY KEY(user_id, group_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[2]); - $this->assertEquals("CREATE TABLE cms_users_tags (user_id INT NOT NULL, tag_id INT NOT NULL, INDEX IDX_93F5A1ADA76ED395 (user_id), INDEX IDX_93F5A1ADBAD26311 (tag_id), PRIMARY KEY(user_id, tag_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[3]); - $this->assertEquals("CREATE TABLE cms_tags (id INT AUTO_INCREMENT NOT NULL, tag_name VARCHAR(50) DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[4]); - $this->assertEquals("CREATE TABLE cms_addresses (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, country VARCHAR(50) NOT NULL, zip VARCHAR(50) NOT NULL, city VARCHAR(50) NOT NULL, UNIQUE INDEX UNIQ_ACAC157BA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[5]); - $this->assertEquals("CREATE TABLE cms_emails (id INT AUTO_INCREMENT NOT NULL, email VARCHAR(250) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[6]); - $this->assertEquals("CREATE TABLE cms_phonenumbers (phonenumber VARCHAR(50) NOT NULL, user_id INT DEFAULT NULL, INDEX IDX_F21F790FA76ED395 (user_id), PRIMARY KEY(phonenumber)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[7]); - $this->assertEquals("ALTER TABLE cms_users ADD CONSTRAINT FK_3AF03EC5A832C1C9 FOREIGN KEY (email_id) REFERENCES cms_emails (id)", $sql[8]); - $this->assertEquals("ALTER TABLE cms_users_groups ADD CONSTRAINT FK_7EA9409AA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id)", $sql[9]); - $this->assertEquals("ALTER TABLE cms_users_groups ADD CONSTRAINT FK_7EA9409AFE54D947 FOREIGN KEY (group_id) REFERENCES cms_groups (id)", $sql[10]); - $this->assertEquals("ALTER TABLE cms_users_tags ADD CONSTRAINT FK_93F5A1ADA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id)", $sql[11]); - $this->assertEquals("ALTER TABLE cms_users_tags ADD CONSTRAINT FK_93F5A1ADBAD26311 FOREIGN KEY (tag_id) REFERENCES cms_tags (id)", $sql[12]); - $this->assertEquals("ALTER TABLE cms_addresses ADD CONSTRAINT FK_ACAC157BA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id)", $sql[13]); - $this->assertEquals("ALTER TABLE cms_phonenumbers ADD CONSTRAINT FK_F21F790FA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id)", $sql[14]); - - $this->assertEquals(15, count($sql)); + self::assertEquals("CREATE TABLE cms_groups (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[0]); + self::assertEquals("CREATE TABLE cms_users (id INT AUTO_INCREMENT NOT NULL, email_id INT DEFAULT NULL, status VARCHAR(50) DEFAULT NULL, username VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, UNIQUE INDEX UNIQ_3AF03EC5F85E0677 (username), UNIQUE INDEX UNIQ_3AF03EC5A832C1C9 (email_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[1]); + self::assertEquals("CREATE TABLE cms_users_groups (user_id INT NOT NULL, group_id INT NOT NULL, INDEX IDX_7EA9409AA76ED395 (user_id), INDEX IDX_7EA9409AFE54D947 (group_id), PRIMARY KEY(user_id, group_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[2]); + self::assertEquals("CREATE TABLE cms_users_tags (user_id INT NOT NULL, tag_id INT NOT NULL, INDEX IDX_93F5A1ADA76ED395 (user_id), INDEX IDX_93F5A1ADBAD26311 (tag_id), PRIMARY KEY(user_id, tag_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[3]); + self::assertEquals("CREATE TABLE cms_tags (id INT AUTO_INCREMENT NOT NULL, tag_name VARCHAR(50) DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[4]); + self::assertEquals("CREATE TABLE cms_addresses (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, country VARCHAR(50) NOT NULL, zip VARCHAR(50) NOT NULL, city VARCHAR(50) NOT NULL, UNIQUE INDEX UNIQ_ACAC157BA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[5]); + self::assertEquals("CREATE TABLE cms_emails (id INT AUTO_INCREMENT NOT NULL, email VARCHAR(250) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[6]); + self::assertEquals("CREATE TABLE cms_phonenumbers (phonenumber VARCHAR(50) NOT NULL, user_id INT DEFAULT NULL, INDEX IDX_F21F790FA76ED395 (user_id), PRIMARY KEY(phonenumber)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[7]); + self::assertEquals("ALTER TABLE cms_users ADD CONSTRAINT FK_3AF03EC5A832C1C9 FOREIGN KEY (email_id) REFERENCES cms_emails (id)", $sql[8]); + self::assertEquals("ALTER TABLE cms_users_groups ADD CONSTRAINT FK_7EA9409AA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id)", $sql[9]); + self::assertEquals("ALTER TABLE cms_users_groups ADD CONSTRAINT FK_7EA9409AFE54D947 FOREIGN KEY (group_id) REFERENCES cms_groups (id)", $sql[10]); + self::assertEquals("ALTER TABLE cms_users_tags ADD CONSTRAINT FK_93F5A1ADA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id)", $sql[11]); + self::assertEquals("ALTER TABLE cms_users_tags ADD CONSTRAINT FK_93F5A1ADBAD26311 FOREIGN KEY (tag_id) REFERENCES cms_tags (id)", $sql[12]); + self::assertEquals("ALTER TABLE cms_addresses ADD CONSTRAINT FK_ACAC157BA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id)", $sql[13]); + self::assertEquals("ALTER TABLE cms_phonenumbers ADD CONSTRAINT FK_F21F790FA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id)", $sql[14]); + + self::assertEquals(15, count($sql)); } public function testGetCreateSchemaSql2() { $classes = [ - $this->_em->getClassMetadata(Models\Generic\DecimalModel::class) + $this->em->getClassMetadata(Models\Generic\DecimalModel::class) ]; - $tool = new SchemaTool($this->_em); + $tool = new SchemaTool($this->em); $sql = $tool->getCreateSchemaSql($classes); - $this->assertEquals(1, count($sql)); - $this->assertEquals("CREATE TABLE decimal_model (id INT AUTO_INCREMENT NOT NULL, `decimal` NUMERIC(5, 2) NOT NULL, `high_scale` NUMERIC(14, 4) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[0]); + self::assertEquals(1, count($sql)); + self::assertEquals("CREATE TABLE decimal_model (id INT AUTO_INCREMENT NOT NULL, `decimal` NUMERIC(5, 2) NOT NULL, `high_scale` NUMERIC(14, 4) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[0]); } public function testGetCreateSchemaSql3() { $classes = [ - $this->_em->getClassMetadata(Models\Generic\BooleanModel::class) + $this->em->getClassMetadata(Models\Generic\BooleanModel::class) ]; - $tool = new SchemaTool($this->_em); + $tool = new SchemaTool($this->em); $sql = $tool->getCreateSchemaSql($classes); - $this->assertEquals(1, count($sql)); - $this->assertEquals("CREATE TABLE boolean_model (id INT AUTO_INCREMENT NOT NULL, booleanField TINYINT(1) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[0]); + self::assertEquals(1, count($sql)); + self::assertEquals("CREATE TABLE boolean_model (id INT AUTO_INCREMENT NOT NULL, booleanField TINYINT(1) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[0]); } /** @@ -80,24 +83,24 @@ public function testGetCreateSchemaSql3() public function testGetCreateSchemaSql4() { $classes = [ - $this->_em->getClassMetadata(MysqlSchemaNamespacedEntity::class) + $this->em->getClassMetadata(MysqlSchemaNamespacedEntity::class) ]; - $tool = new SchemaTool($this->_em); + $tool = new SchemaTool($this->em); $sql = $tool->getCreateSchemaSql($classes); - $this->assertEquals(0, count($sql)); + self::assertEquals(0, count($sql)); } } /** - * @Entity - * @Table("namespace.entity") + * @ORM\Entity + * @ORM\Table("namespace.entity") */ class MysqlSchemaNamespacedEntity { - /** @Column(type="integer") @Id @GeneratedValue */ + /** @ORM\Column(type="integer") @ORM\Id @ORM\GeneratedValue */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/PostgreSqlSchemaToolTest.php b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/PostgreSqlSchemaToolTest.php index 5ebf84c5644..a4d763df8ac 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/PostgreSqlSchemaToolTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/PostgreSqlSchemaToolTest.php @@ -1,7 +1,10 @@ _em->getConnection()->getDatabasePlatform()->getName() !== 'postgresql') { + if ($this->em->getConnection()->getDatabasePlatform()->getName() !== 'postgresql') { $this->markTestSkipped('The ' . __CLASS__ .' requires the use of postgresql.'); } } public function testPostgresMetadataSequenceIncrementedBy10() { - $address = $this->_em->getClassMetadata(Models\CMS\CmsAddress::class); + $address = $this->em->getClassMetadata(Models\CMS\CmsAddress::class); - $this->assertEquals(1, $address->sequenceGeneratorDefinition['allocationSize']); + self::assertEquals(1, $address->getProperty('id')->getValueGenerator()->getDefinition()['allocationSize']); } public function testGetCreateSchemaSql() { $classes = [ - $this->_em->getClassMetadata(Models\CMS\CmsAddress::class), - $this->_em->getClassMetadata(Models\CMS\CmsUser::class), - $this->_em->getClassMetadata(Models\CMS\CmsPhonenumber::class), + $this->em->getClassMetadata(Models\CMS\CmsAddress::class), + $this->em->getClassMetadata(Models\CMS\CmsUser::class), + $this->em->getClassMetadata(Models\CMS\CmsPhonenumber::class), ]; - $tool = new SchemaTool($this->_em); + $tool = new SchemaTool($this->em); $sql = $tool->getCreateSchemaSql($classes); $sqlCount = count($sql); - $this->assertEquals("CREATE TABLE cms_addresses (id INT NOT NULL, user_id INT DEFAULT NULL, country VARCHAR(50) NOT NULL, zip VARCHAR(50) NOT NULL, city VARCHAR(50) NOT NULL, PRIMARY KEY(id))", array_shift($sql)); - $this->assertEquals("CREATE UNIQUE INDEX UNIQ_ACAC157BA76ED395 ON cms_addresses (user_id)", array_shift($sql)); - $this->assertEquals("CREATE TABLE cms_users (id INT NOT NULL, email_id INT DEFAULT NULL, status VARCHAR(50) DEFAULT NULL, username VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id))", array_shift($sql)); - $this->assertEquals("CREATE UNIQUE INDEX UNIQ_3AF03EC5F85E0677 ON cms_users (username)", array_shift($sql)); - $this->assertEquals("CREATE UNIQUE INDEX UNIQ_3AF03EC5A832C1C9 ON cms_users (email_id)", array_shift($sql)); - $this->assertEquals("CREATE TABLE cms_users_groups (user_id INT NOT NULL, group_id INT NOT NULL, PRIMARY KEY(user_id, group_id))", array_shift($sql)); - $this->assertEquals("CREATE INDEX IDX_7EA9409AA76ED395 ON cms_users_groups (user_id)", array_shift($sql)); - $this->assertEquals("CREATE INDEX IDX_7EA9409AFE54D947 ON cms_users_groups (group_id)", array_shift($sql)); - $this->assertEquals("CREATE TABLE cms_users_tags (user_id INT NOT NULL, tag_id INT NOT NULL, PRIMARY KEY(user_id, tag_id))", array_shift($sql)); - $this->assertEquals("CREATE INDEX IDX_93F5A1ADA76ED395 ON cms_users_tags (user_id)", array_shift($sql)); - $this->assertEquals("CREATE INDEX IDX_93F5A1ADBAD26311 ON cms_users_tags (tag_id)", array_shift($sql)); - $this->assertEquals("CREATE TABLE cms_phonenumbers (phonenumber VARCHAR(50) NOT NULL, user_id INT DEFAULT NULL, PRIMARY KEY(phonenumber))", array_shift($sql)); - $this->assertEquals("CREATE INDEX IDX_F21F790FA76ED395 ON cms_phonenumbers (user_id)", array_shift($sql)); - $this->assertEquals("CREATE SEQUENCE cms_addresses_id_seq INCREMENT BY 1 MINVALUE 1 START 1", array_shift($sql)); - $this->assertEquals("CREATE SEQUENCE cms_users_id_seq INCREMENT BY 1 MINVALUE 1 START 1", array_shift($sql)); - $this->assertEquals("ALTER TABLE cms_addresses ADD CONSTRAINT FK_ACAC157BA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql)); - $this->assertEquals("ALTER TABLE cms_users ADD CONSTRAINT FK_3AF03EC5A832C1C9 FOREIGN KEY (email_id) REFERENCES cms_emails (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql)); - $this->assertEquals("ALTER TABLE cms_users_groups ADD CONSTRAINT FK_7EA9409AA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql)); - $this->assertEquals("ALTER TABLE cms_users_groups ADD CONSTRAINT FK_7EA9409AFE54D947 FOREIGN KEY (group_id) REFERENCES cms_groups (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql)); - $this->assertEquals("ALTER TABLE cms_users_tags ADD CONSTRAINT FK_93F5A1ADA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql)); - $this->assertEquals("ALTER TABLE cms_users_tags ADD CONSTRAINT FK_93F5A1ADBAD26311 FOREIGN KEY (tag_id) REFERENCES cms_tags (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql)); - $this->assertEquals("ALTER TABLE cms_phonenumbers ADD CONSTRAINT FK_F21F790FA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql)); - - $this->assertEquals([], $sql, "SQL Array should be empty now."); - $this->assertEquals(22, $sqlCount, "Total of 22 queries should be executed"); + self::assertEquals("CREATE TABLE cms_addresses (id INT NOT NULL, user_id INT DEFAULT NULL, country VARCHAR(50) NOT NULL, zip VARCHAR(50) NOT NULL, city VARCHAR(50) NOT NULL, PRIMARY KEY(id))", array_shift($sql)); + self::assertEquals("CREATE UNIQUE INDEX UNIQ_ACAC157BA76ED395 ON cms_addresses (user_id)", array_shift($sql)); + self::assertEquals("CREATE TABLE cms_users (id INT NOT NULL, email_id INT DEFAULT NULL, status VARCHAR(50) DEFAULT NULL, username VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id))", array_shift($sql)); + self::assertEquals("CREATE UNIQUE INDEX UNIQ_3AF03EC5F85E0677 ON cms_users (username)", array_shift($sql)); + self::assertEquals("CREATE UNIQUE INDEX UNIQ_3AF03EC5A832C1C9 ON cms_users (email_id)", array_shift($sql)); + self::assertEquals("CREATE TABLE cms_users_groups (user_id INT NOT NULL, group_id INT NOT NULL, PRIMARY KEY(user_id, group_id))", array_shift($sql)); + self::assertEquals("CREATE INDEX IDX_7EA9409AA76ED395 ON cms_users_groups (user_id)", array_shift($sql)); + self::assertEquals("CREATE INDEX IDX_7EA9409AFE54D947 ON cms_users_groups (group_id)", array_shift($sql)); + self::assertEquals("CREATE TABLE cms_users_tags (user_id INT NOT NULL, tag_id INT NOT NULL, PRIMARY KEY(user_id, tag_id))", array_shift($sql)); + self::assertEquals("CREATE INDEX IDX_93F5A1ADA76ED395 ON cms_users_tags (user_id)", array_shift($sql)); + self::assertEquals("CREATE INDEX IDX_93F5A1ADBAD26311 ON cms_users_tags (tag_id)", array_shift($sql)); + self::assertEquals("CREATE TABLE cms_phonenumbers (phonenumber VARCHAR(50) NOT NULL, user_id INT DEFAULT NULL, PRIMARY KEY(phonenumber))", array_shift($sql)); + self::assertEquals("CREATE INDEX IDX_F21F790FA76ED395 ON cms_phonenumbers (user_id)", array_shift($sql)); + self::assertEquals("CREATE SEQUENCE cms_addresses_id_seq INCREMENT BY 1 MINVALUE 1 START 1", array_shift($sql)); + self::assertEquals("CREATE SEQUENCE cms_users_id_seq INCREMENT BY 1 MINVALUE 1 START 1", array_shift($sql)); + self::assertEquals("ALTER TABLE cms_addresses ADD CONSTRAINT FK_ACAC157BA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql)); + self::assertEquals("ALTER TABLE cms_users ADD CONSTRAINT FK_3AF03EC5A832C1C9 FOREIGN KEY (email_id) REFERENCES cms_emails (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql)); + self::assertEquals("ALTER TABLE cms_users_groups ADD CONSTRAINT FK_7EA9409AA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql)); + self::assertEquals("ALTER TABLE cms_users_groups ADD CONSTRAINT FK_7EA9409AFE54D947 FOREIGN KEY (group_id) REFERENCES cms_groups (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql)); + self::assertEquals("ALTER TABLE cms_users_tags ADD CONSTRAINT FK_93F5A1ADA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql)); + self::assertEquals("ALTER TABLE cms_users_tags ADD CONSTRAINT FK_93F5A1ADBAD26311 FOREIGN KEY (tag_id) REFERENCES cms_tags (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql)); + self::assertEquals("ALTER TABLE cms_phonenumbers ADD CONSTRAINT FK_F21F790FA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql)); + + self::assertEquals([], $sql, "SQL Array should be empty now."); + self::assertEquals(22, $sqlCount, "Total of 22 queries should be executed"); } public function testGetCreateSchemaSql2() { $classes = [ - $this->_em->getClassMetadata(Models\Generic\DecimalModel::class) + $this->em->getClassMetadata(Models\Generic\DecimalModel::class) ]; - $tool = new SchemaTool($this->_em); + $tool = new SchemaTool($this->em); $sql = $tool->getCreateSchemaSql($classes); - $this->assertEquals(2, count($sql)); + self::assertEquals(2, count($sql)); - $this->assertEquals('CREATE TABLE decimal_model (id INT NOT NULL, "decimal" NUMERIC(5, 2) NOT NULL, "high_scale" NUMERIC(14, 4) NOT NULL, PRIMARY KEY(id))', $sql[0]); - $this->assertEquals("CREATE SEQUENCE decimal_model_id_seq INCREMENT BY 1 MINVALUE 1 START 1", $sql[1]); + self::assertEquals('CREATE TABLE decimal_model (id INT NOT NULL, "decimal" NUMERIC(5, 2) NOT NULL, "high_scale" NUMERIC(14, 4) NOT NULL, PRIMARY KEY(id))', $sql[0]); + self::assertEquals("CREATE SEQUENCE decimal_model_id_seq INCREMENT BY 1 MINVALUE 1 START 1", $sql[1]); } public function testGetCreateSchemaSql3() { $classes = [ - $this->_em->getClassMetadata(Models\Generic\BooleanModel::class) + $this->em->getClassMetadata(Models\Generic\BooleanModel::class) ]; - $tool = new SchemaTool($this->_em); + $tool = new SchemaTool($this->em); $sql = $tool->getCreateSchemaSql($classes); - $this->assertEquals(2, count($sql)); - $this->assertEquals("CREATE TABLE boolean_model (id INT NOT NULL, booleanField BOOLEAN NOT NULL, PRIMARY KEY(id))", $sql[0]); - $this->assertEquals("CREATE SEQUENCE boolean_model_id_seq INCREMENT BY 1 MINVALUE 1 START 1", $sql[1]); + self::assertEquals(2, count($sql)); + self::assertEquals("CREATE TABLE boolean_model (id INT NOT NULL, booleanField BOOLEAN NOT NULL, PRIMARY KEY(id))", $sql[0]); + self::assertEquals("CREATE SEQUENCE boolean_model_id_seq INCREMENT BY 1 MINVALUE 1 START 1", $sql[1]); } public function testGetDropSchemaSql() { $classes = [ - $this->_em->getClassMetadata(Models\CMS\CmsAddress::class), - $this->_em->getClassMetadata(Models\CMS\CmsUser::class), - $this->_em->getClassMetadata(Models\CMS\CmsPhonenumber::class), + $this->em->getClassMetadata(Models\CMS\CmsAddress::class), + $this->em->getClassMetadata(Models\CMS\CmsUser::class), + $this->em->getClassMetadata(Models\CMS\CmsPhonenumber::class), ]; - $tool = new SchemaTool($this->_em); + $tool = new SchemaTool($this->em); $sql = $tool->getDropSchemaSQL($classes); - $this->assertEquals(17, count($sql)); + self::assertEquals(17, count($sql)); $dropSequenceSQLs = 0; @@ -112,7 +115,7 @@ public function testGetDropSchemaSql() $dropSequenceSQLs++; } } - $this->assertEquals(4, $dropSequenceSQLs, "Expect 4 sequences to be dropped."); + self::assertEquals(4, $dropSequenceSQLs, "Expect 4 sequences to be dropped."); } /** @@ -121,23 +124,23 @@ public function testGetDropSchemaSql() public function testUpdateSchemaWithPostgreSQLSchema() { $classes = [ - $this->_em->getClassMetadata(DDC1657Screen::class), - $this->_em->getClassMetadata(DDC1657Avatar::class), + $this->em->getClassMetadata(DDC1657Screen::class), + $this->em->getClassMetadata(DDC1657Avatar::class), ]; - $tool = new SchemaTool($this->_em); + $tool = new SchemaTool($this->em); $tool->createSchema($classes); $sql = $tool->getUpdateSchemaSql($classes); $sql = array_filter($sql, function($sql) { return (strpos($sql, "DROP SEQUENCE stonewood.") === 0); }); - $this->assertCount(0, $sql, implode("\n", $sql)); + self::assertCount(0, $sql, implode("\n", $sql)); } } /** - * @Entity - * @Table(name="stonewood.screen") + * @ORM\Entity + * @ORM\Table(name="stonewood.screen") */ class DDC1657Screen { @@ -145,9 +148,9 @@ class DDC1657Screen * Identifier * @var int * - * @Id - * @GeneratedValue(strategy="IDENTITY") - * @Column(name="pk", type="integer", nullable=false) + * @ORM\Id + * @ORM\GeneratedValue(strategy="IDENTITY") + * @ORM\Column(name="pk", type="integer", nullable=false) */ private $pk; @@ -155,7 +158,7 @@ class DDC1657Screen * Title * @var string * - * @Column(name="title", type="string", length=255, nullable=false) + * @ORM\Column(name="title", type="string", length=255, nullable=false) */ private $title; @@ -163,31 +166,31 @@ class DDC1657Screen * Path * @var string * - * @Column(name="path", type="string", length=255, nullable=false) + * @ORM\Column(name="path", type="string", length=255, nullable=false) */ private $path; /** * Register date - * @var Date + * @var \DateTime * - * @Column(name="ddate", type="date", nullable=false) + * @ORM\Column(name="ddate", type="date", nullable=false) */ private $ddate; /** * Avatar - * @var Stonewood\Model\Entity\Avatar + * @var DDC1657Avatar * - * @ManyToOne(targetEntity="DDC1657Avatar") - * @JoinColumn(name="pk_avatar", referencedColumnName="pk", nullable=true, onDelete="CASCADE") + * @ORM\ManyToOne(targetEntity="DDC1657Avatar") + * @ORM\JoinColumn(name="pk_avatar", referencedColumnName="pk", nullable=true, onDelete="CASCADE") */ private $avatar; } /** - * @Entity - * @Table(name="stonewood.avatar") + * @ORM\Entity + * @ORM\Table(name="stonewood.avatar") */ class DDC1657Avatar { @@ -195,9 +198,9 @@ class DDC1657Avatar * Identifier * @var int * - * @Id - * @GeneratedValue(strategy="IDENTITY") - * @Column(name="pk", type="integer", nullable=false) + * @ORM\Id + * @ORM\GeneratedValue(strategy="IDENTITY") + * @ORM\Column(name="pk", type="integer", nullable=false) */ private $pk; } diff --git a/tests/Doctrine/Tests/ORM/Functional/SchemaValidatorTest.php b/tests/Doctrine/Tests/ORM/Functional/SchemaValidatorTest.php index 5ab0f07c07e..b139b48c8b1 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaValidatorTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaValidatorTest.php @@ -1,5 +1,7 @@ _em); - $classes = []; + $validator = new SchemaValidator($this->em); + $classes = []; - foreach (self::$_modelSets[$modelSet] as $className) { - $classes[] = $this->_em->getClassMetadata($className); + foreach (self::$modelSets[$modelSet] as $className) { + $classes[] = $this->em->getClassMetadata($className); } foreach ($classes as $class) { $ce = $validator->validateClass($class); - $this->assertEmpty($ce, "Invalid Modelset: " . $modelSet . " class " . $class->name . ": ". implode("\n", $ce)); + self::assertEmpty($ce, "Invalid Modelset: " . $modelSet . " class " . $class->getClassName() . ": ". implode("\n", $ce)); } } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheAbstractTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheAbstractTest.php index becf7edbb4d..7138dbd6dbb 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheAbstractTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheAbstractTest.php @@ -1,5 +1,7 @@ cache = $this->_em->getCache(); + $this->cache = $this->em->getCache(); } protected function loadFixturesCountries() @@ -62,9 +64,9 @@ protected function loadFixturesCountries() $this->countries[] = $brazil; $this->countries[] = $germany; - $this->_em->persist($brazil); - $this->_em->persist($germany); - $this->_em->flush(); + $this->em->persist($brazil); + $this->em->persist($germany); + $this->em->flush(); } protected function loadFixturesStates() @@ -79,12 +81,12 @@ protected function loadFixturesStates() $this->states[] = $bavaria; $this->states[] = $berlin; - $this->_em->persist($saopaulo); - $this->_em->persist($rio); - $this->_em->persist($bavaria); - $this->_em->persist($berlin); + $this->em->persist($saopaulo); + $this->em->persist($rio); + $this->em->persist($bavaria); + $this->em->persist($berlin); - $this->_em->flush(); + $this->em->flush(); } protected function loadFixturesCities() @@ -104,12 +106,12 @@ protected function loadFixturesCities() $this->cities[] = $munich; $this->cities[] = $berlin; - $this->_em->persist($saopaulo); - $this->_em->persist($rio); - $this->_em->persist($munich); - $this->_em->persist($berlin); + $this->em->persist($saopaulo); + $this->em->persist($rio); + $this->em->persist($munich); + $this->em->persist($berlin); - $this->_em->flush(); + $this->em->flush(); } protected function loadFixturesTraveler() @@ -117,13 +119,13 @@ protected function loadFixturesTraveler() $t1 = new Traveler("Fabio Silva"); $t2 = new Traveler("Doctrine Bot"); - $this->_em->persist($t1); - $this->_em->persist($t2); + $this->em->persist($t1); + $this->em->persist($t2); $this->travelers[] = $t1; $this->travelers[] = $t2; - $this->_em->flush(); + $this->em->flush(); } protected function loadFixturesTravelersWithProfile() @@ -136,15 +138,15 @@ protected function loadFixturesTravelersWithProfile() $t1->setProfile($p1); $t2->setProfile($p2); - $this->_em->persist($p1); - $this->_em->persist($p2); - $this->_em->persist($t1); - $this->_em->persist($t2); + $this->em->persist($p1); + $this->em->persist($p2); + $this->em->persist($t1); + $this->em->persist($t2); $this->travelersWithProfile[] = $t1; $this->travelersWithProfile[] = $t2; - $this->_em->flush(); + $this->em->flush(); } protected function loadFixturesTravelersProfileInfo() @@ -157,12 +159,12 @@ protected function loadFixturesTravelersProfileInfo() $p1->setInfo($i1); $p2->setInfo($i2); - $this->_em->persist($i1); - $this->_em->persist($i2); - $this->_em->persist($p1); - $this->_em->persist($p2); + $this->em->persist($i1); + $this->em->persist($i2); + $this->em->persist($p1); + $this->em->persist($p2); - $this->_em->flush(); + $this->em->flush(); } protected function loadFixturesTravels() @@ -178,15 +180,15 @@ protected function loadFixturesTravels() $t2->addVisitedCity($this->cities[1]); $t2->addVisitedCity($this->cities[3]); - $this->_em->persist($t1); - $this->_em->persist($t2); - $this->_em->persist($t3); + $this->em->persist($t1); + $this->em->persist($t2); + $this->em->persist($t3); $this->travels[] = $t1; $this->travels[] = $t2; $this->travels[] = $t3; - $this->_em->flush(); + $this->em->flush(); } protected function loadFixturesAttractions() @@ -208,10 +210,10 @@ protected function loadFixturesAttractions() $this->cities[3]->addAttraction($this->attractions[6]); foreach ($this->attractions as $attraction) { - $this->_em->persist($attraction); + $this->em->persist($attraction); } - $this->_em->flush(); + $this->em->flush(); } protected function loadFixturesAttractionsInfo() @@ -222,10 +224,10 @@ protected function loadFixturesAttractionsInfo() $this->attractionsInfo[] = new AttractionLocationInfo('Some St 2', $this->attractions[3]); foreach ($this->attractionsInfo as $info) { - $this->_em->persist($info); + $this->em->persist($info); } - $this->_em->flush(); + $this->em->flush(); } protected function loadFixturesPersonWithAddress() @@ -249,14 +251,14 @@ protected function loadFixturesPersonWithAddress() $this->addresses[] = $address2; foreach ($this->people as $person) { - $this->_em->persist($person); + $this->em->persist($person); } foreach ($this->addresses as $address) { - $this->_em->persist($address); + $this->em->persist($address); } - $this->_em->flush(); + $this->em->flush(); } protected function getEntityRegion($className) diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyTest.php index 9dff7df1d1c..94ee7767bc0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyTest.php @@ -1,5 +1,7 @@ loadFixturesStates(); $this->loadFixturesCities(); - $this->_em->clear(); + $this->em->clear(); $this->evictRegions(); $leavingFromId = $this->cities[0]->getId(); $goingToId = $this->cities[1]->getId(); - $leavingFrom = $this->_em->find(City::class, $leavingFromId); - $goingTo = $this->_em->find(City::class, $goingToId); + $leavingFrom = $this->em->find(City::class, $leavingFromId); + $goingTo = $this->em->find(City::class, $goingToId); $flight = new Flight($leavingFrom, $goingTo); $id = [ 'leavingFrom' => $leavingFromId, @@ -31,29 +33,29 @@ public function testPutAndLoadCompositPrimaryKeyEntities() $flight->setDeparture(new \DateTime('tomorrow')); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); - $this->_em->persist($flight); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($flight); + $this->em->flush(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Flight::class, $id)); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + self::assertTrue($this->cache->containsEntity(Flight::class, $id)); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); $queryCount = $this->getCurrentQueryCount(); - $flight = $this->_em->find(Flight::class, $id); + $flight = $this->em->find(Flight::class, $id); $leavingFrom = $flight->getLeavingFrom(); $goingTo = $flight->getGoingTo(); - $this->assertInstanceOf(Flight::class, $flight); - $this->assertInstanceOf(City::class, $goingTo); - $this->assertInstanceOf(City::class, $leavingFrom); + self::assertInstanceOf(Flight::class, $flight); + self::assertInstanceOf(City::class, $goingTo); + self::assertInstanceOf(City::class, $leavingFrom); - $this->assertEquals($goingTo->getId(), $goingToId); - $this->assertEquals($leavingFrom->getId(), $leavingFromId); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($goingTo->getId(), $goingToId); + self::assertEquals($leavingFrom->getId(), $leavingFromId); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); } public function testRemoveCompositPrimaryKeyEntities() @@ -62,13 +64,13 @@ public function testRemoveCompositPrimaryKeyEntities() $this->loadFixturesStates(); $this->loadFixturesCities(); - $this->_em->clear(); + $this->em->clear(); $this->evictRegions(); $leavingFromId = $this->cities[0]->getId(); $goingToId = $this->cities[1]->getId(); - $leavingFrom = $this->_em->find(City::class, $leavingFromId); - $goingTo = $this->_em->find(City::class, $goingToId); + $leavingFrom = $this->em->find(City::class, $leavingFromId); + $goingTo = $this->em->find(City::class, $goingToId); $flight = new Flight($leavingFrom, $goingTo); $id = [ 'leavingFrom' => $leavingFromId, @@ -77,25 +79,25 @@ public function testRemoveCompositPrimaryKeyEntities() $flight->setDeparture(new \DateTime('tomorrow')); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); - $this->_em->persist($flight); - $this->_em->flush(); + $this->em->persist($flight); + $this->em->flush(); - $this->assertTrue($this->cache->containsEntity(Flight::class, $id)); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + self::assertTrue($this->cache->containsEntity(Flight::class, $id)); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); - $this->_em->remove($flight); - $this->_em->flush(); - $this->_em->clear(); + $this->em->remove($flight); + $this->em->flush(); + $this->em->clear(); - $this->assertFalse($this->cache->containsEntity(Flight::class, $id)); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + self::assertFalse($this->cache->containsEntity(Flight::class, $id)); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); - $this->assertNull($this->_em->find(Flight::class, $id)); + self::assertNull($this->em->find(Flight::class, $id)); } public function testUpdateCompositPrimaryKeyEntities() @@ -104,15 +106,15 @@ public function testUpdateCompositPrimaryKeyEntities() $this->loadFixturesStates(); $this->loadFixturesCities(); - $this->_em->clear(); + $this->em->clear(); $this->evictRegions(); $now = new \DateTime('now'); $tomorrow = new \DateTime('tomorrow'); $leavingFromId = $this->cities[0]->getId(); $goingToId = $this->cities[1]->getId(); - $leavingFrom = $this->_em->find(City::class, $leavingFromId); - $goingTo = $this->_em->find(City::class, $goingToId); + $leavingFrom = $this->em->find(City::class, $leavingFromId); + $goingTo = $this->em->find(City::class, $goingToId); $flight = new Flight($leavingFrom, $goingTo); $id = [ 'leavingFrom' => $leavingFromId, @@ -121,55 +123,55 @@ public function testUpdateCompositPrimaryKeyEntities() $flight->setDeparture($now); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); - $this->_em->persist($flight); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($flight); + $this->em->flush(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Flight::class, $id)); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + self::assertTrue($this->cache->containsEntity(Flight::class, $id)); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); $queryCount = $this->getCurrentQueryCount(); - $flight = $this->_em->find(Flight::class, $id); + $flight = $this->em->find(Flight::class, $id); $leavingFrom = $flight->getLeavingFrom(); $goingTo = $flight->getGoingTo(); - $this->assertInstanceOf(Flight::class, $flight); - $this->assertInstanceOf(City::class, $goingTo); - $this->assertInstanceOf(City::class, $leavingFrom); + self::assertInstanceOf(Flight::class, $flight); + self::assertInstanceOf(City::class, $goingTo); + self::assertInstanceOf(City::class, $leavingFrom); - $this->assertEquals($goingTo->getId(), $goingToId); - $this->assertEquals($flight->getDeparture(), $now); - $this->assertEquals($leavingFrom->getId(), $leavingFromId); - $this->assertEquals($leavingFrom->getId(), $leavingFromId); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($goingTo->getId(), $goingToId); + self::assertEquals($flight->getDeparture(), $now); + self::assertEquals($leavingFrom->getId(), $leavingFromId); + self::assertEquals($leavingFrom->getId(), $leavingFromId); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); $flight->setDeparture($tomorrow); - $this->_em->persist($flight); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($flight); + $this->em->flush(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Flight::class, $id)); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + self::assertTrue($this->cache->containsEntity(Flight::class, $id)); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); $queryCount = $this->getCurrentQueryCount(); - $flight = $this->_em->find(Flight::class, $id); + $flight = $this->em->find(Flight::class, $id); $leavingFrom = $flight->getLeavingFrom(); $goingTo = $flight->getGoingTo(); - $this->assertInstanceOf(Flight::class, $flight); - $this->assertInstanceOf(City::class, $goingTo); - $this->assertInstanceOf(City::class, $leavingFrom); + self::assertInstanceOf(Flight::class, $flight); + self::assertInstanceOf(City::class, $goingTo); + self::assertInstanceOf(City::class, $leavingFrom); - $this->assertEquals($goingTo->getId(), $goingToId); - $this->assertEquals($flight->getDeparture(), $tomorrow); - $this->assertEquals($leavingFrom->getId(), $leavingFromId); - $this->assertEquals($leavingFrom->getId(), $leavingFromId); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($goingTo->getId(), $goingToId); + self::assertEquals($flight->getDeparture(), $tomorrow); + self::assertEquals($leavingFrom->getId(), $leavingFromId); + self::assertEquals($leavingFrom->getId(), $leavingFromId); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyWithAssociationsTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyWithAssociationsTest.php index 8af09c9bf0d..fd186a7632a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyWithAssociationsTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyWithAssociationsTest.php @@ -1,5 +1,7 @@ useModelSet('geonames'); parent::setUp(); - $this->cache = $this->_em->getCache(); + $this->cache = $this->em->getCache(); $it = new Country("IT", "Italy"); - $this->_em->persist($it); - $this->_em->flush(); + $this->em->persist($it); + $this->em->flush(); $admin1 = new Admin1(1, "Rome", $it); - $this->_em->persist($admin1); - $this->_em->flush(); + $this->em->persist($admin1); + $this->em->flush(); $name1 = new Admin1AlternateName(1, "Roma", $admin1); $name2 = new Admin1AlternateName(2, "Rome", $admin1); @@ -39,37 +41,37 @@ public function setUp() $admin1->names[] = $name1; $admin1->names[] = $name2; - $this->_em->persist($admin1); - $this->_em->persist($name1); - $this->_em->persist($name2); + $this->em->persist($admin1); + $this->em->persist($name1); + $this->em->persist($name2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $this->evictRegions(); } public function testFindByReturnsCachedEntity() { - $admin1Repo = $this->_em->getRepository(Admin1::class); + $admin1Repo = $this->em->getRepository(Admin1::class); $queries = $this->getCurrentQueryCount(); $admin1Rome = $admin1Repo->findOneBy(['country' => 'IT', 'id' => 1]); - $this->assertEquals("Italy", $admin1Rome->country->name); - $this->assertEquals(2, count($admin1Rome->names)); - $this->assertEquals($queries + 3, $this->getCurrentQueryCount()); + self::assertEquals("Italy", $admin1Rome->country->name); + self::assertEquals(2, count($admin1Rome->names)); + self::assertEquals($queries + 3, $this->getCurrentQueryCount()); - $this->_em->clear(); + $this->em->clear(); $queries = $this->getCurrentQueryCount(); $admin1Rome = $admin1Repo->findOneBy(['country' => 'IT', 'id' => 1]); - $this->assertEquals("Italy", $admin1Rome->country->name); - $this->assertEquals(2, count($admin1Rome->names)); - $this->assertEquals($queries, $this->getCurrentQueryCount()); + self::assertEquals("Italy", $admin1Rome->country->name); + self::assertEquals(2, count($admin1Rome->names)); + self::assertEquals($queries, $this->getCurrentQueryCount()); } private function evictRegions() diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheConcurrentTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheConcurrentTest.php index 0f4ca383284..f09b3246b0b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheConcurrentTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheConcurrentTest.php @@ -1,8 +1,12 @@ enableSecondLevelCache(); + parent::setUp(); $this->cacheFactory = new CacheFactorySecondLevelCacheConcurrentTest($this->getSharedSecondLevelCacheDriverImpl()); - $this->_em->getConfiguration() + $this->em->getConfiguration() ->getSecondLevelCacheConfiguration() ->setCacheFactory($this->cacheFactory); - $this->countryMetadata = $this->_em->getClassMetadata(Country::class); - $countryMetadata = clone $this->countryMetadata; - - $countryMetadata->cache['usage'] = ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE; + $this->countryMetadata = clone $this->em->getClassMetadata(Country::class); - $this->_em->getMetadataFactory()->setMetadataFor(Country::class, $countryMetadata); - } - - protected function tearDown() - { - parent::tearDown(); - - $this->_em->getMetadataFactory()->setMetadataFor(Country::class, $this->countryMetadata); + $this->countryMetadata->setCache( + new CacheMetadata( + CacheUsage::NONSTRICT_READ_WRITE, + 'doctrine_tests_models_cache_country' + ) + ); } public function testBasicConcurrentEntityReadLock() { $this->loadFixturesCountries(); - $this->_em->clear(); + $this->em->clear(); $countryId = $this->countries[0]->getId(); $cacheId = new EntityCacheKey(Country::class, ['id'=>$countryId]); - $region = $this->_em->getCache()->getEntityCacheRegion(Country::class); + $region = $this->em->getCache()->getEntityCacheRegion(Country::class); - $this->assertTrue($this->cache->containsEntity(Country::class, $countryId)); + self::assertTrue($this->cache->containsEntity(Country::class, $countryId)); /** @var \Doctrine\Tests\Mocks\ConcurrentRegionMock */ $region->setLock($cacheId, Lock::createLockRead()); // another proc lock the entity cache - $this->assertFalse($this->cache->containsEntity(Country::class, $countryId)); + self::assertFalse($this->cache->containsEntity(Country::class, $countryId)); $queryCount = $this->getCurrentQueryCount(); - $country = $this->_em->find(Country::class, $countryId); + $country = $this->em->find(Country::class, $countryId); - $this->assertInstanceOf(Country::class, $country); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertFalse($this->cache->containsEntity(Country::class, $countryId)); + self::assertInstanceOf(Country::class, $country); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertFalse($this->cache->containsEntity(Country::class, $countryId)); } public function testBasicConcurrentCollectionReadLock() @@ -82,62 +82,64 @@ public function testBasicConcurrentCollectionReadLock() $this->loadFixturesStates(); $this->loadFixturesCities(); - $this->_em->clear(); + $this->em->clear(); $this->evictRegions(); $stateId = $this->states[0]->getId(); - $state = $this->_em->find(State::class, $stateId); + $state = $this->em->find(State::class, $stateId); - $this->assertInstanceOf(State::class, $state); - $this->assertInstanceOf(Country::class, $state->getCountry()); - $this->assertNotNull($state->getCountry()->getName()); - $this->assertCount(2, $state->getCities()); + self::assertInstanceOf(State::class, $state); + self::assertInstanceOf(Country::class, $state->getCountry()); + self::assertNotNull($state->getCountry()->getName()); + self::assertCount(2, $state->getCities()); - $this->_em->clear(); + $this->em->clear(); $this->secondLevelCacheLogger->clearStats(); $stateId = $this->states[0]->getId(); $cacheId = new CollectionCacheKey(State::class, 'cities', ['id'=>$stateId]); - $region = $this->_em->getCache()->getCollectionCacheRegion(State::class, 'cities'); + $region = $this->em->getCache()->getCollectionCacheRegion(State::class, 'cities'); - $this->assertTrue($this->cache->containsCollection(State::class, 'cities', $stateId)); + self::assertTrue($this->cache->containsCollection(State::class, 'cities', $stateId)); /* @var $region \Doctrine\Tests\Mocks\ConcurrentRegionMock */ $region->setLock($cacheId, Lock::createLockRead()); // another proc lock the entity cache - $this->assertFalse($this->cache->containsCollection(State::class, 'cities', $stateId)); + self::assertFalse($this->cache->containsCollection(State::class, 'cities', $stateId)); $queryCount = $this->getCurrentQueryCount(); - $state = $this->_em->find(State::class, $stateId); + $state = $this->em->find(State::class, $stateId); - $this->assertEquals(0, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(0, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(0, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(State::class))); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); + self::assertEquals(0, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(State::class))); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); - $this->assertInstanceOf(State::class, $state); - $this->assertCount(2, $state->getCities()); + self::assertInstanceOf(State::class, $state); + self::assertCount(2, $state->getCities()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(State::class, 'cities'))); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(State::class, 'cities'))); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertFalse($this->cache->containsCollection(State::class, 'cities', $stateId)); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertFalse($this->cache->containsCollection(State::class, 'cities', $stateId)); } } class CacheFactorySecondLevelCacheConcurrentTest extends DefaultCacheFactory { + private $cache; + public function __construct(Cache $cache) { $this->cache = $cache; } - public function getRegion(array $cache) + public function getRegion(CacheMetadata $cache) { - $region = new DefaultRegion($cache['region'], $this->cache); + $region = new DefaultRegion($cache->getRegion(), $this->cache); $mock = new ConcurrentRegionMock($region); return $mock; diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCriteriaTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCriteriaTest.php index 17d0ac7fc7e..75a7faf6d57 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCriteriaTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCriteriaTest.php @@ -1,5 +1,7 @@ loadFixturesCountries(); $this->evictRegions(); - $this->_em->clear(); + $this->em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $repository = $this->_em->getRepository(Country::class); + $repository = $this->em->getRepository(Country::class); $queryCount = $this->getCurrentQueryCount(); $name = $this->countries[0]->getName(); $result1 = $repository->matching(new Criteria( @@ -32,25 +34,25 @@ public function testMatchingPut() // Because matching returns lazy collection, we force initialization $result1->toArray(); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertEquals($this->countries[0]->getId(), $result1[0]->getId()); - $this->assertEquals($this->countries[0]->getName(), $result1[0]->getName()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals($this->countries[0]->getId(), $result1[0]->getId()); + self::assertEquals($this->countries[0]->getName(), $result1[0]->getName()); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->_em->clear(); + $this->em->clear(); $result2 = $repository->matching(new Criteria( Criteria::expr()->eq('name', $name) )); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertCount(1, $result2); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(1, $result2); - $this->assertInstanceOf(Country::class, $result2[0]); + self::assertInstanceOf(Country::class, $result2[0]); - $this->assertEquals($result1[0]->getId(), $result2[0]->getId()); - $this->assertEquals($result1[0]->getName(), $result2[0]->getName()); + self::assertEquals($result1[0]->getId(), $result2[0]->getId()); + self::assertEquals($result1[0]->getName(), $result2[0]->getName()); } public function testRepositoryMatching() @@ -58,11 +60,11 @@ public function testRepositoryMatching() $this->evictRegions(); $this->loadFixturesCountries(); - $this->_em->clear(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $repository = $this->_em->getRepository(Country::class); + $repository = $this->em->getRepository(Country::class); $queryCount = $this->getCurrentQueryCount(); $result1 = $repository->matching(new Criteria( Criteria::expr()->eq('name', $this->countries[0]->getName()) @@ -71,12 +73,12 @@ public function testRepositoryMatching() // Because matching returns lazy collection, we force initialization $result1->toArray(); - $this->assertCount(1, $result1); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertEquals($this->countries[0]->getId(), $result1[0]->getId()); - $this->assertEquals($this->countries[0]->getName(), $result1[0]->getName()); + self::assertCount(1, $result1); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals($this->countries[0]->getId(), $result1[0]->getId()); + self::assertEquals($this->countries[0]->getName(), $result1[0]->getName()); - $this->_em->clear(); + $this->em->clear(); $result2 = $repository->matching(new Criteria( Criteria::expr()->eq('name', $this->countries[0]->getName()) @@ -85,13 +87,13 @@ public function testRepositoryMatching() // Because matching returns lazy collection, we force initialization $result2->toArray(); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertCount(1, $result2); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(1, $result2); - $this->assertInstanceOf(Country::class, $result2[0]); + self::assertInstanceOf(Country::class, $result2[0]); - $this->assertEquals($this->countries[0]->getId(), $result2[0]->getId()); - $this->assertEquals($this->countries[0]->getName(), $result2[0]->getName()); + self::assertEquals($this->countries[0]->getId(), $result2[0]->getId()); + self::assertEquals($this->countries[0]->getName(), $result2[0]->getName()); $result3 = $repository->matching(new Criteria( Criteria::expr()->eq('name', $this->countries[1]->getName()) @@ -100,25 +102,25 @@ public function testRepositoryMatching() // Because matching returns lazy collection, we force initialization $result3->toArray(); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); - $this->assertCount(1, $result3); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + self::assertCount(1, $result3); - $this->assertInstanceOf(Country::class, $result3[0]); + self::assertInstanceOf(Country::class, $result3[0]); - $this->assertEquals($this->countries[1]->getId(), $result3[0]->getId()); - $this->assertEquals($this->countries[1]->getName(), $result3[0]->getName()); + self::assertEquals($this->countries[1]->getId(), $result3[0]->getId()); + self::assertEquals($this->countries[1]->getName(), $result3[0]->getName()); $result4 = $repository->matching(new Criteria( Criteria::expr()->eq('name', $this->countries[1]->getName()) )); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); - $this->assertCount(1, $result4); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + self::assertCount(1, $result4); - $this->assertInstanceOf(Country::class, $result4[0]); + self::assertInstanceOf(Country::class, $result4[0]); - $this->assertEquals($this->countries[1]->getId(), $result4[0]->getId()); - $this->assertEquals($this->countries[1]->getName(), $result4[0]->getName()); + self::assertEquals($this->countries[1]->getId(), $result4[0]->getId()); + self::assertEquals($this->countries[1]->getName(), $result4[0]->getName()); } public function testCollectionMatching() @@ -126,10 +128,10 @@ public function testCollectionMatching() $this->loadFixturesCountries(); $this->loadFixturesStates(); $this->loadFixturesCities(); - $this->_em->clear(); + $this->em->clear(); $this->secondLevelCacheLogger->clearStats(); - $entity = $this->_em->find(State::class, $this->states[0]->getId()); + $entity = $this->em->find(State::class, $this->states[0]->getId()); $itemName = $this->states[0]->getCities()->get(0)->getName(); $queryCount = $this->getCurrentQueryCount(); $collection = $entity->getCities(); @@ -137,22 +139,22 @@ public function testCollectionMatching() Criteria::expr()->eq('name', $itemName) )); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf(Collection::class, $matching); - $this->assertCount(1, $matching); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertInstanceOf(Collection::class, $matching); + self::assertCount(1, $matching); - $this->_em->clear(); + $this->em->clear(); - $entity = $this->_em->find(State::class, $this->states[0]->getId()); + $entity = $this->em->find(State::class, $this->states[0]->getId()); $queryCount = $this->getCurrentQueryCount(); $collection = $entity->getCities(); $matching = $collection->matching(new Criteria( Criteria::expr()->eq('name', $itemName) )); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(Collection::class, $matching); - $this->assertCount(1, $matching); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertInstanceOf(Collection::class, $matching); + self::assertCount(1, $matching); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheExtraLazyCollectionTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheExtraLazyCollectionTest.php index 75499ac302c..f709ea4132a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheExtraLazyCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheExtraLazyCollectionTest.php @@ -1,7 +1,10 @@ _em->getClassMetadata(Travel::class); - $targetEntity = $this->_em->getClassMetadata(City::class); + $sourceEntity = $this->em->getClassMetadata(Travel::class); + $targetEntity = $this->em->getClassMetadata(City::class); - $sourceEntity->associationMappings['visitedCities']['fetch'] = ClassMetadata::FETCH_EXTRA_LAZY; - $targetEntity->associationMappings['travels']['fetch'] = ClassMetadata::FETCH_EXTRA_LAZY; + $sourceEntity->getProperty('visitedCities')->setFetchMode(FetchMode::EXTRA_LAZY); + $targetEntity->getProperty('travels')->setFetchMode(FetchMode::EXTRA_LAZY); } public function tearDown() { parent::tearDown(); - $sourceEntity = $this->_em->getClassMetadata(Travel::class); - $targetEntity = $this->_em->getClassMetadata(City::class); + $sourceEntity = $this->em->getClassMetadata(Travel::class); + $targetEntity = $this->em->getClassMetadata(City::class); - $sourceEntity->associationMappings['visitedCities']['fetch'] = ClassMetadata::FETCH_LAZY; - $targetEntity->associationMappings['travels']['fetch'] = ClassMetadata::FETCH_LAZY; + $sourceEntity->getProperty('visitedCities')->setFetchMode(FetchMode::LAZY); + $targetEntity->getProperty('travels')->setFetchMode(FetchMode::LAZY); } public function testCacheCountAfterAddThenFlush() @@ -42,40 +45,40 @@ public function testCacheCountAfterAddThenFlush() $this->loadFixturesTraveler(); $this->loadFixturesTravels(); - $this->_em->clear(); + $this->em->clear(); $ownerId = $this->travels[0]->getId(); - $owner = $this->_em->find(Travel::class, $ownerId); - $ref = $this->_em->find(State::class, $this->states[1]->getId()); + $owner = $this->em->find(Travel::class, $ownerId); + $ref = $this->em->find(State::class, $this->states[1]->getId()); - $this->assertTrue($this->cache->containsEntity(Travel::class, $ownerId)); - $this->assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $ownerId)); + self::assertTrue($this->cache->containsEntity(Travel::class, $ownerId)); + self::assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $ownerId)); $newItem = new City("New City", $ref); $owner->getVisitedCities()->add($newItem); - $this->_em->persist($newItem); - $this->_em->persist($owner); + $this->em->persist($newItem); + $this->em->persist($owner); $queryCount = $this->getCurrentQueryCount(); - $this->assertFalse($owner->getVisitedCities()->isInitialized()); - $this->assertEquals(4, $owner->getVisitedCities()->count()); - $this->assertFalse($owner->getVisitedCities()->isInitialized()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertFalse($owner->getVisitedCities()->isInitialized()); + self::assertEquals(4, $owner->getVisitedCities()->count()); + self::assertFalse($owner->getVisitedCities()->isInitialized()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->_em->flush(); + $this->em->flush(); - $this->assertFalse($owner->getVisitedCities()->isInitialized()); - $this->assertFalse($this->cache->containsCollection(Travel::class, 'visitedCities', $ownerId)); + self::assertFalse($owner->getVisitedCities()->isInitialized()); + self::assertFalse($this->cache->containsCollection(Travel::class, 'visitedCities', $ownerId)); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); - $owner = $this->_em->find(Travel::class, $ownerId); + $owner = $this->em->find(Travel::class, $ownerId); - $this->assertEquals(4, $owner->getVisitedCities()->count()); - $this->assertFalse($owner->getVisitedCities()->isInitialized()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals(4, $owner->getVisitedCities()->count()); + self::assertFalse($owner->getVisitedCities()->isInitialized()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheJoinTableInheritanceTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheJoinTableInheritanceTest.php index f9b9542444e..3abd5308b1c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheJoinTableInheritanceTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheJoinTableInheritanceTest.php @@ -1,5 +1,7 @@ cache->getEntityCacheRegion(AttractionContactInfo::class); $locationRegion = $this->cache->getEntityCacheRegion(AttractionLocationInfo::class); - $this->assertEquals($infoRegion->getName(), $contactRegion->getName()); - $this->assertEquals($infoRegion->getName(), $locationRegion->getName()); + self::assertEquals($infoRegion->getName(), $contactRegion->getName()); + self::assertEquals($infoRegion->getName(), $locationRegion->getName()); } public function testPutOnPersistJoinTableInheritance() @@ -31,12 +33,12 @@ public function testPutOnPersistJoinTableInheritance() $this->loadFixturesAttractions(); $this->loadFixturesAttractionsInfo(); - $this->_em->clear(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(AttractionInfo::class, $this->attractionsInfo[0]->getId())); - $this->assertTrue($this->cache->containsEntity(AttractionInfo::class, $this->attractionsInfo[1]->getId())); - $this->assertTrue($this->cache->containsEntity(AttractionInfo::class, $this->attractionsInfo[2]->getId())); - $this->assertTrue($this->cache->containsEntity(AttractionInfo::class, $this->attractionsInfo[3]->getId())); + self::assertTrue($this->cache->containsEntity(AttractionInfo::class, $this->attractionsInfo[0]->getId())); + self::assertTrue($this->cache->containsEntity(AttractionInfo::class, $this->attractionsInfo[1]->getId())); + self::assertTrue($this->cache->containsEntity(AttractionInfo::class, $this->attractionsInfo[2]->getId())); + self::assertTrue($this->cache->containsEntity(AttractionInfo::class, $this->attractionsInfo[3]->getId())); } public function testJoinTableCountaisRootClass() @@ -47,11 +49,11 @@ public function testJoinTableCountaisRootClass() $this->loadFixturesAttractions(); $this->loadFixturesAttractionsInfo(); - $this->_em->clear(); + $this->em->clear(); foreach ($this->attractionsInfo as $info) { - $this->assertTrue($this->cache->containsEntity(AttractionInfo::class, $info->getId())); - $this->assertTrue($this->cache->containsEntity(get_class($info), $info->getId())); + self::assertTrue($this->cache->containsEntity(AttractionInfo::class, $info->getId())); + self::assertTrue($this->cache->containsEntity(get_class($info), $info->getId())); } } @@ -63,61 +65,61 @@ public function testPutAndLoadJoinTableEntities() $this->loadFixturesAttractions(); $this->loadFixturesAttractionsInfo(); - $this->_em->clear(); + $this->em->clear(); $this->cache->evictEntityRegion(AttractionInfo::class); $entityId1 = $this->attractionsInfo[0]->getId(); $entityId2 = $this->attractionsInfo[1]->getId(); - $this->assertFalse($this->cache->containsEntity(AttractionInfo::class, $entityId1)); - $this->assertFalse($this->cache->containsEntity(AttractionInfo::class, $entityId2)); - $this->assertFalse($this->cache->containsEntity(AttractionContactInfo::class, $entityId1)); - $this->assertFalse($this->cache->containsEntity(AttractionContactInfo::class, $entityId2)); + self::assertFalse($this->cache->containsEntity(AttractionInfo::class, $entityId1)); + self::assertFalse($this->cache->containsEntity(AttractionInfo::class, $entityId2)); + self::assertFalse($this->cache->containsEntity(AttractionContactInfo::class, $entityId1)); + self::assertFalse($this->cache->containsEntity(AttractionContactInfo::class, $entityId2)); $queryCount = $this->getCurrentQueryCount(); - $entity1 = $this->_em->find(AttractionInfo::class, $entityId1); - $entity2 = $this->_em->find(AttractionInfo::class, $entityId2); + $entity1 = $this->em->find(AttractionInfo::class, $entityId1); + $entity2 = $this->em->find(AttractionInfo::class, $entityId2); //load entity and relation whit sub classes - $this->assertEquals($queryCount + 4, $this->getCurrentQueryCount()); + self::assertEquals($queryCount + 4, $this->getCurrentQueryCount()); - $this->assertTrue($this->cache->containsEntity(AttractionInfo::class, $entityId1)); - $this->assertTrue($this->cache->containsEntity(AttractionInfo::class, $entityId2)); - $this->assertTrue($this->cache->containsEntity(AttractionContactInfo::class, $entityId1)); - $this->assertTrue($this->cache->containsEntity(AttractionContactInfo::class, $entityId2)); + self::assertTrue($this->cache->containsEntity(AttractionInfo::class, $entityId1)); + self::assertTrue($this->cache->containsEntity(AttractionInfo::class, $entityId2)); + self::assertTrue($this->cache->containsEntity(AttractionContactInfo::class, $entityId1)); + self::assertTrue($this->cache->containsEntity(AttractionContactInfo::class, $entityId2)); - $this->assertInstanceOf(AttractionInfo::class, $entity1); - $this->assertInstanceOf(AttractionInfo::class, $entity2); - $this->assertInstanceOf(AttractionContactInfo::class, $entity1); - $this->assertInstanceOf(AttractionContactInfo::class, $entity2); + self::assertInstanceOf(AttractionInfo::class, $entity1); + self::assertInstanceOf(AttractionInfo::class, $entity2); + self::assertInstanceOf(AttractionContactInfo::class, $entity1); + self::assertInstanceOf(AttractionContactInfo::class, $entity2); - $this->assertEquals($this->attractionsInfo[0]->getId(), $entity1->getId()); - $this->assertEquals($this->attractionsInfo[0]->getFone(), $entity1->getFone()); + self::assertEquals($this->attractionsInfo[0]->getId(), $entity1->getId()); + self::assertEquals($this->attractionsInfo[0]->getFone(), $entity1->getFone()); - $this->assertEquals($this->attractionsInfo[1]->getId(), $entity2->getId()); - $this->assertEquals($this->attractionsInfo[1]->getFone(), $entity2->getFone()); + self::assertEquals($this->attractionsInfo[1]->getId(), $entity2->getId()); + self::assertEquals($this->attractionsInfo[1]->getFone(), $entity2->getFone()); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); - $entity3 = $this->_em->find(AttractionInfo::class, $entityId1); - $entity4 = $this->_em->find(AttractionInfo::class, $entityId2); + $entity3 = $this->em->find(AttractionInfo::class, $entityId1); + $entity4 = $this->em->find(AttractionInfo::class, $entityId2); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(AttractionInfo::class, $entity3); - $this->assertInstanceOf(AttractionInfo::class, $entity4); - $this->assertInstanceOf(AttractionContactInfo::class, $entity3); - $this->assertInstanceOf(AttractionContactInfo::class, $entity4); + self::assertInstanceOf(AttractionInfo::class, $entity3); + self::assertInstanceOf(AttractionInfo::class, $entity4); + self::assertInstanceOf(AttractionContactInfo::class, $entity3); + self::assertInstanceOf(AttractionContactInfo::class, $entity4); - $this->assertNotSame($entity1, $entity3); - $this->assertEquals($entity1->getId(), $entity3->getId()); - $this->assertEquals($entity1->getFone(), $entity3->getFone()); + self::assertNotSame($entity1, $entity3); + self::assertEquals($entity1->getId(), $entity3->getId()); + self::assertEquals($entity1->getFone(), $entity3->getFone()); - $this->assertNotSame($entity2, $entity4); - $this->assertEquals($entity2->getId(), $entity4->getId()); - $this->assertEquals($entity2->getFone(), $entity4->getFone()); + self::assertNotSame($entity2, $entity4); + self::assertEquals($entity2->getId(), $entity4->getId()); + self::assertEquals($entity2->getFone(), $entity4->getFone()); } public function testQueryCacheFindAllJoinTableEntities() @@ -128,28 +130,28 @@ public function testQueryCacheFindAllJoinTableEntities() $this->loadFixturesAttractions(); $this->loadFixturesAttractionsInfo(); $this->evictRegions(); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT i, a FROM Doctrine\Tests\Models\Cache\AttractionInfo i JOIN i.attraction a'; - $result1 = $this->_em->createQuery($dql) + $result1 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertCount(count($this->attractionsInfo), $result1); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(count($this->attractionsInfo), $result1); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->_em->clear(); + $this->em->clear(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertCount(count($this->attractionsInfo), $result2); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(count($this->attractionsInfo), $result2); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); foreach ($result2 as $entity) { - $this->assertInstanceOf(AttractionInfo::class, $entity); + self::assertInstanceOf(AttractionInfo::class, $entity); } } @@ -161,33 +163,33 @@ public function testOneToManyRelationJoinTable() $this->loadFixturesAttractions(); $this->loadFixturesAttractionsInfo(); $this->evictRegions(); - $this->_em->clear(); + $this->em->clear(); - $entity = $this->_em->find(Attraction::class, $this->attractions[0]->getId()); + $entity = $this->em->find(Attraction::class, $this->attractions[0]->getId()); - $this->assertInstanceOf(Attraction::class, $entity); - $this->assertInstanceOf(PersistentCollection::class, $entity->getInfos()); - $this->assertCount(1, $entity->getInfos()); + self::assertInstanceOf(Attraction::class, $entity); + self::assertInstanceOf(PersistentCollection::class, $entity->getInfos()); + self::assertCount(1, $entity->getInfos()); $ownerId = $this->attractions[0]->getId(); $queryCount = $this->getCurrentQueryCount(); - $this->assertTrue($this->cache->containsEntity(Attraction::class, $ownerId)); - $this->assertTrue($this->cache->containsCollection(Attraction::class, 'infos', $ownerId)); + self::assertTrue($this->cache->containsEntity(Attraction::class, $ownerId)); + self::assertTrue($this->cache->containsCollection(Attraction::class, 'infos', $ownerId)); - $this->assertInstanceOf(AttractionContactInfo::class, $entity->getInfos()->get(0)); - $this->assertEquals($this->attractionsInfo[0]->getFone(), $entity->getInfos()->get(0)->getFone()); + self::assertInstanceOf(AttractionContactInfo::class, $entity->getInfos()->get(0)); + self::assertEquals($this->attractionsInfo[0]->getFone(), $entity->getInfos()->get(0)->getFone()); - $this->_em->clear(); + $this->em->clear(); - $entity = $this->_em->find(Attraction::class, $this->attractions[0]->getId()); + $entity = $this->em->find(Attraction::class, $this->attractions[0]->getId()); - $this->assertInstanceOf(Attraction::class, $entity); - $this->assertInstanceOf(PersistentCollection::class, $entity->getInfos()); - $this->assertCount(1, $entity->getInfos()); + self::assertInstanceOf(Attraction::class, $entity); + self::assertInstanceOf(PersistentCollection::class, $entity->getInfos()); + self::assertCount(1, $entity->getInfos()); - $this->assertInstanceOf(AttractionContactInfo::class, $entity->getInfos()->get(0)); - $this->assertEquals($this->attractionsInfo[0]->getFone(), $entity->getInfos()->get(0)->getFone()); + self::assertInstanceOf(AttractionContactInfo::class, $entity->getInfos()->get(0)); + self::assertEquals($this->attractionsInfo[0]->getFone(), $entity->getInfos()->get(0)->getFone()); } public function testQueryCacheShouldBeEvictedOnTimestampUpdate() @@ -198,38 +200,38 @@ public function testQueryCacheShouldBeEvictedOnTimestampUpdate() $this->loadFixturesAttractions(); $this->loadFixturesAttractionsInfo(); $this->evictRegions(); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT attractionInfo FROM Doctrine\Tests\Models\Cache\AttractionInfo attractionInfo'; - $result1 = $this->_em->createQuery($dql) + $result1 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertCount(count($this->attractionsInfo), $result1); - $this->assertEquals($queryCount + 5, $this->getCurrentQueryCount()); + self::assertCount(count($this->attractionsInfo), $result1); + self::assertEquals($queryCount + 5, $this->getCurrentQueryCount()); $contact = new AttractionContactInfo( '1234-1234', - $this->_em->find(Attraction::class, $this->attractions[5]->getId()) + $this->em->find(Attraction::class, $this->attractions[5]->getId()) ); - $this->_em->persist($contact); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($contact); + $this->em->flush(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertCount(count($this->attractionsInfo) + 1, $result2); - $this->assertEquals($queryCount + 6, $this->getCurrentQueryCount()); + self::assertCount(count($this->attractionsInfo) + 1, $result2); + self::assertEquals($queryCount + 6, $this->getCurrentQueryCount()); foreach ($result2 as $entity) { - $this->assertInstanceOf(AttractionInfo::class, $entity); + self::assertInstanceOf(AttractionInfo::class, $entity); } } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToManyTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToManyTest.php index efe19f3e074..1ad0defdc69 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToManyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToManyTest.php @@ -1,5 +1,7 @@ loadFixturesCities(); $this->loadFixturesTraveler(); $this->loadFixturesTravels(); - $this->_em->clear(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Travel::class, $this->travels[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Travel::class, $this->travels[1]->getId())); + self::assertTrue($this->cache->containsEntity(Travel::class, $this->travels[0]->getId())); + self::assertTrue($this->cache->containsEntity(Travel::class, $this->travels[1]->getId())); - $this->assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[0]->getId())); - $this->assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[1]->getId())); + self::assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[0]->getId())); + self::assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[1]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[2]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[3]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[2]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[3]->getId())); } public function testPutAndLoadManyToManyRelation() @@ -45,104 +47,104 @@ public function testPutAndLoadManyToManyRelation() $this->loadFixturesTraveler(); $this->loadFixturesTravels(); - $this->_em->clear(); + $this->em->clear(); $this->cache->evictEntityRegion(City::class); $this->cache->evictEntityRegion(Travel::class); $this->cache->evictCollectionRegion(Travel::class, 'visitedCities'); $this->secondLevelCacheLogger->clearStats(); - $this->assertFalse($this->cache->containsEntity(Travel::class, $this->travels[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Travel::class, $this->travels[1]->getId())); + self::assertFalse($this->cache->containsEntity(Travel::class, $this->travels[0]->getId())); + self::assertFalse($this->cache->containsEntity(Travel::class, $this->travels[1]->getId())); - $this->assertFalse($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[0]->getId())); - $this->assertFalse($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[1]->getId())); + self::assertFalse($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[0]->getId())); + self::assertFalse($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[1]->getId())); - $this->assertFalse($this->cache->containsEntity(City::class, $this->cities[0]->getId())); - $this->assertFalse($this->cache->containsEntity(City::class, $this->cities[1]->getId())); - $this->assertFalse($this->cache->containsEntity(City::class, $this->cities[2]->getId())); - $this->assertFalse($this->cache->containsEntity(City::class, $this->cities[3]->getId())); + self::assertFalse($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + self::assertFalse($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + self::assertFalse($this->cache->containsEntity(City::class, $this->cities[2]->getId())); + self::assertFalse($this->cache->containsEntity(City::class, $this->cities[3]->getId())); - $t1 = $this->_em->find(Travel::class, $this->travels[0]->getId()); - $t2 = $this->_em->find(Travel::class, $this->travels[1]->getId()); + $t1 = $this->em->find(Travel::class, $this->travels[0]->getId()); + $t2 = $this->em->find(Travel::class, $this->travels[1]->getId()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Travel::class))); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(Travel::class))); + self::assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Travel::class))); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(Travel::class))); //trigger lazy load - $this->assertCount(3, $t1->getVisitedCities()); - $this->assertCount(2, $t2->getVisitedCities()); + self::assertCount(3, $t1->getVisitedCities()); + self::assertCount(2, $t2->getVisitedCities()); - $this->assertEquals(4, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(4, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getCollectionRegion(Travel::class, 'visitedCities'))); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(Travel::class, 'visitedCities'))); + self::assertEquals(4, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(4, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getCollectionRegion(Travel::class, 'visitedCities'))); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(Travel::class, 'visitedCities'))); - $this->assertInstanceOf(City::class, $t1->getVisitedCities()->get(0)); - $this->assertInstanceOf(City::class, $t1->getVisitedCities()->get(1)); - $this->assertInstanceOf(City::class, $t1->getVisitedCities()->get(2)); + self::assertInstanceOf(City::class, $t1->getVisitedCities()->get(0)); + self::assertInstanceOf(City::class, $t1->getVisitedCities()->get(1)); + self::assertInstanceOf(City::class, $t1->getVisitedCities()->get(2)); - $this->assertInstanceOf(City::class, $t2->getVisitedCities()->get(0)); - $this->assertInstanceOf(City::class, $t2->getVisitedCities()->get(1)); + self::assertInstanceOf(City::class, $t2->getVisitedCities()->get(0)); + self::assertInstanceOf(City::class, $t2->getVisitedCities()->get(1)); - $this->assertTrue($this->cache->containsEntity(Travel::class, $this->travels[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Travel::class, $this->travels[1]->getId())); + self::assertTrue($this->cache->containsEntity(Travel::class, $this->travels[0]->getId())); + self::assertTrue($this->cache->containsEntity(Travel::class, $this->travels[1]->getId())); - $this->assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[0]->getId())); - $this->assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[1]->getId())); + self::assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[0]->getId())); + self::assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[1]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[2]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[3]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[2]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[3]->getId())); - $this->_em->clear(); + $this->em->clear(); $this->secondLevelCacheLogger->clearStats(); $queryCount = $this->getCurrentQueryCount(); - $t3 = $this->_em->find(Travel::class, $this->travels[0]->getId()); - $t4 = $this->_em->find(Travel::class, $this->travels[1]->getId()); + $t3 = $this->em->find(Travel::class, $this->travels[0]->getId()); + $t4 = $this->em->find(Travel::class, $this->travels[1]->getId()); //trigger lazy load from cache - $this->assertCount(3, $t3->getVisitedCities()); - $this->assertCount(2, $t4->getVisitedCities()); + self::assertCount(3, $t3->getVisitedCities()); + self::assertCount(2, $t4->getVisitedCities()); - $this->assertInstanceOf(City::class, $t3->getVisitedCities()->get(0)); - $this->assertInstanceOf(City::class, $t3->getVisitedCities()->get(1)); - $this->assertInstanceOf(City::class, $t3->getVisitedCities()->get(2)); + self::assertInstanceOf(City::class, $t3->getVisitedCities()->get(0)); + self::assertInstanceOf(City::class, $t3->getVisitedCities()->get(1)); + self::assertInstanceOf(City::class, $t3->getVisitedCities()->get(2)); - $this->assertInstanceOf(City::class, $t4->getVisitedCities()->get(0)); - $this->assertInstanceOf(City::class, $t4->getVisitedCities()->get(1)); + self::assertInstanceOf(City::class, $t4->getVisitedCities()->get(0)); + self::assertInstanceOf(City::class, $t4->getVisitedCities()->get(1)); - $this->assertEquals(4, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(Travel::class))); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(Travel::class, 'visitedCities'))); + self::assertEquals(4, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(Travel::class))); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(Travel::class, 'visitedCities'))); - $this->assertNotSame($t1->getVisitedCities()->get(0), $t3->getVisitedCities()->get(0)); - $this->assertEquals($t1->getVisitedCities()->get(0)->getId(), $t3->getVisitedCities()->get(0)->getId()); - $this->assertEquals($t1->getVisitedCities()->get(0)->getName(), $t3->getVisitedCities()->get(0)->getName()); + self::assertNotSame($t1->getVisitedCities()->get(0), $t3->getVisitedCities()->get(0)); + self::assertEquals($t1->getVisitedCities()->get(0)->getId(), $t3->getVisitedCities()->get(0)->getId()); + self::assertEquals($t1->getVisitedCities()->get(0)->getName(), $t3->getVisitedCities()->get(0)->getName()); - $this->assertNotSame($t1->getVisitedCities()->get(1), $t3->getVisitedCities()->get(1)); - $this->assertEquals($t1->getVisitedCities()->get(1)->getId(), $t3->getVisitedCities()->get(1)->getId()); - $this->assertEquals($t1->getVisitedCities()->get(1)->getName(), $t3->getVisitedCities()->get(1)->getName()); + self::assertNotSame($t1->getVisitedCities()->get(1), $t3->getVisitedCities()->get(1)); + self::assertEquals($t1->getVisitedCities()->get(1)->getId(), $t3->getVisitedCities()->get(1)->getId()); + self::assertEquals($t1->getVisitedCities()->get(1)->getName(), $t3->getVisitedCities()->get(1)->getName()); - $this->assertNotSame($t1->getVisitedCities()->get(2), $t3->getVisitedCities()->get(2)); - $this->assertEquals($t1->getVisitedCities()->get(2)->getId(), $t3->getVisitedCities()->get(2)->getId()); - $this->assertEquals($t1->getVisitedCities()->get(2)->getName(), $t3->getVisitedCities()->get(2)->getName()); + self::assertNotSame($t1->getVisitedCities()->get(2), $t3->getVisitedCities()->get(2)); + self::assertEquals($t1->getVisitedCities()->get(2)->getId(), $t3->getVisitedCities()->get(2)->getId()); + self::assertEquals($t1->getVisitedCities()->get(2)->getName(), $t3->getVisitedCities()->get(2)->getName()); - $this->assertNotSame($t2->getVisitedCities()->get(0), $t4->getVisitedCities()->get(0)); - $this->assertEquals($t2->getVisitedCities()->get(0)->getId(), $t4->getVisitedCities()->get(0)->getId()); - $this->assertEquals($t2->getVisitedCities()->get(0)->getName(), $t4->getVisitedCities()->get(0)->getName()); + self::assertNotSame($t2->getVisitedCities()->get(0), $t4->getVisitedCities()->get(0)); + self::assertEquals($t2->getVisitedCities()->get(0)->getId(), $t4->getVisitedCities()->get(0)->getId()); + self::assertEquals($t2->getVisitedCities()->get(0)->getName(), $t4->getVisitedCities()->get(0)->getName()); - $this->assertNotSame($t2->getVisitedCities()->get(1), $t4->getVisitedCities()->get(1)); - $this->assertEquals($t2->getVisitedCities()->get(1)->getId(), $t4->getVisitedCities()->get(1)->getId()); - $this->assertEquals($t2->getVisitedCities()->get(1)->getName(), $t4->getVisitedCities()->get(1)->getName()); + self::assertNotSame($t2->getVisitedCities()->get(1), $t4->getVisitedCities()->get(1)); + self::assertEquals($t2->getVisitedCities()->get(1)->getId(), $t4->getVisitedCities()->get(1)->getId()); + self::assertEquals($t2->getVisitedCities()->get(1)->getName(), $t4->getVisitedCities()->get(1)->getName()); - $this->assertEquals(4, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals(4, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); } public function testStoreManyToManyAssociationWhitCascade() @@ -166,24 +168,24 @@ public function testStoreManyToManyAssociationWhitCascade() $travel->addVisitedCity($this->cities[1]); $travel->addVisitedCity($this->cities[3]); - $this->_em->persist($traveler); - $this->_em->persist($travel); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($traveler); + $this->em->persist($travel); + $this->em->flush(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Travel::class, $travel->getId())); - $this->assertTrue($this->cache->containsEntity(Traveler::class, $traveler->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[3]->getId())); - $this->assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $travel->getId())); + self::assertTrue($this->cache->containsEntity(Travel::class, $travel->getId())); + self::assertTrue($this->cache->containsEntity(Traveler::class, $traveler->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[3]->getId())); + self::assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $travel->getId())); $queryCount1 = $this->getCurrentQueryCount(); - $t1 = $this->_em->find(Travel::class, $travel->getId()); + $t1 = $this->em->find(Travel::class, $travel->getId()); - $this->assertInstanceOf(Travel::class, $t1); - $this->assertCount(3, $t1->getVisitedCities()); - $this->assertEquals($queryCount1, $this->getCurrentQueryCount()); + self::assertInstanceOf(Travel::class, $t1); + self::assertCount(3, $t1->getVisitedCities()); + self::assertEquals($queryCount1, $this->getCurrentQueryCount()); } /** @@ -200,19 +202,19 @@ public function testReadOnlyCollection() $this->loadFixturesTraveler(); $this->loadFixturesTravels(); - $this->_em->clear(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Travel::class, $this->travels[0]->getId())); - $this->assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[0]->getId())); + self::assertTrue($this->cache->containsEntity(Travel::class, $this->travels[0]->getId())); + self::assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[0]->getId())); - $travel = $this->_em->find(Travel::class, $this->travels[0]->getId()); + $travel = $this->em->find(Travel::class, $this->travels[0]->getId()); - $this->assertCount(3, $travel->getVisitedCities()); + self::assertCount(3, $travel->getVisitedCities()); $travel->getVisitedCities()->remove(0); - $this->_em->persist($travel); - $this->_em->flush(); + $this->em->persist($travel); + $this->em->flush(); } public function testManyToManyWithEmptyRelation() @@ -222,25 +224,25 @@ public function testManyToManyWithEmptyRelation() $this->loadFixturesCities(); $this->loadFixturesTraveler(); $this->loadFixturesTravels(); - $this->_em->clear(); + $this->em->clear(); $this->evictRegions(); $queryCount = $this->getCurrentQueryCount(); $entitiId = $this->travels[2]->getId(); //empty travel - $entity = $this->_em->find(Travel::class, $entitiId); + $entity = $this->em->find(Travel::class, $entitiId); - $this->assertEquals(0, $entity->getVisitedCities()->count()); - $this->assertEquals($queryCount+2, $this->getCurrentQueryCount()); + self::assertEquals(0, $entity->getVisitedCities()->count()); + self::assertEquals($queryCount+2, $this->getCurrentQueryCount()); - $this->_em->clear(); + $this->em->clear(); - $entity = $this->_em->find(Travel::class, $entitiId); + $entity = $this->em->find(Travel::class, $entitiId); $queryCount = $this->getCurrentQueryCount(); - $this->assertEquals(0, $entity->getVisitedCities()->count()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals(0, $entity->getVisitedCities()->count()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToOneTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToOneTest.php index 7af52f741c2..cc75aaed65d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToOneTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToOneTest.php @@ -1,5 +1,7 @@ loadFixturesCountries(); $this->loadFixturesStates(); - $this->_em->clear(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->states[0]->getCountry()->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->states[1]->getCountry()->getId())); - $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->states[0]->getCountry()->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->states[1]->getCountry()->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); } public function testPutAndLoadManyToOneRelation() { $this->loadFixturesCountries(); $this->loadFixturesStates(); - $this->_em->clear(); + $this->em->clear(); $this->cache->evictEntityRegion(State::class); $this->cache->evictEntityRegion(Country::class); - $this->assertFalse($this->cache->containsEntity(State::class, $this->states[0]->getId())); - $this->assertFalse($this->cache->containsEntity(State::class, $this->states[1]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->states[0]->getCountry()->getId())); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->states[1]->getCountry()->getId())); + self::assertFalse($this->cache->containsEntity(State::class, $this->states[0]->getId())); + self::assertFalse($this->cache->containsEntity(State::class, $this->states[1]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->states[0]->getCountry()->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->states[1]->getCountry()->getId())); - $c1 = $this->_em->find(State::class, $this->states[0]->getId()); - $c2 = $this->_em->find(State::class, $this->states[1]->getId()); + $c1 = $this->em->find(State::class, $this->states[0]->getId()); + $c2 = $this->em->find(State::class, $this->states[1]->getId()); //trigger lazy load - $this->assertNotNull($c1->getCountry()->getName()); - $this->assertNotNull($c2->getCountry()->getName()); + self::assertNotNull($c1->getCountry()->getName()); + self::assertNotNull($c2->getCountry()->getName()); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->states[0]->getCountry()->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->states[1]->getCountry()->getId())); - $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->states[0]->getCountry()->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->states[1]->getCountry()->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); - $this->assertInstanceOf(State::class, $c1); - $this->assertInstanceOf(State::class, $c2); - $this->assertInstanceOf(Country::class, $c1->getCountry()); - $this->assertInstanceOf(Country::class, $c2->getCountry()); + self::assertInstanceOf(State::class, $c1); + self::assertInstanceOf(State::class, $c2); + self::assertInstanceOf(Country::class, $c1->getCountry()); + self::assertInstanceOf(Country::class, $c2->getCountry()); - $this->assertEquals($this->states[0]->getId(), $c1->getId()); - $this->assertEquals($this->states[0]->getName(), $c1->getName()); - $this->assertEquals($this->states[0]->getCountry()->getId(), $c1->getCountry()->getId()); - $this->assertEquals($this->states[0]->getCountry()->getName(), $c1->getCountry()->getName()); + self::assertEquals($this->states[0]->getId(), $c1->getId()); + self::assertEquals($this->states[0]->getName(), $c1->getName()); + self::assertEquals($this->states[0]->getCountry()->getId(), $c1->getCountry()->getId()); + self::assertEquals($this->states[0]->getCountry()->getName(), $c1->getCountry()->getName()); - $this->assertEquals($this->states[1]->getId(), $c2->getId()); - $this->assertEquals($this->states[1]->getName(), $c2->getName()); - $this->assertEquals($this->states[1]->getCountry()->getId(), $c2->getCountry()->getId()); - $this->assertEquals($this->states[1]->getCountry()->getName(), $c2->getCountry()->getName()); + self::assertEquals($this->states[1]->getId(), $c2->getId()); + self::assertEquals($this->states[1]->getName(), $c2->getName()); + self::assertEquals($this->states[1]->getCountry()->getId(), $c2->getCountry()->getId()); + self::assertEquals($this->states[1]->getCountry()->getName(), $c2->getCountry()->getName()); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); - $c3 = $this->_em->find(State::class, $this->states[0]->getId()); - $c4 = $this->_em->find(State::class, $this->states[1]->getId()); + $c3 = $this->em->find(State::class, $this->states[0]->getId()); + $c4 = $this->em->find(State::class, $this->states[1]->getId()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); //trigger lazy load from cache - $this->assertNotNull($c3->getCountry()->getName()); - $this->assertNotNull($c4->getCountry()->getName()); + self::assertNotNull($c3->getCountry()->getName()); + self::assertNotNull($c4->getCountry()->getName()); - $this->assertInstanceOf(State::class, $c3); - $this->assertInstanceOf(State::class, $c4); - $this->assertInstanceOf(Country::class, $c3->getCountry()); - $this->assertInstanceOf(Country::class, $c4->getCountry()); + self::assertInstanceOf(State::class, $c3); + self::assertInstanceOf(State::class, $c4); + self::assertInstanceOf(Country::class, $c3->getCountry()); + self::assertInstanceOf(Country::class, $c4->getCountry()); - $this->assertEquals($c1->getId(), $c3->getId()); - $this->assertEquals($c1->getName(), $c3->getName()); + self::assertEquals($c1->getId(), $c3->getId()); + self::assertEquals($c1->getName(), $c3->getName()); - $this->assertEquals($c2->getId(), $c4->getId()); - $this->assertEquals($c2->getName(), $c4->getName()); + self::assertEquals($c2->getId(), $c4->getId()); + self::assertEquals($c2->getName(), $c4->getName()); - $this->assertEquals($this->states[0]->getCountry()->getId(), $c3->getCountry()->getId()); - $this->assertEquals($this->states[0]->getCountry()->getName(), $c3->getCountry()->getName()); + self::assertEquals($this->states[0]->getCountry()->getId(), $c3->getCountry()->getId()); + self::assertEquals($this->states[0]->getCountry()->getName(), $c3->getCountry()->getName()); - $this->assertEquals($this->states[1]->getCountry()->getId(), $c4->getCountry()->getId()); - $this->assertEquals($this->states[1]->getCountry()->getName(), $c4->getCountry()->getName()); + self::assertEquals($this->states[1]->getCountry()->getId(), $c4->getCountry()->getId()); + self::assertEquals($this->states[1]->getCountry()->getName(), $c4->getCountry()->getName()); } public function testInverseSidePutShouldEvictCollection() @@ -104,40 +106,40 @@ public function testInverseSidePutShouldEvictCollection() $this->loadFixturesCountries(); $this->loadFixturesStates(); - $this->_em->clear(); + $this->em->clear(); $this->cache->evictEntityRegion(State::class); $this->cache->evictEntityRegion(Country::class); //evict collection on add - $c3 = $this->_em->find(State::class, $this->states[0]->getId()); + $c3 = $this->em->find(State::class, $this->states[0]->getId()); $prev = $c3->getCities(); $count = $prev->count(); $city = new City("Buenos Aires", $c3); $c3->addCity($city); - $this->_em->persist($city); - $this->_em->persist($c3); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($city); + $this->em->persist($c3); + $this->em->flush(); + $this->em->clear(); - $state = $this->_em->find(State::class, $c3->getId()); + $state = $this->em->find(State::class, $c3->getId()); $queryCount = $this->getCurrentQueryCount(); // Association was cleared from EM - $this->assertNotEquals($prev, $state->getCities()); + self::assertNotEquals($prev, $state->getCities()); // New association has one more item (cache was evicted) - $this->assertEquals($count + 1, $state->getCities()->count()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($count + 1, $state->getCities()->count()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); } public function testShouldNotReloadWhenAssociationIsMissing() { $this->loadFixturesCountries(); $this->loadFixturesStates(); - $this->_em->clear(); + $this->em->clear(); $stateId1 = $this->states[0]->getId(); $stateId2 = $this->states[3]->getId(); @@ -145,74 +147,74 @@ public function testShouldNotReloadWhenAssociationIsMissing() $countryId1 = $this->states[0]->getCountry()->getId(); $countryId2 = $this->states[3]->getCountry()->getId(); - $this->assertTrue($this->cache->containsEntity(Country::class, $countryId1)); - $this->assertTrue($this->cache->containsEntity(Country::class, $countryId2)); - $this->assertTrue($this->cache->containsEntity(State::class, $stateId1)); - $this->assertTrue($this->cache->containsEntity(State::class, $stateId2)); + self::assertTrue($this->cache->containsEntity(Country::class, $countryId1)); + self::assertTrue($this->cache->containsEntity(Country::class, $countryId2)); + self::assertTrue($this->cache->containsEntity(State::class, $stateId1)); + self::assertTrue($this->cache->containsEntity(State::class, $stateId2)); $this->cache->evictEntityRegion(Country::class); - $this->assertFalse($this->cache->containsEntity(Country::class, $countryId1)); - $this->assertFalse($this->cache->containsEntity(Country::class, $countryId2)); + self::assertFalse($this->cache->containsEntity(Country::class, $countryId1)); + self::assertFalse($this->cache->containsEntity(Country::class, $countryId2)); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); - $state1 = $this->_em->find(State::class, $stateId1); - $state2 = $this->_em->find(State::class, $stateId2); + $state1 = $this->em->find(State::class, $stateId1); + $state2 = $this->em->find(State::class, $stateId2); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::class, $state1); - $this->assertInstanceOf(State::class, $state2); - $this->assertInstanceOf(Country::class, $state1->getCountry()); - $this->assertInstanceOf(Country::class, $state2->getCountry()); + self::assertInstanceOf(State::class, $state1); + self::assertInstanceOf(State::class, $state2); + self::assertInstanceOf(Country::class, $state1->getCountry()); + self::assertInstanceOf(Country::class, $state2->getCountry()); $queryCount = $this->getCurrentQueryCount(); - $this->assertNotNull($state1->getCountry()->getName()); - $this->assertNotNull($state2->getCountry()->getName()); - $this->assertEquals($countryId1, $state1->getCountry()->getId()); - $this->assertEquals($countryId2, $state2->getCountry()->getId()); + self::assertNotNull($state1->getCountry()->getName()); + self::assertNotNull($state2->getCountry()->getName()); + self::assertEquals($countryId1, $state1->getCountry()->getId()); + self::assertEquals($countryId2, $state2->getCountry()->getId()); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount()); } public function testPutAndLoadNonCacheableManyToOne() { - $this->assertNull($this->cache->getEntityCacheRegion(Action::class)); - $this->assertInstanceOf(Region::class, $this->cache->getEntityCacheRegion(Token::class)); + self::assertNull($this->cache->getEntityCacheRegion(Action::class)); + self::assertInstanceOf(Region::class, $this->cache->getEntityCacheRegion(Token::class)); $token = new Token('token-hash'); $action = new Action('exec'); $action->addToken($token); - $this->_em->persist($token); + $this->em->persist($token); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Token::class, $token->token)); - $this->assertFalse($this->cache->containsEntity(Token::class, $action->name)); + self::assertTrue($this->cache->containsEntity(Token::class, $token->token)); + self::assertFalse($this->cache->containsEntity(Token::class, $action->name)); $queryCount = $this->getCurrentQueryCount(); - $entity = $this->_em->find(Token::class, $token->token); + $entity = $this->em->find(Token::class, $token->token); - $this->assertInstanceOf(Token::class, $entity); - $this->assertEquals('token-hash', $entity->token); + self::assertInstanceOf(Token::class, $entity); + self::assertEquals('token-hash', $entity->token); - $this->assertInstanceOf(Action::class, $entity->getAction()); - $this->assertEquals('exec', $entity->getAction()->name); + self::assertInstanceOf(Action::class, $entity->getAction()); + self::assertEquals('exec', $entity->getAction()->name); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); } public function testPutAndLoadNonCacheableCompositeManyToOne() { - $this->assertNull($this->cache->getEntityCacheRegion(Action::class)); - $this->assertNull($this->cache->getEntityCacheRegion(ComplexAction::class)); - $this->assertInstanceOf(Region::class, $this->cache->getEntityCacheRegion(Token::class)); + self::assertNull($this->cache->getEntityCacheRegion(Action::class)); + self::assertNull($this->cache->getEntityCacheRegion(ComplexAction::class)); + self::assertInstanceOf(Region::class, $this->cache->getEntityCacheRegion(Token::class)); $token = new Token('token-hash'); @@ -226,38 +228,38 @@ public function testPutAndLoadNonCacheableCompositeManyToOne() $token->action = $action2; - $this->_em->persist($token); + $this->em->persist($token); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Token::class, $token->token)); - $this->assertFalse($this->cache->containsEntity(Action::class, $action1->name)); - $this->assertFalse($this->cache->containsEntity(Action::class, $action2->name)); - $this->assertFalse($this->cache->containsEntity(Action::class, $action3->name)); + self::assertTrue($this->cache->containsEntity(Token::class, $token->token)); + self::assertFalse($this->cache->containsEntity(Action::class, $action1->name)); + self::assertFalse($this->cache->containsEntity(Action::class, $action2->name)); + self::assertFalse($this->cache->containsEntity(Action::class, $action3->name)); $queryCount = $this->getCurrentQueryCount(); /** * @var $entity Token */ - $entity = $this->_em->find(Token::class, $token->token); + $entity = $this->em->find(Token::class, $token->token); - $this->assertInstanceOf(Token::class, $entity); - $this->assertEquals('token-hash', $entity->token); + self::assertInstanceOf(Token::class, $entity); + self::assertEquals('token-hash', $entity->token); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(Action::class, $entity->getAction()); - $this->assertInstanceOf(ComplexAction::class, $entity->getComplexAction()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertInstanceOf(Action::class, $entity->getAction()); + self::assertInstanceOf(ComplexAction::class, $entity->getComplexAction()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(Action::class, $entity->getComplexAction()->getAction1()); - $this->assertInstanceOf(Action::class, $entity->getComplexAction()->getAction2()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertInstanceOf(Action::class, $entity->getComplexAction()->getAction1()); + self::assertInstanceOf(Action::class, $entity->getComplexAction()->getAction2()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertEquals('login', $entity->getComplexAction()->getAction1()->name); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertEquals('rememberme', $entity->getComplexAction()->getAction2()->name); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals('login', $entity->getComplexAction()->getAction1()->name); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals('rememberme', $entity->getComplexAction()->getAction2()->name); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToManyTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToManyTest.php index 9f347cc5ba1..061272603b1 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToManyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToManyTest.php @@ -1,5 +1,7 @@ loadFixturesStates(); $this->loadFixturesCities(); - $this->_em->clear(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); - $this->assertTrue($this->cache->containsCollection(State::class, 'cities', $this->states[0]->getId())); - $this->assertTrue($this->cache->containsCollection(State::class, 'cities', $this->states[1]->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); + self::assertTrue($this->cache->containsCollection(State::class, 'cities', $this->states[0]->getId())); + self::assertTrue($this->cache->containsCollection(State::class, 'cities', $this->states[1]->getId())); } public function testPutAndLoadOneToManyRelation() @@ -34,97 +36,97 @@ public function testPutAndLoadOneToManyRelation() $this->loadFixturesCountries(); $this->loadFixturesStates(); $this->loadFixturesCities(); - $this->_em->clear(); + $this->em->clear(); $this->secondLevelCacheLogger->clearStats(); $this->cache->evictEntityRegion(State::class); $this->cache->evictEntityRegion(City::class); $this->cache->evictCollectionRegion(State::class, 'cities'); - $this->assertFalse($this->cache->containsEntity(State::class, $this->states[0]->getId())); - $this->assertFalse($this->cache->containsEntity(State::class, $this->states[1]->getId())); + self::assertFalse($this->cache->containsEntity(State::class, $this->states[0]->getId())); + self::assertFalse($this->cache->containsEntity(State::class, $this->states[1]->getId())); - $this->assertFalse($this->cache->containsCollection(State::class, 'cities', $this->states[0]->getId())); - $this->assertFalse($this->cache->containsCollection(State::class, 'cities', $this->states[1]->getId())); + self::assertFalse($this->cache->containsCollection(State::class, 'cities', $this->states[0]->getId())); + self::assertFalse($this->cache->containsCollection(State::class, 'cities', $this->states[1]->getId())); - $this->assertFalse($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(0)->getId())); - $this->assertFalse($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(1)->getId())); - $this->assertFalse($this->cache->containsEntity(City::class, $this->states[1]->getCities()->get(0)->getId())); - $this->assertFalse($this->cache->containsEntity(City::class, $this->states[1]->getCities()->get(1)->getId())); + self::assertFalse($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(0)->getId())); + self::assertFalse($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(1)->getId())); + self::assertFalse($this->cache->containsEntity(City::class, $this->states[1]->getCities()->get(0)->getId())); + self::assertFalse($this->cache->containsEntity(City::class, $this->states[1]->getCities()->get(1)->getId())); - $s1 = $this->_em->find(State::class, $this->states[0]->getId()); - $s2 = $this->_em->find(State::class, $this->states[1]->getId()); + $s1 = $this->em->find(State::class, $this->states[0]->getId()); + $s2 = $this->em->find(State::class, $this->states[1]->getId()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(State::class))); + self::assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(State::class))); //trigger lazy load - $this->assertCount(2, $s1->getCities()); - $this->assertCount(2, $s2->getCities()); + self::assertCount(2, $s1->getCities()); + self::assertCount(2, $s2->getCities()); - $this->assertEquals(4, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(4, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getCollectionRegion(State::class, 'cities'))); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(State::class, 'cities'))); + self::assertEquals(4, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(4, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getCollectionRegion(State::class, 'cities'))); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(State::class, 'cities'))); - $this->assertInstanceOf(City::class, $s1->getCities()->get(0)); - $this->assertInstanceOf(City::class, $s1->getCities()->get(1)); + self::assertInstanceOf(City::class, $s1->getCities()->get(0)); + self::assertInstanceOf(City::class, $s1->getCities()->get(1)); - $this->assertInstanceOf(City::class, $s2->getCities()->get(0)); - $this->assertInstanceOf(City::class, $s2->getCities()->get(1)); + self::assertInstanceOf(City::class, $s2->getCities()->get(0)); + self::assertInstanceOf(City::class, $s2->getCities()->get(1)); - $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); - $this->assertTrue($this->cache->containsCollection(State::class, 'cities', $this->states[0]->getId())); - $this->assertTrue($this->cache->containsCollection(State::class, 'cities', $this->states[1]->getId())); + self::assertTrue($this->cache->containsCollection(State::class, 'cities', $this->states[0]->getId())); + self::assertTrue($this->cache->containsCollection(State::class, 'cities', $this->states[1]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(0)->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(1)->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->states[1]->getCities()->get(0)->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->states[1]->getCities()->get(1)->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(0)->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(1)->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->states[1]->getCities()->get(0)->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->states[1]->getCities()->get(1)->getId())); - $this->_em->clear(); + $this->em->clear(); $this->secondLevelCacheLogger->clearStats(); $queryCount = $this->getCurrentQueryCount(); - $s3 = $this->_em->find(State::class, $this->states[0]->getId()); - $s4 = $this->_em->find(State::class, $this->states[1]->getId()); + $s3 = $this->em->find(State::class, $this->states[0]->getId()); + $s4 = $this->em->find(State::class, $this->states[1]->getId()); //trigger lazy load from cache - $this->assertCount(2, $s3->getCities()); - $this->assertCount(2, $s4->getCities()); + self::assertCount(2, $s3->getCities()); + self::assertCount(2, $s4->getCities()); - $this->assertEquals(4, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::class, 'cities'))); + self::assertEquals(4, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::class, 'cities'))); - $this->assertInstanceOf(City::class, $s3->getCities()->get(0)); - $this->assertInstanceOf(City::class, $s3->getCities()->get(1)); - $this->assertInstanceOf(City::class, $s4->getCities()->get(0)); - $this->assertInstanceOf(City::class, $s4->getCities()->get(1)); + self::assertInstanceOf(City::class, $s3->getCities()->get(0)); + self::assertInstanceOf(City::class, $s3->getCities()->get(1)); + self::assertInstanceOf(City::class, $s4->getCities()->get(0)); + self::assertInstanceOf(City::class, $s4->getCities()->get(1)); - $this->assertNotSame($s1->getCities()->get(0), $s3->getCities()->get(0)); - $this->assertEquals($s1->getCities()->get(0)->getId(), $s3->getCities()->get(0)->getId()); - $this->assertEquals($s1->getCities()->get(0)->getName(), $s3->getCities()->get(0)->getName()); + self::assertNotSame($s1->getCities()->get(0), $s3->getCities()->get(0)); + self::assertEquals($s1->getCities()->get(0)->getId(), $s3->getCities()->get(0)->getId()); + self::assertEquals($s1->getCities()->get(0)->getName(), $s3->getCities()->get(0)->getName()); - $this->assertNotSame($s1->getCities()->get(1), $s3->getCities()->get(1)); - $this->assertEquals($s1->getCities()->get(1)->getId(), $s3->getCities()->get(1)->getId()); - $this->assertEquals($s1->getCities()->get(1)->getName(), $s3->getCities()->get(1)->getName()); + self::assertNotSame($s1->getCities()->get(1), $s3->getCities()->get(1)); + self::assertEquals($s1->getCities()->get(1)->getId(), $s3->getCities()->get(1)->getId()); + self::assertEquals($s1->getCities()->get(1)->getName(), $s3->getCities()->get(1)->getName()); - $this->assertNotSame($s2->getCities()->get(0), $s4->getCities()->get(0)); - $this->assertEquals($s2->getCities()->get(0)->getId(), $s4->getCities()->get(0)->getId()); - $this->assertEquals($s2->getCities()->get(0)->getName(), $s4->getCities()->get(0)->getName()); + self::assertNotSame($s2->getCities()->get(0), $s4->getCities()->get(0)); + self::assertEquals($s2->getCities()->get(0)->getId(), $s4->getCities()->get(0)->getId()); + self::assertEquals($s2->getCities()->get(0)->getName(), $s4->getCities()->get(0)->getName()); - $this->assertNotSame($s2->getCities()->get(1), $s4->getCities()->get(1)); - $this->assertEquals($s2->getCities()->get(1)->getId(), $s4->getCities()->get(1)->getId()); - $this->assertEquals($s2->getCities()->get(1)->getName(), $s4->getCities()->get(1)->getName()); + self::assertNotSame($s2->getCities()->get(1), $s4->getCities()->get(1)); + self::assertEquals($s2->getCities()->get(1)->getId(), $s4->getCities()->get(1)->getId()); + self::assertEquals($s2->getCities()->get(1)->getName(), $s4->getCities()->get(1)->getName()); - $this->assertEquals(4, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals(4, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); } public function testLoadOneToManyCollectionFromDatabaseWhenEntityMissing() @@ -132,39 +134,39 @@ public function testLoadOneToManyCollectionFromDatabaseWhenEntityMissing() $this->loadFixturesCountries(); $this->loadFixturesStates(); $this->loadFixturesCities(); - $this->_em->clear(); + $this->em->clear(); //trigger lazy load from database - $this->assertCount(2, $this->_em->find(State::class, $this->states[0]->getId())->getCities()); + self::assertCount(2, $this->em->find(State::class, $this->states[0]->getId())->getCities()); - $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsCollection(State::class, 'cities', $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(0)->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(1)->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + self::assertTrue($this->cache->containsCollection(State::class, 'cities', $this->states[0]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(0)->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(1)->getId())); $queryCount = $this->getCurrentQueryCount(); $stateId = $this->states[0]->getId(); - $state = $this->_em->find(State::class, $stateId); + $state = $this->em->find(State::class, $stateId); $cityId = $this->states[0]->getCities()->get(1)->getId(); //trigger lazy load from cache - $this->assertCount(2, $state->getCities()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertTrue($this->cache->containsEntity(City::class, $cityId)); + self::assertCount(2, $state->getCities()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertTrue($this->cache->containsEntity(City::class, $cityId)); $this->cache->evictEntity(City::class, $cityId); - $this->assertFalse($this->cache->containsEntity(City::class, $cityId)); - $this->assertTrue($this->cache->containsEntity(State::class, $stateId)); - $this->assertTrue($this->cache->containsCollection(State::class, 'cities', $stateId)); + self::assertFalse($this->cache->containsEntity(City::class, $cityId)); + self::assertTrue($this->cache->containsEntity(State::class, $stateId)); + self::assertTrue($this->cache->containsCollection(State::class, 'cities', $stateId)); - $this->_em->clear(); + $this->em->clear(); - $state = $this->_em->find(State::class, $stateId); + $state = $this->em->find(State::class, $stateId); //trigger lazy load from database - $this->assertCount(2, $state->getCities()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(2, $state->getCities()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } @@ -175,12 +177,12 @@ public function testShoudNotPutOneToManyRelationOnPersist() $state = new State("State Foo", $this->countries[0]); - $this->_em->persist($state); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($state); + $this->em->flush(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(State::class, $state->getId())); - $this->assertFalse($this->cache->containsCollection(State::class, 'cities', $state->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $state->getId())); + self::assertFalse($this->cache->containsCollection(State::class, 'cities', $state->getId())); } public function testOneToManyRemove() @@ -189,103 +191,103 @@ public function testOneToManyRemove() $this->loadFixturesStates(); $this->loadFixturesCities(); - $this->_em->clear(); + $this->em->clear(); $this->secondLevelCacheLogger->clearStats(); $this->cache->evictEntityRegion(State::class); $this->cache->evictEntityRegion(City::class); $this->cache->evictCollectionRegion(State::class, 'cities'); - $this->assertFalse($this->cache->containsEntity(State::class, $this->states[0]->getId())); - $this->assertFalse($this->cache->containsCollection(State::class, 'cities', $this->states[0]->getId())); - $this->assertFalse($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(0)->getId())); - $this->assertFalse($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(1)->getId())); + self::assertFalse($this->cache->containsEntity(State::class, $this->states[0]->getId())); + self::assertFalse($this->cache->containsCollection(State::class, 'cities', $this->states[0]->getId())); + self::assertFalse($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(0)->getId())); + self::assertFalse($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(1)->getId())); - $entity = $this->_em->find(State::class, $this->states[0]->getId()); + $entity = $this->em->find(State::class, $this->states[0]->getId()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(State::class))); + self::assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(State::class))); //trigger lazy load - $this->assertCount(2, $entity->getCities()); + self::assertCount(2, $entity->getCities()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getCollectionRegion(State::class, 'cities'))); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(State::class, 'cities'))); + self::assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getCollectionRegion(State::class, 'cities'))); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(State::class, 'cities'))); - $this->assertInstanceOf(City::class, $entity->getCities()->get(0)); - $this->assertInstanceOf(City::class, $entity->getCities()->get(1)); + self::assertInstanceOf(City::class, $entity->getCities()->get(0)); + self::assertInstanceOf(City::class, $entity->getCities()->get(1)); - $this->_em->clear(); + $this->em->clear(); $this->secondLevelCacheLogger->clearStats(); $queryCount = $this->getCurrentQueryCount(); - $state = $this->_em->find(State::class, $this->states[0]->getId()); + $state = $this->em->find(State::class, $this->states[0]->getId()); //trigger lazy load from cache - $this->assertCount(2, $state->getCities()); + self::assertCount(2, $state->getCities()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::class, 'cities'))); + self::assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::class, 'cities'))); $city0 = $state->getCities()->get(0); $city1 = $state->getCities()->get(1); - $this->assertInstanceOf(City::class, $city0); - $this->assertInstanceOf(City::class, $city1); + self::assertInstanceOf(City::class, $city0); + self::assertInstanceOf(City::class, $city1); - $this->assertEquals($entity->getCities()->get(0)->getName(), $city0->getName()); - $this->assertEquals($entity->getCities()->get(1)->getName(), $city1->getName()); + self::assertEquals($entity->getCities()->get(0)->getName(), $city0->getName()); + self::assertEquals($entity->getCities()->get(1)->getName(), $city1->getName()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); $state->getCities()->removeElement($city0); - $this->_em->remove($city0); - $this->_em->persist($state); - $this->_em->flush(); - $this->_em->clear(); + $this->em->remove($city0); + $this->em->persist($state); + $this->em->flush(); + $this->em->clear(); $this->secondLevelCacheLogger->clearStats(); $queryCount = $this->getCurrentQueryCount(); - $state = $this->_em->find(State::class, $this->states[0]->getId()); + $state = $this->em->find(State::class, $this->states[0]->getId()); //trigger lazy load from cache - $this->assertCount(1, $state->getCities()); + self::assertCount(1, $state->getCities()); $city1 = $state->getCities()->get(0); - $this->assertInstanceOf(City::class, $city1); - $this->assertEquals($entity->getCities()->get(1)->getName(), $city1->getName()); + self::assertInstanceOf(City::class, $city1); + self::assertEquals($entity->getCities()->get(1)->getName(), $city1->getName()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::class, 'cities'))); + self::assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::class, 'cities'))); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); $state->getCities()->remove(0); - $this->_em->remove($city1); - $this->_em->persist($state); - $this->_em->flush(); - $this->_em->clear(); + $this->em->remove($city1); + $this->em->persist($state); + $this->em->flush(); + $this->em->clear(); $this->secondLevelCacheLogger->clearStats(); $queryCount = $this->getCurrentQueryCount(); - $state = $this->_em->find(State::class, $this->states[0]->getId()); + $state = $this->em->find(State::class, $this->states[0]->getId()); - $this->assertCount(0, $state->getCities()); + self::assertCount(0, $state->getCities()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::class, 'cities'))); + self::assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::class, 'cities'))); } public function testOneToManyWithEmptyRelation() @@ -298,22 +300,22 @@ public function testOneToManyWithEmptyRelation() $this->cache->evictEntityRegion(City::class); $this->cache->evictEntityRegion(State::class); $this->cache->evictCollectionRegion(State::class, 'cities'); - $this->_em->clear(); + $this->em->clear(); $entitiId = $this->states[2]->getId(); // bavaria (cities count = 0) $queryCount = $this->getCurrentQueryCount(); - $entity = $this->_em->find(State::class, $entitiId); + $entity = $this->em->find(State::class, $entitiId); - $this->assertEquals(0, $entity->getCities()->count()); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + self::assertEquals(0, $entity->getCities()->count()); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount()); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); - $entity = $this->_em->find(State::class, $entitiId); + $entity = $this->em->find(State::class, $entitiId); - $this->assertEquals(0, $entity->getCities()->count()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals(0, $entity->getCities()->count()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); } @@ -327,27 +329,27 @@ public function testOneToManyCount() $this->cache->evictEntityRegion(City::class); $this->cache->evictEntityRegion(State::class); $this->cache->evictCollectionRegion(State::class, 'cities'); - $this->_em->clear(); + $this->em->clear(); $entityId = $this->states[0]->getId(); $queryCount = $this->getCurrentQueryCount(); - $entity = $this->_em->find(State::class, $entityId); + $entity = $this->em->find(State::class, $entityId); - $this->assertEquals(2, $entity->getCities()->count()); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + self::assertEquals(2, $entity->getCities()->count()); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount()); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); - $entity = $this->_em->find(State::class, $entityId); + $entity = $this->em->find(State::class, $entityId); - $this->assertEquals(2, $entity->getCities()->count()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals(2, $entity->getCities()->count()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); } public function testCacheInitializeCollectionWithNewObjects() { - $this->_em->clear(); + $this->em->clear(); $this->evictRegions(); @@ -357,40 +359,40 @@ public function testCacheInitializeCollectionWithNewObjects() $traveler->getTravels()->add(new Travel($traveler)); } - $this->_em->persist($traveler); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($traveler); + $this->em->flush(); + $this->em->clear(); - $this->assertCount(3, $traveler->getTravels()); + self::assertCount(3, $traveler->getTravels()); $travelerId = $traveler->getId(); $queryCount = $this->getCurrentQueryCount(); - $entity = $this->_em->find(Traveler::class, $travelerId); + $entity = $this->em->find(Traveler::class, $travelerId); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertFalse($entity->getTravels()->isInitialized()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertFalse($entity->getTravels()->isInitialized()); $newItem = new Travel($entity); $entity->getTravels()->add($newItem); - $this->assertFalse($entity->getTravels()->isInitialized()); - $this->assertCount(4, $entity->getTravels()); - $this->assertTrue($entity->getTravels()->isInitialized()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertFalse($entity->getTravels()->isInitialized()); + self::assertCount(4, $entity->getTravels()); + self::assertTrue($entity->getTravels()->isInitialized()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $query = "SELECT t, tt FROM Doctrine\Tests\Models\Cache\Traveler t JOIN t.travels tt WHERE t.id = $travelerId"; - $result = $this->_em->createQuery($query)->getSingleResult(); + $result = $this->em->createQuery($query)->getSingleResult(); - $this->assertEquals(4, $result->getTravels()->count()); + self::assertEquals(4, $result->getTravels()->count()); } public function testPutAndLoadNonCacheableOneToMany() { - $this->assertNull($this->cache->getEntityCacheRegion(Login::class)); - $this->assertInstanceOf(Region::class, $this->cache->getEntityCacheRegion(Token::class)); + self::assertNull($this->cache->getEntityCacheRegion(Login::class)); + self::assertInstanceOf(Region::class, $this->cache->getEntityCacheRegion(Token::class)); $l1 = new Login('session1'); $l2 = new Login('session2'); @@ -398,21 +400,21 @@ public function testPutAndLoadNonCacheableOneToMany() $token->addLogin($l1); $token->addLogin($l2); - $this->_em->persist($token); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($token); + $this->em->flush(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Token::class, $token->token)); + self::assertTrue($this->cache->containsEntity(Token::class, $token->token)); $queryCount = $this->getCurrentQueryCount(); - $entity = $this->_em->find(Token::class, $token->token); + $entity = $this->em->find(Token::class, $token->token); - $this->assertInstanceOf(Token::class, $entity); - $this->assertEquals('token-hash', $entity->token); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertInstanceOf(Token::class, $entity); + self::assertEquals('token-hash', $entity->token); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertCount(2, $entity->logins); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(2, $entity->logins); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToOneTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToOneTest.php index 6e428814d3f..a42acecb308 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToOneTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToOneTest.php @@ -1,5 +1,7 @@ loadFixturesCities(); $this->loadFixturesTravelersWithProfile(); - $this->_em->clear(); + $this->em->clear(); $entity1 = $this->travelersWithProfile[0]; $entity2 = $this->travelersWithProfile[1]; - $this->assertTrue($this->cache->containsEntity(Traveler::class, $entity1->getId())); - $this->assertTrue($this->cache->containsEntity(Traveler::class, $entity2->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity2->getProfile()->getId())); + self::assertTrue($this->cache->containsEntity(Traveler::class, $entity1->getId())); + self::assertTrue($this->cache->containsEntity(Traveler::class, $entity2->getId())); + self::assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); + self::assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity2->getProfile()->getId())); } public function testPutOneToOneOnBidirectionalPersist() @@ -42,17 +44,17 @@ public function testPutOneToOneOnBidirectionalPersist() $this->loadFixturesTravelersWithProfile(); $this->loadFixturesTravelersProfileInfo(); - $this->_em->clear(); + $this->em->clear(); $entity1 = $this->travelersWithProfile[0]; $entity2 = $this->travelersWithProfile[1]; - $this->assertTrue($this->cache->containsEntity(Traveler::class, $entity1->getId())); - $this->assertTrue($this->cache->containsEntity(Traveler::class, $entity2->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity2->getProfile()->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfileInfo::class, $entity1->getProfile()->getInfo()->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfileInfo::class, $entity2->getProfile()->getInfo()->getId())); + self::assertTrue($this->cache->containsEntity(Traveler::class, $entity1->getId())); + self::assertTrue($this->cache->containsEntity(Traveler::class, $entity2->getId())); + self::assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); + self::assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity2->getProfile()->getId())); + self::assertTrue($this->cache->containsEntity(TravelerProfileInfo::class, $entity1->getProfile()->getInfo()->getId())); + self::assertTrue($this->cache->containsEntity(TravelerProfileInfo::class, $entity2->getProfile()->getInfo()->getId())); } public function testPutAndLoadOneToOneUnidirectionalRelation() @@ -63,7 +65,7 @@ public function testPutAndLoadOneToOneUnidirectionalRelation() $this->loadFixturesTravelersWithProfile(); $this->loadFixturesTravelersProfileInfo(); - $this->_em->clear(); + $this->em->clear(); $this->cache->evictEntityRegion(Traveler::class); $this->cache->evictEntityRegion(TravelerProfile::class); @@ -71,60 +73,60 @@ public function testPutAndLoadOneToOneUnidirectionalRelation() $entity1 = $this->travelersWithProfile[0]; $entity2 = $this->travelersWithProfile[1]; - $this->assertFalse($this->cache->containsEntity(Traveler::class, $entity1->getId())); - $this->assertFalse($this->cache->containsEntity(Traveler::class, $entity2->getId())); - $this->assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); - $this->assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity2->getProfile()->getId())); + self::assertFalse($this->cache->containsEntity(Traveler::class, $entity1->getId())); + self::assertFalse($this->cache->containsEntity(Traveler::class, $entity2->getId())); + self::assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); + self::assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity2->getProfile()->getId())); - $t1 = $this->_em->find(Traveler::class, $entity1->getId()); - $t2 = $this->_em->find(Traveler::class, $entity2->getId()); + $t1 = $this->em->find(Traveler::class, $entity1->getId()); + $t2 = $this->em->find(Traveler::class, $entity2->getId()); - $this->assertTrue($this->cache->containsEntity(Traveler::class, $entity1->getId())); - $this->assertTrue($this->cache->containsEntity(Traveler::class, $entity2->getId())); + self::assertTrue($this->cache->containsEntity(Traveler::class, $entity1->getId())); + self::assertTrue($this->cache->containsEntity(Traveler::class, $entity2->getId())); // The inverse side its not cached - $this->assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); - $this->assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity2->getProfile()->getId())); + self::assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); + self::assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity2->getProfile()->getId())); - $this->assertInstanceOf(Traveler::class, $t1); - $this->assertInstanceOf(Traveler::class, $t2); - $this->assertInstanceOf(TravelerProfile::class, $t1->getProfile()); - $this->assertInstanceOf(TravelerProfile::class, $t2->getProfile()); + self::assertInstanceOf(Traveler::class, $t1); + self::assertInstanceOf(Traveler::class, $t2); + self::assertInstanceOf(TravelerProfile::class, $t1->getProfile()); + self::assertInstanceOf(TravelerProfile::class, $t2->getProfile()); - $this->assertEquals($entity1->getId(), $t1->getId()); - $this->assertEquals($entity1->getName(), $t1->getName()); - $this->assertEquals($entity1->getProfile()->getId(), $t1->getProfile()->getId()); - $this->assertEquals($entity1->getProfile()->getName(), $t1->getProfile()->getName()); + self::assertEquals($entity1->getId(), $t1->getId()); + self::assertEquals($entity1->getName(), $t1->getName()); + self::assertEquals($entity1->getProfile()->getId(), $t1->getProfile()->getId()); + self::assertEquals($entity1->getProfile()->getName(), $t1->getProfile()->getName()); - $this->assertEquals($entity2->getId(), $t2->getId()); - $this->assertEquals($entity2->getName(), $t2->getName()); - $this->assertEquals($entity2->getProfile()->getId(), $t2->getProfile()->getId()); - $this->assertEquals($entity2->getProfile()->getName(), $t2->getProfile()->getName()); + self::assertEquals($entity2->getId(), $t2->getId()); + self::assertEquals($entity2->getName(), $t2->getName()); + self::assertEquals($entity2->getProfile()->getId(), $t2->getProfile()->getId()); + self::assertEquals($entity2->getProfile()->getName(), $t2->getProfile()->getName()); // its all cached now - $this->assertTrue($this->cache->containsEntity(Traveler::class, $entity1->getId())); - $this->assertTrue($this->cache->containsEntity(Traveler::class, $entity2->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); + self::assertTrue($this->cache->containsEntity(Traveler::class, $entity1->getId())); + self::assertTrue($this->cache->containsEntity(Traveler::class, $entity2->getId())); + self::assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); + self::assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); // load from cache - $t3 = $this->_em->find(Traveler::class, $entity1->getId()); - $t4 = $this->_em->find(Traveler::class, $entity2->getId()); + $t3 = $this->em->find(Traveler::class, $entity1->getId()); + $t4 = $this->em->find(Traveler::class, $entity2->getId()); - $this->assertInstanceOf(Traveler::class, $t3); - $this->assertInstanceOf(Traveler::class, $t4); - $this->assertInstanceOf(TravelerProfile::class, $t3->getProfile()); - $this->assertInstanceOf(TravelerProfile::class, $t4->getProfile()); + self::assertInstanceOf(Traveler::class, $t3); + self::assertInstanceOf(Traveler::class, $t4); + self::assertInstanceOf(TravelerProfile::class, $t3->getProfile()); + self::assertInstanceOf(TravelerProfile::class, $t4->getProfile()); - $this->assertEquals($entity1->getProfile()->getId(), $t3->getProfile()->getId()); - $this->assertEquals($entity2->getProfile()->getId(), $t4->getProfile()->getId()); + self::assertEquals($entity1->getProfile()->getId(), $t3->getProfile()->getId()); + self::assertEquals($entity2->getProfile()->getId(), $t4->getProfile()->getId()); - $this->assertEquals($entity1->getProfile()->getName(), $t3->getProfile()->getName()); - $this->assertEquals($entity2->getProfile()->getName(), $t4->getProfile()->getName()); + self::assertEquals($entity1->getProfile()->getName(), $t3->getProfile()->getName()); + self::assertEquals($entity2->getProfile()->getName(), $t4->getProfile()->getName()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); } public function testPutAndLoadOneToOneBidirectionalRelation() @@ -135,7 +137,7 @@ public function testPutAndLoadOneToOneBidirectionalRelation() $this->loadFixturesTravelersWithProfile(); $this->loadFixturesTravelersProfileInfo(); - $this->_em->clear(); + $this->em->clear(); $this->cache->evictEntityRegion(Traveler::class); $this->cache->evictEntityRegion(TravelerProfile::class); @@ -144,59 +146,59 @@ public function testPutAndLoadOneToOneBidirectionalRelation() $entity1 = $this->travelersWithProfile[0]->getProfile(); $entity2 = $this->travelersWithProfile[1]->getProfile(); - $this->assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity1->getId())); - $this->assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity2->getId())); - $this->assertFalse($this->cache->containsEntity(TravelerProfileInfo::class, $entity1->getInfo()->getId())); - $this->assertFalse($this->cache->containsEntity(TravelerProfileInfo::class, $entity2->getInfo()->getId())); + self::assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity1->getId())); + self::assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity2->getId())); + self::assertFalse($this->cache->containsEntity(TravelerProfileInfo::class, $entity1->getInfo()->getId())); + self::assertFalse($this->cache->containsEntity(TravelerProfileInfo::class, $entity2->getInfo()->getId())); - $p1 = $this->_em->find(TravelerProfile::class, $entity1->getId()); - $p2 = $this->_em->find(TravelerProfile::class, $entity2->getId()); + $p1 = $this->em->find(TravelerProfile::class, $entity1->getId()); + $p2 = $this->em->find(TravelerProfile::class, $entity2->getId()); - $this->assertEquals($entity1->getId(), $p1->getId()); - $this->assertEquals($entity1->getName(), $p1->getName()); - $this->assertEquals($entity1->getInfo()->getId(), $p1->getInfo()->getId()); - $this->assertEquals($entity1->getInfo()->getDescription(), $p1->getInfo()->getDescription()); + self::assertEquals($entity1->getId(), $p1->getId()); + self::assertEquals($entity1->getName(), $p1->getName()); + self::assertEquals($entity1->getInfo()->getId(), $p1->getInfo()->getId()); + self::assertEquals($entity1->getInfo()->getDescription(), $p1->getInfo()->getDescription()); - $this->assertEquals($entity2->getId(), $p2->getId()); - $this->assertEquals($entity2->getName(), $p2->getName()); - $this->assertEquals($entity2->getInfo()->getId(), $p2->getInfo()->getId()); - $this->assertEquals($entity2->getInfo()->getDescription(), $p2->getInfo()->getDescription()); + self::assertEquals($entity2->getId(), $p2->getId()); + self::assertEquals($entity2->getName(), $p2->getName()); + self::assertEquals($entity2->getInfo()->getId(), $p2->getInfo()->getId()); + self::assertEquals($entity2->getInfo()->getDescription(), $p2->getInfo()->getDescription()); - $this->assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity1->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity2->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfileInfo::class, $entity1->getInfo()->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfileInfo::class, $entity2->getInfo()->getId())); + self::assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity1->getId())); + self::assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity2->getId())); + self::assertTrue($this->cache->containsEntity(TravelerProfileInfo::class, $entity1->getInfo()->getId())); + self::assertTrue($this->cache->containsEntity(TravelerProfileInfo::class, $entity2->getInfo()->getId())); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); - $p3 = $this->_em->find(TravelerProfile::class, $entity1->getId()); - $p4 = $this->_em->find(TravelerProfile::class, $entity2->getId()); + $p3 = $this->em->find(TravelerProfile::class, $entity1->getId()); + $p4 = $this->em->find(TravelerProfile::class, $entity2->getId()); - $this->assertInstanceOf(TravelerProfile::class, $p3); - $this->assertInstanceOf(TravelerProfile::class, $p4); - $this->assertInstanceOf(TravelerProfileInfo::class, $p3->getInfo()); - $this->assertInstanceOf(TravelerProfileInfo::class, $p4->getInfo()); + self::assertInstanceOf(TravelerProfile::class, $p3); + self::assertInstanceOf(TravelerProfile::class, $p4); + self::assertInstanceOf(TravelerProfileInfo::class, $p3->getInfo()); + self::assertInstanceOf(TravelerProfileInfo::class, $p4->getInfo()); - $this->assertEquals($entity1->getId(), $p3->getId()); - $this->assertEquals($entity1->getName(), $p3->getName()); - $this->assertEquals($entity1->getInfo()->getId(), $p3->getInfo()->getId()); - $this->assertEquals($entity1->getInfo()->getDescription(), $p3->getInfo()->getDescription()); + self::assertEquals($entity1->getId(), $p3->getId()); + self::assertEquals($entity1->getName(), $p3->getName()); + self::assertEquals($entity1->getInfo()->getId(), $p3->getInfo()->getId()); + self::assertEquals($entity1->getInfo()->getDescription(), $p3->getInfo()->getDescription()); - $this->assertEquals($entity2->getId(), $p4->getId()); - $this->assertEquals($entity2->getName(), $p4->getName()); - $this->assertEquals($entity2->getInfo()->getId(), $p4->getInfo()->getId()); - $this->assertEquals($entity2->getInfo()->getDescription(), $p4->getInfo()->getDescription()); + self::assertEquals($entity2->getId(), $p4->getId()); + self::assertEquals($entity2->getName(), $p4->getName()); + self::assertEquals($entity2->getInfo()->getId(), $p4->getInfo()->getId()); + self::assertEquals($entity2->getInfo()->getDescription(), $p4->getInfo()->getDescription()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); } public function testInverseSidePutAndLoadOneToOneBidirectionalRelation() { $this->loadFixturesPersonWithAddress(); - $this->_em->clear(); + $this->em->clear(); $this->cache->evictEntityRegion(Person::class); $this->cache->evictEntityRegion(Address::class); @@ -204,81 +206,81 @@ public function testInverseSidePutAndLoadOneToOneBidirectionalRelation() $entity1 = $this->addresses[0]->person; $entity2 = $this->addresses[1]->person; - $this->assertFalse($this->cache->containsEntity(Person::class, $entity1->id)); - $this->assertFalse($this->cache->containsEntity(Person::class, $entity2->id)); - $this->assertFalse($this->cache->containsEntity(Address::class, $entity1->address->id)); - $this->assertFalse($this->cache->containsEntity(Address::class, $entity2->address->id)); + self::assertFalse($this->cache->containsEntity(Person::class, $entity1->id)); + self::assertFalse($this->cache->containsEntity(Person::class, $entity2->id)); + self::assertFalse($this->cache->containsEntity(Address::class, $entity1->address->id)); + self::assertFalse($this->cache->containsEntity(Address::class, $entity2->address->id)); - $p1 = $this->_em->find(Person::class, $entity1->id); - $p2 = $this->_em->find(Person::class, $entity2->id); + $p1 = $this->em->find(Person::class, $entity1->id); + $p2 = $this->em->find(Person::class, $entity2->id); - $this->assertEquals($entity1->id, $p1->id); - $this->assertEquals($entity1->name, $p1->name); - $this->assertEquals($entity1->address->id, $p1->address->id); - $this->assertEquals($entity1->address->location, $p1->address->location); + self::assertEquals($entity1->id, $p1->id); + self::assertEquals($entity1->name, $p1->name); + self::assertEquals($entity1->address->id, $p1->address->id); + self::assertEquals($entity1->address->location, $p1->address->location); - $this->assertEquals($entity2->id, $p2->id); - $this->assertEquals($entity2->name, $p2->name); - $this->assertEquals($entity2->address->id, $p2->address->id); - $this->assertEquals($entity2->address->location, $p2->address->location); + self::assertEquals($entity2->id, $p2->id); + self::assertEquals($entity2->name, $p2->name); + self::assertEquals($entity2->address->id, $p2->address->id); + self::assertEquals($entity2->address->location, $p2->address->location); - $this->assertTrue($this->cache->containsEntity(Person::class, $entity1->id)); - $this->assertTrue($this->cache->containsEntity(Person::class, $entity2->id)); + self::assertTrue($this->cache->containsEntity(Person::class, $entity1->id)); + self::assertTrue($this->cache->containsEntity(Person::class, $entity2->id)); // The inverse side its not cached - $this->assertFalse($this->cache->containsEntity(Address::class, $entity1->address->id)); - $this->assertFalse($this->cache->containsEntity(Address::class, $entity2->address->id)); + self::assertFalse($this->cache->containsEntity(Address::class, $entity1->address->id)); + self::assertFalse($this->cache->containsEntity(Address::class, $entity2->address->id)); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); - $p3 = $this->_em->find(Person::class, $entity1->id); - $p4 = $this->_em->find(Person::class, $entity2->id); + $p3 = $this->em->find(Person::class, $entity1->id); + $p4 = $this->em->find(Person::class, $entity2->id); - $this->assertInstanceOf(Person::class, $p3); - $this->assertInstanceOf(Person::class, $p4); - $this->assertInstanceOf(Address::class, $p3->address); - $this->assertInstanceOf(Address::class, $p4->address); + self::assertInstanceOf(Person::class, $p3); + self::assertInstanceOf(Person::class, $p4); + self::assertInstanceOf(Address::class, $p3->address); + self::assertInstanceOf(Address::class, $p4->address); - $this->assertEquals($entity1->id, $p3->id); - $this->assertEquals($entity1->name, $p3->name); - $this->assertEquals($entity1->address->id, $p3->address->id); - $this->assertEquals($entity1->address->location, $p3->address->location); + self::assertEquals($entity1->id, $p3->id); + self::assertEquals($entity1->name, $p3->name); + self::assertEquals($entity1->address->id, $p3->address->id); + self::assertEquals($entity1->address->location, $p3->address->location); - $this->assertEquals($entity2->id, $p4->id); - $this->assertEquals($entity2->name, $p4->name); - $this->assertEquals($entity2->address->id, $p4->address->id); - $this->assertEquals($entity2->address->location, $p4->address->location); + self::assertEquals($entity2->id, $p4->id); + self::assertEquals($entity2->name, $p4->name); + self::assertEquals($entity2->address->id, $p4->address->id); + self::assertEquals($entity2->address->location, $p4->address->location); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount()); } public function testPutAndLoadNonCacheableOneToOne() { - $this->assertNull($this->cache->getEntityCacheRegion(Client::class)); - $this->assertInstanceOf(Region::class, $this->cache->getEntityCacheRegion(Token::class)); + self::assertNull($this->cache->getEntityCacheRegion(Client::class)); + self::assertInstanceOf(Region::class, $this->cache->getEntityCacheRegion(Token::class)); $client = new Client('FabioBatSilva'); $token = new Token('token-hash', $client); - $this->_em->persist($client); - $this->_em->persist($token); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($client); + $this->em->persist($token); + $this->em->flush(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); - $this->assertTrue($this->cache->containsEntity(Token::class, $token->token)); - $this->assertFalse($this->cache->containsEntity(Client::class, $client->id)); + self::assertTrue($this->cache->containsEntity(Token::class, $token->token)); + self::assertFalse($this->cache->containsEntity(Client::class, $client->id)); - $entity = $this->_em->find(Token::class, $token->token); + $entity = $this->em->find(Token::class, $token->token); - $this->assertInstanceOf(Token::class, $entity); - $this->assertInstanceOf(Client::class, $entity->getClient()); - $this->assertEquals('token-hash', $entity->token); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertInstanceOf(Token::class, $entity); + self::assertInstanceOf(Client::class, $entity->getClient()); + self::assertEquals('token-hash', $entity->token); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertEquals('FabioBatSilva', $entity->getClient()->name); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals('FabioBatSilva', $entity->getClient()->name); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheQueryCacheTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheQueryCacheTest.php index 0a32886dd0f..4abf245db07 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheQueryCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheQueryCacheTest.php @@ -1,5 +1,7 @@ loadFixturesCountries(); $this->secondLevelCacheLogger->clearStats(); - $this->_em->clear(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; - $result1 = $this->_em->createQuery($dql)->setCacheable(true)->getResult(); + $result1 = $this->em->createQuery($dql)->setCacheable(true)->getResult(); - $this->assertCount(2, $result1); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertEquals($this->countries[0]->getId(), $result1[0]->getId()); - $this->assertEquals($this->countries[1]->getId(), $result1[1]->getId()); - $this->assertEquals($this->countries[0]->getName(), $result1[0]->getName()); - $this->assertEquals($this->countries[1]->getName(), $result1[1]->getName()); + self::assertCount(2, $result1); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals($this->countries[0]->getId(), $result1[0]->getId()); + self::assertEquals($this->countries[1]->getId(), $result1[1]->getId()); + self::assertEquals($this->countries[0]->getName(), $result1[0]->getName()); + self::assertEquals($this->countries[1]->getName(), $result1[1]->getName()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); - $this->_em->clear(); + $this->em->clear(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertCount(2, $result2); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(2, $result2); - $this->assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(3, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(3, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getDefaultQueryRegionName())); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); - $this->assertInstanceOf(Country::class, $result2[0]); - $this->assertInstanceOf(Country::class, $result2[1]); + self::assertInstanceOf(Country::class, $result2[0]); + self::assertInstanceOf(Country::class, $result2[1]); - $this->assertEquals($result1[0]->getId(), $result2[0]->getId()); - $this->assertEquals($result1[1]->getId(), $result2[1]->getId()); + self::assertEquals($result1[0]->getId(), $result2[0]->getId()); + self::assertEquals($result1[1]->getId(), $result2[1]->getId()); - $this->assertEquals($result1[0]->getName(), $result2[0]->getName()); - $this->assertEquals($result1[1]->getName(), $result2[1]->getName()); + self::assertEquals($result1[0]->getName(), $result2[0]->getName()); + self::assertEquals($result1[1]->getName(), $result2[1]->getName()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(3, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(3, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getDefaultQueryRegionName())); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); } public function testQueryCacheModeGet() @@ -89,37 +91,37 @@ public function testQueryCacheModeGet() $this->evictRegions(); $this->secondLevelCacheLogger->clearStats(); - $this->_em->clear(); + $this->em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; - $queryGet = $this->_em->createQuery($dql) + $queryGet = $this->em->createQuery($dql) ->setCacheMode(Cache::MODE_GET) ->setCacheable(true); // MODE_GET should never add items to the cache. - $this->assertCount(2, $queryGet->getResult()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(2, $queryGet->getResult()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertCount(2, $queryGet->getResult()); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + self::assertCount(2, $queryGet->getResult()); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount()); - $result = $this->_em->createQuery($dql) + $result = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertCount(2, $result); - $this->assertEquals($queryCount + 3, $this->getCurrentQueryCount()); + self::assertCount(2, $result); + self::assertEquals($queryCount + 3, $this->getCurrentQueryCount()); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); // MODE_GET should read items if exists. - $this->assertCount(2, $queryGet->getResult()); - $this->assertEquals($queryCount + 3, $this->getCurrentQueryCount()); + self::assertCount(2, $queryGet->getResult()); + self::assertEquals($queryCount + 3, $this->getCurrentQueryCount()); } public function testQueryCacheModePut() @@ -129,37 +131,37 @@ public function testQueryCacheModePut() $this->evictRegions(); $this->secondLevelCacheLogger->clearStats(); - $this->_em->clear(); + $this->em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; - $result = $this->_em->createQuery($dql) + $result = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $this->assertCount(2, $result); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(2, $result); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $queryPut = $this->_em->createQuery($dql) + $queryPut = $this->em->createQuery($dql) ->setCacheMode(Cache::MODE_PUT) ->setCacheable(true); // MODE_PUT should never read itens from cache. - $this->assertCount(2, $queryPut->getResult()); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - - $this->assertCount(2, $queryPut->getResult()); - $this->assertEquals($queryCount + 3, $this->getCurrentQueryCount()); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertCount(2, $queryPut->getResult()); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + + self::assertCount(2, $queryPut->getResult()); + self::assertEquals($queryCount + 3, $this->getCurrentQueryCount()); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); } public function testQueryCacheModeRefresh() @@ -169,23 +171,23 @@ public function testQueryCacheModeRefresh() $this->evictRegions(); $this->secondLevelCacheLogger->clearStats(); - $this->_em->clear(); + $this->em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $region = $this->cache->getEntityCacheRegion(Country::class); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; - $result = $this->_em->createQuery($dql) + $result = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $this->assertCount(2, $result); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(2, $result); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); $countryId1 = $this->countries[0]->getId(); $countryId2 = $this->countries[1]->getId(); @@ -199,26 +201,26 @@ public function testQueryCacheModeRefresh() $region->put($key1, $entry1); $region->put($key2, $entry2); - $this->_em->clear(); + $this->em->clear(); - $queryRefresh = $this->_em->createQuery($dql) + $queryRefresh = $this->em->createQuery($dql) ->setCacheMode(Cache::MODE_REFRESH) ->setCacheable(true); // MODE_REFRESH should never read itens from cache. $result1 = $queryRefresh->getResult(); - $this->assertCount(2, $result1); - $this->assertEquals($countryName1, $result1[0]->getName()); - $this->assertEquals($countryName2, $result1[1]->getName()); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + self::assertCount(2, $result1); + self::assertEquals($countryName1, $result1[0]->getName()); + self::assertEquals($countryName2, $result1[1]->getName()); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount()); - $this->_em->clear(); + $this->em->clear(); $result2 = $queryRefresh->getResult(); - $this->assertCount(2, $result2); - $this->assertEquals($countryName1, $result2[0]->getName()); - $this->assertEquals($countryName2, $result2[1]->getName()); - $this->assertEquals($queryCount + 3, $this->getCurrentQueryCount()); + self::assertCount(2, $result2); + self::assertEquals($countryName1, $result2[0]->getName()); + self::assertEquals($countryName2, $result2[1]->getName()); + self::assertEquals($queryCount + 3, $this->getCurrentQueryCount()); } public function testBasicQueryCachePutEntityCache() @@ -228,61 +230,61 @@ public function testBasicQueryCachePutEntityCache() $this->evictRegions(); $this->secondLevelCacheLogger->clearStats(); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; - $result1 = $this->_em->createQuery($dql)->setCacheable(true)->getResult(); + $result1 = $this->em->createQuery($dql)->setCacheable(true)->getResult(); - $this->assertCount(2, $result1); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertEquals($this->countries[0]->getId(), $result1[0]->getId()); - $this->assertEquals($this->countries[1]->getId(), $result1[1]->getId()); - $this->assertEquals($this->countries[0]->getName(), $result1[0]->getName()); - $this->assertEquals($this->countries[1]->getName(), $result1[1]->getName()); + self::assertCount(2, $result1); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals($this->countries[0]->getId(), $result1[0]->getId()); + self::assertEquals($this->countries[1]->getId(), $result1[1]->getId()); + self::assertEquals($this->countries[0]->getName(), $result1[0]->getName()); + self::assertEquals($this->countries[1]->getName(), $result1[1]->getName()); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $this->assertEquals(3, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); + self::assertEquals(3, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); - $this->_em->clear(); + $this->em->clear(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertCount(2, $result2); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(2, $result2); - $this->assertEquals(3, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(3, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(3, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(3, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getDefaultQueryRegionName())); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); - $this->assertInstanceOf(Country::class, $result2[0]); - $this->assertInstanceOf(Country::class, $result2[1]); + self::assertInstanceOf(Country::class, $result2[0]); + self::assertInstanceOf(Country::class, $result2[1]); - $this->assertEquals($result1[0]->getId(), $result2[0]->getId()); - $this->assertEquals($result1[1]->getId(), $result2[1]->getId()); + self::assertEquals($result1[0]->getId(), $result2[0]->getId()); + self::assertEquals($result1[1]->getId(), $result2[1]->getId()); - $this->assertEquals($result1[0]->getName(), $result2[0]->getName()); - $this->assertEquals($result1[1]->getName(), $result2[1]->getName()); + self::assertEquals($result1[0]->getName(), $result2[0]->getName()); + self::assertEquals($result1[1]->getName(), $result2[1]->getName()); - $this->assertEquals(3, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(3, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(3, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(3, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getDefaultQueryRegionName())); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); } /** @@ -302,70 +304,70 @@ public function testMultipleNestedDQLAliases() $this->secondLevelCacheLogger->clearStats(); $this->evictRegions(); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT s, c, a FROM Doctrine\Tests\Models\Cache\State s JOIN s.cities c JOIN c.attractions a'; - $result1 = $this->_em->createQuery($dql) + $result1 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertCount(2, $result1); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(2, $result1); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[2]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[3]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[2]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $this->cities[3]->getId())); - $this->assertTrue($this->cache->containsEntity(Attraction::class, $this->attractions[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Attraction::class, $this->attractions[1]->getId())); - $this->assertTrue($this->cache->containsEntity(Attraction::class, $this->attractions[2]->getId())); - $this->assertTrue($this->cache->containsEntity(Attraction::class, $this->attractions[3]->getId())); + self::assertTrue($this->cache->containsEntity(Attraction::class, $this->attractions[0]->getId())); + self::assertTrue($this->cache->containsEntity(Attraction::class, $this->attractions[1]->getId())); + self::assertTrue($this->cache->containsEntity(Attraction::class, $this->attractions[2]->getId())); + self::assertTrue($this->cache->containsEntity(Attraction::class, $this->attractions[3]->getId())); - $this->assertInstanceOf(State::class, $result1[0]); - $this->assertInstanceOf(State::class, $result1[1]); + self::assertInstanceOf(State::class, $result1[0]); + self::assertInstanceOf(State::class, $result1[1]); - $this->assertCount(2, $result1[0]->getCities()); - $this->assertCount(2, $result1[1]->getCities()); + self::assertCount(2, $result1[0]->getCities()); + self::assertCount(2, $result1[1]->getCities()); - $this->assertInstanceOf(City::class, $result1[0]->getCities()->get(0)); - $this->assertInstanceOf(City::class, $result1[0]->getCities()->get(1)); - $this->assertInstanceOf(City::class, $result1[1]->getCities()->get(0)); - $this->assertInstanceOf(City::class, $result1[1]->getCities()->get(1)); + self::assertInstanceOf(City::class, $result1[0]->getCities()->get(0)); + self::assertInstanceOf(City::class, $result1[0]->getCities()->get(1)); + self::assertInstanceOf(City::class, $result1[1]->getCities()->get(0)); + self::assertInstanceOf(City::class, $result1[1]->getCities()->get(1)); - $this->assertCount(2, $result1[0]->getCities()->get(0)->getAttractions()); - $this->assertCount(2, $result1[0]->getCities()->get(1)->getAttractions()); - $this->assertCount(2, $result1[1]->getCities()->get(0)->getAttractions()); - $this->assertCount(1, $result1[1]->getCities()->get(1)->getAttractions()); + self::assertCount(2, $result1[0]->getCities()->get(0)->getAttractions()); + self::assertCount(2, $result1[0]->getCities()->get(1)->getAttractions()); + self::assertCount(2, $result1[1]->getCities()->get(0)->getAttractions()); + self::assertCount(1, $result1[1]->getCities()->get(1)->getAttractions()); - $this->_em->clear(); + $this->em->clear(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertCount(2, $result2); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(2, $result2); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::class, $result2[0]); - $this->assertInstanceOf(State::class, $result2[1]); + self::assertInstanceOf(State::class, $result2[0]); + self::assertInstanceOf(State::class, $result2[1]); - $this->assertCount(2, $result2[0]->getCities()); - $this->assertCount(2, $result2[1]->getCities()); + self::assertCount(2, $result2[0]->getCities()); + self::assertCount(2, $result2[1]->getCities()); - $this->assertInstanceOf(City::class, $result2[0]->getCities()->get(0)); - $this->assertInstanceOf(City::class, $result2[0]->getCities()->get(1)); - $this->assertInstanceOf(City::class, $result2[1]->getCities()->get(0)); - $this->assertInstanceOf(City::class, $result2[1]->getCities()->get(1)); + self::assertInstanceOf(City::class, $result2[0]->getCities()->get(0)); + self::assertInstanceOf(City::class, $result2[0]->getCities()->get(1)); + self::assertInstanceOf(City::class, $result2[1]->getCities()->get(0)); + self::assertInstanceOf(City::class, $result2[1]->getCities()->get(1)); - $this->assertCount(2, $result2[0]->getCities()->get(0)->getAttractions()); - $this->assertCount(2, $result2[0]->getCities()->get(1)->getAttractions()); - $this->assertCount(2, $result2[1]->getCities()->get(0)->getAttractions()); - $this->assertCount(1, $result2[1]->getCities()->get(1)->getAttractions()); + self::assertCount(2, $result2[0]->getCities()->get(0)->getAttractions()); + self::assertCount(2, $result2[0]->getCities()->get(1)->getAttractions()); + self::assertCount(2, $result2[1]->getCities()->get(0)->getAttractions()); + self::assertCount(1, $result2[1]->getCities()->get(1)->getAttractions()); } public function testBasicQueryParams() @@ -373,36 +375,36 @@ public function testBasicQueryParams() $this->evictRegions(); $this->loadFixturesCountries(); - $this->_em->clear(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $queryCount = $this->getCurrentQueryCount(); $name = $this->countries[0]->getName(); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c WHERE c.name = :name'; - $result1 = $this->_em->createQuery($dql) + $result1 = $this->em->createQuery($dql) ->setCacheable(true) ->setParameter('name', $name) ->getResult(); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertEquals($this->countries[0]->getId(), $result1[0]->getId()); - $this->assertEquals($this->countries[0]->getName(), $result1[0]->getName()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals($this->countries[0]->getId(), $result1[0]->getId()); + self::assertEquals($this->countries[0]->getName(), $result1[0]->getName()); - $this->_em->clear(); + $this->em->clear(); - $result2 = $this->_em->createQuery($dql)->setCacheable(true) + $result2 = $this->em->createQuery($dql)->setCacheable(true) ->setParameter('name', $name) ->getResult(); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertCount(1, $result2); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(1, $result2); - $this->assertInstanceOf(Country::class, $result2[0]); + self::assertInstanceOf(Country::class, $result2[0]); - $this->assertEquals($result1[0]->getId(), $result2[0]->getId()); - $this->assertEquals($result1[0]->getName(), $result2[0]->getName()); + self::assertEquals($result1[0]->getId(), $result2[0]->getId()); + self::assertEquals($result1[0]->getName(), $result2[0]->getName()); } public function testLoadFromDatabaseWhenEntityMissing() @@ -410,54 +412,54 @@ public function testLoadFromDatabaseWhenEntityMissing() $this->evictRegions(); $this->loadFixturesCountries(); - $this->_em->clear(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; - $result1 = $this->_em->createQuery($dql)->setCacheable(true)->getResult(); + $result1 = $this->em->createQuery($dql)->setCacheable(true)->getResult(); - $this->assertCount(2, $result1); - $this->assertEquals($queryCount + 1 , $this->getCurrentQueryCount()); - $this->assertEquals($this->countries[0]->getId(), $result1[0]->getId()); - $this->assertEquals($this->countries[1]->getId(), $result1[1]->getId()); - $this->assertEquals($this->countries[0]->getName(), $result1[0]->getName()); - $this->assertEquals($this->countries[1]->getName(), $result1[1]->getName()); + self::assertCount(2, $result1); + self::assertEquals($queryCount + 1 , $this->getCurrentQueryCount()); + self::assertEquals($this->countries[0]->getId(), $result1[0]->getId()); + self::assertEquals($this->countries[1]->getId(), $result1[1]->getId()); + self::assertEquals($this->countries[0]->getName(), $result1[0]->getName()); + self::assertEquals($this->countries[1]->getName(), $result1[1]->getName()); - $this->assertEquals(3, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); + self::assertEquals(3, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); $this->cache->evictEntity(Country::class, $result1[0]->getId()); - $this->assertFalse($this->cache->containsEntity(Country::class, $result1[0]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $result1[0]->getId())); - $this->_em->clear(); + $this->em->clear(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertEquals($queryCount + 2 , $this->getCurrentQueryCount()); - $this->assertCount(2, $result2); + self::assertEquals($queryCount + 2 , $this->getCurrentQueryCount()); + self::assertCount(2, $result2); - $this->assertEquals(5, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(3, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); + self::assertEquals(5, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(3, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); - $this->assertInstanceOf(Country::class, $result2[0]); - $this->assertInstanceOf(Country::class, $result2[1]); + self::assertInstanceOf(Country::class, $result2[0]); + self::assertInstanceOf(Country::class, $result2[1]); - $this->assertEquals($result1[0]->getId(), $result2[0]->getId()); - $this->assertEquals($result1[1]->getId(), $result2[1]->getId()); + self::assertEquals($result1[0]->getId(), $result2[0]->getId()); + self::assertEquals($result1[1]->getId(), $result2[1]->getId()); - $this->assertEquals($result1[0]->getName(), $result2[0]->getName()); - $this->assertEquals($result1[1]->getName(), $result2[1]->getName()); + self::assertEquals($result1[0]->getName(), $result2[0]->getName()); + self::assertEquals($result1[1]->getName(), $result2[1]->getName()); - $this->assertEquals($queryCount + 2 , $this->getCurrentQueryCount()); + self::assertEquals($queryCount + 2 , $this->getCurrentQueryCount()); } public function testBasicQueryFetchJoinsOneToMany() @@ -467,62 +469,62 @@ public function testBasicQueryFetchJoinsOneToMany() $this->loadFixturesCities(); $this->evictRegions(); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT s, c FROM Doctrine\Tests\Models\Cache\State s JOIN s.cities c'; - $result1 = $this->_em->createQuery($dql) + $result1 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::class, $result1[0]); - $this->assertInstanceOf(State::class, $result1[1]); - $this->assertCount(2, $result1[0]->getCities()); - $this->assertCount(2, $result1[1]->getCities()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertInstanceOf(State::class, $result1[0]); + self::assertInstanceOf(State::class, $result1[1]); + self::assertCount(2, $result1[0]->getCities()); + self::assertCount(2, $result1[1]->getCities()); - $this->assertInstanceOf(City::class, $result1[0]->getCities()->get(0)); - $this->assertInstanceOf(City::class, $result1[0]->getCities()->get(1)); - $this->assertInstanceOf(City::class, $result1[1]->getCities()->get(0)); - $this->assertInstanceOf(City::class, $result1[1]->getCities()->get(1)); + self::assertInstanceOf(City::class, $result1[0]->getCities()->get(0)); + self::assertInstanceOf(City::class, $result1[0]->getCities()->get(1)); + self::assertInstanceOf(City::class, $result1[1]->getCities()->get(0)); + self::assertInstanceOf(City::class, $result1[1]->getCities()->get(1)); - $this->assertNotNull($result1[0]->getCities()->get(0)->getId()); - $this->assertNotNull($result1[0]->getCities()->get(1)->getId()); - $this->assertNotNull($result1[1]->getCities()->get(0)->getId()); - $this->assertNotNull($result1[1]->getCities()->get(1)->getId()); + self::assertNotNull($result1[0]->getCities()->get(0)->getId()); + self::assertNotNull($result1[0]->getCities()->get(1)->getId()); + self::assertNotNull($result1[1]->getCities()->get(0)->getId()); + self::assertNotNull($result1[1]->getCities()->get(1)->getId()); - $this->assertNotNull($result1[0]->getCities()->get(0)->getName()); - $this->assertNotNull($result1[0]->getCities()->get(1)->getName()); - $this->assertNotNull($result1[1]->getCities()->get(0)->getName()); - $this->assertNotNull($result1[1]->getCities()->get(1)->getName()); + self::assertNotNull($result1[0]->getCities()->get(0)->getName()); + self::assertNotNull($result1[0]->getCities()->get(1)->getName()); + self::assertNotNull($result1[1]->getCities()->get(0)->getName()); + self::assertNotNull($result1[1]->getCities()->get(1)->getName()); - $this->_em->clear(); + $this->em->clear(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertInstanceOf(State::class, $result2[0]); - $this->assertInstanceOf(State::class, $result2[1]); - $this->assertCount(2, $result2[0]->getCities()); - $this->assertCount(2, $result2[1]->getCities()); + self::assertInstanceOf(State::class, $result2[0]); + self::assertInstanceOf(State::class, $result2[1]); + self::assertCount(2, $result2[0]->getCities()); + self::assertCount(2, $result2[1]->getCities()); - $this->assertInstanceOf(City::class, $result2[0]->getCities()->get(0)); - $this->assertInstanceOf(City::class, $result2[0]->getCities()->get(1)); - $this->assertInstanceOf(City::class, $result2[1]->getCities()->get(0)); - $this->assertInstanceOf(City::class, $result2[1]->getCities()->get(1)); + self::assertInstanceOf(City::class, $result2[0]->getCities()->get(0)); + self::assertInstanceOf(City::class, $result2[0]->getCities()->get(1)); + self::assertInstanceOf(City::class, $result2[1]->getCities()->get(0)); + self::assertInstanceOf(City::class, $result2[1]->getCities()->get(1)); - $this->assertNotNull($result2[0]->getCities()->get(0)->getId()); - $this->assertNotNull($result2[0]->getCities()->get(1)->getId()); - $this->assertNotNull($result2[1]->getCities()->get(0)->getId()); - $this->assertNotNull($result2[1]->getCities()->get(1)->getId()); + self::assertNotNull($result2[0]->getCities()->get(0)->getId()); + self::assertNotNull($result2[0]->getCities()->get(1)->getId()); + self::assertNotNull($result2[1]->getCities()->get(0)->getId()); + self::assertNotNull($result2[1]->getCities()->get(1)->getId()); - $this->assertNotNull($result2[0]->getCities()->get(0)->getName()); - $this->assertNotNull($result2[0]->getCities()->get(1)->getName()); - $this->assertNotNull($result2[1]->getCities()->get(0)->getName()); - $this->assertNotNull($result2[1]->getCities()->get(1)->getName()); + self::assertNotNull($result2[0]->getCities()->get(0)->getName()); + self::assertNotNull($result2[0]->getCities()->get(1)->getName()); + self::assertNotNull($result2[1]->getCities()->get(0)->getName()); + self::assertNotNull($result2[1]->getCities()->get(1)->getName()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } public function testBasicQueryFetchJoinsManyToOne() @@ -530,66 +532,66 @@ public function testBasicQueryFetchJoinsManyToOne() $this->loadFixturesCountries(); $this->loadFixturesStates(); $this->loadFixturesCities(); - $this->_em->clear(); + $this->em->clear(); $this->evictRegions(); $this->secondLevelCacheLogger->clearStats(); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT c, s FROM Doctrine\Tests\Models\Cache\City c JOIN c.state s'; - $result1 = $this->_em->createQuery($dql) + $result1 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertCount(4, $result1); - $this->assertInstanceOf(City::class, $result1[0]); - $this->assertInstanceOf(City::class, $result1[1]); - $this->assertInstanceOf(State::class, $result1[0]->getState()); - $this->assertInstanceOf(State::class, $result1[1]->getState()); + self::assertCount(4, $result1); + self::assertInstanceOf(City::class, $result1[0]); + self::assertInstanceOf(City::class, $result1[1]); + self::assertInstanceOf(State::class, $result1[0]->getState()); + self::assertInstanceOf(State::class, $result1[1]->getState()); - $this->assertTrue($this->cache->containsEntity(City::class, $result1[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $result1[1]->getId())); - $this->assertTrue($this->cache->containsEntity(State::class, $result1[0]->getState()->getId())); - $this->assertTrue($this->cache->containsEntity(State::class, $result1[1]->getState()->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $result1[0]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $result1[1]->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $result1[0]->getState()->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $result1[1]->getState()->getId())); - $this->assertEquals(7, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); - $this->assertEquals(4, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(City::class))); + self::assertEquals(7, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); + self::assertEquals(4, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(City::class))); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->_em->clear(); + $this->em->clear(); $this->secondLevelCacheLogger->clearStats(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertCount(4, $result1); - $this->assertInstanceOf(City::class, $result2[0]); - $this->assertInstanceOf(City::class, $result2[1]); - $this->assertInstanceOf(State::class, $result2[0]->getState()); - $this->assertInstanceOf(State::class, $result2[1]->getState()); + self::assertCount(4, $result1); + self::assertInstanceOf(City::class, $result2[0]); + self::assertInstanceOf(City::class, $result2[1]); + self::assertInstanceOf(State::class, $result2[0]->getState()); + self::assertInstanceOf(State::class, $result2[1]->getState()); - $this->assertNotNull($result2[0]->getId()); - $this->assertNotNull($result2[0]->getId()); - $this->assertNotNull($result2[1]->getState()->getId()); - $this->assertNotNull($result2[1]->getState()->getId()); + self::assertNotNull($result2[0]->getId()); + self::assertNotNull($result2[0]->getId()); + self::assertNotNull($result2[1]->getState()->getId()); + self::assertNotNull($result2[1]->getState()->getId()); - $this->assertNotNull($result2[0]->getName()); - $this->assertNotNull($result2[0]->getName()); - $this->assertNotNull($result2[1]->getState()->getName()); - $this->assertNotNull($result2[1]->getState()->getName()); + self::assertNotNull($result2[0]->getName()); + self::assertNotNull($result2[0]->getName()); + self::assertNotNull($result2[1]->getState()->getName()); + self::assertNotNull($result2[1]->getState()->getName()); - $this->assertEquals($result1[0]->getName(), $result2[0]->getName()); - $this->assertEquals($result1[1]->getName(), $result2[1]->getName()); - $this->assertEquals($result1[0]->getState()->getName(), $result2[0]->getState()->getName()); - $this->assertEquals($result1[1]->getState()->getName(), $result2[1]->getState()->getName()); + self::assertEquals($result1[0]->getName(), $result2[0]->getName()); + self::assertEquals($result1[1]->getName(), $result2[1]->getName()); + self::assertEquals($result1[0]->getState()->getName(), $result2[0]->getState()->getName()); + self::assertEquals($result1[1]->getState()->getName(), $result2[1]->getState()->getName()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } public function testReloadQueryIfToOneIsNotFound() @@ -597,44 +599,44 @@ public function testReloadQueryIfToOneIsNotFound() $this->loadFixturesCountries(); $this->loadFixturesStates(); $this->loadFixturesCities(); - $this->_em->clear(); + $this->em->clear(); $this->evictRegions(); $this->secondLevelCacheLogger->clearStats(); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT c, s FROM Doctrine\Tests\Models\Cache\City c JOIN c.state s'; - $result1 = $this->_em->createQuery($dql) + $result1 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertCount(4, $result1); - $this->assertInstanceOf(City::class, $result1[0]); - $this->assertInstanceOf(City::class, $result1[1]); - $this->assertInstanceOf(State::class, $result1[0]->getState()); - $this->assertInstanceOf(State::class, $result1[1]->getState()); + self::assertCount(4, $result1); + self::assertInstanceOf(City::class, $result1[0]); + self::assertInstanceOf(City::class, $result1[1]); + self::assertInstanceOf(State::class, $result1[0]->getState()); + self::assertInstanceOf(State::class, $result1[1]->getState()); - $this->assertTrue($this->cache->containsEntity(City::class, $result1[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::class, $result1[1]->getId())); - $this->assertTrue($this->cache->containsEntity(State::class, $result1[0]->getState()->getId())); - $this->assertTrue($this->cache->containsEntity(State::class, $result1[1]->getState()->getId())); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertTrue($this->cache->containsEntity(City::class, $result1[0]->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $result1[1]->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $result1[0]->getState()->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $result1[1]->getState()->getId())); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->_em->clear(); + $this->em->clear(); $this->cache->evictEntityRegion(State::class); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertCount(4, $result1); - $this->assertInstanceOf(City::class, $result2[0]); - $this->assertInstanceOf(City::class, $result2[1]); - $this->assertInstanceOf(State::class, $result2[0]->getState()); - $this->assertInstanceOf(State::class, $result2[1]->getState()); + self::assertCount(4, $result1); + self::assertInstanceOf(City::class, $result2[0]); + self::assertInstanceOf(City::class, $result2[1]); + self::assertInstanceOf(State::class, $result2[0]->getState()); + self::assertInstanceOf(State::class, $result2[1]->getState()); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount()); } public function testReloadQueryIfToManyAssociationItemIsNotFound() @@ -644,44 +646,44 @@ public function testReloadQueryIfToManyAssociationItemIsNotFound() $this->loadFixturesCities(); $this->evictRegions(); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT s, c FROM Doctrine\Tests\Models\Cache\State s JOIN s.cities c'; - $result1 = $this->_em->createQuery($dql) + $result1 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::class, $result1[0]); - $this->assertInstanceOf(State::class, $result1[1]); - $this->assertCount(2, $result1[0]->getCities()); - $this->assertCount(2, $result1[1]->getCities()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertInstanceOf(State::class, $result1[0]); + self::assertInstanceOf(State::class, $result1[1]); + self::assertCount(2, $result1[0]->getCities()); + self::assertCount(2, $result1[1]->getCities()); - $this->assertInstanceOf(City::class, $result1[0]->getCities()->get(0)); - $this->assertInstanceOf(City::class, $result1[0]->getCities()->get(1)); - $this->assertInstanceOf(City::class, $result1[1]->getCities()->get(0)); - $this->assertInstanceOf(City::class, $result1[1]->getCities()->get(1)); + self::assertInstanceOf(City::class, $result1[0]->getCities()->get(0)); + self::assertInstanceOf(City::class, $result1[0]->getCities()->get(1)); + self::assertInstanceOf(City::class, $result1[1]->getCities()->get(0)); + self::assertInstanceOf(City::class, $result1[1]->getCities()->get(1)); - $this->_em->clear(); + $this->em->clear(); $this->cache->evictEntityRegion(City::class); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertInstanceOf(State::class, $result2[0]); - $this->assertInstanceOf(State::class, $result2[1]); - $this->assertCount(2, $result2[0]->getCities()); - $this->assertCount(2, $result2[1]->getCities()); + self::assertInstanceOf(State::class, $result2[0]); + self::assertInstanceOf(State::class, $result2[1]); + self::assertCount(2, $result2[0]->getCities()); + self::assertCount(2, $result2[1]->getCities()); - $this->assertInstanceOf(City::class, $result2[0]->getCities()->get(0)); - $this->assertInstanceOf(City::class, $result2[0]->getCities()->get(1)); - $this->assertInstanceOf(City::class, $result2[1]->getCities()->get(0)); - $this->assertInstanceOf(City::class, $result2[1]->getCities()->get(1)); + self::assertInstanceOf(City::class, $result2[0]->getCities()->get(0)); + self::assertInstanceOf(City::class, $result2[0]->getCities()->get(1)); + self::assertInstanceOf(City::class, $result2[1]->getCities()->get(0)); + self::assertInstanceOf(City::class, $result2[1]->getCities()->get(1)); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount()); } public function testBasicNativeQueryCache() @@ -690,10 +692,10 @@ public function testBasicNativeQueryCache() $this->loadFixturesCountries(); $this->secondLevelCacheLogger->clearStats(); - $this->_em->clear(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $rsm = new ResultSetMapping; $rsm->addEntityResult(Country::class, 'c'); @@ -702,53 +704,53 @@ public function testBasicNativeQueryCache() $queryCount = $this->getCurrentQueryCount(); $sql = 'SELECT id, name FROM cache_country'; - $result1 = $this->_em->createNativeQuery($sql, $rsm)->setCacheable(true)->getResult(); + $result1 = $this->em->createNativeQuery($sql, $rsm)->setCacheable(true)->getResult(); - $this->assertCount(2, $result1); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertEquals($this->countries[0]->getId(), $result1[0]->getId()); - $this->assertEquals($this->countries[1]->getId(), $result1[1]->getId()); - $this->assertEquals($this->countries[0]->getName(), $result1[0]->getName()); - $this->assertEquals($this->countries[1]->getName(), $result1[1]->getName()); + self::assertCount(2, $result1); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals($this->countries[0]->getId(), $result1[0]->getId()); + self::assertEquals($this->countries[1]->getId(), $result1[1]->getId()); + self::assertEquals($this->countries[0]->getName(), $result1[0]->getName()); + self::assertEquals($this->countries[1]->getName(), $result1[1]->getName()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); - $this->_em->clear(); + $this->em->clear(); - $result2 = $this->_em->createNativeQuery($sql, $rsm) + $result2 = $this->em->createNativeQuery($sql, $rsm) ->setCacheable(true) ->getResult(); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertCount(2, $result2); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(2, $result2); - $this->assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(3, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(3, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getDefaultQueryRegionName())); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); - $this->assertInstanceOf(Country::class, $result2[0]); - $this->assertInstanceOf(Country::class, $result2[1]); + self::assertInstanceOf(Country::class, $result2[0]); + self::assertInstanceOf(Country::class, $result2[1]); - $this->assertEquals($result1[0]->getId(), $result2[0]->getId()); - $this->assertEquals($result1[1]->getId(), $result2[1]->getId()); + self::assertEquals($result1[0]->getId(), $result2[0]->getId()); + self::assertEquals($result1[1]->getId(), $result2[1]->getId()); - $this->assertEquals($result1[0]->getName(), $result2[0]->getName()); - $this->assertEquals($result1[1]->getName(), $result2[1]->getName()); + self::assertEquals($result1[0]->getName(), $result2[0]->getName()); + self::assertEquals($result1[1]->getName(), $result2[1]->getName()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(3, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(3, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getDefaultQueryRegionName())); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getDefaultQueryRegionName())); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); } public function testQueryDependsOnFirstAndMaxResultResult() @@ -757,41 +759,41 @@ public function testQueryDependsOnFirstAndMaxResultResult() $this->loadFixturesCountries(); $this->secondLevelCacheLogger->clearStats(); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; - $result1 = $this->_em->createQuery($dql) + $result1 = $this->em->createQuery($dql) ->setCacheable(true) ->setFirstResult(1) ->setMaxResults(1) ->getResult(); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->_em->clear(); + $this->em->clear(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->em->createQuery($dql) ->setCacheable(true) ->setFirstResult(2) ->setMaxResults(1) ->getResult(); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); - $this->_em->clear(); + $this->em->clear(); - $result3 = $this->_em->createQuery($dql) + $result3 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertEquals($queryCount + 3, $this->getCurrentQueryCount()); - $this->assertEquals(3, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(3, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals($queryCount + 3, $this->getCurrentQueryCount()); + self::assertEquals(3, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(3, $this->secondLevelCacheLogger->getMissCount()); } public function testQueryCacheLifetime() @@ -800,7 +802,7 @@ public function testQueryCacheLifetime() $this->loadFixturesCountries(); $this->secondLevelCacheLogger->clearStats(); - $this->_em->clear(); + $this->em->clear(); $getHash = function(AbstractQuery $query){ $method = new \ReflectionMethod($query, 'getHash'); @@ -811,39 +813,39 @@ public function testQueryCacheLifetime() $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result1 = $query->setCacheable(true) ->setLifetime(3600) ->getResult(); - $this->assertNotEmpty($result1); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertNotEmpty($result1); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->_em->clear(); + $this->em->clear(); $key = new QueryCacheKey($getHash($query), 3600); $entry = $this->cache->getQueryCache() ->getRegion() ->get($key); - $this->assertInstanceOf(Cache\QueryCacheEntry::class, $entry); + self::assertInstanceOf(Cache\QueryCacheEntry::class, $entry); $entry->time = $entry->time / 2; $this->cache->getQueryCache() ->getRegion() ->put($key, $entry); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->em->createQuery($dql) ->setCacheable(true) ->setLifetime(3600) ->getResult(); - $this->assertNotEmpty($result2); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); + self::assertNotEmpty($result2); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); } public function testQueryCacheRegion() @@ -852,65 +854,65 @@ public function testQueryCacheRegion() $this->loadFixturesCountries(); $this->secondLevelCacheLogger->clearStats(); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $query1 = clone $query; $result1 = $query1->setCacheable(true) ->setCacheRegion('foo_region') ->getResult(); - $this->assertNotEmpty($result1); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertEquals(0, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount('foo_region')); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount('foo_region')); + self::assertNotEmpty($result1); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals(0, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount('foo_region')); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount('foo_region')); $query2 = clone $query; $result2 = $query2->setCacheable(true) ->setCacheRegion('bar_region') ->getResult(); - $this->assertNotEmpty($result2); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); - $this->assertEquals(0, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount('bar_region')); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount('bar_region')); + self::assertNotEmpty($result2); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + self::assertEquals(0, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount('bar_region')); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount('bar_region')); $query3 = clone $query; $result3 = $query3->setCacheable(true) ->setCacheRegion('foo_region') ->getResult(); - $this->assertNotEmpty($result3); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); - $this->assertEquals(3, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount('foo_region')); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount('foo_region')); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount('foo_region')); + self::assertNotEmpty($result3); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + self::assertEquals(3, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount('foo_region')); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount('foo_region')); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount('foo_region')); $query4 = clone $query; $result4 = $query4->setCacheable(true) ->setCacheRegion('bar_region') ->getResult(); - $this->assertNotEmpty($result3); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); - $this->assertEquals(6, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount('bar_region')); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount('bar_region')); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount('bar_region')); + self::assertNotEmpty($result3); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + self::assertEquals(6, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount('bar_region')); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount('bar_region')); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount('bar_region')); } public function testResolveAssociationCacheEntry() @@ -919,12 +921,12 @@ public function testResolveAssociationCacheEntry() $this->loadFixturesCountries(); $this->loadFixturesStates(); - $this->_em->clear(); + $this->em->clear(); $stateId = $this->states[0]->getId(); $countryName = $this->states[0]->getCountry()->getName(); $dql = 'SELECT s FROM Doctrine\Tests\Models\Cache\State s WHERE s.id = :id'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $queryCount = $this->getCurrentQueryCount(); $query1 = clone $query; @@ -934,15 +936,15 @@ public function testResolveAssociationCacheEntry() ->setMaxResults(1) ->getSingleResult(); - $this->assertNotNull($state1); - $this->assertNotNull($state1->getCountry()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::class, $state1); - $this->assertInstanceOf(Proxy::class, $state1->getCountry()); - $this->assertEquals($countryName, $state1->getCountry()->getName()); - $this->assertEquals($stateId, $state1->getId()); + self::assertNotNull($state1); + self::assertNotNull($state1->getCountry()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertInstanceOf(State::class, $state1); + self::assertInstanceOf(Proxy::class, $state1->getCountry()); + self::assertEquals($countryName, $state1->getCountry()->getName()); + self::assertEquals($stateId, $state1->getId()); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); $query2 = clone $query; @@ -952,13 +954,13 @@ public function testResolveAssociationCacheEntry() ->setMaxResults(1) ->getSingleResult(); - $this->assertNotNull($state2); - $this->assertNotNull($state2->getCountry()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::class, $state2); - $this->assertInstanceOf(Proxy::class, $state2->getCountry()); - $this->assertEquals($countryName, $state2->getCountry()->getName()); - $this->assertEquals($stateId, $state2->getId()); + self::assertNotNull($state2); + self::assertNotNull($state2->getCountry()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertInstanceOf(State::class, $state2); + self::assertInstanceOf(Proxy::class, $state2->getCountry()); + self::assertEquals($countryName, $state2->getCountry()->getName()); + self::assertEquals($stateId, $state2->getId()); } public function testResolveToOneAssociationCacheEntry() @@ -969,11 +971,11 @@ public function testResolveToOneAssociationCacheEntry() $this->loadFixturesCities(); $this->evictRegions(); - $this->_em->clear(); + $this->em->clear(); $cityId = $this->cities[0]->getId(); $dql = 'SELECT c, s FROM Doctrine\Tests\Models\Cache\City c JOIN c.state s WHERE c.id = :id'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $queryCount = $this->getCurrentQueryCount(); $query1 = clone $query; @@ -983,13 +985,13 @@ public function testResolveToOneAssociationCacheEntry() ->setMaxResults(1) ->getSingleResult(); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf(City::class, $city1); - $this->assertInstanceOf(State::class, $city1->getState()); - $this->assertInstanceOf(City::class, $city1->getState()->getCities()->get(0)); - $this->assertInstanceOf(State::class, $city1->getState()->getCities()->get(0)->getState()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertInstanceOf(City::class, $city1); + self::assertInstanceOf(State::class, $city1->getState()); + self::assertInstanceOf(City::class, $city1->getState()->getCities()->get(0)); + self::assertInstanceOf(State::class, $city1->getState()->getCities()->get(0)->getState()); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); $query2 = clone $query; @@ -999,11 +1001,11 @@ public function testResolveToOneAssociationCacheEntry() ->setMaxResults(1) ->getSingleResult(); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(City::class, $city2); - $this->assertInstanceOf(State::class, $city2->getState()); - $this->assertInstanceOf(City::class, $city2->getState()->getCities()->get(0)); - $this->assertInstanceOf(State::class, $city2->getState()->getCities()->get(0)->getState()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertInstanceOf(City::class, $city2); + self::assertInstanceOf(State::class, $city2->getState()); + self::assertInstanceOf(City::class, $city2->getState()->getCities()->get(0)); + self::assertInstanceOf(State::class, $city2->getState()->getCities()->get(0)->getState()); } public function testResolveToManyAssociationCacheEntry() @@ -1014,11 +1016,11 @@ public function testResolveToManyAssociationCacheEntry() $this->loadFixturesCities(); $this->evictRegions(); - $this->_em->clear(); + $this->em->clear(); $stateId = $this->states[0]->getId(); $dql = 'SELECT s, c FROM Doctrine\Tests\Models\Cache\State s JOIN s.cities c WHERE s.id = :id'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $queryCount = $this->getCurrentQueryCount(); $query1 = clone $query; @@ -1028,14 +1030,14 @@ public function testResolveToManyAssociationCacheEntry() ->setMaxResults(1) ->getSingleResult(); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::class, $state1); - $this->assertInstanceOf(Proxy::class, $state1->getCountry()); - $this->assertInstanceOf(City::class, $state1->getCities()->get(0)); - $this->assertInstanceOf(State::class, $state1->getCities()->get(0)->getState()); - $this->assertSame($state1, $state1->getCities()->get(0)->getState()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertInstanceOf(State::class, $state1); + self::assertInstanceOf(Proxy::class, $state1->getCountry()); + self::assertInstanceOf(City::class, $state1->getCities()->get(0)); + self::assertInstanceOf(State::class, $state1->getCities()->get(0)->getState()); + self::assertSame($state1, $state1->getCities()->get(0)->getState()); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); $query2 = clone $query; @@ -1045,12 +1047,12 @@ public function testResolveToManyAssociationCacheEntry() ->setMaxResults(1) ->getSingleResult(); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::class, $state2); - $this->assertInstanceOf(Proxy::class, $state2->getCountry()); - $this->assertInstanceOf(City::class, $state2->getCities()->get(0)); - $this->assertInstanceOf(State::class, $state2->getCities()->get(0)->getState()); - $this->assertSame($state2, $state2->getCities()->get(0)->getState()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertInstanceOf(State::class, $state2); + self::assertInstanceOf(Proxy::class, $state2->getCountry()); + self::assertInstanceOf(City::class, $state2->getCities()->get(0)); + self::assertInstanceOf(State::class, $state2->getCities()->get(0)->getState()); + self::assertSame($state2, $state2->getCities()->get(0)->getState()); } public function testHintClearEntityRegionUpdateStatement() @@ -1058,15 +1060,15 @@ public function testHintClearEntityRegionUpdateStatement() $this->evictRegions(); $this->loadFixturesCountries(); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $this->_em->createQuery('DELETE Doctrine\Tests\Models\Cache\Country u WHERE u.id = 4') + $this->em->createQuery('DELETE Doctrine\Tests\Models\Cache\Country u WHERE u.id = 4') ->setHint(Query::HINT_CACHE_EVICT, true) ->execute(); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); } public function testHintClearEntityRegionDeleteStatement() @@ -1074,15 +1076,15 @@ public function testHintClearEntityRegionDeleteStatement() $this->evictRegions(); $this->loadFixturesCountries(); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $this->_em->createQuery("UPDATE Doctrine\Tests\Models\Cache\Country u SET u.name = 'foo' WHERE u.id = 1") + $this->em->createQuery("UPDATE Doctrine\Tests\Models\Cache\Country u SET u.name = 'foo' WHERE u.id = 1") ->setHint(Query::HINT_CACHE_EVICT, true) ->execute(); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); } /** @@ -1094,7 +1096,7 @@ public function testCacheablePartialQueryException() $this->evictRegions(); $this->loadFixturesCountries(); - $this->_em->createQuery("SELECT PARTIAL c.{id} FROM Doctrine\Tests\Models\Cache\Country c") + $this->em->createQuery("SELECT PARTIAL c.{id} FROM Doctrine\Tests\Models\Cache\Country c") ->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true) ->setCacheable(true) ->getResult(); @@ -1106,7 +1108,7 @@ public function testCacheablePartialQueryException() */ public function testNonCacheableQueryDeleteStatementException() { - $this->_em->createQuery("DELETE Doctrine\Tests\Models\Cache\Country u WHERE u.id = 4") + $this->em->createQuery("DELETE Doctrine\Tests\Models\Cache\Country u WHERE u.id = 4") ->setCacheable(true) ->getResult(); } @@ -1117,7 +1119,7 @@ public function testNonCacheableQueryDeleteStatementException() */ public function testNonCacheableQueryUpdateStatementException() { - $this->_em->createQuery("UPDATE Doctrine\Tests\Models\Cache\Country u SET u.name = 'foo' WHERE u.id = 4") + $this->em->createQuery("UPDATE Doctrine\Tests\Models\Cache\Country u SET u.name = 'foo' WHERE u.id = 4") ->setCacheable(true) ->getResult(); } @@ -1125,33 +1127,33 @@ public function testNonCacheableQueryUpdateStatementException() public function testQueryCacheShouldBeEvictedOnTimestampUpdate() { $this->loadFixturesCountries(); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT country FROM Doctrine\Tests\Models\Cache\Country country'; - $result1 = $this->_em->createQuery($dql) + $result1 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertCount(2, $result1); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(2, $result1); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->_em->persist(new Country('France')); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist(new Country('France')); + $this->em->flush(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertCount(3, $result2); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(3, $result2); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); foreach ($result2 as $entity) { - $this->assertInstanceOf(Country::class, $entity); + self::assertInstanceOf(Country::class, $entity); } } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheRepositoryTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheRepositoryTest.php index c8c4303c4da..d9b6cd45dfe 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheRepositoryTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheRepositoryTest.php @@ -1,5 +1,7 @@ loadFixturesCountries(); $this->secondLevelCacheLogger->clearStats(); - $this->_em->clear(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $queryCount = $this->getCurrentQueryCount(); - $repository = $this->_em->getRepository(Country::class); + $repository = $this->em->getRepository(Country::class); $country1 = $repository->find($this->countries[0]->getId()); $country2 = $repository->find($this->countries[1]->getId()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(Country::class, $country1); - $this->assertInstanceOf(Country::class, $country2); + self::assertInstanceOf(Country::class, $country1); + self::assertInstanceOf(Country::class, $country2); - $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(0, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(Country::class))); + self::assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(0, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(Country::class))); } @@ -43,30 +45,30 @@ public function testRepositoryCacheFindAll() $this->loadFixturesCountries(); $this->evictRegions(); $this->secondLevelCacheLogger->clearStats(); - $this->_em->clear(); + $this->em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $repository = $this->_em->getRepository(Country::class); + $repository = $this->em->getRepository(Country::class); $queryCount = $this->getCurrentQueryCount(); - $this->assertCount(2, $repository->findAll()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(2, $repository->findAll()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); $queryCount = $this->getCurrentQueryCount(); $countries = $repository->findAll(); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(Country::class, $countries[0]); - $this->assertInstanceOf(Country::class, $countries[1]); + self::assertInstanceOf(Country::class, $countries[0]); + self::assertInstanceOf(Country::class, $countries[1]); - $this->assertEquals(3, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(3, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); } public function testRepositoryCacheFindAllInvalidation() @@ -74,47 +76,46 @@ public function testRepositoryCacheFindAllInvalidation() $this->loadFixturesCountries(); $this->evictRegions(); $this->secondLevelCacheLogger->clearStats(); - $this->_em->clear(); + $this->em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $repository = $this->_em->getRepository(Country::class); + $repository = $this->em->getRepository(Country::class); $queryCount = $this->getCurrentQueryCount(); - $this->assertCount(2, $repository->findAll()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(2, $repository->findAll()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); $queryCount = $this->getCurrentQueryCount(); $countries = $repository->findAll(); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - - $this->assertCount(2, $countries); - $this->assertInstanceOf(Country::class, $countries[0]); - $this->assertInstanceOf(Country::class, $countries[1]); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertCount(2, $countries); + self::assertInstanceOf(Country::class, $countries[0]); + self::assertInstanceOf(Country::class, $countries[1]); $country = new Country('foo'); - $this->_em->persist($country); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($country); + $this->em->flush(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); - $this->assertCount(3, $repository->findAll()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(3, $repository->findAll()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); $country = $repository->find($country->getId()); - $this->_em->remove($country); - $this->_em->flush(); - $this->_em->clear(); + $this->em->remove($country); + $this->em->flush(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); - $this->assertCount(2, $repository->findAll()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(2, $repository->findAll()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } public function testRepositoryCacheFindBy() @@ -122,29 +123,29 @@ public function testRepositoryCacheFindBy() $this->loadFixturesCountries(); $this->evictRegions(); $this->secondLevelCacheLogger->clearStats(); - $this->_em->clear(); + $this->em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); $criteria = ['name'=>$this->countries[0]->getName()]; - $repository = $this->_em->getRepository(Country::class); + $repository = $this->em->getRepository(Country::class); $queryCount = $this->getCurrentQueryCount(); - $this->assertCount(1, $repository->findBy($criteria)); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(1, $repository->findBy($criteria)); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); $queryCount = $this->getCurrentQueryCount(); $countries = $repository->findBy($criteria); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertCount(1, $countries); - $this->assertInstanceOf(Country::class, $countries[0]); + self::assertCount(1, $countries); + self::assertInstanceOf(Country::class, $countries[0]); - $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); } public function testRepositoryCacheFindOneBy() @@ -152,28 +153,28 @@ public function testRepositoryCacheFindOneBy() $this->loadFixturesCountries(); $this->evictRegions(); $this->secondLevelCacheLogger->clearStats(); - $this->_em->clear(); + $this->em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); $criteria = ['name'=>$this->countries[0]->getName()]; - $repository = $this->_em->getRepository(Country::class); + $repository = $this->em->getRepository(Country::class); $queryCount = $this->getCurrentQueryCount(); - $this->assertNotNull($repository->findOneBy($criteria)); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertNotNull($repository->findOneBy($criteria)); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); $queryCount = $this->getCurrentQueryCount(); $country = $repository->findOneBy($criteria); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(Country::class, $country); + self::assertInstanceOf(Country::class, $country); - $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); } public function testRepositoryCacheFindAllToOneAssociation() @@ -184,68 +185,68 @@ public function testRepositoryCacheFindAllToOneAssociation() $this->evictRegions(); $this->secondLevelCacheLogger->clearStats(); - $this->_em->clear(); + $this->em->clear(); // load from database - $repository = $this->_em->getRepository(State::class); + $repository = $this->em->getRepository(State::class); $queryCount = $this->getCurrentQueryCount(); $entities = $repository->findAll(); - $this->assertCount(4, $entities); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(4, $entities); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::class, $entities[0]); - $this->assertInstanceOf(State::class, $entities[1]); - $this->assertInstanceOf(Country::class, $entities[0]->getCountry()); - $this->assertInstanceOf(Country::class, $entities[0]->getCountry()); - $this->assertInstanceOf(Proxy::class, $entities[0]->getCountry()); - $this->assertInstanceOf(Proxy::class, $entities[1]->getCountry()); + self::assertInstanceOf(State::class, $entities[0]); + self::assertInstanceOf(State::class, $entities[1]); + self::assertInstanceOf(Country::class, $entities[0]->getCountry()); + self::assertInstanceOf(Country::class, $entities[0]->getCountry()); + self::assertInstanceOf(Proxy::class, $entities[0]->getCountry()); + self::assertInstanceOf(Proxy::class, $entities[1]->getCountry()); // load from cache $queryCount = $this->getCurrentQueryCount(); $entities = $repository->findAll(); - $this->assertCount(4, $entities); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertCount(4, $entities); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::class, $entities[0]); - $this->assertInstanceOf(State::class, $entities[1]); - $this->assertInstanceOf(Country::class, $entities[0]->getCountry()); - $this->assertInstanceOf(Country::class, $entities[1]->getCountry()); - $this->assertInstanceOf(Proxy::class, $entities[0]->getCountry()); - $this->assertInstanceOf(Proxy::class, $entities[1]->getCountry()); + self::assertInstanceOf(State::class, $entities[0]); + self::assertInstanceOf(State::class, $entities[1]); + self::assertInstanceOf(Country::class, $entities[0]->getCountry()); + self::assertInstanceOf(Country::class, $entities[1]->getCountry()); + self::assertInstanceOf(Proxy::class, $entities[0]->getCountry()); + self::assertInstanceOf(Proxy::class, $entities[1]->getCountry()); // invalidate cache - $this->_em->persist(new State('foo', $this->_em->find(Country::class, $this->countries[0]->getId()))); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist(new State('foo', $this->em->find(Country::class, $this->countries[0]->getId()))); + $this->em->flush(); + $this->em->clear(); // load from database $queryCount = $this->getCurrentQueryCount(); $entities = $repository->findAll(); - $this->assertCount(5, $entities); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(5, $entities); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::class, $entities[0]); - $this->assertInstanceOf(State::class, $entities[1]); - $this->assertInstanceOf(Country::class, $entities[0]->getCountry()); - $this->assertInstanceOf(Country::class, $entities[1]->getCountry()); - $this->assertInstanceOf(Proxy::class, $entities[0]->getCountry()); - $this->assertInstanceOf(Proxy::class, $entities[1]->getCountry()); + self::assertInstanceOf(State::class, $entities[0]); + self::assertInstanceOf(State::class, $entities[1]); + self::assertInstanceOf(Country::class, $entities[0]->getCountry()); + self::assertInstanceOf(Country::class, $entities[1]->getCountry()); + self::assertInstanceOf(Proxy::class, $entities[0]->getCountry()); + self::assertInstanceOf(Proxy::class, $entities[1]->getCountry()); // load from cache $queryCount = $this->getCurrentQueryCount(); $entities = $repository->findAll(); - $this->assertCount(5, $entities); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertCount(5, $entities); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::class, $entities[0]); - $this->assertInstanceOf(State::class, $entities[1]); - $this->assertInstanceOf(Country::class, $entities[0]->getCountry()); - $this->assertInstanceOf(Country::class, $entities[1]->getCountry()); - $this->assertInstanceOf(Proxy::class, $entities[0]->getCountry()); - $this->assertInstanceOf(Proxy::class, $entities[1]->getCountry()); + self::assertInstanceOf(State::class, $entities[0]); + self::assertInstanceOf(State::class, $entities[1]); + self::assertInstanceOf(Country::class, $entities[0]->getCountry()); + self::assertInstanceOf(Country::class, $entities[1]->getCountry()); + self::assertInstanceOf(Proxy::class, $entities[0]->getCountry()); + self::assertInstanceOf(Proxy::class, $entities[1]->getCountry()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheSingleTableInheritanceTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheSingleTableInheritanceTest.php index 858adb3a19c..5df66e84f16 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheSingleTableInheritanceTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheSingleTableInheritanceTest.php @@ -1,5 +1,7 @@ cache->getEntityCacheRegion(Beach::class); $barRegion = $this->cache->getEntityCacheRegion(Bar::class); - $this->assertEquals($attractionRegion->getName(), $restaurantRegion->getName()); - $this->assertEquals($attractionRegion->getName(), $beachRegion->getName()); - $this->assertEquals($attractionRegion->getName(), $barRegion->getName()); + self::assertEquals($attractionRegion->getName(), $restaurantRegion->getName()); + self::assertEquals($attractionRegion->getName(), $beachRegion->getName()); + self::assertEquals($attractionRegion->getName(), $barRegion->getName()); } public function testPutOnPersistSingleTableInheritance() @@ -33,10 +35,10 @@ public function testPutOnPersistSingleTableInheritance() $this->loadFixturesCities(); $this->loadFixturesAttractions(); - $this->_em->clear(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Bar::class, $this->attractions[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Bar::class, $this->attractions[1]->getId())); + self::assertTrue($this->cache->containsEntity(Bar::class, $this->attractions[0]->getId())); + self::assertTrue($this->cache->containsEntity(Bar::class, $this->attractions[1]->getId())); } public function testCountaisRootClass() @@ -46,11 +48,11 @@ public function testCountaisRootClass() $this->loadFixturesCities(); $this->loadFixturesAttractions(); - $this->_em->clear(); + $this->em->clear(); foreach ($this->attractions as $attraction) { - $this->assertTrue($this->cache->containsEntity(Attraction::class, $attraction->getId())); - $this->assertTrue($this->cache->containsEntity(get_class($attraction), $attraction->getId())); + self::assertTrue($this->cache->containsEntity(Attraction::class, $attraction->getId())); + self::assertTrue($this->cache->containsEntity(get_class($attraction), $attraction->getId())); } } @@ -61,58 +63,58 @@ public function testPutAndLoadEntities() $this->loadFixturesCities(); $this->loadFixturesAttractions(); - $this->_em->clear(); + $this->em->clear(); $this->cache->evictEntityRegion(Attraction::class); $entityId1 = $this->attractions[0]->getId(); $entityId2 = $this->attractions[1]->getId(); - $this->assertFalse($this->cache->containsEntity(Attraction::class, $entityId1)); - $this->assertFalse($this->cache->containsEntity(Attraction::class, $entityId2)); - $this->assertFalse($this->cache->containsEntity(Bar::class, $entityId1)); - $this->assertFalse($this->cache->containsEntity(Bar::class, $entityId2)); + self::assertFalse($this->cache->containsEntity(Attraction::class, $entityId1)); + self::assertFalse($this->cache->containsEntity(Attraction::class, $entityId2)); + self::assertFalse($this->cache->containsEntity(Bar::class, $entityId1)); + self::assertFalse($this->cache->containsEntity(Bar::class, $entityId2)); - $entity1 = $this->_em->find(Attraction::class, $entityId1); - $entity2 = $this->_em->find(Attraction::class, $entityId2); + $entity1 = $this->em->find(Attraction::class, $entityId1); + $entity2 = $this->em->find(Attraction::class, $entityId2); - $this->assertTrue($this->cache->containsEntity(Attraction::class, $entityId1)); - $this->assertTrue($this->cache->containsEntity(Attraction::class, $entityId2)); - $this->assertTrue($this->cache->containsEntity(Bar::class, $entityId1)); - $this->assertTrue($this->cache->containsEntity(Bar::class, $entityId2)); + self::assertTrue($this->cache->containsEntity(Attraction::class, $entityId1)); + self::assertTrue($this->cache->containsEntity(Attraction::class, $entityId2)); + self::assertTrue($this->cache->containsEntity(Bar::class, $entityId1)); + self::assertTrue($this->cache->containsEntity(Bar::class, $entityId2)); - $this->assertInstanceOf(Attraction::class, $entity1); - $this->assertInstanceOf(Attraction::class, $entity2); - $this->assertInstanceOf(Bar::class, $entity1); - $this->assertInstanceOf(Bar::class, $entity2); + self::assertInstanceOf(Attraction::class, $entity1); + self::assertInstanceOf(Attraction::class, $entity2); + self::assertInstanceOf(Bar::class, $entity1); + self::assertInstanceOf(Bar::class, $entity2); - $this->assertEquals($this->attractions[0]->getId(), $entity1->getId()); - $this->assertEquals($this->attractions[0]->getName(), $entity1->getName()); + self::assertEquals($this->attractions[0]->getId(), $entity1->getId()); + self::assertEquals($this->attractions[0]->getName(), $entity1->getName()); - $this->assertEquals($this->attractions[1]->getId(), $entity2->getId()); - $this->assertEquals($this->attractions[1]->getName(), $entity2->getName()); + self::assertEquals($this->attractions[1]->getId(), $entity2->getId()); + self::assertEquals($this->attractions[1]->getName(), $entity2->getName()); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); - $entity3 = $this->_em->find(Attraction::class, $entityId1); - $entity4 = $this->_em->find(Attraction::class, $entityId2); + $entity3 = $this->em->find(Attraction::class, $entityId1); + $entity4 = $this->em->find(Attraction::class, $entityId2); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(Attraction::class, $entity3); - $this->assertInstanceOf(Attraction::class, $entity4); - $this->assertInstanceOf(Bar::class, $entity3); - $this->assertInstanceOf(Bar::class, $entity4); + self::assertInstanceOf(Attraction::class, $entity3); + self::assertInstanceOf(Attraction::class, $entity4); + self::assertInstanceOf(Bar::class, $entity3); + self::assertInstanceOf(Bar::class, $entity4); - $this->assertNotSame($entity1, $entity3); - $this->assertEquals($entity1->getId(), $entity3->getId()); - $this->assertEquals($entity1->getName(), $entity3->getName()); + self::assertNotSame($entity1, $entity3); + self::assertEquals($entity1->getId(), $entity3->getId()); + self::assertEquals($entity1->getName(), $entity3->getName()); - $this->assertNotSame($entity2, $entity4); - $this->assertEquals($entity2->getId(), $entity4->getId()); - $this->assertEquals($entity2->getName(), $entity4->getName()); + self::assertNotSame($entity2, $entity4); + self::assertEquals($entity2->getId(), $entity4->getId()); + self::assertEquals($entity2->getName(), $entity4->getName()); } public function testQueryCacheFindAll() @@ -122,28 +124,28 @@ public function testQueryCacheFindAll() $this->loadFixturesCities(); $this->loadFixturesAttractions(); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT a FROM Doctrine\Tests\Models\Cache\Attraction a'; - $result1 = $this->_em->createQuery($dql) + $result1 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertCount(count($this->attractions), $result1); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(count($this->attractions), $result1); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->_em->clear(); + $this->em->clear(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertCount(count($this->attractions), $result2); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(count($this->attractions), $result2); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); foreach ($result2 as $entity) { - $this->assertInstanceOf(Attraction::class, $entity); + self::assertInstanceOf(Attraction::class, $entity); } } @@ -154,15 +156,15 @@ public function testShouldNotPutOneToManyRelationOnPersist() $this->loadFixturesCities(); $this->loadFixturesAttractions(); - $this->_em->clear(); + $this->em->clear(); foreach ($this->cities as $city) { - $this->assertTrue($this->cache->containsEntity(City::class, $city->getId())); - $this->assertFalse($this->cache->containsCollection(City::class, 'attractions', $city->getId())); + self::assertTrue($this->cache->containsEntity(City::class, $city->getId())); + self::assertFalse($this->cache->containsCollection(City::class, 'attractions', $city->getId())); } foreach ($this->attractions as $attraction) { - $this->assertTrue($this->cache->containsEntity(Attraction::class, $attraction->getId())); + self::assertTrue($this->cache->containsEntity(Attraction::class, $attraction->getId())); } } @@ -177,39 +179,39 @@ public function testOneToManyRelationSingleTable() $this->cache->evictEntityRegion(Attraction::class); $this->cache->evictCollectionRegion(City::class, 'attractions'); - $this->_em->clear(); + $this->em->clear(); - $entity = $this->_em->find(City::class, $this->cities[0]->getId()); + $entity = $this->em->find(City::class, $this->cities[0]->getId()); - $this->assertInstanceOf(City::class, $entity); - $this->assertInstanceOf(PersistentCollection::class, $entity->getAttractions()); - $this->assertCount(2, $entity->getAttractions()); + self::assertInstanceOf(City::class, $entity); + self::assertInstanceOf(PersistentCollection::class, $entity->getAttractions()); + self::assertCount(2, $entity->getAttractions()); $ownerId = $this->cities[0]->getId(); $queryCount = $this->getCurrentQueryCount(); - $this->assertTrue($this->cache->containsEntity(City::class, $ownerId)); - $this->assertTrue($this->cache->containsCollection(City::class, 'attractions', $ownerId)); + self::assertTrue($this->cache->containsEntity(City::class, $ownerId)); + self::assertTrue($this->cache->containsCollection(City::class, 'attractions', $ownerId)); - $this->assertInstanceOf(Bar::class, $entity->getAttractions()->get(0)); - $this->assertInstanceOf(Bar::class, $entity->getAttractions()->get(1)); - $this->assertEquals($this->attractions[0]->getName(), $entity->getAttractions()->get(0)->getName()); - $this->assertEquals($this->attractions[1]->getName(), $entity->getAttractions()->get(1)->getName()); + self::assertInstanceOf(Bar::class, $entity->getAttractions()->get(0)); + self::assertInstanceOf(Bar::class, $entity->getAttractions()->get(1)); + self::assertEquals($this->attractions[0]->getName(), $entity->getAttractions()->get(0)->getName()); + self::assertEquals($this->attractions[1]->getName(), $entity->getAttractions()->get(1)->getName()); - $this->_em->clear(); + $this->em->clear(); - $entity = $this->_em->find(City::class, $ownerId); + $entity = $this->em->find(City::class, $ownerId); - $this->assertInstanceOf(City::class, $entity); - $this->assertInstanceOf(PersistentCollection::class, $entity->getAttractions()); - $this->assertCount(2, $entity->getAttractions()); + self::assertInstanceOf(City::class, $entity); + self::assertInstanceOf(PersistentCollection::class, $entity->getAttractions()); + self::assertCount(2, $entity->getAttractions()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(Bar::class, $entity->getAttractions()->get(0)); - $this->assertInstanceOf(Bar::class, $entity->getAttractions()->get(1)); - $this->assertEquals($this->attractions[0]->getName(), $entity->getAttractions()->get(0)->getName()); - $this->assertEquals($this->attractions[1]->getName(), $entity->getAttractions()->get(1)->getName()); + self::assertInstanceOf(Bar::class, $entity->getAttractions()->get(0)); + self::assertInstanceOf(Bar::class, $entity->getAttractions()->get(1)); + self::assertEquals($this->attractions[0]->getName(), $entity->getAttractions()->get(0)->getName()); + self::assertEquals($this->attractions[1]->getName(), $entity->getAttractions()->get(1)->getName()); } public function testQueryCacheShouldBeEvictedOnTimestampUpdate() @@ -218,38 +220,38 @@ public function testQueryCacheShouldBeEvictedOnTimestampUpdate() $this->loadFixturesStates(); $this->loadFixturesCities(); $this->loadFixturesAttractions(); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT attraction FROM Doctrine\Tests\Models\Cache\Attraction attraction'; - $result1 = $this->_em->createQuery($dql) + $result1 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertCount(count($this->attractions), $result1); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(count($this->attractions), $result1); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); $contact = new Beach( 'Botafogo', - $this->_em->find(City::class, $this->cities[1]->getId()) + $this->em->find(City::class, $this->cities[1]->getId()) ); - $this->_em->persist($contact); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($contact); + $this->em->flush(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertCount(count($this->attractions) + 1, $result2); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertCount(count($this->attractions) + 1, $result2); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); foreach ($result2 as $entity) { - $this->assertInstanceOf(Attraction::class, $entity); + self::assertInstanceOf(Attraction::class, $entity); } } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheTest.php index 32047dda39b..8612ef8dbfc 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheTest.php @@ -1,5 +1,7 @@ loadFixturesCountries(); - $this->_em->clear(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); } public function testPutAndLoadEntities() { $this->loadFixturesCountries(); - $this->_em->clear(); + $this->em->clear(); - $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); + self::assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); $this->cache->evictEntityRegion(Country::class); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $c1 = $this->_em->find(Country::class, $this->countries[0]->getId()); - $c2 = $this->_em->find(Country::class, $this->countries[1]->getId()); + $c1 = $this->em->find(Country::class, $this->countries[0]->getId()); + $c2 = $this->em->find(Country::class, $this->countries[1]->getId()); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $this->assertInstanceOf(Country::class, $c1); - $this->assertInstanceOf(Country::class, $c2); + self::assertInstanceOf(Country::class, $c1); + self::assertInstanceOf(Country::class, $c2); - $this->assertEquals($this->countries[0]->getId(), $c1->getId()); - $this->assertEquals($this->countries[0]->getName(), $c1->getName()); + self::assertEquals($this->countries[0]->getId(), $c1->getId()); + self::assertEquals($this->countries[0]->getName(), $c1->getName()); - $this->assertEquals($this->countries[1]->getId(), $c2->getId()); - $this->assertEquals($this->countries[1]->getName(), $c2->getName()); + self::assertEquals($this->countries[1]->getId(), $c2->getId()); + self::assertEquals($this->countries[1]->getName(), $c2->getName()); - $this->_em->clear(); + $this->em->clear(); $queryCount = $this->getCurrentQueryCount(); - $c3 = $this->_em->find(Country::class, $this->countries[0]->getId()); - $c4 = $this->_em->find(Country::class, $this->countries[1]->getId()); + $c3 = $this->em->find(Country::class, $this->countries[0]->getId()); + $c4 = $this->em->find(Country::class, $this->countries[1]->getId()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(Country::class))); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(Country::class))); - $this->assertInstanceOf(Country::class, $c3); - $this->assertInstanceOf(Country::class, $c4); + self::assertInstanceOf(Country::class, $c3); + self::assertInstanceOf(Country::class, $c4); - $this->assertEquals($c1->getId(), $c3->getId()); - $this->assertEquals($c1->getName(), $c3->getName()); + self::assertEquals($c1->getId(), $c3->getId()); + self::assertEquals($c1->getName(), $c3->getName()); - $this->assertEquals($c2->getId(), $c4->getId()); - $this->assertEquals($c2->getName(), $c4->getName()); + self::assertEquals($c2->getId(), $c4->getId()); + self::assertEquals($c2->getName(), $c4->getName()); } public function testRemoveEntities() { $this->loadFixturesCountries(); - $this->_em->clear(); + $this->em->clear(); - $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); $this->cache->evictEntityRegion(Country::class); $this->secondLevelCacheLogger->clearRegionStats($this->getEntityRegion(Country::class)); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $c1 = $this->_em->find(Country::class, $this->countries[0]->getId()); - $c2 = $this->_em->find(Country::class, $this->countries[1]->getId()); + $c1 = $this->em->find(Country::class, $this->countries[0]->getId()); + $c2 = $this->em->find(Country::class, $this->countries[1]->getId()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $this->assertInstanceOf(Country::class, $c1); - $this->assertInstanceOf(Country::class, $c2); + self::assertInstanceOf(Country::class, $c1); + self::assertInstanceOf(Country::class, $c2); - $this->assertEquals($this->countries[0]->getId(), $c1->getId()); - $this->assertEquals($this->countries[0]->getName(), $c1->getName()); + self::assertEquals($this->countries[0]->getId(), $c1->getId()); + self::assertEquals($this->countries[0]->getName(), $c1->getName()); - $this->assertEquals($this->countries[1]->getId(), $c2->getId()); - $this->assertEquals($this->countries[1]->getName(), $c2->getName()); + self::assertEquals($this->countries[1]->getId(), $c2->getId()); + self::assertEquals($this->countries[1]->getName(), $c2->getName()); - $this->_em->remove($c1); - $this->_em->remove($c2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->remove($c1); + $this->em->remove($c2); + $this->em->flush(); + $this->em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + self::assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $this->assertNull($this->_em->find(Country::class, $this->countries[0]->getId())); - $this->assertNull($this->_em->find(Country::class, $this->countries[1]->getId())); + self::assertNull($this->em->find(Country::class, $this->countries[0]->getId())); + self::assertNull($this->em->find(Country::class, $this->countries[1]->getId())); - $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); } public function testUpdateEntities() { $this->loadFixturesCountries(); $this->loadFixturesStates(); - $this->_em->clear(); + $this->em->clear(); - $this->assertEquals(6, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); - $this->assertEquals(4, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); + self::assertEquals(6, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); + self::assertEquals(4, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); $this->cache->evictEntityRegion(State::class); $this->secondLevelCacheLogger->clearRegionStats($this->getEntityRegion(State::class)); - $this->assertFalse($this->cache->containsEntity(State::class, $this->states[0]->getId())); - $this->assertFalse($this->cache->containsEntity(State::class, $this->states[1]->getId())); + self::assertFalse($this->cache->containsEntity(State::class, $this->states[0]->getId())); + self::assertFalse($this->cache->containsEntity(State::class, $this->states[1]->getId())); - $s1 = $this->_em->find(State::class, $this->states[0]->getId()); - $s2 = $this->_em->find(State::class, $this->states[1]->getId()); + $s1 = $this->em->find(State::class, $this->states[0]->getId()); + $s2 = $this->em->find(State::class, $this->states[1]->getId()); - $this->assertEquals(4, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); + self::assertEquals(4, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); - $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); - $this->assertInstanceOf(State::class, $s1); - $this->assertInstanceOf(State::class, $s2); + self::assertInstanceOf(State::class, $s1); + self::assertInstanceOf(State::class, $s2); - $this->assertEquals($this->states[0]->getId(), $s1->getId()); - $this->assertEquals($this->states[0]->getName(), $s1->getName()); + self::assertEquals($this->states[0]->getId(), $s1->getId()); + self::assertEquals($this->states[0]->getName(), $s1->getName()); - $this->assertEquals($this->states[1]->getId(), $s2->getId()); - $this->assertEquals($this->states[1]->getName(), $s2->getName()); + self::assertEquals($this->states[1]->getId(), $s2->getId()); + self::assertEquals($this->states[1]->getName(), $s2->getName()); $s1->setName("NEW NAME 1"); $s2->setName("NEW NAME 2"); - $this->_em->persist($s1); - $this->_em->persist($s2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($s1); + $this->em->persist($s2); + $this->em->flush(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); - $this->assertEquals(6, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); - $this->assertEquals(4, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); + self::assertEquals(6, $this->secondLevelCacheLogger->getPutCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); + self::assertEquals(4, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); $queryCount = $this->getCurrentQueryCount(); - $c3 = $this->_em->find(State::class, $this->states[0]->getId()); - $c4 = $this->_em->find(State::class, $this->states[1]->getId()); + $c3 = $this->em->find(State::class, $this->states[0]->getId()); + $c4 = $this->em->find(State::class, $this->states[1]->getId()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); + self::assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + self::assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); - $this->assertInstanceOf(State::class, $c3); - $this->assertInstanceOf(State::class, $c4); + self::assertInstanceOf(State::class, $c3); + self::assertInstanceOf(State::class, $c4); - $this->assertEquals($s1->getId(), $c3->getId()); - $this->assertEquals("NEW NAME 1", $c3->getName()); + self::assertEquals($s1->getId(), $c3->getId()); + self::assertEquals("NEW NAME 1", $c3->getName()); - $this->assertEquals($s2->getId(), $c4->getId()); - $this->assertEquals("NEW NAME 2", $c4->getName()); + self::assertEquals($s2->getId(), $c4->getId()); + self::assertEquals("NEW NAME 2", $c4->getName()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); + self::assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); + self::assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); } public function testPostFlushFailure() @@ -203,7 +205,7 @@ public function testPostFlushFailure() ] ); - $this->_em->getEventManager() + $this->em->getEventManager() ->addEventListener(Events::postFlush, $listener); $country = new Country("Brazil"); @@ -212,14 +214,14 @@ public function testPostFlushFailure() try { - $this->_em->persist($country); - $this->_em->flush(); + $this->em->persist($country); + $this->em->flush(); $this->fail('Should throw exception'); } catch (\RuntimeException $exc) { - $this->assertNotNull($country->getId()); - $this->assertEquals('post flush failure', $exc->getMessage()); - $this->assertTrue($this->cache->containsEntity(Country::class, $country->getId())); + self::assertNotNull($country->getId()); + self::assertEquals('post flush failure', $exc->getMessage()); + self::assertTrue($this->cache->containsEntity(Country::class, $country->getId())); } } @@ -227,7 +229,7 @@ public function testPostUpdateFailure() { $this->loadFixturesCountries(); $this->loadFixturesStates(); - $this->_em->clear(); + $this->em->clear(); $listener = new ListenerSecondLevelCacheTest( [ @@ -237,45 +239,45 @@ public function testPostUpdateFailure() ] ); - $this->_em->getEventManager() + $this->em->getEventManager() ->addEventListener(Events::postUpdate, $listener); $this->cache->evictEntityRegion(State::class); $stateId = $this->states[0]->getId(); $stateName = $this->states[0]->getName(); - $state = $this->_em->find(State::class, $stateId); + $state = $this->em->find(State::class, $stateId); - $this->assertTrue($this->cache->containsEntity(State::class, $stateId)); - $this->assertInstanceOf(State::class, $state); - $this->assertEquals($stateName, $state->getName()); + self::assertTrue($this->cache->containsEntity(State::class, $stateId)); + self::assertInstanceOf(State::class, $state); + self::assertEquals($stateName, $state->getName()); $state->setName($stateName . uniqid()); - $this->_em->persist($state); + $this->em->persist($state); try { - $this->_em->flush(); + $this->em->flush(); $this->fail('Should throw exception'); } catch (\Exception $exc) { - $this->assertEquals('post update failure', $exc->getMessage()); + self::assertEquals('post update failure', $exc->getMessage()); } - $this->_em->clear(); + $this->em->clear(); - $this->assertTrue($this->cache->containsEntity(State::class, $stateId)); + self::assertTrue($this->cache->containsEntity(State::class, $stateId)); - $state = $this->_em->find(State::class, $stateId); + $state = $this->em->find(State::class, $stateId); - $this->assertInstanceOf(State::class, $state); - $this->assertEquals($stateName, $state->getName()); + self::assertInstanceOf(State::class, $state); + self::assertEquals($stateName, $state->getName()); } public function testPostRemoveFailure() { $this->loadFixturesCountries(); - $this->_em->clear(); + $this->em->clear(); $listener = new ListenerSecondLevelCacheTest( [ @@ -285,49 +287,49 @@ public function testPostRemoveFailure() ] ); - $this->_em->getEventManager() + $this->em->getEventManager() ->addEventListener(Events::postRemove, $listener); $this->cache->evictEntityRegion(Country::class); $countryId = $this->countries[0]->getId(); - $country = $this->_em->find(Country::class, $countryId); + $country = $this->em->find(Country::class, $countryId); - $this->assertTrue($this->cache->containsEntity(Country::class, $countryId)); - $this->assertInstanceOf(Country::class, $country); + self::assertTrue($this->cache->containsEntity(Country::class, $countryId)); + self::assertInstanceOf(Country::class, $country); - $this->_em->remove($country); + $this->em->remove($country); try { - $this->_em->flush(); + $this->em->flush(); $this->fail('Should throw exception'); } catch (\Exception $exc) { - $this->assertEquals('post remove failure', $exc->getMessage()); + self::assertEquals('post remove failure', $exc->getMessage()); } - $this->_em->clear(); + $this->em->clear(); - $this->assertFalse( + self::assertFalse( $this->cache->containsEntity(Country::class, $countryId), 'Removal attempts should clear the cache entry corresponding to the entity' ); - $this->assertInstanceOf(Country::class, $this->_em->find(Country::class, $countryId)); + self::assertInstanceOf(Country::class, $this->em->find(Country::class, $countryId)); } public function testCachedNewEntityExists() { $this->loadFixturesCountries(); - $persister = $this->_em->getUnitOfWork()->getEntityPersister(Country::class); + $persister = $this->em->getUnitOfWork()->getEntityPersister(Country::class); $queryCount = $this->getCurrentQueryCount(); - $this->assertTrue($persister->exists($this->countries[0])); + self::assertTrue($persister->exists($this->countries[0])); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertFalse($persister->exists(new Country('Foo'))); + self::assertFalse($persister->exists(new Country('Foo'))); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SequenceEmulatedIdentityStrategyTest.php b/tests/Doctrine/Tests/ORM/Functional/SequenceEmulatedIdentityStrategyTest.php index d425936f5bd..685d4cf8774 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SequenceEmulatedIdentityStrategyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SequenceEmulatedIdentityStrategyTest.php @@ -1,8 +1,11 @@ _em->getConnection()->getDatabasePlatform()->usesSequenceEmulatedIdentityColumns()) { + if ( ! $this->em->getConnection()->getDatabasePlatform()->usesSequenceEmulatedIdentityColumns()) { $this->markTestSkipped( 'This test is special to platforms emulating IDENTITY key generation strategy through sequences.' ); } else { try { - $this->_schemaTool->createSchema( - [$this->_em->getClassMetadata(SequenceEmulatedIdentityEntity::class)] + $this->schemaTool->createSchema( + [$this->em->getClassMetadata(SequenceEmulatedIdentityEntity::class)] ); } catch (\Exception $e) { // Swallow all exceptions. We do not test the schema tool here. @@ -36,7 +39,7 @@ protected function tearDown() { parent::tearDown(); - $connection = $this->_em->getConnection(); + $connection = $this->em->getConnection(); $platform = $connection->getDatabasePlatform(); // drop sequence manually due to dependency @@ -51,21 +54,21 @@ public function testPreSavePostSaveCallbacksAreInvoked() { $entity = new SequenceEmulatedIdentityEntity(); $entity->setValue('hello'); - $this->_em->persist($entity); - $this->_em->flush(); - $this->assertTrue(is_numeric($entity->getId())); - $this->assertTrue($entity->getId() > 0); - $this->assertTrue($this->_em->contains($entity)); + $this->em->persist($entity); + $this->em->flush(); + self::assertTrue(is_numeric($entity->getId())); + self::assertTrue($entity->getId() > 0); + self::assertTrue($this->em->contains($entity)); } } -/** @Entity @Table(name="seq_identity") */ +/** @ORM\Entity @ORM\Table(name="seq_identity") */ class SequenceEmulatedIdentityEntity { - /** @Id @Column(type="integer") @GeneratedValue(strategy="IDENTITY") */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ private $value; public function getId() diff --git a/tests/Doctrine/Tests/ORM/Functional/SequenceGeneratorTest.php b/tests/Doctrine/Tests/ORM/Functional/SequenceGeneratorTest.php index 290984f3584..bc0b27e6d59 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SequenceGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SequenceGeneratorTest.php @@ -1,6 +1,10 @@ _em->getConnection()->getDatabasePlatform()->supportsSequences()) { + if (! $this->em->getConnection()->getDatabasePlatform()->supportsSequences()) { $this->markTestSkipped('Only working for Databases that support sequences.'); } try { - $this->_schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(SequenceEntity::class), + $this->em->getClassMetadata(SequenceEntity::class), ] ); } catch(\Exception $e) { @@ -31,25 +35,25 @@ public function setUp() public function testHighAllocationSizeSequence() { for ($i = 0; $i < 11; ++$i) { - $this->_em->persist(new SequenceEntity()); + $this->em->persist(new SequenceEntity()); } - $this->_em->flush(); + $this->em->flush(); - self::assertCount(11, $this->_em->getRepository(SequenceEntity::class)->findAll()); + self::assertCount(11, $this->em->getRepository(SequenceEntity::class)->findAll()); } } /** - * @Entity + * @ORM\Entity */ class SequenceEntity { /** - * @Id - * @column(type="integer") - * @GeneratedValue(strategy="SEQUENCE") - * @SequenceGenerator(allocationSize=5, sequenceName="person_id_seq") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="SEQUENCE") + * @ORM\SequenceGenerator(allocationSize=5,sequenceName="person_id_seq") */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/SingleTableCompositeKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/SingleTableCompositeKeyTest.php index 091c79f5412..6b38266240f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SingleTableCompositeKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SingleTableCompositeKeyTest.php @@ -1,4 +1,6 @@ _em->persist($childEntity); - $this->_em->flush(); + $this->em->persist($childEntity); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); $entity = $this->findEntity(); - $this->assertEquals($childEntity, $entity); + self::assertEquals($childEntity, $entity); } /** @@ -36,20 +38,20 @@ public function testInsertWithCompositeKey() public function testUpdateWithCompositeKey() { $childEntity = new SingleChildClass(); - $this->_em->persist($childEntity); - $this->_em->flush(); + $this->em->persist($childEntity); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); $entity = $this->findEntity(); $entity->extension = 'ext-new'; - $this->_em->persist($entity); - $this->_em->flush(); + $this->em->persist($entity); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); $persistedEntity = $this->findEntity(); - $this->assertEquals($entity, $persistedEntity); + self::assertEquals($entity, $persistedEntity); } /** @@ -57,6 +59,6 @@ public function testUpdateWithCompositeKey() */ private function findEntity() { - return $this->_em->find(SingleRootClass::class, ['keyPart1' => 'part-1', 'keyPart2' => 'part-2']); + return $this->em->find(SingleRootClass::class, ['keyPart1' => 'part-1', 'keyPart2' => 'part-2']); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SingleTableInheritanceTest.php b/tests/Doctrine/Tests/ORM/Functional/SingleTableInheritanceTest.php index 5bafffd790f..282d1dc387f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SingleTableInheritanceTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SingleTableInheritanceTest.php @@ -1,9 +1,12 @@ setSalary(100); $this->engineers[] = $engineer4; - $this->_em->persist($this->salesPerson); - $this->_em->persist($engineer1); - $this->_em->persist($engineer2); - $this->_em->persist($engineer3); - $this->_em->persist($engineer4); + $this->em->persist($this->salesPerson); + $this->em->persist($engineer1); + $this->em->persist($engineer2); + $this->em->persist($engineer3); + $this->em->persist($engineer4); } public function loadFullFixture() @@ -93,11 +96,11 @@ public function loadFullFixture() $this->ultra->addEngineer($this->engineers[3]); $this->ultra->addEngineer($this->engineers[0]); - $this->_em->persist($this->fix); - $this->_em->persist($this->flex); - $this->_em->persist($this->ultra); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($this->fix); + $this->em->persist($this->flex); + $this->em->persist($this->ultra); + $this->em->flush(); + $this->em->clear(); } public function testPersistChildOfBaseClass() @@ -108,15 +111,15 @@ public function testPersistChildOfBaseClass() $fixContract->setFixPrice(1000); $fixContract->setSalesPerson($this->salesPerson); - $this->_em->persist($fixContract); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($fixContract); + $this->em->flush(); + $this->em->clear(); - $contract = $this->_em->find(CompanyFixContract::class, $fixContract->getId()); + $contract = $this->em->find(CompanyFixContract::class, $fixContract->getId()); - $this->assertInstanceOf(CompanyFixContract::class, $contract); - $this->assertEquals(1000, $contract->getFixPrice()); - $this->assertEquals($this->salesPerson->getId(), $contract->getSalesPerson()->getId()); + self::assertInstanceOf(CompanyFixContract::class, $contract); + self::assertEquals(1000, $contract->getFixPrice()); + self::assertEquals($this->salesPerson->getId(), $contract->getSalesPerson()->getId()); } public function testPersistDeepChildOfBaseClass() @@ -129,104 +132,104 @@ public function testPersistDeepChildOfBaseClass() $ultraContract->setPricePerHour(50); $ultraContract->setMaxPrice(7000); - $this->_em->persist($ultraContract); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($ultraContract); + $this->em->flush(); + $this->em->clear(); - $contract = $this->_em->find(CompanyFlexUltraContract::class, $ultraContract->getId()); + $contract = $this->em->find(CompanyFlexUltraContract::class, $ultraContract->getId()); - $this->assertInstanceOf(CompanyFlexUltraContract::class, $contract); - $this->assertEquals(7000, $contract->getMaxPrice()); - $this->assertEquals(100, $contract->getHoursWorked()); - $this->assertEquals(50, $contract->getPricePerHour()); + self::assertInstanceOf(CompanyFlexUltraContract::class, $contract); + self::assertEquals(7000, $contract->getMaxPrice()); + self::assertEquals(100, $contract->getHoursWorked()); + self::assertEquals(50, $contract->getPricePerHour()); } public function testChildClassLifecycleUpdate() { $this->loadFullFixture(); - $fix = $this->_em->find(CompanyContract::class, $this->fix->getId()); + $fix = $this->em->find(CompanyContract::class, $this->fix->getId()); $fix->setFixPrice(2500); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $newFix = $this->_em->find(CompanyContract::class, $this->fix->getId()); - $this->assertEquals(2500, $newFix->getFixPrice()); + $newFix = $this->em->find(CompanyContract::class, $this->fix->getId()); + self::assertEquals(2500, $newFix->getFixPrice()); } public function testChildClassLifecycleRemove() { $this->loadFullFixture(); - $fix = $this->_em->find(CompanyContract::class, $this->fix->getId()); - $this->_em->remove($fix); - $this->_em->flush(); + $fix = $this->em->find(CompanyContract::class, $this->fix->getId()); + $this->em->remove($fix); + $this->em->flush(); - $this->assertNull($this->_em->find(CompanyContract::class, $this->fix->getId())); + self::assertNull($this->em->find(CompanyContract::class, $this->fix->getId())); } public function testFindAllForAbstractBaseClass() { $this->loadFullFixture(); - $contracts = $this->_em->getRepository(CompanyContract::class)->findAll(); + $contracts = $this->em->getRepository(CompanyContract::class)->findAll(); - $this->assertEquals(3, count($contracts)); - $this->assertContainsOnly(CompanyContract::class, $contracts); + self::assertEquals(3, count($contracts)); + self::assertContainsOnly(CompanyContract::class, $contracts); } public function testFindAllForChildClass() { $this->loadFullFixture(); - $this->assertEquals(1, count($this->_em->getRepository(CompanyFixContract::class)->findAll())); - $this->assertEquals(2, count($this->_em->getRepository(CompanyFlexContract::class)->findAll())); - $this->assertEquals(1, count($this->_em->getRepository(CompanyFlexUltraContract::class)->findAll())); + self::assertEquals(1, count($this->em->getRepository(CompanyFixContract::class)->findAll())); + self::assertEquals(2, count($this->em->getRepository(CompanyFlexContract::class)->findAll())); + self::assertEquals(1, count($this->em->getRepository(CompanyFlexUltraContract::class)->findAll())); } public function testFindForAbstractBaseClass() { $this->loadFullFixture(); - $contract = $this->_em->find(CompanyContract::class, $this->fix->getId()); + $contract = $this->em->find(CompanyContract::class, $this->fix->getId()); - $this->assertInstanceOf(CompanyFixContract::class, $contract); - $this->assertEquals(1000, $contract->getFixPrice()); + self::assertInstanceOf(CompanyFixContract::class, $contract); + self::assertEquals(1000, $contract->getFixPrice()); } public function testQueryForAbstractBaseClass() { $this->loadFullFixture(); - $contracts = $this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c')->getResult(); + $contracts = $this->em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c')->getResult(); - $this->assertEquals(3, count($contracts)); - $this->assertContainsOnly(CompanyContract::class, $contracts); + self::assertEquals(3, count($contracts)); + self::assertContainsOnly(CompanyContract::class, $contracts); } public function testQueryForChildClass() { $this->loadFullFixture(); - $this->assertEquals(1, count($this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyFixContract c')->getResult())); - $this->assertEquals(2, count($this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyFlexContract c')->getResult())); - $this->assertEquals(1, count($this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract c')->getResult())); + self::assertEquals(1, count($this->em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyFixContract c')->getResult())); + self::assertEquals(2, count($this->em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyFlexContract c')->getResult())); + self::assertEquals(1, count($this->em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract c')->getResult())); } public function testQueryBaseClassWithJoin() { $this->loadFullFixture(); - $contracts = $this->_em->createQuery('SELECT c, p FROM Doctrine\Tests\Models\Company\CompanyContract c JOIN c.salesPerson p')->getResult(); - $this->assertEquals(3, count($contracts)); - $this->assertContainsOnly(CompanyContract::class, $contracts); + $contracts = $this->em->createQuery('SELECT c, p FROM Doctrine\Tests\Models\Company\CompanyContract c JOIN c.salesPerson p')->getResult(); + self::assertEquals(3, count($contracts)); + self::assertContainsOnly(CompanyContract::class, $contracts); } public function testQueryScalarWithDiscriminatorValue() { $this->loadFullFixture(); - $contracts = $this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c ORDER BY c.id')->getScalarResult(); + $contracts = $this->em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c ORDER BY c.id')->getScalarResult(); $discrValues = \array_map(function($a) { return $a['c_discr']; @@ -234,7 +237,7 @@ public function testQueryScalarWithDiscriminatorValue() sort($discrValues); - $this->assertEquals(['fix', 'flexible', 'flexultra'], $discrValues); + self::assertEquals(['fix', 'flexible', 'flexultra'], $discrValues); } public function testQueryChildClassWithCondition() @@ -242,10 +245,10 @@ public function testQueryChildClassWithCondition() $this->loadFullFixture(); $dql = 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyFixContract c WHERE c.fixPrice = ?1'; - $contract = $this->_em->createQuery($dql)->setParameter(1, 1000)->getSingleResult(); + $contract = $this->em->createQuery($dql)->setParameter(1, 1000)->getSingleResult(); - $this->assertInstanceOf(CompanyFixContract::class, $contract); - $this->assertEquals(1000, $contract->getFixPrice()); + self::assertInstanceOf(CompanyFixContract::class, $contract); + self::assertEquals(1000, $contract->getFixPrice()); } /** @@ -256,15 +259,15 @@ public function testUpdateChildClassWithCondition() $this->loadFullFixture(); $dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyFlexContract c SET c.hoursWorked = c.hoursWorked * 2 WHERE c.hoursWorked = 150'; - $affected = $this->_em->createQuery($dql)->execute(); + $affected = $this->em->createQuery($dql)->execute(); - $this->assertEquals(1, $affected); + self::assertEquals(1, $affected); - $flexContract = $this->_em->find(CompanyContract::class, $this->flex->getId()); - $ultraContract = $this->_em->find(CompanyContract::class, $this->ultra->getId()); + $flexContract = $this->em->find(CompanyContract::class, $this->flex->getId()); + $ultraContract = $this->em->find(CompanyContract::class, $this->ultra->getId()); - $this->assertEquals(300, $ultraContract->getHoursWorked()); - $this->assertEquals(100, $flexContract->getHoursWorked()); + self::assertEquals(300, $ultraContract->getHoursWorked()); + self::assertEquals(100, $flexContract->getHoursWorked()); } public function testUpdateBaseClassWithCondition() @@ -272,14 +275,14 @@ public function testUpdateBaseClassWithCondition() $this->loadFullFixture(); $dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyContract c SET c.completed = true WHERE c.completed = false'; - $affected = $this->_em->createQuery($dql)->execute(); + $affected = $this->em->createQuery($dql)->execute(); - $this->assertEquals(1, $affected); + self::assertEquals(1, $affected); $dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyContract c SET c.completed = false'; - $affected = $this->_em->createQuery($dql)->execute(); + $affected = $this->em->createQuery($dql)->execute(); - $this->assertEquals(3, $affected); + self::assertEquals(3, $affected); } public function testDeleteByChildClassCondition() @@ -287,9 +290,9 @@ public function testDeleteByChildClassCondition() $this->loadFullFixture(); $dql = 'DELETE Doctrine\Tests\Models\Company\CompanyFlexContract c'; - $affected = $this->_em->createQuery($dql)->execute(); + $affected = $this->em->createQuery($dql)->execute(); - $this->assertEquals(2, $affected); + self::assertEquals(2, $affected); } public function testDeleteByBaseClassCondition() @@ -297,14 +300,14 @@ public function testDeleteByBaseClassCondition() $this->loadFullFixture(); $dql = "DELETE Doctrine\Tests\Models\Company\CompanyContract c WHERE c.completed = true"; - $affected = $this->_em->createQuery($dql)->execute(); + $affected = $this->em->createQuery($dql)->execute(); - $this->assertEquals(2, $affected); + self::assertEquals(2, $affected); - $contracts = $this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c')->getResult(); - $this->assertEquals(1, count($contracts)); + $contracts = $this->em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c')->getResult(); + self::assertEquals(1, count($contracts)); - $this->assertFalse($contracts[0]->isCompleted(), "Only non completed contracts should be left."); + self::assertFalse($contracts[0]->isCompleted(), "Only non completed contracts should be left."); } /** @@ -315,10 +318,10 @@ public function testDeleteJoinTableRecords() $this->loadFullFixture(); // remove managed copy of the fix contract - $this->_em->remove($this->_em->find(get_class($this->fix), $this->fix->getId())); - $this->_em->flush(); + $this->em->remove($this->em->find(get_class($this->fix), $this->fix->getId())); + $this->em->flush(); - $this->assertNull($this->_em->find(get_class($this->fix), $this->fix->getId()), "Contract should not be present in the database anymore."); + self::assertNull($this->em->find(get_class($this->fix), $this->fix->getId()), "Contract should not be present in the database anymore."); } /** @@ -328,21 +331,21 @@ public function testFindByAssociation() { $this->loadFullFixture(); - $repos = $this->_em->getRepository(CompanyContract::class); + $repos = $this->em->getRepository(CompanyContract::class); $contracts = $repos->findBy(['salesPerson' => $this->salesPerson->getId()]); - $this->assertEquals(3, count($contracts), "There should be 3 entities related to " . $this->salesPerson->getId() . " for 'Doctrine\Tests\Models\Company\CompanyContract'"); + self::assertEquals(3, count($contracts), "There should be 3 entities related to " . $this->salesPerson->getId() . " for 'Doctrine\Tests\Models\Company\CompanyContract'"); - $repos = $this->_em->getRepository(CompanyFixContract::class); + $repos = $this->em->getRepository(CompanyFixContract::class); $contracts = $repos->findBy(['salesPerson' => $this->salesPerson->getId()]); - $this->assertEquals(1, count($contracts), "There should be 1 entities related to " . $this->salesPerson->getId() . " for 'Doctrine\Tests\Models\Company\CompanyFixContract'"); + self::assertEquals(1, count($contracts), "There should be 1 entities related to " . $this->salesPerson->getId() . " for 'Doctrine\Tests\Models\Company\CompanyFixContract'"); - $repos = $this->_em->getRepository(CompanyFlexContract::class); + $repos = $this->em->getRepository(CompanyFlexContract::class); $contracts = $repos->findBy(['salesPerson' => $this->salesPerson->getId()]); - $this->assertEquals(2, count($contracts), "There should be 2 entities related to " . $this->salesPerson->getId() . " for 'Doctrine\Tests\Models\Company\CompanyFlexContract'"); + self::assertEquals(2, count($contracts), "There should be 2 entities related to " . $this->salesPerson->getId() . " for 'Doctrine\Tests\Models\Company\CompanyFlexContract'"); - $repos = $this->_em->getRepository(CompanyFlexUltraContract::class); + $repos = $this->em->getRepository(CompanyFlexUltraContract::class); $contracts = $repos->findBy(['salesPerson' => $this->salesPerson->getId()]); - $this->assertEquals(1, count($contracts), "There should be 1 entities related to " . $this->salesPerson->getId() . " for 'Doctrine\Tests\Models\Company\CompanyFlexUltraContract'"); + self::assertEquals(1, count($contracts), "There should be 1 entities related to " . $this->salesPerson->getId() . " for 'Doctrine\Tests\Models\Company\CompanyFlexUltraContract'"); } /** @@ -352,17 +355,17 @@ public function testInheritanceMatching() { $this->loadFullFixture(); - $repository = $this->_em->getRepository(CompanyContract::class); + $repository = $this->em->getRepository(CompanyContract::class); $contracts = $repository->matching(new Criteria( Criteria::expr()->eq('salesPerson', $this->salesPerson) )); - $this->assertEquals(3, count($contracts)); + self::assertEquals(3, count($contracts)); - $repository = $this->_em->getRepository(CompanyFixContract::class); + $repository = $this->em->getRepository(CompanyFixContract::class); $contracts = $repository->matching(new Criteria( Criteria::expr()->eq('salesPerson', $this->salesPerson) )); - $this->assertEquals(1, count($contracts)); + self::assertEquals(1, count($contracts)); } /** @@ -372,7 +375,7 @@ public function testMatchingNonObjectOnAssocationThrowsException() { $this->loadFullFixture(); - $repository = $this->_em->getRepository(CompanyContract::class); + $repository = $this->em->getRepository(CompanyContract::class); $this->expectException(PersisterException::class); $this->expectExceptionMessage('annot match on Doctrine\Tests\Models\Company\CompanyContract::salesPerson with a non-object value.'); @@ -392,14 +395,14 @@ public function testGetReferenceEntityWithSubclasses() { $this->loadFullFixture(); - $ref = $this->_em->getReference(CompanyContract::class, $this->fix->getId()); - $this->assertNotInstanceOf(Proxy::class, $ref, "Cannot Request a proxy from a class that has subclasses."); - $this->assertInstanceOf(CompanyContract::class, $ref); - $this->assertInstanceOf(CompanyFixContract::class, $ref, "Direct fetch of the reference has to load the child class Employee directly."); - $this->_em->clear(); + $ref = $this->em->getReference(CompanyContract::class, $this->fix->getId()); + self::assertNotInstanceOf(Proxy::class, $ref, "Cannot Request a proxy from a class that has subclasses."); + self::assertInstanceOf(CompanyContract::class, $ref); + self::assertInstanceOf(CompanyFixContract::class, $ref, "Direct fetch of the reference has to load the child class Employee directly."); + $this->em->clear(); - $ref = $this->_em->getReference(CompanyFixContract::class, $this->fix->getId()); - $this->assertInstanceOf(Proxy::class, $ref, "A proxy can be generated only if no subclasses exists for the requested reference."); + $ref = $this->em->getReference(CompanyFixContract::class, $this->fix->getId()); + self::assertInstanceOf(Proxy::class, $ref, "A proxy can be generated only if no subclasses exists for the requested reference."); } /** @@ -410,11 +413,12 @@ public function testEagerLoadInheritanceHierarchy() $this->loadFullFixture(); $dql = 'SELECT f FROM Doctrine\Tests\Models\Company\CompanyFixContract f WHERE f.id = ?1'; - $contract = $this->_em->createQuery($dql) - ->setFetchMode(CompanyFixContract::class, 'salesPerson', ClassMetadata::FETCH_EAGER) - ->setParameter(1, $this->fix->getId()) - ->getSingleResult(); + $contract = $this->em + ->createQuery($dql) + ->setFetchMode(CompanyFixContract::class, 'salesPerson', FetchMode::EAGER) + ->setParameter(1, $this->fix->getId()) + ->getSingleResult(); - $this->assertNotInstanceOf(Proxy::class, $contract->getSalesPerson()); + self::assertNotInstanceOf(Proxy::class, $contract->getSalesPerson()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/StandardEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Functional/StandardEntityPersisterTest.php index bef1f768212..25794dfa49b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/StandardEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/StandardEntityPersisterTest.php @@ -1,5 +1,7 @@ setPayment('Credit card'); $customer->setCart($cart); - $this->_em->persist($customer); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($customer); + $this->em->flush(); + $this->em->clear(); $cardId = $cart->getId(); unset($cart); - $class = $this->_em->getClassMetadata(ECommerceCart::class); + $class = $this->em->getClassMetadata(ECommerceCart::class); - $persister = $this->_em->getUnitOfWork()->getEntityPersister(ECommerceCart::class); + $persister = $this->em->getUnitOfWork()->getEntityPersister(ECommerceCart::class); $newCart = new ECommerceCart(); - $this->_em->getUnitOfWork()->registerManaged($newCart, ['id' => $cardId], []); - $persister->load(['customer_id' => $customer->getId()], $newCart, $class->associationMappings['customer']); - $this->assertEquals('Credit card', $newCart->getPayment()); + $this->em->getUnitOfWork()->registerManaged($newCart, ['id' => $cardId], []); + $persister->load(['customer_id' => $customer->getId()], $newCart, $class->getProperty('customer')); + self::assertEquals('Credit card', $newCart->getPayment()); } /** @@ -57,14 +59,14 @@ public function testAddPersistRetrieve() $p = new ECommerceProduct; $p->addFeature($f1); $p->addFeature($f2); - $this->_em->persist($p); + $this->em->persist($p); - $this->_em->flush(); + $this->em->flush(); - $this->assertEquals(2, count($p->getFeatures())); - $this->assertInstanceOf(PersistentCollection::class, $p->getFeatures()); + self::assertEquals(2, count($p->getFeatures())); + self::assertInstanceOf(PersistentCollection::class, $p->getFeatures()); - $q = $this->_em->createQuery( + $q = $this->em->createQuery( 'SELECT p, f FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p JOIN p.features f' @@ -72,15 +74,15 @@ public function testAddPersistRetrieve() $res = $q->getResult(); - $this->assertEquals(2, count($p->getFeatures())); - $this->assertInstanceOf(PersistentCollection::class, $p->getFeatures()); + self::assertEquals(2, count($p->getFeatures())); + self::assertInstanceOf(PersistentCollection::class, $p->getFeatures()); // Check that the features are the same instances still foreach ($p->getFeatures() as $feature) { if ($feature->getDescription() == 'AC-3') { - $this->assertTrue($feature === $f1); + self::assertTrue($feature === $f1); } else { - $this->assertTrue($feature === $f2); + self::assertTrue($feature === $f2); } } @@ -91,10 +93,10 @@ public function testAddPersistRetrieve() $p->addFeature($f3); // Now we persist the Feature #3 - $this->_em->persist($p); - $this->_em->flush(); + $this->em->persist($p); + $this->em->flush(); - $q = $this->_em->createQuery( + $q = $this->em->createQuery( 'SELECT p, f FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p JOIN p.features f' @@ -103,6 +105,6 @@ public function testAddPersistRetrieve() $res = $q->getResult(); // Persisted Product now must have 3 Feature items - $this->assertEquals(3, count($res[0]->getFeatures())); + self::assertEquals(3, count($res[0]->getFeatures())); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1040Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1040Test.php index 988e8ba99d2..d007f1eb555 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1040Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1040Test.php @@ -1,5 +1,7 @@ text = "Yadda Yadda!"; $article->setAuthor($user); - $this->_em->persist($user); - $this->_em->persist($article); - $this->_em->flush(); + $this->em->persist($user); + $this->em->persist($article); + $this->em->flush(); $dql = "SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = :author"; - $this->_em->createQuery($dql) + $this->em->createQuery($dql) ->setParameter('author', $user) ->getResult(); $dql = "SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = :author AND a.user = :author"; - $this->_em->createQuery($dql) + $this->em->createQuery($dql) ->setParameter('author', $user) ->getResult(); $dql = "SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.topic = :topic AND a.user = :author AND a.user = :author"; - $farticle = $this->_em->createQuery($dql) + $farticle = $this->em->createQuery($dql) ->setParameter('author', $user) ->setParameter('topic', 'This is John Galt speaking!') ->getSingleResult(); - $this->assertSame($article, $farticle); + self::assertSame($article, $farticle); } public function testUseMultiplePositionalParameters() @@ -64,17 +66,17 @@ public function testUseMultiplePositionalParameters() $article->text = "Yadda Yadda!"; $article->setAuthor($user); - $this->_em->persist($user); - $this->_em->persist($article); - $this->_em->flush(); + $this->em->persist($user); + $this->em->persist($article); + $this->em->flush(); $dql = "SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.topic = ?1 AND a.user = ?2 AND a.user = ?3"; - $farticle = $this->_em->createQuery($dql) + $farticle = $this->em->createQuery($dql) ->setParameter(1, 'This is John Galt speaking!') ->setParameter(2, $user) ->setParameter(3, $user) ->getSingleResult(); - $this->assertSame($article, $farticle); + self::assertSame($article, $farticle); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1041Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1041Test.php index ed27ed10044..d9a0c6bbde6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1041Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1041Test.php @@ -1,5 +1,7 @@ setFixPrice(2000); - $this->_em->persist($fix); - $this->_em->flush(); + $this->em->persist($fix); + $this->em->flush(); $id = $fix->getId(); - $this->assertNull($this->_em->find(Models\Company\CompanyFlexContract::class, $id)); - $this->assertNull($this->_em->getReference(Models\Company\CompanyFlexContract::class, $id)); - $this->assertNull($this->_em->getPartialReference(Models\Company\CompanyFlexContract::class, $id)); + self::assertNull($this->em->find(Models\Company\CompanyFlexContract::class, $id)); + self::assertNull($this->em->getReference(Models\Company\CompanyFlexContract::class, $id)); + self::assertNull($this->em->getPartialReference(Models\Company\CompanyFlexContract::class, $id)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1043Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1043Test.php index 9b35eb006c2..d83af0f59f2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1043Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1043Test.php @@ -1,5 +1,7 @@ username = "jgalt"; $user->status = "+44"; - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); $user->status = "44"; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $user = $this->_em->find(CmsUser::class, $user->id); - $this->assertSame("44", $user->status); + $user = $this->em->find(CmsUser::class, $user->id); + self::assertSame("44", $user->status); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1080Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1080Test.php index 59ee4bb58ff..7947bb57e81 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1080Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1080Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1080Foo::class), - $this->_em->getClassMetadata(DDC1080Bar::class), - $this->_em->getClassMetadata(DDC1080FooBar::class), + $this->em->getClassMetadata(DDC1080Foo::class), + $this->em->getClassMetadata(DDC1080Bar::class), + $this->em->getClassMetadata(DDC1080FooBar::class), ] ); @@ -46,54 +49,54 @@ public function testHydration() $foobar3->setBar($bar3); $foobar3->setOrderNr(0); - $this->_em->persist($foo1); - $this->_em->persist($foo2); - $this->_em->persist($bar1); - $this->_em->persist($bar2); - $this->_em->persist($bar3); - $this->_em->flush(); - - $this->_em->persist($foobar1); - $this->_em->persist($foobar2); - $this->_em->persist($foobar3); - $this->_em->flush(); - $this->_em->clear(); - - $foo = $this->_em->find(DDC1080Foo::class, $foo1->getFooID()); + $this->em->persist($foo1); + $this->em->persist($foo2); + $this->em->persist($bar1); + $this->em->persist($bar2); + $this->em->persist($bar3); + $this->em->flush(); + + $this->em->persist($foobar1); + $this->em->persist($foobar2); + $this->em->persist($foobar3); + $this->em->flush(); + $this->em->clear(); + + $foo = $this->em->find(DDC1080Foo::class, $foo1->getFooID()); + $fooBars = $foo->getFooBars(); - $this->assertEquals(3, count($fooBars), "Should return three foobars."); + self::assertEquals(3, count($fooBars), "Should return three foobars."); } } - /** - * @Entity - * @Table(name="foo") + * @ORM\Entity + * @ORM\Table(name="foo") */ class DDC1080Foo { - /** - * @Id - * @Column(name="fooID", type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(name="fooID", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ - protected $_fooID; + protected $fooID; + /** - * @Column(name="fooTitle", type="string") + * @ORM\Column(name="fooTitle", type="string") */ - protected $_fooTitle; + + protected $fooTitle; /** - * @OneToMany(targetEntity="DDC1080FooBar", mappedBy="_foo", - * cascade={"persist"}) - * @OrderBy({"_orderNr"="ASC"}) + * @ORM\OneToMany(targetEntity="DDC1080FooBar", mappedBy="foo", cascade={"persist"}) + * @ORM\OrderBy({"orderNr"="ASC"}) */ - protected $_fooBars; + protected $fooBars; public function __construct() { - $this->_fooBars = new \Doctrine\Common\Collections\ArrayCollection(); + $this->fooBars = new \Doctrine\Common\Collections\ArrayCollection(); } /** @@ -101,7 +104,7 @@ public function __construct() */ public function getFooID() { - return $this->_fooID; + return $this->fooID; } /** @@ -109,7 +112,7 @@ public function getFooID() */ public function getFooTitle() { - return $this->_fooTitle; + return $this->fooTitle; } /** @@ -117,7 +120,7 @@ public function getFooTitle() */ public function getFooBars() { - return $this->_fooBars; + return $this->fooBars; } /** @@ -125,7 +128,7 @@ public function getFooBars() */ public function setFooID($fooID) { - $this->_fooID = $fooID; + $this->fooID = $fooID; } /** @@ -133,7 +136,7 @@ public function setFooID($fooID) */ public function setFooTitle($fooTitle) { - $this->_fooTitle = $fooTitle; + $this->fooTitle = $fooTitle; } /** @@ -141,37 +144,37 @@ public function setFooTitle($fooTitle) */ public function setFooBars($fooBars) { - $this->_fooBars = $fooBars; + $this->fooBars = $fooBars; } } /** - * @Entity - * @Table(name="bar") + * @ORM\Entity + * @ORM\Table(name="bar") */ class DDC1080Bar { - /** - * @Id - * @Column(name="barID", type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(name="barID", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ - protected $_barID; + protected $barID; + /** - * @Column(name="barTitle", type="string") + * @ORM\Column(name="barTitle", type="string") */ - protected $_barTitle; + protected $barTitle; + /** - * @OneToMany(targetEntity="DDC1080FooBar", mappedBy="_bar", - * cascade={"persist"}) - * @OrderBy({"_orderNr"="ASC"}) + * @ORM\OneToMany(targetEntity="DDC1080FooBar", mappedBy="bar", cascade={"persist"}) + * @ORM\OrderBy({"orderNr"="ASC"}) */ - protected $_fooBars; + protected $fooBars; public function __construct() { - $this->_fooBars = new \Doctrine\Common\Collections\ArrayCollection(); + $this->fooBars = new \Doctrine\Common\Collections\ArrayCollection(); } /** @@ -179,7 +182,7 @@ public function __construct() */ public function getBarID() { - return $this->_barID; + return $this->barID; } /** @@ -187,7 +190,7 @@ public function getBarID() */ public function getBarTitle() { - return $this->_barTitle; + return $this->barTitle; } /** @@ -195,7 +198,7 @@ public function getBarTitle() */ public function getFooBars() { - return $this->_fooBars; + return $this->fooBars; } /** @@ -203,7 +206,7 @@ public function getFooBars() */ public function setBarID($barID) { - $this->_barID = $barID; + $this->barID = $barID; } /** @@ -211,7 +214,7 @@ public function setBarID($barID) */ public function setBarTitle($barTitle) { - $this->_barTitle = $barTitle; + $this->barTitle = $barTitle; } /** @@ -219,35 +222,34 @@ public function setBarTitle($barTitle) */ public function setFooBars($fooBars) { - $this->_fooBars = $fooBars; + $this->fooBars = $fooBars; } } /** - * @Table(name="fooBar") - * @Entity + * @ORM\Table(name="fooBar") + * @ORM\Entity */ class DDC1080FooBar { - /** - * @ManyToOne(targetEntity="DDC1080Foo") - * @JoinColumn(name="fooID", referencedColumnName="fooID") - * @Id + * @ORM\ManyToOne(targetEntity="DDC1080Foo") + * @ORM\JoinColumn(name="fooID", referencedColumnName="fooID") + * @ORM\Id */ - protected $_foo = null; + protected $foo = null; /** - * @ManyToOne(targetEntity="DDC1080Bar") - * @JoinColumn(name="barID", referencedColumnName="barID") - * @Id + * @ORM\ManyToOne(targetEntity="DDC1080Bar") + * @ORM\JoinColumn(name="barID", referencedColumnName="barID") + * @ORM\Id */ - protected $_bar = null; + protected $bar = null; /** * @var int orderNr - * @Column(name="orderNr", type="integer", nullable=false) + * @ORM\Column(name="orderNr", type="integer", nullable=false) */ - protected $_orderNr = null; + protected $orderNr = null; /** * Retrieve the foo property @@ -256,7 +258,7 @@ class DDC1080FooBar */ public function getFoo() { - return $this->_foo; + return $this->foo; } /** @@ -267,7 +269,8 @@ public function getFoo() */ public function setFoo($foo) { - $this->_foo = $foo; + $this->foo = $foo; + return $this; } @@ -278,7 +281,7 @@ public function setFoo($foo) */ public function getBar() { - return $this->_bar; + return $this->bar; } /** @@ -289,7 +292,8 @@ public function getBar() */ public function setBar($bar) { - $this->_bar = $bar; + $this->bar = $bar; + return $this; } @@ -300,7 +304,7 @@ public function setBar($bar) */ public function getOrderNr() { - return $this->_orderNr; + return $this->orderNr; } /** @@ -311,9 +315,9 @@ public function getOrderNr() */ public function setOrderNr($orderNr) { - $this->_orderNr = $orderNr; + $this->orderNr = $orderNr; + return $this; } - } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1113Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1113Test.php index 324e8481219..bdfd2ca8bc5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1113Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1113Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1113Engine::class), - $this->_em->getClassMetadata(DDC1113Vehicle::class), - $this->_em->getClassMetadata(DDC1113Car::class), - $this->_em->getClassMetadata(DDC1113Bus::class), + $this->em->getClassMetadata(DDC1113Engine::class), + $this->em->getClassMetadata(DDC1113Vehicle::class), + $this->em->getClassMetadata(DDC1113Car::class), + $this->em->getClassMetadata(DDC1113Bus::class), ] ); } catch (\Exception $e) { @@ -33,45 +37,45 @@ public function testIssue() $bus = new DDC1113Bus(); $bus->engine = new DDC1113Engine(); - $this->_em->persist($car); - $this->_em->flush(); + $this->em->persist($car); + $this->em->flush(); - $this->_em->persist($bus); - $this->_em->flush(); + $this->em->persist($bus); + $this->em->flush(); - $this->_em->remove($bus); - $this->_em->remove($car); - $this->_em->flush(); + $this->em->remove($bus); + $this->em->remove($car); + $this->em->flush(); - self::assertEmpty($this->_em->getRepository(DDC1113Car::class)->findAll()); - self::assertEmpty($this->_em->getRepository(DDC1113Bus::class)->findAll()); - self::assertEmpty($this->_em->getRepository(DDC1113Engine::class)->findAll()); + self::assertEmpty($this->em->getRepository(DDC1113Car::class)->findAll()); + self::assertEmpty($this->em->getRepository(DDC1113Bus::class)->findAll()); + self::assertEmpty($this->em->getRepository(DDC1113Engine::class)->findAll()); } } /** - * @Entity - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorMap({"vehicle" = "DDC1113Vehicle", "car" = "DDC1113Car", "bus" = "DDC1113Bus"}) + * @ORM\Entity + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorMap({"vehicle" = "DDC1113Vehicle", "car" = "DDC1113Car", "bus" = "DDC1113Bus"}) */ class DDC1113Vehicle { - /** @Id @GeneratedValue @Column(type="integer") */ + /** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ public $id; /** - * @ManyToOne(targetEntity="DDC1113Vehicle") + * @ORM\ManyToOne(targetEntity="DDC1113Vehicle") */ public $parent; - /** @OneToOne(targetEntity="DDC1113Engine", cascade={"persist", "remove"}) */ + /** @ORM\OneToOne(targetEntity="DDC1113Engine", cascade={"persist", "remove"}) */ public $engine; } /** - * @Entity + * @ORM\Entity */ class DDC1113Car extends DDC1113Vehicle { @@ -79,7 +83,7 @@ class DDC1113Car extends DDC1113Vehicle } /** - * @Entity + * @ORM\Entity */ class DDC1113Bus extends DDC1113Vehicle { @@ -87,12 +91,12 @@ class DDC1113Bus extends DDC1113Vehicle } /** - * @Entity + * @ORM\Entity */ class DDC1113Engine { - /** @Id @GeneratedValue @Column(type="integer") */ + /** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1129Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1129Test.php index 81c95010298..9b237b0616b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1129Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1129Test.php @@ -1,5 +1,7 @@ text = "I don't know."; $article->topic = "Who is John Galt?"; - $this->_em->persist($article); - $this->_em->flush(); + $this->em->persist($article); + $this->em->flush(); - $this->assertEquals(1, $article->version); + self::assertEquals(1, $article->version); - $class = $this->_em->getClassMetadata(CmsArticle::class); - $uow = $this->_em->getUnitOfWork(); + $class = $this->em->getClassMetadata(CmsArticle::class); + $uow = $this->em->getUnitOfWork(); $uow->computeChangeSet($class, $article); $changeSet = $uow->getEntityChangeSet($article); - $this->assertEquals(0, count($changeSet), "No changesets should be computed."); + self::assertEquals(0, count($changeSet), "No changesets should be computed."); $article->text = "This is John Galt speaking."; - $this->_em->flush(); + $this->em->flush(); - $this->assertEquals(2, $article->version); + self::assertEquals(2, $article->version); $uow->computeChangeSet($class, $article); $changeSet = $uow->getEntityChangeSet($article); - $this->assertEquals(0, count($changeSet), "No changesets should be computed."); + self::assertEquals(0, count($changeSet), "No changesets should be computed."); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1151Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1151Test.php index 5677801b408..c49358f415f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1151Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1151Test.php @@ -1,7 +1,11 @@ _em->getConnection()->getDatabasePlatform()->getName() != 'postgresql') { + if ($this->em->getConnection()->getDatabasePlatform()->getName() != 'postgresql') { $this->markTestSkipped("This test is useful for all databases, but designed only for postgresql."); } - $sql = $this->_schemaTool->getCreateSchemaSql( + $sql = $this->schemaTool->getCreateSchemaSql( [ - $this->_em->getClassMetadata(DDC1151User::class), - $this->_em->getClassMetadata(DDC1151Group::class), + $this->em->getClassMetadata(DDC1151User::class), + $this->em->getClassMetadata(DDC1151Group::class), ] ); - $this->assertEquals("CREATE TABLE \"User\" (id INT NOT NULL, PRIMARY KEY(id))", $sql[0]); - $this->assertEquals("CREATE TABLE ddc1151user_ddc1151group (ddc1151user_id INT NOT NULL, ddc1151group_id INT NOT NULL, PRIMARY KEY(ddc1151user_id, ddc1151group_id))", $sql[1]); - $this->assertEquals("CREATE INDEX IDX_88A3259AC5AD08A ON ddc1151user_ddc1151group (ddc1151user_id)", $sql[2]); - $this->assertEquals("CREATE INDEX IDX_88A32597357E0B1 ON ddc1151user_ddc1151group (ddc1151group_id)", $sql[3]); - $this->assertEquals("CREATE TABLE \"Group\" (id INT NOT NULL, PRIMARY KEY(id))", $sql[4]); - $this->assertEquals("CREATE SEQUENCE \"User_id_seq\" INCREMENT BY 1 MINVALUE 1 START 1", $sql[5]); - $this->assertEquals("CREATE SEQUENCE \"Group_id_seq\" INCREMENT BY 1 MINVALUE 1 START 1", $sql[6]); - $this->assertEquals("ALTER TABLE ddc1151user_ddc1151group ADD CONSTRAINT FK_88A3259AC5AD08A FOREIGN KEY (ddc1151user_id) REFERENCES \"User\" (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE", $sql[7]); - $this->assertEquals("ALTER TABLE ddc1151user_ddc1151group ADD CONSTRAINT FK_88A32597357E0B1 FOREIGN KEY (ddc1151group_id) REFERENCES \"Group\" (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE", $sql[8]); + self::assertEquals("CREATE TABLE \"User\" (id INT NOT NULL, PRIMARY KEY(id))", $sql[0]); + self::assertEquals("CREATE TABLE ddc1151user_ddc1151group (ddc1151user_id INT NOT NULL, ddc1151group_id INT NOT NULL, PRIMARY KEY(ddc1151user_id, ddc1151group_id))", $sql[1]); + self::assertEquals("CREATE INDEX IDX_88A3259AC5AD08A ON ddc1151user_ddc1151group (ddc1151user_id)", $sql[2]); + self::assertEquals("CREATE INDEX IDX_88A32597357E0B1 ON ddc1151user_ddc1151group (ddc1151group_id)", $sql[3]); + self::assertEquals("CREATE TABLE \"Group\" (id INT NOT NULL, PRIMARY KEY(id))", $sql[4]); + self::assertEquals("CREATE SEQUENCE \"User_id_seq\" INCREMENT BY 1 MINVALUE 1 START 1", $sql[5]); + self::assertEquals("CREATE SEQUENCE \"Group_id_seq\" INCREMENT BY 1 MINVALUE 1 START 1", $sql[6]); + self::assertEquals("ALTER TABLE ddc1151user_ddc1151group ADD CONSTRAINT FK_88A3259AC5AD08A FOREIGN KEY (ddc1151user_id) REFERENCES \"User\" (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE", $sql[7]); + self::assertEquals("ALTER TABLE ddc1151user_ddc1151group ADD CONSTRAINT FK_88A32597357E0B1 FOREIGN KEY (ddc1151group_id) REFERENCES \"Group\" (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE", $sql[8]); } } /** - * @Entity - * @Table(name="`User`") + * @ORM\Entity + * @ORM\Table(name="User") */ class DDC1151User { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @ManyToMany(targetEntity="DDC1151Group") */ + /** @ORM\ManyToMany(targetEntity="DDC1151Group") */ public $groups; } /** - * @Entity - * @Table(name="`Group`") + * @ORM\Entity + * @ORM\Table(name="Group") */ class DDC1151Group { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1163Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1163Test.php index f287034925a..446590e3913 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1163Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1163Test.php @@ -1,7 +1,10 @@ _em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_schemaTool->createSchema( + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1163Product::class), - $this->_em->getClassMetadata(DDC1163SpecialProduct::class), - $this->_em->getClassMetadata(DDC1163ProxyHolder::class), - $this->_em->getClassMetadata(DDC1163Tag::class), + $this->em->getClassMetadata(DDC1163Product::class), + $this->em->getClassMetadata(DDC1163SpecialProduct::class), + $this->em->getClassMetadata(DDC1163ProxyHolder::class), + $this->em->getClassMetadata(DDC1163Tag::class), ] ); } @@ -26,27 +29,27 @@ protected function setUp() public function testIssue() { $this->createSpecialProductAndProxyHolderReferencingIt(); - $this->_em->clear(); + $this->em->clear(); $this->createProxyForSpecialProduct(); $this->setPropertyAndAssignTagToSpecialProduct(); // fails - $this->_em->flush(); + $this->em->flush(); } private function createSpecialProductAndProxyHolderReferencingIt() { $specialProduct = new DDC1163SpecialProduct(); - $this->_em->persist($specialProduct); + $this->em->persist($specialProduct); $proxyHolder = new DDC1163ProxyHolder(); - $this->_em->persist($proxyHolder); + $this->em->persist($proxyHolder); $proxyHolder->setSpecialProduct($specialProduct); - $this->_em->flush(); + $this->em->flush(); $this->productId = $specialProduct->getId(); $this->proxyHolderId = $proxyHolder->getId(); @@ -62,49 +65,49 @@ private function createSpecialProductAndProxyHolderReferencingIt() private function createProxyForSpecialProduct() { /* @var $proxyHolder DDC1163ProxyHolder */ - $proxyHolder = $this->_em->find(DDC1163ProxyHolder::class, $this->proxyHolderId); + $proxyHolder = $this->em->find(DDC1163ProxyHolder::class, $this->proxyHolderId); - $this->assertInstanceOf(DDC1163SpecialProduct::class, $proxyHolder->getSpecialProduct()); + self::assertInstanceOf(DDC1163SpecialProduct::class, $proxyHolder->getSpecialProduct()); } private function setPropertyAndAssignTagToSpecialProduct() { /* @var $specialProduct DDC1163SpecialProduct */ - $specialProduct = $this->_em->find(DDC1163SpecialProduct::class, $this->productId); + $specialProduct = $this->em->find(DDC1163SpecialProduct::class, $this->productId); - $this->assertInstanceOf(DDC1163SpecialProduct::class, $specialProduct); - $this->assertInstanceOf(Proxy::class, $specialProduct); + self::assertInstanceOf(DDC1163SpecialProduct::class, $specialProduct); + self::assertInstanceOf(Proxy::class, $specialProduct); $specialProduct->setSubclassProperty('foobar'); // this screams violation of law of demeter ;) - $this->assertEquals( + self::assertEquals( DDC1163SpecialProduct::class, - $this->_em->getUnitOfWork()->getEntityPersister(get_class($specialProduct))->getClassMetadata()->name + $this->em->getUnitOfWork()->getEntityPersister(get_class($specialProduct))->getClassMetadata()->getClassName() ); $tag = new DDC1163Tag('Foo'); - $this->_em->persist($tag); + $this->em->persist($tag); $tag->setProduct($specialProduct); } } /** - * @Entity + * @ORM\Entity */ class DDC1163ProxyHolder { /** * @var int - * @Column(name="id", type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") + * @ORM\Column(name="id", type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var SpecialProduct - * @OneToOne(targetEntity="DDC1163SpecialProduct") + * @ORM\OneToOne(targetEntity="DDC1163SpecialProduct") */ private $specialProduct; @@ -126,19 +129,19 @@ public function getSpecialProduct() } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="type", type="string") - * @DiscriminatorMap({"special" = "DDC1163SpecialProduct"}) + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="type", type="string") + * @ORM\DiscriminatorMap({"special" = "DDC1163SpecialProduct"}) */ abstract class DDC1163Product { /** * @var int - * @Column(name="id", type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") + * @ORM\Column(name="id", type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; @@ -150,14 +153,14 @@ public function getId() } /** - * @Entity + * @ORM\Entity */ class DDC1163SpecialProduct extends DDC1163Product { /** * @var string - * @Column(name="subclass_property", type="string", nullable=true) + * @ORM\Column(name="subclass_property", type="string", nullable=true) */ private $subclassProperty; @@ -172,28 +175,28 @@ public function setSubclassProperty($value) } /** - * @Entity + * @ORM\Entity */ class DDC1163Tag { /** * @var int - * @Column(name="id", type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") + * @ORM\Column(name="id", type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string - * @Column(name="name", type="string") + * @ORM\Column(name="name", type="string") */ private $name; /** * @var Product - * @ManyToOne(targetEntity="DDC1163Product", inversedBy="tags") - * @JoinColumns({ - * @JoinColumn(name="product_id", referencedColumnName="id") + * @ORM\ManyToOne(targetEntity="DDC1163Product", inversedBy="tags") + * @ORM\JoinColumns({ + * @ORM\JoinColumn(name="product_id", referencedColumnName="id") * }) */ private $product; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC117Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC117Test.php index 8478a5f66d6..5aa72a78f31 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC117Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC117Test.php @@ -1,5 +1,7 @@ article1 = new DDC117Article("Foo"); $this->article2 = new DDC117Article("Bar"); - $this->_em->persist($this->article1); - $this->_em->persist($this->article2); - $this->_em->flush(); + $this->em->persist($this->article1); + $this->em->persist($this->article2); + $this->em->flush(); $link = new DDC117Link($this->article1, $this->article2, "Link-Description"); - $this->_em->persist($link); + $this->em->persist($link); $this->reference = new DDC117Reference($this->article1, $this->article2, "Test-Description"); - $this->_em->persist($this->reference); + $this->em->persist($this->reference); $this->translation = new DDC117Translation($this->article1, "en", "Bar"); - $this->_em->persist($this->translation); + $this->em->persist($this->translation); $this->articleDetails = new DDC117ArticleDetails($this->article1, "Very long text"); - $this->_em->persist($this->articleDetails); - $this->_em->flush(); + $this->em->persist($this->articleDetails); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); } /** @@ -56,36 +58,36 @@ public function testAssociationOnlyCompositeKey() { $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; - $mapRef = $this->_em->find(DDC117Reference::class, $idCriteria); - $this->assertInstanceOf(DDC117Reference::class, $mapRef); - $this->assertInstanceOf(DDC117Article::class, $mapRef->target()); - $this->assertInstanceOf(DDC117Article::class, $mapRef->source()); - $this->assertSame($mapRef, $this->_em->find(DDC117Reference::class, $idCriteria)); + $mapRef = $this->em->find(DDC117Reference::class, $idCriteria); + self::assertInstanceOf(DDC117Reference::class, $mapRef); + self::assertInstanceOf(DDC117Article::class, $mapRef->target()); + self::assertInstanceOf(DDC117Article::class, $mapRef->source()); + self::assertSame($mapRef, $this->em->find(DDC117Reference::class, $idCriteria)); - $this->_em->clear(); + $this->em->clear(); $dql = 'SELECT r, s FROM ' . DDC117Reference::class . ' r JOIN r.source s WHERE r.source = ?1'; - $dqlRef = $this->_em->createQuery($dql)->setParameter(1, 1)->getSingleResult(); + $dqlRef = $this->em->createQuery($dql)->setParameter(1, 1)->getSingleResult(); - $this->assertInstanceOf(DDC117Reference::class, $mapRef); - $this->assertInstanceOf(DDC117Article::class, $mapRef->target()); - $this->assertInstanceOf(DDC117Article::class, $mapRef->source()); - $this->assertSame($dqlRef, $this->_em->find(DDC117Reference::class, $idCriteria)); + self::assertInstanceOf(DDC117Reference::class, $mapRef); + self::assertInstanceOf(DDC117Article::class, $mapRef->target()); + self::assertInstanceOf(DDC117Article::class, $mapRef->source()); + self::assertSame($dqlRef, $this->em->find(DDC117Reference::class, $idCriteria)); - $this->_em->clear(); + $this->em->clear(); $dql = 'SELECT r, s FROM ' . DDC117Reference::class . ' r JOIN r.source s WHERE s.title = ?1'; - $dqlRef = $this->_em->createQuery($dql)->setParameter(1, 'Foo')->getSingleResult(); + $dqlRef = $this->em->createQuery($dql)->setParameter(1, 'Foo')->getSingleResult(); - $this->assertInstanceOf(DDC117Reference::class, $dqlRef); - $this->assertInstanceOf(DDC117Article::class, $dqlRef->target()); - $this->assertInstanceOf(DDC117Article::class, $dqlRef->source()); - $this->assertSame($dqlRef, $this->_em->find(DDC117Reference::class, $idCriteria)); + self::assertInstanceOf(DDC117Reference::class, $dqlRef); + self::assertInstanceOf(DDC117Article::class, $dqlRef->target()); + self::assertInstanceOf(DDC117Article::class, $dqlRef->source()); + self::assertSame($dqlRef, $this->em->find(DDC117Reference::class, $idCriteria)); $dql = 'SELECT r, s FROM ' . DDC117Reference::class . ' r JOIN r.source s WHERE s.title = ?1'; - $dqlRef = $this->_em->createQuery($dql)->setParameter(1, 'Foo')->getSingleResult(); + $dqlRef = $this->em->createQuery($dql)->setParameter(1, 'Foo')->getSingleResult(); - $this->_em->contains($dqlRef); + $this->em->contains($dqlRef); } /** @@ -95,15 +97,15 @@ public function testUpdateAssociationEntity() { $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; - $mapRef = $this->_em->find(DDC117Reference::class, $idCriteria); - $this->assertNotNull($mapRef); + $mapRef = $this->em->find(DDC117Reference::class, $idCriteria); + self::assertNotNull($mapRef); $mapRef->setDescription("New Description!!"); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $mapRef = $this->_em->find(DDC117Reference::class, $idCriteria); + $mapRef = $this->em->find(DDC117Reference::class, $idCriteria); - $this->assertEquals('New Description!!', $mapRef->getDescription()); + self::assertEquals('New Description!!', $mapRef->getDescription()); } /** @@ -112,13 +114,13 @@ public function testUpdateAssociationEntity() public function testFetchDql() { $dql = "SELECT r, s FROM Doctrine\Tests\Models\DDC117\DDC117Reference r JOIN r.source s WHERE s.title = ?1"; - $refs = $this->_em->createQuery($dql)->setParameter(1, 'Foo')->getResult(); + $refs = $this->em->createQuery($dql)->setParameter(1, 'Foo')->getResult(); - $this->assertTrue(count($refs) > 0, "Has to contain at least one Reference."); + self::assertTrue(count($refs) > 0, "Has to contain at least one Reference."); foreach ($refs AS $ref) { - $this->assertInstanceOf(DDC117Reference::class, $ref, "Contains only Reference instances."); - $this->assertTrue($this->_em->contains($ref), "Contains Reference in the IdentityMap."); + self::assertInstanceOf(DDC117Reference::class, $ref, "Contains only Reference instances."); + self::assertTrue($this->em->contains($ref), "Contains Reference in the IdentityMap."); } } @@ -129,13 +131,13 @@ public function testRemoveCompositeElement() { $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; - $refRep = $this->_em->find(DDC117Reference::class, $idCriteria); + $refRep = $this->em->find(DDC117Reference::class, $idCriteria); - $this->_em->remove($refRep); - $this->_em->flush(); - $this->_em->clear(); + $this->em->remove($refRep); + $this->em->flush(); + $this->em->clear(); - $this->assertNull($this->_em->find(DDC117Reference::class, $idCriteria)); + self::assertNull($this->em->find(DDC117Reference::class, $idCriteria)); } /** @@ -147,12 +149,12 @@ public function testDqlRemoveCompositeElement() $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; $dql = "DELETE Doctrine\Tests\Models\DDC117\DDC117Reference r WHERE r.source = ?1 AND r.target = ?2"; - $this->_em->createQuery($dql) + $this->em->createQuery($dql) ->setParameter(1, $this->article1->id()) ->setParameter(2, $this->article2->id()) ->execute(); - $this->assertNull($this->_em->find(DDC117Reference::class, $idCriteria)); + self::assertNull($this->em->find(DDC117Reference::class, $idCriteria)); } /** @@ -160,27 +162,27 @@ public function testDqlRemoveCompositeElement() */ public function testInverseSideAccess() { - $this->article1 = $this->_em->find(DDC117Article::class, $this->article1->id()); + $this->article1 = $this->em->find(DDC117Article::class, $this->article1->id()); - $this->assertEquals(1, count($this->article1->references())); + self::assertEquals(1, count($this->article1->references())); foreach ($this->article1->references() AS $this->reference) { - $this->assertInstanceOf(DDC117Reference::class, $this->reference); - $this->assertSame($this->article1, $this->reference->source()); + self::assertInstanceOf(DDC117Reference::class, $this->reference); + self::assertSame($this->article1, $this->reference->source()); } - $this->_em->clear(); + $this->em->clear(); $dql = 'SELECT a, r FROM Doctrine\Tests\Models\DDC117\DDC117Article a INNER JOIN a.references r WHERE a.id = ?1'; - $articleDql = $this->_em->createQuery($dql) + $articleDql = $this->em->createQuery($dql) ->setParameter(1, $this->article1->id()) ->getSingleResult(); - $this->assertEquals(1, count($this->article1->references())); + self::assertEquals(1, count($this->article1->references())); foreach ($this->article1->references() AS $this->reference) { - $this->assertInstanceOf(DDC117Reference::class, $this->reference); - $this->assertSame($this->article1, $this->reference->source()); + self::assertInstanceOf(DDC117Reference::class, $this->reference); + self::assertSame($this->article1, $this->reference->source()); } } @@ -191,20 +193,20 @@ public function testMixedCompositeKey() { $idCriteria = ['article' => $this->article1->id(), 'language' => 'en']; - $this->translation = $this->_em->find(DDC117Translation::class, $idCriteria); - $this->assertInstanceOf(DDC117Translation::class, $this->translation); + $this->translation = $this->em->find(DDC117Translation::class, $idCriteria); + self::assertInstanceOf(DDC117Translation::class, $this->translation); - $this->assertSame($this->translation, $this->_em->find(DDC117Translation::class, $idCriteria)); + self::assertSame($this->translation, $this->em->find(DDC117Translation::class, $idCriteria)); - $this->_em->clear(); + $this->em->clear(); $dql = 'SELECT t, a FROM Doctrine\Tests\Models\DDC117\DDC117Translation t JOIN t.article a WHERE t.article = ?1 AND t.language = ?2'; - $dqlTrans = $this->_em->createQuery($dql) + $dqlTrans = $this->em->createQuery($dql) ->setParameter(1, $this->article1->id()) ->setParameter(2, 'en') ->getSingleResult(); - $this->assertInstanceOf(DDC117Translation::class, $this->translation); + self::assertInstanceOf(DDC117Translation::class, $this->translation); } /** @@ -212,19 +214,19 @@ public function testMixedCompositeKey() */ public function testMixedCompositeKeyViolateUniqueness() { - $this->article1 = $this->_em->find(DDC117Article::class, $this->article1->id()); + $this->article1 = $this->em->find(DDC117Article::class, $this->article1->id()); $this->article1->addTranslation('en', 'Bar'); $this->article1->addTranslation('en', 'Baz'); $exceptionThrown = false; try { // exception depending on the underlying Database Driver - $this->_em->flush(); + $this->em->flush(); } catch(\Exception $e) { $exceptionThrown = true; } - $this->assertTrue($exceptionThrown, "The underlying database driver throws an exception."); + self::assertTrue($exceptionThrown, "The underlying database driver throws an exception."); } /** @@ -233,20 +235,20 @@ public function testMixedCompositeKeyViolateUniqueness() public function testOneToOneForeignObjectId() { $this->article1 = new DDC117Article("Foo"); - $this->_em->persist($this->article1); - $this->_em->flush(); + $this->em->persist($this->article1); + $this->em->flush(); $this->articleDetails = new DDC117ArticleDetails($this->article1, "Very long text"); - $this->_em->persist($this->articleDetails); - $this->_em->flush(); + $this->em->persist($this->articleDetails); + $this->em->flush(); $this->articleDetails->update("not so very long text!"); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); /* @var $article DDC117Article */ - $article = $this->_em->find(get_class($this->article1), $this->article1->id()); - $this->assertEquals('not so very long text!', $article->getText()); + $article = $this->em->find(get_class($this->article1), $this->article1->id()); + self::assertEquals('not so very long text!', $article->getText()); } /** @@ -254,11 +256,11 @@ public function testOneToOneForeignObjectId() */ public function testOneToOneCascadeRemove() { - $article = $this->_em->find(get_class($this->article1), $this->article1->id()); - $this->_em->remove($article); - $this->_em->flush(); + $article = $this->em->find(get_class($this->article1), $this->article1->id()); + $this->em->remove($article); + $this->em->flush(); - $this->assertFalse($this->_em->contains($article->getDetails())); + self::assertFalse($this->em->contains($article->getDetails())); } /** @@ -266,17 +268,17 @@ public function testOneToOneCascadeRemove() */ public function testOneToOneCascadePersist() { - if ( ! $this->_em->getConnection()->getDatabasePlatform()->prefersSequences()) { + if (! $this->em->getConnection()->getDatabasePlatform()->prefersSequences()) { $this->markTestSkipped('Test only works with databases that prefer sequences as ID strategy.'); } $this->article1 = new DDC117Article("Foo"); $this->articleDetails = new DDC117ArticleDetails($this->article1, "Very long text"); - $this->_em->persist($this->article1); - $this->_em->flush(); + $this->em->persist($this->article1); + $this->em->flush(); - self::assertSame($this->articleDetails, $this->_em->find(DDC117ArticleDetails::class, $this->article1)); + self::assertSame($this->articleDetails, $this->em->find(DDC117ArticleDetails::class, $this->article1)); } /** @@ -285,21 +287,21 @@ public function testOneToOneCascadePersist() public function testReferencesToForeignKeyEntities() { $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; - $reference = $this->_em->find(DDC117Reference::class, $idCriteria); + $reference = $this->em->find(DDC117Reference::class, $idCriteria); $idCriteria = ['article' => $this->article1->id(), 'language' => 'en']; - $translation = $this->_em->find(DDC117Translation::class, $idCriteria); + $translation = $this->em->find(DDC117Translation::class, $idCriteria); $approveChanges = new DDC117ApproveChanges($reference->source()->getDetails(), $reference, $translation); - $this->_em->persist($approveChanges); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($approveChanges); + $this->em->flush(); + $this->em->clear(); - $approveChanges = $this->_em->find(DDC117ApproveChanges::class, $approveChanges->getId()); + $approveChanges = $this->em->find(DDC117ApproveChanges::class, $approveChanges->getId()); - $this->assertInstanceOf(DDC117ArticleDetails::class, $approveChanges->getArticleDetails()); - $this->assertInstanceOf(DDC117Reference::class, $approveChanges->getReference()); - $this->assertInstanceOf(DDC117Translation::class, $approveChanges->getTranslation()); + self::assertInstanceOf(DDC117ArticleDetails::class, $approveChanges->getArticleDetails()); + self::assertInstanceOf(DDC117Reference::class, $approveChanges->getReference()); + self::assertInstanceOf(DDC117Translation::class, $approveChanges->getTranslation()); } /** @@ -308,12 +310,12 @@ public function testReferencesToForeignKeyEntities() public function testLoadOneToManyCollectionOfForeignKeyEntities() { /* @var $article DDC117Article */ - $article = $this->_em->find(get_class($this->article1), $this->article1->id()); + $article = $this->em->find(get_class($this->article1), $this->article1->id()); $translations = $article->getTranslations(); - $this->assertFalse($translations->isInitialized()); - $this->assertContainsOnly(DDC117Translation::class, $translations); - $this->assertTrue($translations->isInitialized()); + self::assertFalse($translations->isInitialized()); + self::assertContainsOnly(DDC117Translation::class, $translations); + self::assertTrue($translations->isInitialized()); } /** @@ -323,16 +325,16 @@ public function testLoadManyToManyCollectionOfForeignKeyEntities() { $editor = $this->loadEditorFixture(); - $this->assertFalse($editor->reviewingTranslations->isInitialized()); - $this->assertContainsOnly(DDC117Translation::class, $editor->reviewingTranslations); - $this->assertTrue($editor->reviewingTranslations->isInitialized()); + self::assertFalse($editor->reviewingTranslations->isInitialized()); + self::assertContainsOnly(DDC117Translation::class, $editor->reviewingTranslations); + self::assertTrue($editor->reviewingTranslations->isInitialized()); - $this->_em->clear(); + $this->em->clear(); $dql = "SELECT e, t FROM Doctrine\Tests\Models\DDC117\DDC117Editor e JOIN e.reviewingTranslations t WHERE e.id = ?1"; - $editor = $this->_em->createQuery($dql)->setParameter(1, $editor->id)->getSingleResult(); - $this->assertTrue($editor->reviewingTranslations->isInitialized()); - $this->assertContainsOnly(DDC117Translation::class, $editor->reviewingTranslations); + $editor = $this->em->createQuery($dql)->setParameter(1, $editor->id)->getSingleResult(); + self::assertTrue($editor->reviewingTranslations->isInitialized()); + self::assertContainsOnly(DDC117Translation::class, $editor->reviewingTranslations); } /** @@ -341,14 +343,14 @@ public function testLoadManyToManyCollectionOfForeignKeyEntities() public function testClearManyToManyCollectionOfForeignKeyEntities() { $editor = $this->loadEditorFixture(); - $this->assertEquals(3, count($editor->reviewingTranslations)); + self::assertEquals(3, count($editor->reviewingTranslations)); $editor->reviewingTranslations->clear(); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $editor = $this->_em->find(get_class($editor), $editor->id); - $this->assertEquals(0, count($editor->reviewingTranslations)); + $editor = $this->em->find(get_class($editor), $editor->id); + self::assertEquals(0, count($editor->reviewingTranslations)); } /** @@ -358,24 +360,24 @@ public function testLoadInverseManyToManyCollection() { $editor = $this->loadEditorFixture(); - $this->assertInstanceOf(DDC117Translation::class, $editor->reviewingTranslations[0]); + self::assertInstanceOf(DDC117Translation::class, $editor->reviewingTranslations[0]); $reviewedBy = $editor->reviewingTranslations[0]->getReviewedByEditors(); - $this->assertEquals(1, count($reviewedBy)); - $this->assertSame($editor, $reviewedBy[0]); + self::assertEquals(1, count($reviewedBy)); + self::assertSame($editor, $reviewedBy[0]); - $this->_em->clear(); + $this->em->clear(); $dql = "SELECT t, e FROM Doctrine\Tests\Models\DDC117\DDC117Translation t ". "JOIN t.reviewedByEditors e WHERE t.article = ?1 AND t.language = ?2"; - $trans = $this->_em->createQuery($dql) + $trans = $this->em->createQuery($dql) ->setParameter(1, $this->translation->getArticleId()) ->setParameter(2, $this->translation->getLanguage()) ->getSingleResult(); - $this->assertInstanceOf(DDC117Translation::class, $trans); - $this->assertContainsOnly(DDC117Editor::class, $trans->reviewedByEditors); - $this->assertEquals(1, count($trans->reviewedByEditors)); + self::assertInstanceOf(DDC117Translation::class, $trans); + self::assertContainsOnly(DDC117Editor::class, $trans->reviewedByEditors); + self::assertEquals(1, count($trans->reviewedByEditors)); } /** @@ -386,14 +388,14 @@ public function testLoadOneToManyOfSourceEntityWithAssociationIdentifier() $editor = $this->loadEditorFixture(); $editor->addLastTranslation($editor->reviewingTranslations[0]); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $editor = $this->_em->find(get_class($editor), $editor->id); + $editor = $this->em->find(get_class($editor), $editor->id); $lastTranslatedBy = $editor->reviewingTranslations[0]->getLastTranslatedBy(); $lastTranslatedBy->count(); - $this->assertEquals(1, count($lastTranslatedBy)); + self::assertEquals(1, count($lastTranslatedBy)); } /** @@ -404,42 +406,26 @@ private function loadEditorFixture() $editor = new DDC117Editor("beberlei"); /* @var $article1 DDC117Article */ - $article1 = $this->_em->find(get_class($this->article1), $this->article1->id()); + $article1 = $this->em->find(get_class($this->article1), $this->article1->id()); foreach ($article1->getTranslations() AS $translation) { $editor->reviewingTranslations[] = $translation; } /* @var $article2 DDC117Article */ - $article2 = $this->_em->find(get_class($this->article2), $this->article2->id()); + $article2 = $this->em->find(get_class($this->article2), $this->article2->id()); $article2->addTranslation("de", "Vanille-Krapferl"); // omnomnom $article2->addTranslation("fr", "Sorry can't speak french!"); foreach ($article2->getTranslations() AS $translation) { - $this->_em->persist($translation); // otherwise persisting the editor won't work, reachability! + $this->em->persist($translation); // otherwise persisting the editor won't work, reachability! $editor->reviewingTranslations[] = $translation; } - $this->_em->persist($editor); - $this->_em->flush(); - $this->_em->clear(); - - return $this->_em->find(get_class($editor), $editor->id); - } - - /** - * @group DDC-1519 - */ - public function testMergeForeignKeyIdentifierEntity() - { - $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; - - $refRep = $this->_em->find(DDC117Reference::class, $idCriteria); - - $this->_em->detach($refRep); - $refRep = $this->_em->merge($refRep); + $this->em->persist($editor); + $this->em->flush(); + $this->em->clear(); - $this->assertEquals($this->article1->id(), $refRep->source()->id()); - $this->assertEquals($this->article2->id(), $refRep->target()->id()); + return $this->em->find(get_class($editor), $editor->id); } /** @@ -448,26 +434,26 @@ public function testMergeForeignKeyIdentifierEntity() public function testArrayHydrationWithCompositeKey() { $dql = "SELECT r,s,t FROM Doctrine\Tests\Models\DDC117\DDC117Reference r INNER JOIN r.source s INNER JOIN r.target t"; - $before = count($this->_em->createQuery($dql)->getResult()); + $before = count($this->em->createQuery($dql)->getResult()); - $this->article1 = $this->_em->find(DDC117Article::class, $this->article1->id()); - $this->article2 = $this->_em->find(DDC117Article::class, $this->article2->id()); + $this->article1 = $this->em->find(DDC117Article::class, $this->article1->id()); + $this->article2 = $this->em->find(DDC117Article::class, $this->article2->id()); $this->reference = new DDC117Reference($this->article2, $this->article1, "Test-Description"); - $this->_em->persist($this->reference); + $this->em->persist($this->reference); $this->reference = new DDC117Reference($this->article1, $this->article1, "Test-Description"); - $this->_em->persist($this->reference); + $this->em->persist($this->reference); $this->reference = new DDC117Reference($this->article2, $this->article2, "Test-Description"); - $this->_em->persist($this->reference); + $this->em->persist($this->reference); - $this->_em->flush(); + $this->em->flush(); $dql = "SELECT r,s,t FROM Doctrine\Tests\Models\DDC117\DDC117Reference r INNER JOIN r.source s INNER JOIN r.target t"; - $data = $this->_em->createQuery($dql)->getArrayResult(); + $data = $this->em->createQuery($dql)->getArrayResult(); - $this->assertEquals($before + 3, count($data)); + self::assertEquals($before + 3, count($data)); } /** @@ -479,27 +465,27 @@ public function testGetEntityState() $this->markTestIncomplete('Second level cache - not supported yet'); } - $this->article1 = $this->_em->find(DDC117Article::class, $this->article1->id()); - $this->article2 = $this->_em->find(DDC117Article::class, $this->article2->id()); + $this->article1 = $this->em->find(DDC117Article::class, $this->article1->id()); + $this->article2 = $this->em->find(DDC117Article::class, $this->article2->id()); $this->reference = new DDC117Reference($this->article2, $this->article1, "Test-Description"); - $this->assertEquals(\Doctrine\ORM\UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($this->reference)); + self::assertEquals(\Doctrine\ORM\UnitOfWork::STATE_NEW, $this->em->getUnitOfWork()->getEntityState($this->reference)); $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; - $reference = $this->_em->find(DDC117Reference::class, $idCriteria); + $reference = $this->em->find(DDC117Reference::class, $idCriteria); - $this->assertEquals(\Doctrine\ORM\UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($reference)); + self::assertEquals(\Doctrine\ORM\UnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($reference)); } /** * @group DDC-117 */ public function testIndexByOnCompositeKeyField() { - $article = $this->_em->find(DDC117Article::class, $this->article1->id()); + $article = $this->em->find(DDC117Article::class, $this->article1->id()); - $this->assertInstanceOf(DDC117Article::class, $article); - $this->assertEquals(1, count($article->getLinks())); - $this->assertTrue($article->getLinks()->offsetExists($this->article2->id())); + self::assertInstanceOf(DDC117Article::class, $article); + self::assertEquals(1, count($article->getLinks())); + self::assertTrue($article->getLinks()->offsetExists($this->article2->id())); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1181Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1181Test.php index 564e046e7d3..4eab945b966 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1181Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1181Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1181Hotel::class), - $this->_em->getClassMetadata(DDC1181Booking::class), - $this->_em->getClassMetadata(DDC1181Room::class), + $this->em->getClassMetadata(DDC1181Hotel::class), + $this->em->getClassMetadata(DDC1181Booking::class), + $this->em->getClassMetadata(DDC1181Room::class), ] ); } @@ -27,10 +30,10 @@ public function testIssue() $room1 = new DDC1181Room(); $room2 = new DDC1181Room(); - $this->_em->persist($hotel); - $this->_em->persist($room1); - $this->_em->persist($room2); - $this->_em->flush(); + $this->em->persist($hotel); + $this->em->persist($room1); + $this->em->persist($room2); + $this->em->flush(); $booking1 = new DDC1181Booking; $booking1->hotel = $hotel; @@ -41,27 +44,27 @@ public function testIssue() $hotel->bookings[] = $booking1; $hotel->bookings[] = $booking2; - $this->_em->persist($booking1); - $this->_em->persist($booking2); - $this->_em->flush(); + $this->em->persist($booking1); + $this->em->persist($booking2); + $this->em->flush(); - $this->_em->remove($hotel); - $this->_em->flush(); + $this->em->remove($hotel); + $this->em->flush(); - self::assertEmpty($this->_em->getRepository(DDC1181Booking::class)->findAll()); + self::assertEmpty($this->em->getRepository(DDC1181Booking::class)->findAll()); } } /** - * @Entity + * @ORM\Entity */ class DDC1181Hotel { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; /** - * @oneToMany(targetEntity="DDC1181Booking", mappedBy="hotel", cascade={"remove"}) + * @ORM\OneToMany(targetEntity="DDC1181Booking", mappedBy="hotel", cascade={"remove"}) * @var Booking[] */ public $bookings; @@ -69,37 +72,37 @@ class DDC1181Hotel } /** - * @Entity + * @ORM\Entity */ class DDC1181Booking { /** * @var Hotel * - * @Id - * @ManyToOne(targetEntity="DDC1181Hotel", inversedBy="bookings") - * @JoinColumns({ - * @JoinColumn(name="hotel_id", referencedColumnName="id") + * @ORM\Id + * @ORM\ManyToOne(targetEntity="DDC1181Hotel", inversedBy="bookings") + * @ORM\JoinColumns({ + * @ORM\JoinColumn(name="hotel_id", referencedColumnName="id") * }) */ public $hotel; /** * @var Room * - * @Id - * @ManyToOne(targetEntity="DDC1181Room") - * @JoinColumns({ - * @JoinColumn(name="room_id", referencedColumnName="id") + * @ORM\Id + * @ORM\ManyToOne(targetEntity="DDC1181Room") + * @ORM\JoinColumns({ + * @ORM\JoinColumn(name="room_id", referencedColumnName="id") * }) */ public $room; } /** - * @Entity + * @ORM\Entity */ class DDC1181Room { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1193Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1193Test.php index f4d98cb23a4..f1f7b4a104a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1193Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1193Test.php @@ -1,7 +1,10 @@ _em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_schemaTool->createSchema( + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1193Company::class), - $this->_em->getClassMetadata(DDC1193Person::class), - $this->_em->getClassMetadata(DDC1193Account::class) + $this->em->getClassMetadata(DDC1193Company::class), + $this->em->getClassMetadata(DDC1193Person::class), + $this->em->getClassMetadata(DDC1193Account::class) ] ); } @@ -33,59 +36,59 @@ public function testIssue() $company->member = $person; - $this->_em->persist($company); + $this->em->persist($company); - $this->_em->flush(); + $this->em->flush(); $companyId = $company->id; $accountId = $account->id; - $this->_em->clear(); + $this->em->clear(); - $company = $this->_em->find(get_class($company), $companyId); + $company = $this->em->find(get_class($company), $companyId); - $this->assertTrue($this->_em->getUnitOfWork()->isInIdentityMap($company), "Company is in identity map."); - $this->assertFalse($company->member->__isInitialized__, "Pre-Condition"); - $this->assertTrue($this->_em->getUnitOfWork()->isInIdentityMap($company->member), "Member is in identity map."); + self::assertTrue($this->em->getUnitOfWork()->isInIdentityMap($company), "Company is in identity map."); + self::assertFalse($company->member->__isInitialized(), "Pre-Condition"); + self::assertTrue($this->em->getUnitOfWork()->isInIdentityMap($company->member), "Member is in identity map."); - $this->_em->remove($company); - $this->_em->flush(); + $this->em->remove($company); + $this->em->flush(); - $this->assertEquals(count($this->_em->getRepository(get_class($account))->findAll()), 0); + self::assertEquals(count($this->em->getRepository(get_class($account))->findAll()), 0); } } -/** @Entity */ +/** @ORM\Entity */ class DDC1193Company { /** - * @Id @Column(type="integer") - * @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue */ public $id; - /** @OneToOne(targetEntity="DDC1193Person", cascade={"persist", "remove"}) */ + /** @ORM\OneToOne(targetEntity="DDC1193Person", cascade={"persist", "remove"}) */ public $member; } -/** @Entity */ +/** @ORM\Entity */ class DDC1193Person { /** - * @Id @Column(type="integer") - * @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue */ public $id; /** - * @OneToOne(targetEntity="DDC1193Account", cascade={"persist", "remove"}) + * @ORM\OneToOne(targetEntity="DDC1193Account", cascade={"persist", "remove"}) */ public $account; } -/** @Entity */ +/** @ORM\Entity */ class DDC1193Account { /** - * @Id @Column(type="integer") - * @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue */ public $id; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1209Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1209Test.php index 6c54da296be..a71d4b5615c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1209Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1209Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1209_1::class), - $this->_em->getClassMetadata(DDC1209_2::class), - $this->_em->getClassMetadata(DDC1209_3::class) + $this->em->getClassMetadata(DDC1209_1::class), + $this->em->getClassMetadata(DDC1209_2::class), + $this->em->getClassMetadata(DDC1209_3::class) ] ); } catch(\Exception $e) { @@ -28,10 +31,10 @@ public function testIdentifierCanHaveCustomType() { $entity = new DDC1209_3(); - $this->_em->persist($entity); - $this->_em->flush(); + $this->em->persist($entity); + $this->em->flush(); - self::assertSame($entity, $this->_em->find(DDC1209_3::class, $entity->date)); + self::assertSame($entity, $this->em->find(DDC1209_3::class, $entity->date)); } /** @@ -41,17 +44,17 @@ public function testCompositeIdentifierCanHaveCustomType() { $future1 = new DDC1209_1(); - $this->_em->persist($future1); - $this->_em->flush(); + $this->em->persist($future1); + $this->em->flush(); $future2 = new DDC1209_2($future1); - $this->_em->persist($future2); - $this->_em->flush(); + $this->em->persist($future2); + $this->em->flush(); self::assertSame( $future2, - $this->_em->find( + $this->em->find( DDC1209_2::class, [ 'future1' => $future1, @@ -65,12 +68,12 @@ public function testCompositeIdentifierCanHaveCustomType() } /** - * @Entity + * @ORM\Entity */ class DDC1209_1 { /** - * @Id @GeneratedValue @Column(type="integer") + * @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ private $id; @@ -81,31 +84,31 @@ public function getId() } /** - * @Entity + * @ORM\Entity */ class DDC1209_2 { /** - * @Id - * @ManyToOne(targetEntity="DDC1209_1") - * @JoinColumn(referencedColumnName="id", nullable=false) + * @ORM\Id + * @ORM\ManyToOne(targetEntity="DDC1209_1") + * @ORM\JoinColumn(referencedColumnName="id", nullable=false) */ private $future1; /** - * @Id - * @Column(type="datetime", nullable=false) + * @ORM\Id + * @ORM\Column(type="datetime", nullable=false) */ public $starting_datetime; /** - * @Id - * @Column(type="datetime", nullable=false) + * @ORM\Id + * @ORM\Column(type="datetime", nullable=false) */ public $during_datetime; /** - * @Id - * @Column(type="datetime", nullable=false) + * @ORM\Id + * @ORM\Column(type="datetime", nullable=false) */ public $ending_datetime; @@ -119,13 +122,13 @@ public function __construct(DDC1209_1 $future1) } /** - * @Entity + * @ORM\Entity */ class DDC1209_3 { /** - * @Id - * @Column(type="datetime", name="somedate") + * @ORM\Id + * @ORM\Column(type="datetime", name="somedate") */ public $date; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1225Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1225Test.php index 1bfd6b91e15..88986ce7131 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1225Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1225Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1225_TestEntity1::class), - $this->_em->getClassMetadata(DDC1225_TestEntity2::class), + $this->em->getClassMetadata(DDC1225_TestEntity1::class), + $this->em->getClassMetadata(DDC1225_TestEntity2::class), ] ); } catch(\PDOException $e) { @@ -24,29 +28,29 @@ public function setUp() public function testIssue() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->from(DDC1225_TestEntity1::class, 'te1') ->select('te1') ->where('te1.testEntity2 = ?1') ->setParameter(1, 0); - $this->assertEquals( - strtolower('SELECT t0_.test_entity2_id AS test_entity2_id_0 FROM te1 t0_ WHERE t0_.test_entity2_id = ?'), - strtolower($qb->getQuery()->getSQL()) + self::assertSQLEquals( + 'SELECT t0."test_entity2_id" AS c0 FROM "te1" t0 WHERE t0."test_entity2_id" = ?', + $qb->getQuery()->getSQL() ); } } /** - * @Entity - * @Table(name="te1") + * @ORM\Entity + * @ORM\Table(name="te1") */ class DDC1225_TestEntity1 { /** - * @Id - * @ManyToOne(targetEntity="Doctrine\Tests\ORM\Functional\Ticket\DDC1225_TestEntity2") - * @JoinColumn(name="test_entity2_id", referencedColumnName="id", nullable=false) + * @ORM\Id + * @ORM\ManyToOne(targetEntity="Doctrine\Tests\ORM\Functional\Ticket\DDC1225_TestEntity2") + * @ORM\JoinColumn(name="test_entity2_id", referencedColumnName="id", nullable=false) */ private $testEntity2; @@ -68,15 +72,15 @@ public function getTestEntity2() } /** - * @Entity - * @Table(name="te2") + * @ORM\Entity + * @ORM\Table(name="te2") */ class DDC1225_TestEntity2 { /** - * @Id - * @GeneratedValue(strategy="AUTO") - * @Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") + * @ORM\Column(type="integer") */ private $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1228Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1228Test.php index b4de087a359..439eada3434 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1228Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1228Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1228User::class), - $this->_em->getClassMetadata(DDC1228Profile::class), + $this->em->getClassMetadata(DDC1228User::class), + $this->em->getClassMetadata(DDC1228Profile::class), ] ); } catch(\Exception $e) { @@ -30,25 +34,25 @@ public function testOneToOnePersist() $profile->name = "Foo"; $user->profile = $profile; - $this->_em->persist($user); - $this->_em->persist($profile); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->persist($profile); + $this->em->flush(); + $this->em->clear(); - $user = $this->_em->find(DDC1228User::class, $user->id); + $user = $this->em->find(DDC1228User::class, $user->id); - $this->assertFalse($user->getProfile()->__isInitialized__, "Proxy is not initialized"); + self::assertFalse($user->getProfile()->__isInitialized(), "Proxy is not initialized"); $user->getProfile()->setName("Bar"); - $this->assertTrue($user->getProfile()->__isInitialized__, "Proxy is not initialized"); + self::assertTrue($user->getProfile()->__isInitialized(), "Proxy is not initialized"); - $this->assertEquals("Bar", $user->getProfile()->getName()); - $this->assertEquals(["id" => 1, "name" => "Foo"], $this->_em->getUnitOfWork()->getOriginalEntityData($user->getProfile())); + self::assertEquals("Bar", $user->getProfile()->getName()); + self::assertEquals(["id" => 1, "name" => "Foo"], $this->em->getUnitOfWork()->getOriginalEntityData($user->getProfile())); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $user = $this->_em->find(DDC1228User::class, $user->id); - $this->assertEquals("Bar", $user->getProfile()->getName()); + $user = $this->em->find(DDC1228User::class, $user->id); + self::assertEquals("Bar", $user->getProfile()->getName()); } public function testRefresh() @@ -58,42 +62,42 @@ public function testRefresh() $profile->name = "Foo"; $user->profile = $profile; - $this->_em->persist($user); - $this->_em->persist($profile); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->persist($profile); + $this->em->flush(); + $this->em->clear(); - $user = $this->_em->getReference(DDC1228User::class, $user->id); + $user = $this->em->getReference(DDC1228User::class, $user->id); - $this->_em->refresh($user); + $this->em->refresh($user); $user->name = "Baz"; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $user = $this->_em->find(DDC1228User::class, $user->id); - $this->assertEquals("Baz", $user->name); + $user = $this->em->find(DDC1228User::class, $user->id); + self::assertEquals("Baz", $user->name); } } /** - * @Entity + * @ORM\Entity */ class DDC1228User { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue * @var int */ public $id; /** - * @Column(type="string") + * @ORM\Column(type="string") * @var string */ public $name = 'Bar'; /** - * @OneToOne(targetEntity="DDC1228Profile") + * @ORM\OneToOne(targetEntity="DDC1228Profile") * @var Profile */ public $profile; @@ -105,18 +109,18 @@ public function getProfile() } /** - * @Entity + * @ORM\Entity */ class DDC1228Profile { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue * @var int */ public $id; /** - * @column(type="string") + * @ORM\Column(type="string") * @var string */ public $name; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1238Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1238Test.php index 00c621eeeef..fc6474bdba3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1238Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1238Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1238User::class), + $this->em->getClassMetadata(DDC1238User::class), ] ); } catch(\Exception $e) { @@ -26,18 +30,18 @@ public function testIssue() $user = new DDC1238User; $user->setName("test"); - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); $userId = $user->getId(); - $this->_em->clear(); + $this->em->clear(); - $user = $this->_em->getReference(DDC1238User::class, $userId); - $this->_em->clear(); + $user = $this->em->getReference(DDC1238User::class, $userId); + $this->em->clear(); $userId2 = $user->getId(); - $this->assertEquals($userId, $userId2, "This proxy can still be initialized."); + self::assertEquals($userId, $userId2, "This proxy can still be initialized."); } public function testIssueProxyClear() @@ -45,36 +49,36 @@ public function testIssueProxyClear() $user = new DDC1238User; $user->setName("test"); - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); // force proxy load, getId() doesn't work anymore $user->getName(); $userId = $user->getId(); - $this->_em->clear(); + $this->em->clear(); - $user = $this->_em->getReference(DDC1238User::class, $userId); - $this->_em->clear(); + $user = $this->em->getReference(DDC1238User::class, $userId); + $this->em->clear(); - $user2 = $this->_em->getReference(DDC1238User::class, $userId); + $user2 = $this->em->getReference(DDC1238User::class, $userId); // force proxy load, getId() doesn't work anymore $user->getName(); - $this->assertNull($user->getId(), "Now this is null, we already have a user instance of that type"); + self::assertNull($user->getId(), "Now this is null, we already have a user instance of that type"); } } /** - * @Entity + * @ORM\Entity */ class DDC1238User { - /** @Id @GeneratedValue @Column(type="integer") */ + /** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ private $id; /** - * @Column + * @ORM\Column * @var string */ private $name; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1250Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1250Test.php index a09b1761fea..ee8097472c2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1250Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1250Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1250ClientHistory::class), + $this->em->getClassMetadata(DDC1250ClientHistory::class), ] ); } catch(\PDOException $e) { @@ -30,33 +34,33 @@ public function testIssue() $c2->declinedBy = $c1; $c2->declinedClientsHistory= $c1; - $this->_em->persist($c1); - $this->_em->persist($c2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($c1); + $this->em->persist($c2); + $this->em->flush(); + $this->em->clear(); - $history = $this->_em->createQuery('SELECT h FROM ' . __NAMESPACE__ . '\\DDC1250ClientHistory h WHERE h.id = ?1') + $history = $this->em->createQuery('SELECT h FROM ' . __NAMESPACE__ . '\\DDC1250ClientHistory h WHERE h.id = ?1') ->setParameter(1, $c2->id)->getSingleResult(); - $this->assertInstanceOf(DDC1250ClientHistory::class, $history); + self::assertInstanceOf(DDC1250ClientHistory::class, $history); } } /** - * @Entity + * @ORM\Entity */ class DDC1250ClientHistory { - /** @Id @GeneratedValue @Column(type="integer") */ + /** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ public $id; - /** @OneToOne(targetEntity="DDC1250ClientHistory", inversedBy="declinedBy") - * @JoinColumn(name="declined_clients_history_id", referencedColumnName="id") + /** @ORM\OneToOne(targetEntity="DDC1250ClientHistory", inversedBy="declinedBy") + * @ORM\JoinColumn(name="declined_clients_history_id", referencedColumnName="id") */ public $declinedClientsHistory; /** - * @OneToOne(targetEntity="DDC1250ClientHistory", mappedBy="declinedClientsHistory") + * @ORM\OneToOne(targetEntity="DDC1250ClientHistory", mappedBy="declinedClientsHistory") * @var */ public $declinedBy; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1276Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1276Test.php deleted file mode 100644 index eeaa870ae4d..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1276Test.php +++ /dev/null @@ -1,47 +0,0 @@ -useModelSet('cms'); - parent::setUp(); - } - - public function testIssue() - { - $user = new CmsUser(); - $user->name = "Benjamin"; - $user->username = "beberlei"; - $user->status = "active"; - $this->_em->persist($user); - - for ($i = 0; $i < 2; $i++) { - $group = new CmsGroup(); - $group->name = "group".$i; - $user->groups[] = $group; - $this->_em->persist($group); - } - $this->_em->flush(); - $this->_em->clear(); - - $user = $this->_em->find(CmsUser::class, $user->id); - $cloned = clone $user; - - $this->assertSame($user->groups, $cloned->groups); - $this->assertEquals(2, count($user->groups)); - $this->_em->merge($cloned); - - $this->assertEquals(2, count($user->groups)); - - $this->_em->flush(); - } -} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1300Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1300Test.php index 4f0038b1c89..b8562ec342f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1300Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1300Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1300Foo::class), - $this->_em->getClassMetadata(DDC1300FooLocale::class), + $this->em->getClassMetadata(DDC1300Foo::class), + $this->em->getClassMetadata(DDC1300FooLocale::class), ] ); } @@ -21,50 +26,50 @@ public function setUp() public function testIssue() { $foo = new DDC1300Foo(); - $foo->_fooReference = "foo"; + $foo->fooReference = "foo"; - $this->_em->persist($foo); - $this->_em->flush(); + $this->em->persist($foo); + $this->em->flush(); $locale = new DDC1300FooLocale(); - $locale->_foo = $foo; - $locale->_locale = "en"; - $locale->_title = "blub"; + $locale->foo = $foo; + $locale->locale = "en"; + $locale->title = "blub"; - $this->_em->persist($locale); - $this->_em->flush(); + $this->em->persist($locale); + $this->em->flush(); - $query = $this->_em->createQuery('SELECT f, fl FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1300Foo f JOIN f._fooLocaleRefFoo fl'); + $query = $this->em->createQuery('SELECT f, fl FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1300Foo f JOIN f.fooLocaleRefFoo fl'); $result = $query->getResult(); - $this->assertEquals(1, count($result)); + self::assertEquals(1, count($result)); } } /** - * @Entity + * @ORM\Entity */ class DDC1300Foo { /** * @var int fooID - * @Column(name="fooID", type="integer", nullable=false) - * @GeneratedValue(strategy="AUTO") - * @Id + * @ORM\Column(name="fooID", type="integer", nullable=false) + * @ORM\GeneratedValue(strategy="AUTO") + * @ORM\Id */ - public $_fooID = null; + public $fooID = null; /** * @var string fooReference - * @Column(name="fooReference", type="string", nullable=true, length=45) + * @ORM\Column(name="fooReference", type="string", nullable=true, length=45) */ - public $_fooReference = null; + public $fooReference = null; /** - * @OneToMany(targetEntity="DDC1300FooLocale", mappedBy="_foo", + * @ORM\OneToMany(targetEntity="DDC1300FooLocale", mappedBy="foo", * cascade={"persist"}) */ - public $_fooLocaleRefFoo = null; + public $fooLocaleRefFoo = null; /** * Constructor @@ -74,35 +79,35 @@ class DDC1300Foo */ public function __construct($options = null) { - $this->_fooLocaleRefFoo = new \Doctrine\Common\Collections\ArrayCollection(); + $this->fooLocaleRefFoo = new \Doctrine\Common\Collections\ArrayCollection(); } } /** - * @Entity + * @ORM\Entity */ class DDC1300FooLocale { /** - * @ManyToOne(targetEntity="DDC1300Foo") - * @JoinColumn(name="fooID", referencedColumnName="fooID") - * @Id + * @ORM\ManyToOne(targetEntity="DDC1300Foo") + * @ORM\JoinColumn(name="fooID", referencedColumnName="fooID") + * @ORM\Id */ - public $_foo = null; + public $foo = null; /** * @var string locale - * @Column(name="locale", type="string", nullable=false, length=5) - * @Id + * @ORM\Column(name="locale", type="string", nullable=false, length=5) + * @ORM\Id */ - public $_locale = null; + public $locale = null; /** * @var string title - * @Column(name="title", type="string", nullable=true, length=150) + * @ORM\Column(name="title", type="string", nullable=true, length=150) */ - public $_title = null; + public $title = null; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1301Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1301Test.php index 785b22187ed..625a5996090 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1301Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1301Test.php @@ -1,8 +1,11 @@ useModelSet('legacy'); + parent::setUp(); - $class = $this->_em->getClassMetadata(Models\Legacy\LegacyUser::class); - $class->associationMappings['_articles']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; - $class->associationMappings['_references']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; - $class->associationMappings['_cars']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; + $class = $this->em->getClassMetadata(Models\Legacy\LegacyUser::class); + + $class->getProperty('articles')->setFetchMode(FetchMode::EXTRA_LAZY); + $class->getProperty('references')->setFetchMode(FetchMode::EXTRA_LAZY); + $class->getProperty('cars')->setFetchMode(FetchMode::EXTRA_LAZY); $this->loadFixture(); } @@ -32,96 +37,97 @@ public function tearDown() { parent::tearDown(); - $class = $this->_em->getClassMetadata(Models\Legacy\LegacyUser::class); - $class->associationMappings['_articles']['fetch'] = ClassMetadataInfo::FETCH_LAZY; - $class->associationMappings['_references']['fetch'] = ClassMetadataInfo::FETCH_LAZY; - $class->associationMappings['_cars']['fetch'] = ClassMetadataInfo::FETCH_LAZY; + $class = $this->em->getClassMetadata(Models\Legacy\LegacyUser::class); + + $class->getProperty('articles')->setFetchMode(FetchMode::LAZY); + $class->getProperty('references')->setFetchMode(FetchMode::LAZY); + $class->getProperty('cars')->setFetchMode(FetchMode::LAZY); } public function testCountNotInitializesLegacyCollection() { - $user = $this->_em->find(Models\Legacy\LegacyUser::class, $this->userId); + $user = $this->em->find(Models\Legacy\LegacyUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); - $this->assertFalse($user->_articles->isInitialized()); - $this->assertEquals(2, count($user->_articles)); - $this->assertFalse($user->_articles->isInitialized()); + self::assertFalse($user->articles->isInitialized()); + self::assertEquals(2, count($user->articles)); + self::assertFalse($user->articles->isInitialized()); - foreach ($user->_articles AS $article) { } + foreach ($user->articles AS $article) { } - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount(), "Expecting two queries to be fired for count, then iteration."); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount(), "Expecting two queries to be fired for count, then iteration."); } public function testCountNotInitializesLegacyCollectionWithForeignIdentifier() { - $user = $this->_em->find(Models\Legacy\LegacyUser::class, $this->userId); + $user = $this->em->find(Models\Legacy\LegacyUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); - $this->assertFalse($user->_references->isInitialized()); - $this->assertEquals(2, count($user->_references)); - $this->assertFalse($user->_references->isInitialized()); + self::assertFalse($user->references->isInitialized()); + self::assertEquals(2, count($user->references)); + self::assertFalse($user->references->isInitialized()); - foreach ($user->_references AS $reference) { } + foreach ($user->references AS $reference) { } - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount(), "Expecting two queries to be fired for count, then iteration."); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount(), "Expecting two queries to be fired for count, then iteration."); } public function testCountNotInitializesLegacyManyToManyCollection() { - $user = $this->_em->find(Models\Legacy\LegacyUser::class, $this->userId); + $user = $this->em->find(Models\Legacy\LegacyUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); - $this->assertFalse($user->_cars->isInitialized()); - $this->assertEquals(3, count($user->_cars)); - $this->assertFalse($user->_cars->isInitialized()); + self::assertFalse($user->cars->isInitialized()); + self::assertEquals(3, count($user->cars)); + self::assertFalse($user->cars->isInitialized()); - foreach ($user->_cars AS $reference) { } + foreach ($user->cars AS $reference) { } - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount(), "Expecting two queries to be fired for count, then iteration."); + self::assertEquals($queryCount + 2, $this->getCurrentQueryCount(), "Expecting two queries to be fired for count, then iteration."); } public function loadFixture() { $user1 = new Models\Legacy\LegacyUser(); - $user1->_username = "beberlei"; - $user1->_name = "Benjamin"; - $user1->_status = "active"; + $user1->username = "beberlei"; + $user1->name = "Benjamin"; + $user1->status = "active"; $user2 = new Models\Legacy\LegacyUser(); - $user2->_username = "jwage"; - $user2->_name = "Jonathan"; - $user2->_status = "active"; + $user2->username = "jwage"; + $user2->name = "Jonathan"; + $user2->status = "active"; $user3 = new Models\Legacy\LegacyUser(); - $user3->_username = "romanb"; - $user3->_name = "Roman"; - $user3->_status = "active"; + $user3->username = "romanb"; + $user3->name = "Roman"; + $user3->status = "active"; - $this->_em->persist($user1); - $this->_em->persist($user2); - $this->_em->persist($user3); + $this->em->persist($user1); + $this->em->persist($user2); + $this->em->persist($user3); $article1 = new Models\Legacy\LegacyArticle(); - $article1->_topic = "Test"; - $article1->_text = "Test"; + $article1->topic = "Test"; + $article1->text = "Test"; $article1->setAuthor($user1); $article2 = new Models\Legacy\LegacyArticle(); - $article2->_topic = "Test"; - $article2->_text = "Test"; + $article2->topic = "Test"; + $article2->text = "Test"; $article2->setAuthor($user1); - $this->_em->persist($article1); - $this->_em->persist($article2); + $this->em->persist($article1); + $this->em->persist($article2); $car1 = new Models\Legacy\LegacyCar(); - $car1->_description = "Test1"; + $car1->description = "Test1"; $car2 = new Models\Legacy\LegacyCar(); - $car2->_description = "Test2"; + $car2->description = "Test2"; $car3 = new Models\Legacy\LegacyCar(); - $car3->_description = "Test3"; + $car3->description = "Test3"; $user1->addCar($car1); $user1->addCar($car2); @@ -130,20 +136,20 @@ public function loadFixture() $user2->addCar($car1); $user3->addCar($car1); - $this->_em->persist($car1); - $this->_em->persist($car2); - $this->_em->persist($car3); + $this->em->persist($car1); + $this->em->persist($car2); + $this->em->persist($car3); - $this->_em->flush(); + $this->em->flush(); $detail1 = new Models\Legacy\LegacyUserReference($user1, $user2, "foo"); $detail2 = new Models\Legacy\LegacyUserReference($user1, $user3, "bar"); - $this->_em->persist($detail1); - $this->_em->persist($detail2); + $this->em->persist($detail1); + $this->em->persist($detail2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $this->userId = $user1->getId(); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1306Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1306Test.php index 03c761a959c..d72bec6c8dc 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1306Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1306Test.php @@ -1,5 +1,7 @@ phonenumber = "1234"; // puts user and phone into commit order calculator - $this->_em->persist($phone); - $this->_em->flush(); + $this->em->persist($phone); + $this->em->flush(); $address = new CmsAddress(); $address->city = "bonn"; @@ -33,7 +35,7 @@ public function testIssue() $address->street = "somestreet!"; $address->zip = 12345; - $this->_em->persist($address); + $this->em->persist($address); $user = new CmsUser(); $user->username = "beberlei"; @@ -42,14 +44,14 @@ public function testIssue() $user->setAddress($address); // puts user and address into commit order calculator, but does not calculate user dependencies new - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); - $this->_em->remove($user->getAddress()); - $this->_em->remove($user); - $this->_em->flush(); + $this->em->remove($user->getAddress()); + $this->em->remove($user); + $this->em->flush(); - self::assertEmpty($this->_em->getRepository(CmsAddress::class)->findAll()); - self::assertEmpty($this->_em->getRepository(CmsUser::class)->findAll()); + self::assertEmpty($this->em->getRepository(CmsAddress::class)->findAll()); + self::assertEmpty($this->em->getRepository(CmsUser::class)->findAll()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1335Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1335Test.php index dd475559472..63466e3e44c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1335Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1335Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1335User::class), - $this->_em->getClassMetadata(DDC1335Phone::class), + $this->em->getClassMetadata(DDC1335User::class), + $this->em->getClassMetadata(DDC1335Phone::class), ] ); $this->loadFixture(); @@ -26,77 +30,77 @@ protected function setUp() public function testDql() { $dql = 'SELECT u FROM ' . __NAMESPACE__ . '\DDC1335User u INDEX BY u.id'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertEquals(sizeof($result), 3); - $this->assertArrayHasKey(1, $result); - $this->assertArrayHasKey(2, $result); - $this->assertArrayHasKey(3, $result); + self::assertEquals(sizeof($result), 3); + self::assertArrayHasKey(1, $result); + self::assertArrayHasKey(2, $result); + self::assertArrayHasKey(3, $result); $dql = 'SELECT u, p FROM '.__NAMESPACE__ . '\DDC1335User u INDEX BY u.email INNER JOIN u.phones p INDEX BY p.id'; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $result = $query->getResult(); - $this->assertEquals(sizeof($result), 3); - $this->assertArrayHasKey('foo@foo.com', $result); - $this->assertArrayHasKey('bar@bar.com', $result); - $this->assertArrayHasKey('foobar@foobar.com', $result); + self::assertEquals(sizeof($result), 3); + self::assertArrayHasKey('foo@foo.com', $result); + self::assertArrayHasKey('bar@bar.com', $result); + self::assertArrayHasKey('foobar@foobar.com', $result); - $this->assertEquals(sizeof($result['foo@foo.com']->phones), 3); - $this->assertEquals(sizeof($result['bar@bar.com']->phones), 3); - $this->assertEquals(sizeof($result['foobar@foobar.com']->phones), 3); + self::assertEquals(sizeof($result['foo@foo.com']->phones), 3); + self::assertEquals(sizeof($result['bar@bar.com']->phones), 3); + self::assertEquals(sizeof($result['foobar@foobar.com']->phones), 3); $foo = $result['foo@foo.com']->phones->toArray(); $bar = $result['bar@bar.com']->phones->toArray(); $foobar = $result['foobar@foobar.com']->phones->toArray(); - $this->assertArrayHasKey(1, $foo); - $this->assertArrayHasKey(2, $foo); - $this->assertArrayHasKey(3, $foo); + self::assertArrayHasKey(1, $foo); + self::assertArrayHasKey(2, $foo); + self::assertArrayHasKey(3, $foo); - $this->assertArrayHasKey(4, $bar); - $this->assertArrayHasKey(5, $bar); - $this->assertArrayHasKey(6, $bar); + self::assertArrayHasKey(4, $bar); + self::assertArrayHasKey(5, $bar); + self::assertArrayHasKey(6, $bar); - $this->assertArrayHasKey(7, $foobar); - $this->assertArrayHasKey(8, $foobar); - $this->assertArrayHasKey(9, $foobar); + self::assertArrayHasKey(7, $foobar); + self::assertArrayHasKey(8, $foobar); + self::assertArrayHasKey(9, $foobar); } public function testTicket() { - $builder = $this->_em->createQueryBuilder(); + $builder = $this->em->createQueryBuilder(); $builder->select('u')->from(DDC1335User::class, 'u', 'u.id'); $dql = $builder->getQuery()->getDQL(); $result = $builder->getQuery()->getResult(); - $this->assertEquals(sizeof($result), 3); - $this->assertArrayHasKey(1, $result); - $this->assertArrayHasKey(2, $result); - $this->assertArrayHasKey(3, $result); - $this->assertEquals('SELECT u FROM ' . __NAMESPACE__ . '\DDC1335User u INDEX BY u.id', $dql); + self::assertEquals(sizeof($result), 3); + self::assertArrayHasKey(1, $result); + self::assertArrayHasKey(2, $result); + self::assertArrayHasKey(3, $result); + self::assertEquals('SELECT u FROM ' . __NAMESPACE__ . '\DDC1335User u INDEX BY u.id', $dql); } public function testIndexByUnique() { - $builder = $this->_em->createQueryBuilder(); + $builder = $this->em->createQueryBuilder(); $builder->select('u')->from(DDC1335User::class, 'u', 'u.email'); $dql = $builder->getQuery()->getDQL(); $result = $builder->getQuery()->getResult(); - $this->assertEquals(sizeof($result), 3); - $this->assertArrayHasKey('foo@foo.com', $result); - $this->assertArrayHasKey('bar@bar.com', $result); - $this->assertArrayHasKey('foobar@foobar.com', $result); - $this->assertEquals('SELECT u FROM ' . __NAMESPACE__ . '\DDC1335User u INDEX BY u.email', $dql); + self::assertEquals(sizeof($result), 3); + self::assertArrayHasKey('foo@foo.com', $result); + self::assertArrayHasKey('bar@bar.com', $result); + self::assertArrayHasKey('foobar@foobar.com', $result); + self::assertEquals('SELECT u FROM ' . __NAMESPACE__ . '\DDC1335User u INDEX BY u.email', $dql); } public function testIndexWithJoin() { - $builder = $this->_em->createQueryBuilder(); + $builder = $this->em->createQueryBuilder(); $builder->select('u','p') ->from(DDC1335User::class, 'u', 'u.email') ->join('u.phones', 'p', null, null, 'p.id'); @@ -104,28 +108,28 @@ public function testIndexWithJoin() $dql = $builder->getQuery()->getDQL(); $result = $builder->getQuery()->getResult(); - $this->assertEquals(sizeof($result), 3); - $this->assertArrayHasKey('foo@foo.com', $result); - $this->assertArrayHasKey('bar@bar.com', $result); - $this->assertArrayHasKey('foobar@foobar.com', $result); + self::assertEquals(sizeof($result), 3); + self::assertArrayHasKey('foo@foo.com', $result); + self::assertArrayHasKey('bar@bar.com', $result); + self::assertArrayHasKey('foobar@foobar.com', $result); - $this->assertEquals(sizeof($result['foo@foo.com']->phones), 3); - $this->assertEquals(sizeof($result['bar@bar.com']->phones), 3); - $this->assertEquals(sizeof($result['foobar@foobar.com']->phones), 3); + self::assertEquals(sizeof($result['foo@foo.com']->phones), 3); + self::assertEquals(sizeof($result['bar@bar.com']->phones), 3); + self::assertEquals(sizeof($result['foobar@foobar.com']->phones), 3); - $this->assertArrayHasKey(1, $result['foo@foo.com']->phones->toArray()); - $this->assertArrayHasKey(2, $result['foo@foo.com']->phones->toArray()); - $this->assertArrayHasKey(3, $result['foo@foo.com']->phones->toArray()); + self::assertArrayHasKey(1, $result['foo@foo.com']->phones->toArray()); + self::assertArrayHasKey(2, $result['foo@foo.com']->phones->toArray()); + self::assertArrayHasKey(3, $result['foo@foo.com']->phones->toArray()); - $this->assertArrayHasKey(4, $result['bar@bar.com']->phones->toArray()); - $this->assertArrayHasKey(5, $result['bar@bar.com']->phones->toArray()); - $this->assertArrayHasKey(6, $result['bar@bar.com']->phones->toArray()); + self::assertArrayHasKey(4, $result['bar@bar.com']->phones->toArray()); + self::assertArrayHasKey(5, $result['bar@bar.com']->phones->toArray()); + self::assertArrayHasKey(6, $result['bar@bar.com']->phones->toArray()); - $this->assertArrayHasKey(7, $result['foobar@foobar.com']->phones->toArray()); - $this->assertArrayHasKey(8, $result['foobar@foobar.com']->phones->toArray()); - $this->assertArrayHasKey(9, $result['foobar@foobar.com']->phones->toArray()); + self::assertArrayHasKey(7, $result['foobar@foobar.com']->phones->toArray()); + self::assertArrayHasKey(8, $result['foobar@foobar.com']->phones->toArray()); + self::assertArrayHasKey(9, $result['foobar@foobar.com']->phones->toArray()); - $this->assertEquals('SELECT u, p FROM '.__NAMESPACE__ . '\DDC1335User u INDEX BY u.email INNER JOIN u.phones p INDEX BY p.id', $dql); + self::assertEquals('SELECT u, p FROM '.__NAMESPACE__ . '\DDC1335User u INDEX BY u.email INNER JOIN u.phones p INDEX BY p.id', $dql); } private function loadFixture() @@ -138,38 +142,38 @@ private function loadFixture() $u2 = new DDC1335User("bar@bar.com", "Bar",$p2); $u3 = new DDC1335User("foobar@foobar.com", "Foo Bar",$p3); - $this->_em->persist($u1); - $this->_em->persist($u2); - $this->_em->persist($u3); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($u1); + $this->em->persist($u2); + $this->em->persist($u3); + $this->em->flush(); + $this->em->clear(); } } /** - * @Entity + * @ORM\Entity */ class DDC1335User { /** - * @Id @Column(type="integer") - * @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue */ public $id; /** - * @Column(type="string", unique=true) + * @ORM\Column(type="string", unique=true) */ public $email; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $name; /** - * @OneToMany(targetEntity="DDC1335Phone", mappedBy="user", cascade={"persist", "remove"}) + * @ORM\OneToMany(targetEntity="DDC1335Phone", mappedBy="user", cascade={"persist", "remove"}) */ public $phones; @@ -186,25 +190,25 @@ public function __construct($email, $name, array $numbers = []) } /** - * @Entity + * @ORM\Entity */ class DDC1335Phone { /** - * @Id - * @Column(name="id", type="integer") - * @GeneratedValue + * @ORM\Id + * @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue */ public $id; /** - * @Column(name="numericalValue", type="string", nullable = false) + * @ORM\Column(name="numericalValue", type="string", nullable = false) */ public $numericalValue; /** - * @ManyToOne(targetEntity="DDC1335User", inversedBy="phones") - * @JoinColumn(name="user_id", referencedColumnName="id", nullable = false) + * @ORM\ManyToOne(targetEntity="DDC1335User", inversedBy="phones") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable = false) */ public $user; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1360Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1360Test.php index 6e71e6fc742..35ed77cb104 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1360Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1360Test.php @@ -1,7 +1,10 @@ _em->getConnection()->getDatabasePlatform()->getName() != "postgresql") { + if ($this->em->getConnection()->getDatabasePlatform()->getName() != "postgresql") { $this->markTestSkipped("PostgreSQL only test."); } - $sql = $this->_schemaTool->getCreateSchemaSql( + $sql = $this->schemaTool->getCreateSchemaSql( [ - $this->_em->getClassMetadata(DDC1360DoubleQuote::class) + $this->em->getClassMetadata(DDC1360DoubleQuote::class) ] ); - $this->assertEquals( + self::assertEquals( [ - 'CREATE SCHEMA user', - 'CREATE TABLE "user"."user" (id INT NOT NULL, PRIMARY KEY(id))', - 'CREATE SEQUENCE "user"."user_id_seq" INCREMENT BY 1 MINVALUE 1 START 1', - ], $sql); + 'CREATE SCHEMA user', + 'CREATE TABLE "user"."user" (id INT NOT NULL, PRIMARY KEY(id))', + 'CREATE SEQUENCE "user"."user_id_seq" INCREMENT BY 1 MINVALUE 1 START 1', + ], + $sql + ); } } /** - * @Entity @Table(name="`user`.`user`") + * @ORM\Entity @ORM\Table(name="user.user") */ class DDC1360DoubleQuote { - /** @Id @GeneratedValue @Column(type="integer") */ + /** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1383Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1383Test.php deleted file mode 100644 index 7a13d7ac9bc..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1383Test.php +++ /dev/null @@ -1,98 +0,0 @@ -_schemaTool->createSchema( - [ - $this->_em->getClassMetadata(DDC1383AbstractEntity::class), - $this->_em->getClassMetadata(DDC1383Entity::class), - ] - ); - } catch(\Exception $ignored) {} - } - - public function testFailingCase() - { - $parent = new DDC1383Entity(); - $child = new DDC1383Entity(); - - $child->setReference($parent); - - $this->_em->persist($parent); - $this->_em->persist($child); - - $id = $child->getId(); - - $this->_em->flush(); - $this->_em->clear(); - - // Try merging the parent entity - $child = $this->_em->merge($child); - $parent = $child->getReference(); - - // Parent is not instance of the abstract class - self::assertTrue($parent instanceof DDC1383AbstractEntity, - "Entity class is " . get_class($parent) . ', "DDC1383AbstractEntity" was expected'); - - // Parent is NOT instance of entity - self::assertTrue($parent instanceof DDC1383Entity, - "Entity class is " . get_class($parent) . ', "DDC1383Entity" was expected'); - } -} - -/** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="discr", type="integer") - * @DiscriminatorMap({1 = "DDC1383Entity"}) - */ -abstract class DDC1383AbstractEntity -{ - /** - * @Id - * @Column(type="integer") - * @GeneratedValue - */ - protected $id; - - public function getId() - { - return $this->id; - } - - public function setId($id) - { - $this->id = $id; - } -} - -/** - * @Entity - */ -class DDC1383Entity extends DDC1383AbstractEntity -{ - /** - * @ManyToOne(targetEntity="DDC1383AbstractEntity") - */ - protected $reference; - - public function getReference() - { - return $this->reference; - } - - public function setReference(DDC1383AbstractEntity $reference) - { - $this->reference = $reference; - } -} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1392Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1392Test.php deleted file mode 100644 index 806e61de4da..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1392Test.php +++ /dev/null @@ -1,128 +0,0 @@ -_schemaTool->createSchema( - [ - $this->_em->getClassMetadata(DDC1392File::class), - $this->_em->getClassMetadata(DDC1392Picture::class), - ] - ); - } catch (\Exception $ignored) { - } - } - - public function testFailingCase() - { - $file = new DDC1392File; - - $picture = new DDC1392Picture; - $picture->setFile($file); - - $em = $this->_em; - $em->persist($picture); - $em->flush(); - $em->clear(); - - $fileId = $file->getFileId(); - $pictureId = $picture->getPictureId(); - - $this->assertTrue($fileId > 0); - - $picture = $em->find(DDC1392Picture::class, $pictureId); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $em->getUnitOfWork()->getEntityState($picture->getFile()), "Lazy Proxy should be marked MANAGED."); - - $file = $picture->getFile(); - - // With this activated there will be no problem - //$file->__load(); - - $picture->setFile(null); - - $em->clear(); - - $em->merge($file); - - $em->flush(); - - $q = $this->_em->createQuery("SELECT COUNT(e) FROM " . __NAMESPACE__ . '\DDC1392File e'); - $result = $q->getSingleScalarResult(); - - self::assertEquals(1, $result); - } -} - -/** - * @Entity - */ -class DDC1392Picture -{ - /** - * @Column(name="picture_id", type="integer") - * @Id @GeneratedValue - */ - private $pictureId; - - /** - * @ManyToOne(targetEntity="DDC1392File", cascade={"persist", "remove"}) - * @JoinColumn(name="file_id", referencedColumnName="file_id") - */ - private $file; - - /** - * Get pictureId - */ - public function getPictureId() - { - return $this->pictureId; - } - - /** - * Set file - */ - public function setFile($value = null) - { - $this->file = $value; - } - - /** - * Get file - */ - public function getFile() - { - return $this->file; - } -} - -/** - * @Entity - */ -class DDC1392File -{ - /** - * @Column(name="file_id", type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") - */ - public $fileId; - - /** - * Get fileId - */ - public function getFileId() - { - return $this->fileId; - } -} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1400Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1400Test.php index 1248fe8412d..73bd5056a28 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1400Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1400Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1400Article::class), - $this->_em->getClassMetadata(DDC1400User::class), - $this->_em->getClassMetadata(DDC1400UserState::class), + $this->em->getClassMetadata(DDC1400Article::class), + $this->em->getClassMetadata(DDC1400User::class), + $this->em->getClassMetadata(DDC1400UserState::class), ] ); } catch (\Exception $ignored) { @@ -29,105 +33,89 @@ public function testFailingCase() $user1 = new DDC1400User; $user2 = new DDC1400User; - $this->_em->persist($article); - $this->_em->persist($user1); - $this->_em->persist($user2); - $this->_em->flush(); + $this->em->persist($article); + $this->em->persist($user1); + $this->em->persist($user2); + $this->em->flush(); $userState1 = new DDC1400UserState; $userState1->article = $article; - $userState1->articleId = $article->id; $userState1->user = $user1; - $userState1->userId = $user1->id; $userState2 = new DDC1400UserState; $userState2->article = $article; - $userState2->articleId = $article->id; $userState2->user = $user2; - $userState2->userId = $user2->id; - $this->_em->persist($userState1); - $this->_em->persist($userState2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($userState1); + $this->em->persist($userState2); + $this->em->flush(); + $this->em->clear(); - $user1 = $this->_em->getReference(DDC1400User::class, $user1->id); + $user1 = $this->em->getReference(DDC1400User::class, $user1->id); - $this->_em->createQuery('SELECT a, s FROM ' . DDC1400Article::class . ' a JOIN a.userStates s WITH s.user = :activeUser') + $this->em->createQuery('SELECT a, s FROM ' . DDC1400Article::class . ' a JOIN a.userStates s WITH s.user = :activeUser') ->setParameter('activeUser', $user1) ->getResult(); $queryCount = $this->getCurrentQueryCount(); - $this->_em->flush(); + $this->em->flush(); self::assertSame($queryCount, $this->getCurrentQueryCount(), 'No query should be executed during flush in this case'); } } /** - * @Entity + * @ORM\Entity */ class DDC1400Article { /** - * @Id - * @Column(type="integer") - * @GeneratedValue + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue */ public $id; /** - * @OneToMany(targetEntity="DDC1400UserState", mappedBy="article", indexBy="userId", fetch="EXTRA_LAZY") + * @ORM\OneToMany(targetEntity="DDC1400UserState", mappedBy="article", indexBy="user", fetch="EXTRA_LAZY") */ public $userStates; } /** - * @Entity + * @ORM\Entity */ class DDC1400User { /** - * @Id - * @Column(type="integer") - * @GeneratedValue + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue */ public $id; /** - * @OneToMany(targetEntity="DDC1400UserState", mappedBy="user", indexBy="articleId", fetch="EXTRA_LAZY") + * @ORM\OneToMany(targetEntity="DDC1400UserState", mappedBy="user", indexBy="article", fetch="EXTRA_LAZY") */ public $userStates; } /** - * @Entity + * @ORM\Entity */ class DDC1400UserState { - /** - * @Id - * @ManyToOne(targetEntity="DDC1400Article", inversedBy="userStates") + * @ORM\Id + * @ORM\ManyToOne(targetEntity="DDC1400Article", inversedBy="userStates") */ public $article; /** - * @Id - * @ManyToOne(targetEntity="DDC1400User", inversedBy="userStates") + * @ORM\Id + * @ORM\ManyToOne(targetEntity="DDC1400User", inversedBy="userStates") */ public $user; - - /** - * @Column(name="user_id", type="integer") - */ - public $userId; - - /** - * @Column(name="article_id", type="integer") - */ - public $articleId; - } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1404Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1404Test.php index b3a1a939d21..03b346c5633 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1404Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1404Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1404ParentEntity::class), - $this->_em->getClassMetadata(DDC1404ChildEntity::class), + $this->em->getClassMetadata(DDC1404ParentEntity::class), + $this->em->getClassMetadata(DDC1404ChildEntity::class), ] ); @@ -28,20 +32,20 @@ protected function setUp() public function testTicket() { - $repository = $this->_em->getRepository(DDC1404ChildEntity::class); + $repository = $this->em->getRepository(DDC1404ChildEntity::class); $queryAll = $repository->createNamedQuery('all'); $queryFirst = $repository->createNamedQuery('first'); $querySecond = $repository->createNamedQuery('second'); - $this->assertEquals('SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1404ChildEntity p', $queryAll->getDQL()); - $this->assertEquals('SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1404ChildEntity p WHERE p.id = 1', $queryFirst->getDQL()); - $this->assertEquals('SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1404ChildEntity p WHERE p.id = 2', $querySecond->getDQL()); + self::assertEquals('SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1404ChildEntity p', $queryAll->getDQL()); + self::assertEquals('SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1404ChildEntity p WHERE p.id = 1', $queryFirst->getDQL()); + self::assertEquals('SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1404ChildEntity p WHERE p.id = 2', $querySecond->getDQL()); - $this->assertEquals(sizeof($queryAll->getResult()), 2); - $this->assertEquals(sizeof($queryFirst->getResult()), 1); - $this->assertEquals(sizeof($querySecond->getResult()), 1); + self::assertEquals(sizeof($queryAll->getResult()), 2); + self::assertEquals(sizeof($queryFirst->getResult()), 1); + self::assertEquals(sizeof($querySecond->getResult()), 1); } @@ -50,29 +54,33 @@ public function loadFixtures() $c1 = new DDC1404ChildEntity("ChildEntity 1"); $c2 = new DDC1404ChildEntity("ChildEntity 2"); - $this->_em->persist($c1); - $this->_em->persist($c2); + $this->em->persist($c1); + $this->em->persist($c2); - $this->_em->flush(); + $this->em->flush(); } } /** - * @MappedSuperclass + * @ORM\Entity() + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorMap({ + * "parent" = "DDC1404ParentEntity", + * "child" = "DDC1404ChildEntity" + * }) * - * @NamedQueries({ - * @NamedQuery(name="all", query="SELECT p FROM __CLASS__ p"), - * @NamedQuery(name="first", query="SELECT p FROM __CLASS__ p WHERE p.id = 1"), + * @ORM\NamedQueries({ + * @ORM\NamedQuery(name="all", query="SELECT p FROM __CLASS__ p"), + * @ORM\NamedQuery(name="first", query="SELECT p FROM __CLASS__ p WHERE p.id = 1"), * }) */ class DDC1404ParentEntity { - /** - * @Id - * @Column(type="integer") - * @GeneratedValue() + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue() */ protected $id; @@ -83,22 +91,20 @@ public function getId() { return $this->id; } - } /** - * @Entity + * @ORM\Entity * - * @NamedQueries({ - * @NamedQuery(name="first", query="SELECT p FROM __CLASS__ p WHERE p.id = 1"), - * @NamedQuery(name="second", query="SELECT p FROM __CLASS__ p WHERE p.id = 2") + * @ORM\NamedQueries({ + * @ORM\NamedQuery(name="first", query="SELECT p FROM __CLASS__ p WHERE p.id = 1"), + * @ORM\NamedQuery(name="second", query="SELECT p FROM __CLASS__ p WHERE p.id = 2") * }) */ class DDC1404ChildEntity extends DDC1404ParentEntity { - /** - * @column(type="string") + * @ORM\Column(type="string") */ private $name; @@ -125,5 +131,4 @@ public function setName($name) { $this->name = $name; } - } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC142Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC142Test.php index 287b73dec3b..c6ecefe27ad 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC142Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC142Test.php @@ -1,5 +1,7 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(User::class), - $this->_em->getClassMetadata(Group::class), - $this->_em->getClassMetadata(Phone::class), - $this->_em->getClassMetadata(Address::class), + $this->em->getClassMetadata(User::class), + $this->em->getClassMetadata(Group::class), + $this->em->getClassMetadata(Phone::class), + $this->em->getClassMetadata(Address::class), ] ); } catch(\Exception $e) { @@ -35,56 +37,55 @@ public function testCreateRetrieveUpdateDelete() $user = new User; $user->name = 'FabioBatSilva'; - $this->_em->persist($user); + $this->em->persist($user); $address = new Address; $address->zip = '12345'; - $this->_em->persist($address); + $this->em->persist($address); - $this->_em->flush(); + $this->em->flush(); - $addressRef = $this->_em->getReference(Address::class, $address->getId()); + $addressRef = $this->em->getReference(Address::class, $address->getId()); $user->setAddress($addressRef); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $id = $user->id; - $this->assertNotNull($id); + self::assertNotNull($id); - $user = $this->_em->find(User::class, $id); + $user = $this->em->find(User::class, $id); $address = $user->getAddress(); - $this->assertInstanceOf(User::class, $user); - $this->assertInstanceOf(Address::class, $user->getAddress()); + self::assertInstanceOf(User::class, $user); + self::assertInstanceOf(Address::class, $user->getAddress()); - $this->assertEquals('FabioBatSilva', $user->name); - $this->assertEquals('12345', $address->zip); + self::assertEquals('FabioBatSilva', $user->name); + self::assertEquals('12345', $address->zip); $user->name = 'FabioBatSilva1'; $user->address = null; - $this->_em->persist($user); - $this->_em->remove($address); - $this->_em->flush(); - $this->_em->clear(); - + $this->em->persist($user); + $this->em->remove($address); + $this->em->flush(); + $this->em->clear(); - $user = $this->_em->find(User::class, $id); - $this->assertInstanceOf(User::class, $user); - $this->assertNull($user->getAddress()); - $this->assertEquals('FabioBatSilva1', $user->name); + $user = $this->em->find(User::class, $id); + self::assertInstanceOf(User::class, $user); + self::assertNull($user->getAddress()); + self::assertEquals('FabioBatSilva1', $user->name); - $this->_em->remove($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->remove($user); + $this->em->flush(); + $this->em->clear(); - $this->assertNull($this->_em->find(User::class, $id)); + self::assertNull($this->em->find(User::class, $id)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1430Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1430Test.php index 6b08a832675..bca426b33fc 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1430Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1430Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1430Order::class), - $this->_em->getClassMetadata(DDC1430OrderProduct::class), + $this->em->getClassMetadata(DDC1430Order::class), + $this->em->getClassMetadata(DDC1430OrderProduct::class), ] ); $this->loadFixtures(); @@ -27,7 +31,7 @@ protected function setUp() public function testOrderByFields() { - $repository = $this->_em->getRepository(DDC1430Order::class); + $repository = $this->em->getRepository(DDC1430Order::class); $builder = $repository->createQueryBuilder('o'); $query = $builder->select('o.id, o.date, COUNT(p.id) AS p_count') ->leftJoin('o.products', 'p') @@ -35,30 +39,36 @@ public function testOrderByFields() ->orderBy('o.id') ->getQuery(); - $this->assertSQLEquals('SELECT o.id, o.date, COUNT(p.id) AS p_count FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1430Order o LEFT JOIN o.products p GROUP BY o.id, o.date ORDER BY o.id ASC', $query->getDQL()); - $this->assertSQLEquals('SELECT d0_.order_id AS order_id_0, d0_.created_at AS created_at_1, COUNT(d1_.id) AS sclr_2 FROM DDC1430Order d0_ LEFT JOIN DDC1430OrderProduct d1_ ON d0_.order_id = d1_.order_id GROUP BY d0_.order_id, d0_.created_at ORDER BY d0_.order_id ASC', $query->getSQL()); + self::assertSQLEquals( + 'SELECT o.id, o.date, COUNT(p.id) AS p_count FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1430Order o LEFT JOIN o.products p GROUP BY o.id, o.date ORDER BY o.id ASC', + $query->getDQL() + ); + self::assertSQLEquals( + 'SELECT t0."order_id" AS c0, t0."created_at" AS c1, COUNT(t1."id") AS c2 FROM "DDC1430Order" t0 LEFT JOIN "DDC1430OrderProduct" t1 ON t0."order_id" = t1."order_id" GROUP BY t0."order_id", t0."created_at" ORDER BY t0."order_id" ASC', + $query->getSQL() + ); $result = $query->getResult(); - $this->assertEquals(2, sizeof($result)); + self::assertEquals(2, sizeof($result)); - $this->assertArrayHasKey('id', $result[0]); - $this->assertArrayHasKey('id', $result[1]); + self::assertArrayHasKey('id', $result[0]); + self::assertArrayHasKey('id', $result[1]); - $this->assertArrayHasKey('p_count', $result[0]); - $this->assertArrayHasKey('p_count', $result[1]); + self::assertArrayHasKey('p_count', $result[0]); + self::assertArrayHasKey('p_count', $result[1]); - $this->assertEquals(1, $result[0]['id']); - $this->assertEquals(2, $result[1]['id']); + self::assertEquals(1, $result[0]['id']); + self::assertEquals(2, $result[1]['id']); - $this->assertEquals(2, $result[0]['p_count']); - $this->assertEquals(3, $result[1]['p_count']); + self::assertEquals(2, $result[0]['p_count']); + self::assertEquals(3, $result[1]['p_count']); } public function testOrderByAllObjectFields() { - $repository = $this->_em->getRepository(DDC1430Order::class); + $repository = $this->em->getRepository(DDC1430Order::class); $builder = $repository->createQueryBuilder('o'); $query = $builder->select('o, COUNT(p.id) AS p_count') ->leftJoin('o.products', 'p') @@ -67,27 +77,33 @@ public function testOrderByAllObjectFields() ->getQuery(); - $this->assertSQLEquals('SELECT o, COUNT(p.id) AS p_count FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1430Order o LEFT JOIN o.products p GROUP BY o.id, o.date, o.status ORDER BY o.id ASC', $query->getDQL()); - $this->assertSQLEquals('SELECT d0_.order_id AS order_id_0, d0_.created_at AS created_at_1, d0_.order_status AS order_status_2, COUNT(d1_.id) AS sclr_3 FROM DDC1430Order d0_ LEFT JOIN DDC1430OrderProduct d1_ ON d0_.order_id = d1_.order_id GROUP BY d0_.order_id, d0_.created_at, d0_.order_status ORDER BY d0_.order_id ASC', $query->getSQL()); + self::assertSQLEquals( + 'SELECT o, COUNT(p.id) AS p_count FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1430Order o LEFT JOIN o.products p GROUP BY o.id, o.date, o.status ORDER BY o.id ASC', + $query->getDQL() + ); - $result = $query->getResult(); + self::assertSQLEquals( + 'SELECT t0."order_id" AS c0, t0."created_at" AS c1, t0."order_status" AS c2, COUNT(t1."id") AS c3 FROM "DDC1430Order" t0 LEFT JOIN "DDC1430OrderProduct" t1 ON t0."order_id" = t1."order_id" GROUP BY t0."order_id", t0."created_at", t0."order_status" ORDER BY t0."order_id" ASC', + $query->getSQL() + ); + $result = $query->getResult(); - $this->assertEquals(2, sizeof($result)); + self::assertEquals(2, sizeof($result)); - $this->assertTrue($result[0][0] instanceof DDC1430Order); - $this->assertTrue($result[1][0] instanceof DDC1430Order); + self::assertTrue($result[0][0] instanceof DDC1430Order); + self::assertTrue($result[1][0] instanceof DDC1430Order); - $this->assertEquals($result[0][0]->getId(), 1); - $this->assertEquals($result[1][0]->getId(), 2); + self::assertEquals($result[0][0]->getId(), 1); + self::assertEquals($result[1][0]->getId(), 2); - $this->assertEquals($result[0]['p_count'], 2); - $this->assertEquals($result[1]['p_count'], 3); + self::assertEquals($result[0]['p_count'], 2); + self::assertEquals($result[1]['p_count'], 3); } public function testTicket() { - $repository = $this->_em->getRepository(DDC1430Order::class); + $repository = $this->em->getRepository(DDC1430Order::class); $builder = $repository->createQueryBuilder('o'); $query = $builder->select('o, COUNT(p.id) AS p_count') ->leftJoin('o.products', 'p') @@ -96,22 +112,28 @@ public function testTicket() ->getQuery(); - $this->assertSQLEquals('SELECT o, COUNT(p.id) AS p_count FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1430Order o LEFT JOIN o.products p GROUP BY o ORDER BY o.id ASC', $query->getDQL()); - $this->assertSQLEquals('SELECT d0_.order_id AS order_id_0, d0_.created_at AS created_at_1, d0_.order_status AS order_status_2, COUNT(d1_.id) AS sclr_3 FROM DDC1430Order d0_ LEFT JOIN DDC1430OrderProduct d1_ ON d0_.order_id = d1_.order_id GROUP BY d0_.order_id, d0_.created_at, d0_.order_status ORDER BY d0_.order_id ASC', $query->getSQL()); + self::assertSQLEquals( + 'SELECT o, COUNT(p.id) AS p_count FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1430Order o LEFT JOIN o.products p GROUP BY o ORDER BY o.id ASC', + $query->getDQL() + ); + self::assertSQLEquals( + 'SELECT t0."order_id" AS c0, t0."created_at" AS c1, t0."order_status" AS c2, COUNT(t1."id") AS c3 FROM "DDC1430Order" t0 LEFT JOIN "DDC1430OrderProduct" t1 ON t0."order_id" = t1."order_id" GROUP BY t0."order_id", t0."created_at", t0."order_status" ORDER BY t0."order_id" ASC', + $query->getSQL() + ); $result = $query->getResult(); - $this->assertEquals(2, sizeof($result)); + self::assertEquals(2, sizeof($result)); - $this->assertTrue($result[0][0] instanceof DDC1430Order); - $this->assertTrue($result[1][0] instanceof DDC1430Order); + self::assertTrue($result[0][0] instanceof DDC1430Order); + self::assertTrue($result[1][0] instanceof DDC1430Order); - $this->assertEquals($result[0][0]->getId(), 1); - $this->assertEquals($result[1][0]->getId(), 2); + self::assertEquals($result[0][0]->getId(), 1); + self::assertEquals($result[1][0]->getId(), 2); - $this->assertEquals($result[0]['p_count'], 2); - $this->assertEquals($result[1]['p_count'], 3); + self::assertEquals($result[0]['p_count'], 2); + self::assertEquals($result[1]['p_count'], 3); } public function loadFixtures() @@ -126,44 +148,49 @@ public function loadFixtures() $o2->addProduct(new DDC1430OrderProduct(2.2)); $o2->addProduct(new DDC1430OrderProduct(2.3)); - $this->_em->persist($o1); - $this->_em->persist($o2); + $this->em->persist($o1); + $this->em->persist($o2); - $this->_em->flush(); + $this->em->flush(); } - } /** - * @Entity + * @ORM\Entity */ class DDC1430Order { - /** - * @Id - * @Column(name="order_id", type="integer") - * @GeneratedValue() + * @ORM\Id + * @ORM\Column(name="order_id", type="integer") + * @ORM\GeneratedValue() */ protected $id; /** - * @Column(name="created_at", type="datetime") + * @ORM\Column(name="created_at", type="datetime") */ private $date; /** - * @Column(name="order_status", type="string") + * @ORM\Column(name="order_status", type="string") */ private $status; /** - * @OneToMany(targetEntity="DDC1430OrderProduct", mappedBy="order", cascade={"persist", "remove"}) + * @ORM\OneToMany(targetEntity="DDC1430OrderProduct", mappedBy="order", cascade={"persist", "remove"}) * * @var \Doctrine\Common\Collections\ArrayCollection $products */ private $products; + public function __construct($status) + { + $this->status = $status; + $this->date = new \DateTime(); + $this->products = new \Doctrine\Common\Collections\ArrayCollection(); + } + /** * @return int */ @@ -172,12 +199,6 @@ public function getId() return $this->id; } - public function __construct($status) - { - $this->status = $status; - $this->date = new \DateTime(); - $this->products = new \Doctrine\Common\Collections\ArrayCollection(); - } /** * @return \DateTime */ @@ -221,28 +242,27 @@ public function addProduct(DDC1430OrderProduct $product) } /** - * @Entity + * @ORM\Entity */ class DDC1430OrderProduct { - - /** - * @Id - * @Column(type="integer") - * @GeneratedValue() + /** + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue() */ protected $id; /** * @var DDC1430Order $order * - * @ManyToOne(targetEntity="DDC1430Order", inversedBy="products") - * @JoinColumn(name="order_id", referencedColumnName="order_id", nullable = false) + * @ORM\ManyToOne(targetEntity="DDC1430Order", inversedBy="products") + * @ORM\JoinColumn(name="order_id", referencedColumnName="order_id", nullable = false) */ private $order; /** - * @column(type="float") + * @ORM\Column(type="float") */ private $value; @@ -254,7 +274,7 @@ public function __construct($value) $this->value = $value; } - /** + /** * @return int */ public function getId() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1436Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1436Test.php index 9ffa497cd4d..a3355e4c540 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1436Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1436Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1436Page::class), + $this->em->getClassMetadata(DDC1436Page::class), ] ); } catch (\Exception $ignored) { @@ -28,44 +32,44 @@ public function testIdentityMap() for ($i = 0; $i < 3; $i++) { $page = new DDC1436Page(); $page->setParent($parent); - $this->_em->persist($page); + $this->em->persist($page); $parent = $page; } - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $id = $parent->getId(); // step 1 - $page = $this->_em + $page = $this->em ->createQuery('SELECT p, parent FROM ' . __NAMESPACE__ . '\DDC1436Page p LEFT JOIN p.parent parent WHERE p.id = :id') ->setParameter('id', $id) ->getOneOrNullResult(); - $this->assertInstanceOf(DDC1436Page::class, $page); + self::assertInstanceOf(DDC1436Page::class, $page); // step 2 - $page = $this->_em->find(DDC1436Page::class, $id); - $this->assertInstanceOf(DDC1436Page::class, $page); - $this->assertInstanceOf(DDC1436Page::class, $page->getParent()); - $this->assertInstanceOf(DDC1436Page::class, $page->getParent()->getParent()); + $page = $this->em->find(DDC1436Page::class, $id); + self::assertInstanceOf(DDC1436Page::class, $page); + self::assertInstanceOf(DDC1436Page::class, $page->getParent()); + self::assertInstanceOf(DDC1436Page::class, $page->getParent()->getParent()); } } /** - * @Entity + * @ORM\Entity */ class DDC1436Page { /** - * @Id - * @GeneratedValue - * @Column(type="integer", name="id") + * @ORM\Id + * @ORM\GeneratedValue + * @ORM\Column(type="integer", name="id") */ protected $id; /** - * @ManyToOne(targetEntity="DDC1436Page") - * @JoinColumn(name="pid", referencedColumnName="id") + * @ORM\ManyToOne(targetEntity="DDC1436Page") + * @ORM\JoinColumn(name="pid", referencedColumnName="id") */ protected $parent; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC144Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC144Test.php index 3866c588db0..9752c8c84a0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC144Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC144Test.php @@ -1,18 +1,22 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC144FlowElement::class), - $this->_em->getClassMetadata(DDC144Operand::class), + $this->em->getClassMetadata(DDC144FlowElement::class), + $this->em->getClassMetadata(DDC144Operand::class), ] ); @@ -27,29 +31,32 @@ public function testIssue() $operand->property = 'flowValue'; $operand->operandProperty = 'operandValue'; - $this->_em->persist($operand); - $this->_em->flush(); + $this->em->persist($operand); + $this->em->flush(); - self::assertSame($operand, $this->_em->find(DDC144Operand::class, $operand->id)); + self::assertSame($operand, $this->em->find(DDC144Operand::class, $operand->id)); } } /** - * @Entity - * @Table(name="ddc144_flowelements") - * @InheritanceType("JOINED") - * @DiscriminatorColumn(type="string", name="discr") - * @DiscriminatorMap({"flowelement" = "DDC144FlowElement", "operand" = "DDC144Operand"}) + * @ORM\Entity + * @ORM\Table(name="ddc144_flowelements") + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(type="string", name="discr") + * @ORM\DiscriminatorMap({"flowelement" = "DDC144FlowElement", "operand" = "DDC144Operand"}) */ class DDC144FlowElement { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue + * * @var int */ public $id; - /** @Column */ + /** @ORM\Column */ public $property; } @@ -58,10 +65,9 @@ abstract class DDC144Expression extends DDC144FlowElement abstract public function method(); } -/** @Entity @Table(name="ddc144_operands") */ -class DDC144Operand extends DDC144Expression -{ - /** @Column */ +/** @ORM\Entity @ORM\Table(name="ddc144_operands") */ +class DDC144Operand extends DDC144Expression { + /** @ORM\Column */ public $operandProperty; public function method() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1452Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1452Test.php index 7e7ecc4f841..492a5982df5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1452Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1452Test.php @@ -1,9 +1,12 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1452EntityA::class), - $this->_em->getClassMetadata(DDC1452EntityB::class), + $this->em->getClassMetadata(DDC1452EntityA::class), + $this->em->getClassMetadata(DDC1452EntityB::class), ] ); } catch (\Exception $ignored) { @@ -40,18 +43,18 @@ public function testIssue() $b->entityAFrom = $a1; $b->entityATo = $a2; - $this->_em->persist($a1); - $this->_em->persist($a2); - $this->_em->persist($b); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($a1); + $this->em->persist($a2); + $this->em->persist($b); + $this->em->flush(); + $this->em->clear(); $dql = "SELECT a, b, ba FROM " . __NAMESPACE__ . "\DDC1452EntityA AS a LEFT JOIN a.entitiesB AS b LEFT JOIN b.entityATo AS ba"; - $results = $this->_em->createQuery($dql)->setMaxResults(1)->getResult(); + $results = $this->em->createQuery($dql)->setMaxResults(1)->getResult(); - $this->assertSame($results[0], $results[0]->entitiesB[0]->entityAFrom); - $this->assertFalse( $results[0]->entitiesB[0]->entityATo instanceof Proxy); - $this->assertInstanceOf(Collection::class, $results[0]->entitiesB[0]->entityATo->getEntitiesB()); + self::assertSame($results[0], $results[0]->entitiesB[0]->entityAFrom); + self::assertFalse( $results[0]->entitiesB[0]->entityATo instanceof Proxy); + self::assertInstanceOf(Collection::class, $results[0]->entitiesB[0]->entityATo->getEntitiesB()); } public function testFetchJoinOneToOneFromInverse() @@ -69,34 +72,34 @@ public function testFetchJoinOneToOneFromInverse() $user->address = $address; $address->user = $user; - $this->_em->persist($address); - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($address); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); $dql = "SELECT a, u FROM Doctrine\Tests\Models\CMS\CmsAddress a INNER JOIN a.user u"; - $data = $this->_em->createQuery($dql)->getResult(); - $this->_em->clear(); + $data = $this->em->createQuery($dql)->getResult(); + $this->em->clear(); - $this->assertFalse($data[0]->user instanceof Proxy); + self::assertFalse($data[0]->user instanceof Proxy); $dql = "SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.address a"; - $data = $this->_em->createQuery($dql)->getResult(); + $data = $this->em->createQuery($dql)->getResult(); - $this->assertFalse($data[0]->address instanceof Proxy); + self::assertFalse($data[0]->address instanceof Proxy); } } /** - * @Entity + * @ORM\Entity */ class DDC1452EntityA { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @Column */ + /** @ORM\Column */ public $title; - /** @OneToMany(targetEntity="DDC1452EntityB", mappedBy="entityAFrom") */ + /** @ORM\OneToMany(targetEntity="DDC1452EntityB", mappedBy="entityAFrom") */ public $entitiesB; public function __construct() @@ -111,19 +114,19 @@ public function getEntitiesB() } /** - * @Entity + * @ORM\Entity */ class DDC1452EntityB { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; /** - * @ManyToOne(targetEntity="DDC1452EntityA", inversedBy="entitiesB") + * @ORM\ManyToOne(targetEntity="DDC1452EntityA", inversedBy="entitiesB") */ public $entityAFrom; /** - * @ManyToOne(targetEntity="DDC1452EntityA") + * @ORM\ManyToOne(targetEntity="DDC1452EntityA") */ public $entityATo; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1454Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1454Test.php index 86aba511372..eba76688a49 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1454Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1454Test.php @@ -1,8 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1454File::class), - $this->_em->getClassMetadata(DDC1454Picture::class), + $this->em->getClassMetadata(DDC1454File::class), + $this->em->getClassMetadata(DDC1454Picture::class), ] ); } catch (\Exception $ignored) { @@ -28,28 +31,28 @@ public function testFailingCase() { $pic = new DDC1454Picture(); - self::assertSame(UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($pic)); + self::assertSame(UnitOfWork::STATE_NEW, $this->em->getUnitOfWork()->getEntityState($pic)); } } /** - * @Entity + * @ORM\Entity */ class DDC1454Picture extends DDC1454File { } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="discr", type="string") - * @DiscriminatorMap({"file" = "DDC1454File", "picture" = "DDC1454Picture"}) + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="discr", type="string") + * @ORM\DiscriminatorMap({"file" = "DDC1454File", "picture" = "DDC1454Picture"}) */ class DDC1454File { /** - * @Column(name="file_id", type="integer") - * @Id + * @ORM\Column(name="file_id", type="integer") + * @ORM\Id */ public $fileId; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1458Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1458Test.php index 72d79cd432f..245905492a0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1458Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1458Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(TestEntity::class), - $this->_em->getClassMetadata(TestAdditionalEntity::class) + $this->em->getClassMetadata(TestEntity::class), + $this->em->getClassMetadata(TestAdditionalEntity::class) ] ); } @@ -22,53 +25,53 @@ public function testIssue() $testEntity = new TestEntity(); $testEntity->setValue(3); $testEntity->setAdditional(new TestAdditionalEntity()); - $this->_em->persist($testEntity); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($testEntity); + $this->em->flush(); + $this->em->clear(); // So here the value is 3 - $this->assertEquals(3, $testEntity->getValue()); + self::assertEquals(3, $testEntity->getValue()); - $test = $this->_em->getRepository(TestEntity::class)->find(1); + $test = $this->em->getRepository(TestEntity::class)->find(1); // New value is set $test->setValue(5); // So here the value is 5 - $this->assertEquals(5, $test->getValue()); + self::assertEquals(5, $test->getValue()); // Get the additional entity $additional = $test->getAdditional(); // Still 5.. - $this->assertEquals(5, $test->getValue()); + self::assertEquals(5, $test->getValue()); // Force the proxy to load $additional->getBool(); // The value should still be 5 - $this->assertEquals(5, $test->getValue()); + self::assertEquals(5, $test->getValue()); } } /** - * @Entity + * @ORM\Entity */ class TestEntity { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** - * @Column(type="integer") + * @ORM\Column(type="integer") */ protected $value; /** - * @OneToOne(targetEntity="TestAdditionalEntity", inversedBy="entity", orphanRemoval=true, cascade={"persist", "remove"}) + * @ORM\OneToOne(targetEntity="TestAdditionalEntity", inversedBy="entity", orphanRemoval=true, cascade={"persist", "remove"}) */ protected $additional; @@ -93,22 +96,22 @@ public function setAdditional($additional) } } /** - * @Entity + * @ORM\Entity */ class TestAdditionalEntity { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** - * @OneToOne(targetEntity="TestEntity", mappedBy="additional") + * @ORM\OneToOne(targetEntity="TestEntity", mappedBy="additional") */ protected $entity; /** - * @Column(type="boolean") + * @ORM\Column(type="boolean") */ protected $bool; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1461Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1461Test.php index da7100d683e..e22b9affb8e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1461Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1461Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1461TwitterAccount::class), - $this->_em->getClassMetadata(DDC1461User::class) + $this->em->getClassMetadata(DDC1461TwitterAccount::class), + $this->em->getClassMetadata(DDC1461User::class) ] ); } catch(\Exception $e) { @@ -26,58 +30,58 @@ public function setUp() public function testChangeDetectionDeferredExplicit() { $user = new DDC1461User; - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); - $this->assertEquals(\Doctrine\ORM\UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($user, \Doctrine\ORM\UnitOfWork::STATE_NEW), "Entity should be managed."); - $this->assertEquals(\Doctrine\ORM\UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($user), "Entity should be managed."); + self::assertEquals(\Doctrine\ORM\UnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($user, \Doctrine\ORM\UnitOfWork::STATE_NEW), "Entity should be managed."); + self::assertEquals(\Doctrine\ORM\UnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($user), "Entity should be managed."); $acc = new DDC1461TwitterAccount; $user->twitterAccount = $acc; - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); - $user = $this->_em->find(get_class($user), $user->id); - $this->assertNotNull($user->twitterAccount); + $user = $this->em->find(get_class($user), $user->id); + self::assertNotNull($user->twitterAccount); } } /** - * @Entity - * @ChangeTrackingPolicy("DEFERRED_EXPLICIT") + * @ORM\Entity + * @ORM\ChangeTrackingPolicy("DEFERRED_EXPLICIT") */ class DDC1461User { /** - * @Id - * @GeneratedValue(strategy="AUTO") - * @Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") + * @ORM\Column(type="integer") */ public $id; /** - * @OneToOne(targetEntity="DDC1461TwitterAccount", orphanRemoval=true, fetch="EAGER", cascade = {"persist"}, inversedBy="user") + * @ORM\OneToOne(targetEntity="DDC1461TwitterAccount", orphanRemoval=true, fetch="EAGER", cascade = {"persist"}, inversedBy="user") * @var TwitterAccount */ public $twitterAccount; } /** - * @Entity - * @ChangeTrackingPolicy("DEFERRED_EXPLICIT") + * @ORM\Entity + * @ORM\ChangeTrackingPolicy("DEFERRED_EXPLICIT") */ class DDC1461TwitterAccount { /** - * @Id - * @GeneratedValue(strategy="AUTO") - * @Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") + * @ORM\Column(type="integer") */ public $id; /** - * @OneToOne(targetEntity="DDC1461User", fetch="EAGER") + * @ORM\OneToOne(targetEntity="DDC1461User", fetch="EAGER") */ public $user; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1509Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1509Test.php deleted file mode 100644 index 17cfdf78dc7..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1509Test.php +++ /dev/null @@ -1,146 +0,0 @@ -_schemaTool->createSchema( - [ - $this->_em->getClassMetadata(DDC1509AbstractFile::class), - $this->_em->getClassMetadata(DDC1509File::class), - $this->_em->getClassMetadata(DDC1509Picture::class), - ] - ); - } catch (\Exception $ignored) { - - } - } - - public function testFailingCase() - { - $file = new DDC1509File; - $thumbnail = new DDC1509File; - - $picture = new DDC1509Picture; - $picture->setFile($file); - $picture->setThumbnail($thumbnail); - - - /* @var $em \Doctrine\ORM\EntityManager */ - $em = $this->_em; - $em->persist($picture); - $em->flush(); - $em->clear(); - - $id = $picture->getPictureId(); - - $pic = $em->merge($picture); - /* @var $pic DDC1509Picture */ - - $this->assertNotNull($pic->getThumbnail()); - $this->assertNotNull($pic->getFile()); - } - -} - -/** - * @Entity - */ -class DDC1509Picture -{ - - /** - * @Column(type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") - */ - private $id; - - /** - * @ManyToOne(targetEntity="DDC1509AbstractFile", cascade={"persist", "remove"}) - */ - private $thumbnail; - - /** - * @ManyToOne(targetEntity="DDC1509AbstractFile", cascade={"persist", "remove"}) - */ - private $file; - - /** - * Get pictureId - */ - public function getPictureId() - { - return $this->id; - } - - /** - * Set file - */ - public function setFile($value = null) - { - $this->file = $value; - } - - /** - * Get file - */ - public function getFile() - { - return $this->file; - } - - public function getThumbnail() - { - return $this->thumbnail; - } - - public function setThumbnail($thumbnail) - { - $this->thumbnail = $thumbnail; - } - -} - -/** - * @Entity - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorColumn(name="discr", type="string") - * @DiscriminatorMap({"abstractFile" = "DDC1509AbstractFile", "file" = "DDC1509File"}) - */ -class DDC1509AbstractFile -{ - - /** - * @Column(type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") - */ - public $id; - - /** - * Get fileId - */ - public function getFileId() - { - return $this->id; - } - -} - -/** - * @Entity - */ -class DDC1509File extends DDC1509AbstractFile -{ - -} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1514Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1514Test.php index 1fc8a06efad..ed9e3aff8d9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1514Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1514Test.php @@ -1,8 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1514EntityA::class), - $this->_em->getClassMetadata(DDC1514EntityB::class), - $this->_em->getClassMetadata(DDC1514EntityC::class), + $this->em->getClassMetadata(DDC1514EntityA::class), + $this->em->getClassMetadata(DDC1514EntityB::class), + $this->em->getClassMetadata(DDC1514EntityC::class), ] ); } catch (\Exception $ignored) { @@ -45,37 +48,37 @@ public function testIssue() $c->title = "baz"; $a2->entityC = $c; - $this->_em->persist($a1); - $this->_em->persist($a2); - $this->_em->persist($b1); - $this->_em->persist($b2); - $this->_em->persist($c); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($a1); + $this->em->persist($a2); + $this->em->persist($b1); + $this->em->persist($b2); + $this->em->persist($c); + $this->em->flush(); + $this->em->clear(); $dql = "SELECT a, b, ba, c FROM " . __NAMESPACE__ . "\DDC1514EntityA AS a LEFT JOIN a.entitiesB AS b LEFT JOIN b.entityATo AS ba LEFT JOIN a.entityC AS c ORDER BY a.title"; - $results = $this->_em->createQuery($dql)->getResult(); + $results = $this->em->createQuery($dql)->getResult(); - $this->assertEquals($a1->id, $results[0]->id); - $this->assertNull($results[0]->entityC); + self::assertEquals($a1->id, $results[0]->id); + self::assertNull($results[0]->entityC); - $this->assertEquals($a2->id, $results[1]->id); - $this->assertEquals($c->title, $results[1]->entityC->title); + self::assertEquals($a2->id, $results[1]->id); + self::assertEquals($c->title, $results[1]->entityC->title); } } /** - * @Entity + * @ORM\Entity */ class DDC1514EntityA { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @Column */ + /** @ORM\Column */ public $title; - /** @ManyToMany(targetEntity="DDC1514EntityB", mappedBy="entityAFrom") */ + /** @ORM\ManyToMany(targetEntity="DDC1514EntityB", mappedBy="entityAFrom") */ public $entitiesB; - /** @ManyToOne(targetEntity="DDC1514EntityC") */ + /** @ORM\ManyToOne(targetEntity="DDC1514EntityC") */ public $entityC; public function __construct() @@ -85,30 +88,30 @@ public function __construct() } /** - * @Entity + * @ORM\Entity */ class DDC1514EntityB { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; /** - * @ManyToOne(targetEntity="DDC1514EntityA", inversedBy="entitiesB") + * @ORM\ManyToOne(targetEntity="DDC1514EntityA", inversedBy="entitiesB") */ public $entityAFrom; /** - * @ManyToOne(targetEntity="DDC1514EntityA") + * @ORM\ManyToOne(targetEntity="DDC1514EntityA") */ public $entityATo; } /** - * @Entity + * @ORM\Entity */ class DDC1514EntityC { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @Column */ + /** @ORM\Column */ public $title; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1515Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1515Test.php index 294ae87388f..b301e57337a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1515Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1515Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1515Foo::class), - $this->_em->getClassMetadata(DDC1515Bar::class), + $this->em->getClassMetadata(DDC1515Foo::class), + $this->em->getClassMetadata(DDC1515Bar::class), ] ); } @@ -22,43 +25,43 @@ public function setUp() public function testIssue() { $bar = new DDC1515Bar(); - $this->_em->persist($bar); - $this->_em->flush(); + $this->em->persist($bar); + $this->em->flush(); $foo = new DDC1515Foo(); $foo->bar = $bar; - $this->_em->persist($foo); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($foo); + $this->em->flush(); + $this->em->clear(); - $bar = $this->_em->find(DDC1515Bar::class, $bar->id); - $this->assertInstanceOf(DDC1515Foo::class, $bar->foo); + $bar = $this->em->find(DDC1515Bar::class, $bar->id); + self::assertInstanceOf(DDC1515Foo::class, $bar->foo); } } /** - * @Entity + * @ORM\Entity */ class DDC1515Foo { /** - * @OneToOne(targetEntity="DDC1515Bar", inversedBy="foo") @Id + * @ORM\OneToOne(targetEntity="DDC1515Bar", inversedBy="foo") @ORM\Id */ public $bar; } /** - * @Entity + * @ORM\Entity */ class DDC1515Bar { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; /** - * @OneToOne(targetEntity="DDC1515Foo", mappedBy="bar") + * @ORM\OneToOne(targetEntity="DDC1515Foo", mappedBy="bar") */ public $foo; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1526Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1526Test.php index 7a76e3fb938..91d5ea37b6a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1526Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1526Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1526Menu::class), + $this->em->getClassMetadata(DDC1526Menu::class), ] ); } @@ -27,43 +31,43 @@ public function testIssue() $entity->parent = $parents[($i%3)]; } - $this->_em->persist($entity); + $this->em->persist($entity); $parents[$i] = $entity; } - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $dql = "SELECT m, c FROM " . __NAMESPACE__ . "\DDC1526Menu m LEFT JOIN m.children c"; - $menus = $this->_em->createQuery($dql)->getResult(); + $menus = $this->em->createQuery($dql)->getResult(); // All Children collection now have to be initialized foreach ($menus as $menu) { - $this->assertTrue($menu->children->isInitialized()); + self::assertTrue($menu->children->isInitialized()); } } } /** - * @Entity + * @ORM\Entity */ class DDC1526Menu { /** - * @Column(type="integer") - * @Id - * @GeneratedValue + * @ORM\Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue */ public $id; /** - * @ManyToOne(targetEntity="DDC1526Menu", inversedBy="children") + * @ORM\ManyToOne(targetEntity="DDC1526Menu", inversedBy="children") */ public $parent; /** - * @OneToMany(targetEntity="DDC1526Menu", mappedBy="parent") + * @ORM\OneToMany(targetEntity="DDC1526Menu", mappedBy="parent") */ public $children; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1545Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1545Test.php index 20ebe424c5c..c7446c60e09 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1545Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1545Test.php @@ -1,5 +1,7 @@ user = $user; } - $this->_em->persist($article); - $this->_em->persist($user); - $this->_em->persist($user2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($article); + $this->em->persist($user); + $this->em->persist($user2); + $this->em->flush(); + $this->em->clear(); $this->articleId = $article->id; $this->userId = $user->id; @@ -58,22 +60,22 @@ public function testLinkObjects() $this->initDb(false); // don't join association - $article = $this->_em->find(CmsArticle::class, $this->articleId); + $article = $this->em->find(CmsArticle::class, $this->articleId); - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); $article->user = $user; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $article = $this->_em + $article = $this->em ->createQuery('SELECT a, u FROM Doctrine\Tests\Models\Cms\CmsArticle a LEFT JOIN a.user u WHERE a.id = :id') ->setParameter('id', $this->articleId) ->getOneOrNullResult(); - $this->assertNotNull($article->user); - $this->assertEquals($user->id, $article->user->id); + self::assertNotNull($article->user); + self::assertEquals($user->id, $article->user->id); } public function testLinkObjectsWithAssociationLoaded() @@ -81,25 +83,25 @@ public function testLinkObjectsWithAssociationLoaded() $this->initDb(false); // join association - $article = $this->_em + $article = $this->em ->createQuery('SELECT a, u FROM Doctrine\Tests\Models\Cms\CmsArticle a LEFT JOIN a.user u WHERE a.id = :id') ->setParameter('id', $this->articleId) ->getOneOrNullResult(); - $user = $this->_em->find(CmsUser::class, $this->userId); + $user = $this->em->find(CmsUser::class, $this->userId); $article->user = $user; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $article = $this->_em + $article = $this->em ->createQuery('SELECT a, u FROM Doctrine\Tests\Models\Cms\CmsArticle a LEFT JOIN a.user u WHERE a.id = :id') ->setParameter('id', $this->articleId) ->getOneOrNullResult(); - $this->assertNotNull($article->user); - $this->assertEquals($user->id, $article->user->id); + self::assertNotNull($article->user); + self::assertEquals($user->id, $article->user->id); } public function testUnlinkObjects() @@ -107,19 +109,19 @@ public function testUnlinkObjects() $this->initDb(true); // don't join association - $article = $this->_em->find(CmsArticle::class, $this->articleId); + $article = $this->em->find(CmsArticle::class, $this->articleId); $article->user = null; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $article = $this->_em + $article = $this->em ->createQuery('SELECT a, u FROM Doctrine\Tests\Models\Cms\CmsArticle a LEFT JOIN a.user u WHERE a.id = :id') ->setParameter('id', $this->articleId) ->getOneOrNullResult(); - $this->assertNull($article->user); + self::assertNull($article->user); } public function testUnlinkObjectsWithAssociationLoaded() @@ -127,22 +129,22 @@ public function testUnlinkObjectsWithAssociationLoaded() $this->initDb(true); // join association - $article = $this->_em + $article = $this->em ->createQuery('SELECT a, u FROM Doctrine\Tests\Models\Cms\CmsArticle a LEFT JOIN a.user u WHERE a.id = :id') ->setParameter('id', $this->articleId) ->getOneOrNullResult(); $article->user = null; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $article = $this->_em + $article = $this->em ->createQuery('SELECT a, u FROM Doctrine\Tests\Models\Cms\CmsArticle a LEFT JOIN a.user u WHERE a.id = :id') ->setParameter('id', $this->articleId) ->getOneOrNullResult(); - $this->assertNull($article->user); + self::assertNull($article->user); } public function testChangeLink() @@ -150,22 +152,22 @@ public function testChangeLink() $this->initDb(false); // don't join association - $article = $this->_em->find(CmsArticle::class, $this->articleId); + $article = $this->em->find(CmsArticle::class, $this->articleId); - $user2 = $this->_em->find(CmsUser::class, $this->user2Id); + $user2 = $this->em->find(CmsUser::class, $this->user2Id); $article->user = $user2; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $article = $this->_em + $article = $this->em ->createQuery('SELECT a, u FROM Doctrine\Tests\Models\Cms\CmsArticle a LEFT JOIN a.user u WHERE a.id = :id') ->setParameter('id', $this->articleId) ->getOneOrNullResult(); - $this->assertNotNull($article->user); - $this->assertEquals($user2->id, $article->user->id); + self::assertNotNull($article->user); + self::assertEquals($user2->id, $article->user->id); } public function testChangeLinkWithAssociationLoaded() @@ -173,24 +175,24 @@ public function testChangeLinkWithAssociationLoaded() $this->initDb(false); // join association - $article = $this->_em + $article = $this->em ->createQuery('SELECT a, u FROM Doctrine\Tests\Models\Cms\CmsArticle a LEFT JOIN a.user u WHERE a.id = :id') ->setParameter('id', $this->articleId) ->getOneOrNullResult(); - $user2 = $this->_em->find(CmsUser::class, $this->user2Id); + $user2 = $this->em->find(CmsUser::class, $this->user2Id); $article->user = $user2; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $article = $this->_em + $article = $this->em ->createQuery('SELECT a, u FROM Doctrine\Tests\Models\Cms\CmsArticle a LEFT JOIN a.user u WHERE a.id = :id') ->setParameter('id', $this->articleId) ->getOneOrNullResult(); - $this->assertNotNull($article->user); - $this->assertEquals($user2->id, $article->user->id); + self::assertNotNull($article->user); + self::assertEquals($user2->id, $article->user->id); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1548Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1548Test.php index 6628586cc91..927aea3034b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1548Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1548Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1548E1::class), - $this->_em->getClassMetadata(DDC1548E2::class), - $this->_em->getClassMetadata(DDC1548Rel::class), + $this->em->getClassMetadata(DDC1548E1::class), + $this->em->getClassMetadata(DDC1548E2::class), + $this->em->getClassMetadata(DDC1548Rel::class), ] ); } @@ -22,62 +26,62 @@ public function setUp() public function testIssue() { $rel = new DDC1548Rel(); - $this->_em->persist($rel); - $this->_em->flush(); + $this->em->persist($rel); + $this->em->flush(); $e1 = new DDC1548E1(); $e1->rel = $rel; - $this->_em->persist($e1); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($e1); + $this->em->flush(); + $this->em->clear(); - $obt = $this->_em->find(DDC1548Rel::class, $rel->id); + $obt = $this->em->find(DDC1548Rel::class, $rel->id); - $this->assertNull($obt->e2); + self::assertNull($obt->e2); } } /** - * @Entity + * @ORM\Entity */ class DDC1548E1 { /** - * @Id - * @OneToOne(targetEntity="DDC1548Rel", inversedBy="e1") + * @ORM\Id + * @ORM\OneToOne(targetEntity="DDC1548Rel", inversedBy="e1") */ public $rel; } /** - * @Entity + * @ORM\Entity */ class DDC1548E2 { /** - * @Id - * @OneToOne(targetEntity="DDC1548Rel", inversedBy="e2") + * @ORM\Id + * @ORM\OneToOne(targetEntity="DDC1548Rel", inversedBy="e2") */ public $rel; } /** - * @Entity + * @ORM\Entity */ class DDC1548Rel { /** - * @Id @GeneratedValue - * @Column(type="integer") + * @ORM\Id @ORM\GeneratedValue + * @ORM\Column(type="integer") */ public $id; /** - * @OneToOne(targetEntity="DDC1548E1", mappedBy="rel") + * @ORM\OneToOne(targetEntity="DDC1548E1", mappedBy="rel") */ public $e1; /** - * @OneToOne(targetEntity="DDC1548E2", mappedBy="rel") + * @ORM\OneToOne(targetEntity="DDC1548E2", mappedBy="rel") */ public $e2; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1594Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1594Test.php deleted file mode 100644 index 0c94f73d54c..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1594Test.php +++ /dev/null @@ -1,41 +0,0 @@ -useModelSet('cms'); - parent::setUp(); - } - - public function testIssue() - { - $user = new CmsUser(); - $user->status = 'foo'; - $user->username = 'foo'; - $user->name = 'foo'; - - $this->_em->persist($user); - $this->_em->flush(); - - $this->_em->clear(); - $detachedUser = clone $user; - $detachedUser->name = 'bar'; - $detachedUser->status = 'bar'; - - $newUser = $this->_em->getReference(get_class($user), $user->id); - - $mergedUser = $this->_em->merge($detachedUser); - - $this->assertNotSame($mergedUser, $detachedUser); - $this->assertEquals('bar', $detachedUser->getName()); - $this->assertEquals('bar', $mergedUser->getName()); - } -} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1595Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1595Test.php index 5f0e128b5c0..1d14b6d5c40 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1595Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1595Test.php @@ -1,7 +1,11 @@ _em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\DebugStack); + $this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\DebugStack); - $this->_schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1595BaseInheritance::class), - $this->_em->getClassMetadata(DDC1595InheritedEntity1::class), - $this->_em->getClassMetadata(DDC1595InheritedEntity2::class), + $this->em->getClassMetadata(DDC1595BaseInheritance::class), + $this->em->getClassMetadata(DDC1595InheritedEntity1::class), + $this->em->getClassMetadata(DDC1595InheritedEntity2::class), ] ); } @@ -28,47 +32,48 @@ public function testIssue() { $e1 = new DDC1595InheritedEntity1(); - $this->_em->persist($e1); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($e1); + $this->em->flush(); + $this->em->clear(); - $sqlLogger = $this->_em->getConnection()->getConfiguration()->getSQLLogger(); - $repository = $this->_em->getRepository(DDC1595InheritedEntity1::class); + $sqlLogger = $this->em->getConnection()->getConfiguration()->getSQLLogger(); + $repository = $this->em->getRepository(DDC1595InheritedEntity1::class); $entity1 = $repository->find($e1->id); // DDC-1596 - $this->assertSQLEquals( - "SELECT t0.id AS id_1, t0.type FROM base t0 WHERE t0.id = ? AND t0.type IN ('Entity1')", + self::assertSQLEquals( + 'SELECT t0."id" AS c1, t0."type" FROM "base" t0 WHERE t0."id" = ? AND t0."type" IN (\'Entity1\')', $sqlLogger->queries[count($sqlLogger->queries)]['sql'] ); $entities = $entity1->getEntities()->getValues(); - $this->assertEquals( - "SELECT t0.id AS id_1, t0.type FROM base t0 INNER JOIN entity1_entity2 ON t0.id = entity1_entity2.item WHERE entity1_entity2.parent = ? AND t0.type IN ('Entity2')", + self::assertSQLEquals( + 'SELECT t0."id" AS c1, t0."type" FROM "base" t0 INNER JOIN "entity1_entity2" ON t0."id" = "entity1_entity2"."item" WHERE "entity1_entity2"."parent" = ? AND t0."type" IN (\'Entity2\')', $sqlLogger->queries[count($sqlLogger->queries)]['sql'] ); - $this->_em->clear(); + $this->em->clear(); $entity1 = $repository->find($e1->id); - $entities = $entity1->getEntities()->count(); - $this->assertSQLEquals( - "SELECT COUNT(*) FROM entity1_entity2 t WHERE t.parent = ?", + $entity1->getEntities()->count(); + + self::assertSQLEquals( + 'SELECT COUNT(*) FROM "entity1_entity2" t WHERE t."parent" = ?', $sqlLogger->queries[count($sqlLogger->queries)]['sql'] ); } } /** - * @Entity - * @Table(name="base") + * @ORM\Entity + * @ORM\Table(name="base") * - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorColumn(name="type", type="string") - * @DiscriminatorMap({ + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorColumn(name="type", type="string") + * @ORM\DiscriminatorMap({ * "Entity1" = "DDC1595InheritedEntity1", * "Entity2" = "DDC1595InheritedEntity2" * }) @@ -76,8 +81,8 @@ public function testIssue() abstract class DDC1595BaseInheritance { /** - * @Id @GeneratedValue - * @Column(type="integer") + * @ORM\Id @ORM\GeneratedValue + * @ORM\Column(type="integer") * * @var int */ @@ -85,16 +90,15 @@ abstract class DDC1595BaseInheritance } /** - * @Entity - * @Table(name="entity1") + * @ORM\Entity */ class DDC1595InheritedEntity1 extends DDC1595BaseInheritance { /** - * @ManyToMany(targetEntity="DDC1595InheritedEntity2", fetch="EXTRA_LAZY") - * @JoinTable(name="entity1_entity2", - * joinColumns={@JoinColumn(name="parent", referencedColumnName="id")}, - * inverseJoinColumns={@JoinColumn(name="item", referencedColumnName="id")} + * @ORM\ManyToMany(targetEntity="DDC1595InheritedEntity2", fetch="EXTRA_LAZY") + * @ORM\JoinTable(name="entity1_entity2", + * joinColumns={@ORM\JoinColumn(name="parent", referencedColumnName="id")}, + * inverseJoinColumns={@ORM\JoinColumn(name="item", referencedColumnName="id")} * ) */ protected $entities; @@ -106,8 +110,7 @@ public function getEntities() } /** - * @Entity - * @Table(name="entity2") + * @ORM\Entity */ class DDC1595InheritedEntity2 extends DDC1595BaseInheritance { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC163Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC163Test.php index cea515ce3ec..23aaa006892 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC163Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC163Test.php @@ -1,5 +1,7 @@ addFriend($p4); - $this->_em->persist($p1); - $this->_em->persist($p2); - $this->_em->persist($p3); - $this->_em->persist($p4); + $this->em->persist($p1); + $this->em->persist($p2); + $this->em->persist($p3); + $this->em->persist($p4); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $dql = 'SELECT PARTIAL person.{id,name}, PARTIAL spouse.{id,name}, PARTIAL friend.{id,name} FROM Doctrine\Tests\Models\Company\CompanyPerson person @@ -51,13 +53,13 @@ public function testQueryWithOrConditionUsingTwoRelationOnSameEntity() LEFT JOIN friend.friends friend_friend WHERE person.name=:name AND (spouse_friend.name=:name2 OR friend_friend.name=:name2)'; - $q = $this->_em->createQuery($dql); + $q = $this->em->createQuery($dql); $q->setParameter('name', "p1"); $q->setParameter('name2', "p4"); $result = $q->getScalarResult(); - $this->assertEquals('p3', $result[0]['spouse_name']); - $this->assertEquals('p1', $result[0]['person_name']); - $this->assertEquals('p2', $result[0]['friend_name']); + self::assertEquals('p3', $result[0]['spouse_name']); + self::assertEquals('p1', $result[0]['person_name']); + self::assertEquals('p2', $result[0]['friend_name']); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1643Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1643Test.php index fda16824621..c7d467f7372 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1643Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1643Test.php @@ -1,6 +1,9 @@ useModelSet('cms'); + parent::setUp(); $user1 = new CmsUser(); @@ -32,15 +36,15 @@ public function setUp() $user2->name = "Roman"; $user2->status = "active"; - $this->_em->persist($user1); - $this->_em->persist($user2); - $this->_em->persist($group1); - $this->_em->persist($group2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user1); + $this->em->persist($user2); + $this->em->persist($group1); + $this->em->persist($group2); + $this->em->flush(); + $this->em->clear(); - $this->user1 = $this->_em->find(get_class($user1), $user1->id); - $this->user2 = $this->_em->find(get_class($user1), $user2->id); + $this->user1 = $this->em->find(get_class($user1), $user1->id); + $this->user2 = $this->em->find(get_class($user1), $user2->id); } public function testClonePersistentCollectionAndReuse() @@ -49,12 +53,12 @@ public function testClonePersistentCollectionAndReuse() $user1->groups = clone $user1->groups; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $user1 = $this->_em->find(get_class($user1), $user1->id); + $user1 = $this->em->find(get_class($user1), $user1->id); - $this->assertEquals(2, count($user1->groups)); + self::assertEquals(2, count($user1->groups)); } public function testClonePersistentCollectionAndShare() @@ -64,14 +68,14 @@ public function testClonePersistentCollectionAndShare() $user2->groups = clone $user1->groups; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $user1 = $this->_em->find(get_class($user1), $user1->id); - $user2 = $this->_em->find(get_class($user1), $user2->id); + $user1 = $this->em->find(get_class($user1), $user1->id); + $user2 = $this->em->find(get_class($user1), $user2->id); - $this->assertEquals(2, count($user1->groups)); - $this->assertEquals(2, count($user2->groups)); + self::assertEquals(2, count($user1->groups)); + self::assertEquals(2, count($user2->groups)); } public function testCloneThenDirtyPersistentCollection() @@ -84,15 +88,15 @@ public function testCloneThenDirtyPersistentCollection() $user2->groups = clone $user1->groups; $user2->groups->add($group3); - $this->_em->persist($group3); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($group3); + $this->em->flush(); + $this->em->clear(); - $user1 = $this->_em->find(get_class($user1), $user1->id); - $user2 = $this->_em->find(get_class($user1), $user2->id); + $user1 = $this->em->find(get_class($user1), $user1->id); + $user2 = $this->em->find(get_class($user1), $user2->id); - $this->assertEquals(3, count($user2->groups)); - $this->assertEquals(2, count($user1->groups)); + self::assertEquals(3, count($user2->groups)); + self::assertEquals(2, count($user1->groups)); } public function testNotCloneAndPassAroundFlush() @@ -105,17 +109,17 @@ public function testNotCloneAndPassAroundFlush() $user2->groups = $user1->groups; $user2->groups->add($group3); - $this->assertCount(1, $user1->groups->getInsertDiff()); + self::assertCount(1, $user1->groups->getInsertDiff()); - $this->_em->persist($group3); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($group3); + $this->em->flush(); + $this->em->clear(); - $user1 = $this->_em->find(get_class($user1), $user1->id); - $user2 = $this->_em->find(get_class($user1), $user2->id); + $user1 = $this->em->find(get_class($user1), $user1->id); + $user2 = $this->em->find(get_class($user1), $user2->id); - $this->assertEquals(3, count($user2->groups)); - $this->assertEquals(3, count($user1->groups)); + self::assertEquals(3, count($user2->groups)); + self::assertEquals(3, count($user1->groups)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1654Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1654Test.php index a5a620f63da..2ed7a65e7f3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1654Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1654Test.php @@ -1,7 +1,11 @@ executeUpdate('DELETE FROM ddc1654post_ddc1654comment'); $conn->executeUpdate('DELETE FROM DDC1654Comment'); $conn->executeUpdate('DELETE FROM DDC1654Post'); @@ -32,17 +36,17 @@ public function testManyToManyRemoveFromCollectionOrphanRemoval() $post->comments[] = new DDC1654Comment(); $post->comments[] = new DDC1654Comment(); - $this->_em->persist($post); - $this->_em->flush(); + $this->em->persist($post); + $this->em->flush(); $post->comments->remove(0); $post->comments->remove(1); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $comments = $this->_em->getRepository(DDC1654Comment::class)->findAll(); - $this->assertEquals(0, count($comments)); + $comments = $this->em->getRepository(DDC1654Comment::class)->findAll(); + self::assertEquals(0, count($comments)); } public function testManyToManyRemoveElementFromCollectionOrphanRemoval() @@ -51,17 +55,17 @@ public function testManyToManyRemoveElementFromCollectionOrphanRemoval() $post->comments[] = new DDC1654Comment(); $post->comments[] = new DDC1654Comment(); - $this->_em->persist($post); - $this->_em->flush(); + $this->em->persist($post); + $this->em->flush(); $post->comments->removeElement($post->comments[0]); $post->comments->removeElement($post->comments[1]); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $comments = $this->_em->getRepository(DDC1654Comment::class)->findAll(); - $this->assertEquals(0, count($comments)); + $comments = $this->em->getRepository(DDC1654Comment::class)->findAll(); + self::assertEquals(0, count($comments)); } /** @@ -73,18 +77,18 @@ public function testManyToManyRemoveElementFromReAddToCollectionOrphanRemoval() $post->comments[] = new DDC1654Comment(); $post->comments[] = new DDC1654Comment(); - $this->_em->persist($post); - $this->_em->flush(); + $this->em->persist($post); + $this->em->flush(); $comment = $post->comments[0]; $post->comments->removeElement($comment); $post->comments->add($comment); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $comments = $this->_em->getRepository(DDC1654Comment::class)->findAll(); - $this->assertEquals(2, count($comments)); + $comments = $this->em->getRepository(DDC1654Comment::class)->findAll(); + self::assertEquals(2, count($comments)); } public function testManyToManyClearCollectionOrphanRemoval() @@ -93,16 +97,16 @@ public function testManyToManyClearCollectionOrphanRemoval() $post->comments[] = new DDC1654Comment(); $post->comments[] = new DDC1654Comment(); - $this->_em->persist($post); - $this->_em->flush(); + $this->em->persist($post); + $this->em->flush(); $post->comments->clear(); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $comments = $this->_em->getRepository(DDC1654Comment::class)->findAll(); - $this->assertEquals(0, count($comments)); + $comments = $this->em->getRepository(DDC1654Comment::class)->findAll(); + self::assertEquals(0, count($comments)); } @@ -115,45 +119,45 @@ public function testManyToManyClearCollectionReAddOrphanRemoval() $post->comments[] = new DDC1654Comment(); $post->comments[] = new DDC1654Comment(); - $this->_em->persist($post); - $this->_em->flush(); + $this->em->persist($post); + $this->em->flush(); $comment = $post->comments[0]; $post->comments->clear(); $post->comments->add($comment); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $comments = $this->_em->getRepository(DDC1654Comment::class)->findAll(); - $this->assertEquals(1, count($comments)); + $comments = $this->em->getRepository(DDC1654Comment::class)->findAll(); + self::assertEquals(1, count($comments)); } } /** - * @Entity + * @ORM\Entity */ class DDC1654Post { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; /** - * @ManyToMany(targetEntity="DDC1654Comment", orphanRemoval=true, + * @ORM\ManyToMany(targetEntity="DDC1654Comment", orphanRemoval=true, * cascade={"persist"}) */ public $comments = []; } /** - * @Entity + * @ORM\Entity */ class DDC1654Comment { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1655Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1655Test.php index a63d3635fe5..5856909eb0e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1655Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1655Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1655Foo::class), - $this->_em->getClassMetadata(DDC1655Bar::class), - $this->_em->getClassMetadata(DDC1655Baz::class), + $this->em->getClassMetadata(DDC1655Foo::class), + $this->em->getClassMetadata(DDC1655Bar::class), + $this->em->getClassMetadata(DDC1655Baz::class), ] ); } catch(\Exception $e) { + $this->fail($e->getMessage() . PHP_EOL . $e->getTraceAsString()); + } + } + + protected function tearDown() + { + $conn = static::$sharedConn; + + // In case test is skipped, tearDown is called, but no setup may have run + if (!$conn) { + return; } + + $platform = $conn->getDatabasePlatform(); + + $this->sqlLoggerStack->enabled = false; + + $conn->executeUpdate('DROP TABLE DDC1655Foo'); + $conn->executeUpdate('DROP TABLE DDC1655Baz'); + + // Some drivers require sequence dropping (ie. PostgreSQL) + if ($platform->prefersSequences()) { + $conn->executeUpdate('DROP SEQUENCE DDC1655Foo_id_seq'); + $conn->executeUpdate('DROP SEQUENCE DDC1655Baz_id_seq'); + } + + $this->em->clear(); } public function testPostLoadOneToManyInheritance() { - $cm = $this->_em->getClassMetadata(DDC1655Foo::class); - $this->assertEquals(["postLoad" => ["postLoad"]], $cm->lifecycleCallbacks); + $cm = $this->em->getClassMetadata(DDC1655Foo::class); + self::assertEquals(["postLoad" => ["postLoad"]], $cm->lifecycleCallbacks); - $cm = $this->_em->getClassMetadata(DDC1655Bar::class); - $this->assertEquals(["postLoad" => ["postLoad", "postSubLoaded"]], $cm->lifecycleCallbacks); + $cm = $this->em->getClassMetadata(DDC1655Bar::class); + self::assertEquals(["postLoad" => ["postLoad", "postSubLoaded"]], $cm->lifecycleCallbacks); $baz = new DDC1655Baz(); $foo = new DDC1655Foo(); @@ -39,15 +69,15 @@ public function testPostLoadOneToManyInheritance() $bar = new DDC1655Bar(); $bar->baz = $baz; - $this->_em->persist($foo); - $this->_em->persist($bar); - $this->_em->persist($baz); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($foo); + $this->em->persist($bar); + $this->em->persist($baz); + $this->em->flush(); + $this->em->clear(); - $baz = $this->_em->find(get_class($baz), $baz->id); + $baz = $this->em->find(get_class($baz), $baz->id); foreach ($baz->foos as $foo) { - $this->assertEquals(1, $foo->loaded, "should have loaded callback counter incremented for " . get_class($foo)); + self::assertEquals(1, $foo->loaded, "should have loaded callback counter incremented for " . get_class($foo)); } } @@ -59,54 +89,54 @@ public function testPostLoadInheritanceChild() { $bar = new DDC1655Bar(); - $this->_em->persist($bar); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($bar); + $this->em->flush(); + $this->em->clear(); - $bar = $this->_em->find(get_class($bar), $bar->id); - $this->assertEquals(1, $bar->loaded); - $this->assertEquals(1, $bar->subLoaded); + $bar = $this->em->find(get_class($bar), $bar->id); + self::assertEquals(1, $bar->loaded); + self::assertEquals(1, $bar->subLoaded); - $bar = $this->_em->find(get_class($bar), $bar->id); - $this->assertEquals(1, $bar->loaded); - $this->assertEquals(1, $bar->subLoaded); + $bar = $this->em->find(get_class($bar), $bar->id); + self::assertEquals(1, $bar->loaded); + self::assertEquals(1, $bar->subLoaded); $dql = "SELECT b FROM " . __NAMESPACE__ . "\DDC1655Bar b WHERE b.id = ?1"; - $bar = $this->_em->createQuery($dql)->setParameter(1, $bar->id)->getSingleResult(); + $bar = $this->em->createQuery($dql)->setParameter(1, $bar->id)->getSingleResult(); - $this->assertEquals(1, $bar->loaded); - $this->assertEquals(1, $bar->subLoaded); + self::assertEquals(1, $bar->loaded); + self::assertEquals(1, $bar->subLoaded); - $this->_em->refresh($bar); + $this->em->refresh($bar); - $this->assertEquals(2, $bar->loaded); - $this->assertEquals(2, $bar->subLoaded); + self::assertEquals(2, $bar->loaded); + self::assertEquals(2, $bar->subLoaded); } } /** - * @Entity - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorMap({ + * @ORM\Entity + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorMap({ * "foo" = "DDC1655Foo", * "bar" = "DDC1655Bar" * }) - * @HasLifecycleCallbacks + * @ORM\HasLifecycleCallbacks */ class DDC1655Foo { - /** @Id @GeneratedValue @Column(type="integer") */ + /** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ public $id; public $loaded = 0; /** - * @ManyToOne(targetEntity="DDC1655Baz", inversedBy="foos") + * @ORM\ManyToOne(targetEntity="DDC1655Baz", inversedBy="foos") */ public $baz; /** - * @PostLoad + * @ORM\PostLoad */ public function postLoad() { @@ -115,15 +145,15 @@ public function postLoad() } /** - * @Entity - * @HasLifecycleCallbacks + * @ORM\Entity + * @ORM\HasLifecycleCallbacks */ class DDC1655Bar extends DDC1655Foo { public $subLoaded; /** - * @PostLoad + * @ORM\PostLoad */ public function postSubLoaded() { @@ -132,15 +162,15 @@ public function postSubLoaded() } /** - * @Entity + * @ORM\Entity */ class DDC1655Baz { - /** @Id @GeneratedValue @Column(type="integer") */ + /** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ public $id; /** - * @OneToMany(targetEntity="DDC1655Foo", mappedBy="baz") + * @ORM\OneToMany(targetEntity="DDC1655Foo", mappedBy="baz") */ public $foos = []; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1666Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1666Test.php index e664e537c3d..3914f823e9a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1666Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1666Test.php @@ -1,5 +1,7 @@ setEmail($email = new CmsEmail()); $email->setEmail("kontakt@beberlei.de"); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); - $this->assertTrue($this->_em->contains($email)); + self::assertTrue($this->em->contains($email)); $user->setEmail($newEmail = new CmsEmail()); $newEmail->setEmail("benjamin.eberlei@googlemail.com"); - $this->_em->flush(); + $this->em->flush(); - $this->assertFalse($this->_em->contains($email)); + self::assertFalse($this->em->contains($email)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1685Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1685Test.php index 576b4e28628..60452919c21 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1685Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1685Test.php @@ -1,4 +1,6 @@ useModelSet('ddc117'); + parent::setUp(); - $this->_em->createQuery('DELETE FROM Doctrine\Tests\Models\DDC117\DDC117ArticleDetails ad')->execute(); + $this->em->createQuery('DELETE FROM Doctrine\Tests\Models\DDC117\DDC117ArticleDetails ad')->execute(); $article = new DDC117Article("Foo"); - $this->_em->persist($article); - $this->_em->flush(); + $this->em->persist($article); + $this->em->flush(); $articleDetails = new DDC117ArticleDetails($article, "Very long text"); - $this->_em->persist($articleDetails); - $this->_em->flush(); + $this->em->persist($articleDetails); + $this->em->flush(); $dql = "SELECT ad FROM Doctrine\Tests\Models\DDC117\DDC117ArticleDetails ad"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $this->paginator = new Paginator($query); } public function testPaginateCount() { - $this->assertEquals(1, count($this->paginator)); + self::assertEquals(1, count($this->paginator)); } public function testPaginateIterate() { foreach ($this->paginator as $ad) { - $this->assertInstanceOf(DDC117ArticleDetails::class, $ad); + self::assertInstanceOf(DDC117ArticleDetails::class, $ad); } } public function testPaginateCountNoOutputWalkers() { $this->paginator->setUseOutputWalkers(false); - $this->assertEquals(1, count($this->paginator)); + + self::assertEquals(1, count($this->paginator)); } public function testPaginateIterateNoOutputWalkers() @@ -59,7 +63,7 @@ public function testPaginateIterateNoOutputWalkers() $this->expectExceptionMessage('Paginating an entity with foreign key as identifier only works when using the Output Walkers. Call Paginator#setUseOutputWalkers(true) before iterating the paginator.'); foreach ($this->paginator as $ad) { - $this->assertInstanceOf(DDC117ArticleDetails::class, $ad); + self::assertInstanceOf(DDC117ArticleDetails::class, $ad); } } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC168Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC168Test.php index ddaa83d80eb..27e67545e88 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC168Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC168Test.php @@ -1,5 +1,7 @@ useModelSet('company'); + parent::setUp(); - $this->oldMetadata = $this->_em->getClassMetadata(CompanyEmployee::class); + $this->oldMetadata = $this->em->getClassMetadata(CompanyEmployee::class); $metadata = clone $this->oldMetadata; - ksort($metadata->reflFields); - $this->_em->getMetadataFactory()->setMetadataFor(CompanyEmployee::class, $metadata); + + $this->em->getMetadataFactory()->setMetadataFor(CompanyEmployee::class, $metadata); } public function tearDown() { - $this->_em->getMetadataFactory()->setMetadataFor(CompanyEmployee::class, $this->oldMetadata); + $this->em->getMetadataFactory()->setMetadataFor(CompanyEmployee::class, $this->oldMetadata); + parent::tearDown(); } @@ -30,7 +34,7 @@ public function tearDown() */ public function testJoinedSubclassPersisterRequiresSpecificOrderOfMetadataReflFieldsArray() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $spouse = new CompanyEmployee; $spouse->setName("Blub"); @@ -43,20 +47,20 @@ public function testJoinedSubclassPersisterRequiresSpecificOrderOfMetadataReflFi $employee->setSalary(1000); $employee->setSpouse($spouse); - $this->_em->persist($spouse); - $this->_em->persist($employee); + $this->em->persist($spouse); + $this->em->persist($employee); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $q = $this->_em->createQuery("SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e WHERE e.name = ?1"); + $q = $this->em->createQuery("SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e WHERE e.name = ?1"); $q->setParameter(1, "Foo"); $theEmployee = $q->getSingleResult(); - $this->assertEquals("bar", $theEmployee->getDepartment()); - $this->assertEquals("Foo", $theEmployee->getName()); - $this->assertEquals(1000, $theEmployee->getSalary()); - $this->assertInstanceOf(CompanyEmployee::class, $theEmployee); - $this->assertInstanceOf(CompanyEmployee::class, $theEmployee->getSpouse()); + self::assertEquals("bar", $theEmployee->getDepartment()); + self::assertEquals("Foo", $theEmployee->getName()); + self::assertEquals(1000, $theEmployee->getSalary()); + self::assertInstanceOf(CompanyEmployee::class, $theEmployee); + self::assertInstanceOf(CompanyEmployee::class, $theEmployee->getSpouse()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1690Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1690Test.php index 47e79ed7aee..81d19ceda23 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1690Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1690Test.php @@ -1,9 +1,12 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1690Parent::class), - $this->_em->getClassMetadata(DDC1690Child::class) + $this->em->getClassMetadata(DDC1690Parent::class), + $this->em->getClassMetadata(DDC1690Child::class) ] ); } catch (\Exception $e) { @@ -32,44 +35,44 @@ public function testChangeTracking() $parent->setChild($child); $child->setParent($parent); - $this->_em->persist($parent); - $this->_em->persist($child); + $this->em->persist($parent); + $this->em->persist($child); - $this->assertEquals(1, count($parent->listeners)); - $this->assertEquals(1, count($child->listeners)); + self::assertEquals(1, count($parent->listeners)); + self::assertEquals(1, count($child->listeners)); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $this->assertEquals(1, count($parent->listeners)); - $this->assertEquals(1, count($child->listeners)); + self::assertEquals(1, count($parent->listeners)); + self::assertEquals(1, count($child->listeners)); $parentId = $parent->getId(); $childId = $child->getId(); unset($parent, $child); - $parent = $this->_em->find(DDC1690Parent::class, $parentId); - $child = $this->_em->find(DDC1690Child::class, $childId); + $parent = $this->em->find(DDC1690Parent::class, $parentId); + $child = $this->em->find(DDC1690Child::class, $childId); - $this->assertEquals(1, count($parent->listeners)); - $this->assertInstanceOf(Proxy::class, $child, 'Verifying that $child is a proxy before using proxy API'); - $this->assertCount(0, $child->listeners); + self::assertEquals(1, count($parent->listeners)); + self::assertInstanceOf(Proxy::class, $child, 'Verifying that $child is a proxy before using proxy API'); + self::assertCount(0, $child->listeners); $child->__load(); - $this->assertCount(1, $child->listeners); + self::assertCount(1, $child->listeners); unset($parent, $child); - $parent = $this->_em->find(DDC1690Parent::class, $parentId); + $parent = $this->em->find(DDC1690Parent::class, $parentId); $child = $parent->getChild(); - $this->assertEquals(1, count($parent->listeners)); - $this->assertEquals(1, count($child->listeners)); + self::assertEquals(1, count($parent->listeners)); + self::assertEquals(1, count($child->listeners)); unset($parent, $child); - $child = $this->_em->find(DDC1690Child::class, $childId); + $child = $this->em->find(DDC1690Child::class, $childId); $parent = $child->getParent(); - $this->assertEquals(1, count($parent->listeners)); - $this->assertEquals(1, count($child->listeners)); + self::assertEquals(1, count($parent->listeners)); + self::assertEquals(1, count($child->listeners)); } } @@ -91,15 +94,15 @@ protected function onPropertyChanged($propName, $oldValue, $newValue) { } } -/** @Entity @ChangeTrackingPolicy("NOTIFY") */ +/** @ORM\Entity @ORM\ChangeTrackingPolicy("NOTIFY") */ class DDC1690Parent extends NotifyBaseEntity { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ private $id; - /** @Column */ + /** @ORM\Column */ private $name; - /** @OneToOne(targetEntity="DDC1690Child") */ + /** @ORM\OneToOne(targetEntity="DDC1690Child") */ private $child; function getId() { @@ -124,15 +127,15 @@ function getChild() { } } -/** @Entity */ +/** @ORM\Entity */ class DDC1690Child extends NotifyBaseEntity { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ private $id; - /** @Column */ + /** @ORM\Column */ private $name; - /** @OneToOne(targetEntity="DDC1690Parent", mappedBy="child") */ + /** @ORM\OneToOne(targetEntity="DDC1690Parent", mappedBy="child") */ private $parent; function getId() { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1695Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1695Test.php index 20cef650755..ec8a5c7470b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1695Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1695Test.php @@ -1,158 +1,168 @@ _em->getConnection()->getDatabasePlatform()->getName() != "sqlite") { + parent::setUp(); + + if ($this->em->getConnection()->getDatabasePlatform()->getName() != "sqlite") { $this->markTestSkipped("Only with sqlite"); } + } + + public function testIssue() + { $dql = "SELECT n.smallText, n.publishDate FROM " . __NAMESPACE__ . "\\DDC1695News n"; - $sql = $this->_em->createQuery($dql)->getSQL(); + $sql = $this->em->createQuery($dql)->getSQL(); - $this->assertEquals( - 'SELECT d0_."SmallText" AS SmallText_0, d0_."PublishDate" AS PublishDate_1 FROM "DDC1695News" d0_', + self::assertEquals( + 'SELECT t0."SmallText" AS c0, t0."PublishDate" AS c1 FROM "DDC1695News" t0', $sql ); } } /** - * @Table(name="`DDC1695News`") - * @Entity + * @ORM\Table(name="DDC1695News") + * @ORM\Entity */ class DDC1695News { /** * @var int * - * @Column(name="`IdNews`", type="integer", nullable=false) - * @Id - * @GeneratedValue + * @ORM\Column(name="IdNews", type="integer", nullable=false) + * @ORM\Id + * @ORM\GeneratedValue */ private $idNews; /** * @var int * - * @Column(name="`IdUser`", type="bigint", nullable=false) + * @ORM\Column(name="IdUser", type="bigint", nullable=false) */ private $idUser; /** * @var int * - * @Column(name="`IdLanguage`", type="integer", nullable=false) + * @ORM\Column(name="IdLanguage", type="integer", nullable=false) */ private $idLanguage; /** * @var int * - * @Column(name="`IdCondition`", type="integer", nullable=true) + * @ORM\Column(name="IdCondition", type="integer", nullable=true) */ private $idCondition; /** * @var int * - * @Column(name="`IdHealthProvider`", type="integer", nullable=true) + * @ORM\Column(name="IdHealthProvider", type="integer", nullable=true) */ private $idHealthProvider; /** * @var int * - * @Column(name="`IdSpeciality`", type="integer", nullable=true) + * @ORM\Column(name="IdSpeciality", type="integer", nullable=true) */ private $idSpeciality; /** * @var int * - * @Column(name="`IdMedicineType`", type="integer", nullable=true) + * @ORM\Column(name="IdMedicineType", type="integer", nullable=true) */ private $idMedicineType; /** * @var int * - * @Column(name="`IdTreatment`", type="integer", nullable=true) + * @ORM\Column(name="IdTreatment", type="integer", nullable=true) */ private $idTreatment; /** * @var string * - * @Column(name="`Title`", type="string", nullable=true) + * @ORM\Column(name="Title", type="string", nullable=true) */ private $title; /** * @var string * - * @Column(name="`SmallText`", type="string", nullable=true) + * @ORM\Column(name="SmallText", type="string", nullable=true) */ private $smallText; /** * @var string * - * @Column(name="`LongText`", type="string", nullable=true) + * @ORM\Column(name="LongText", type="string", nullable=true) */ private $longText; /** * @var DateTimeZone * - * @Column(name="`PublishDate`", type="datetimetz", nullable=true) + * @ORM\Column(name="PublishDate", type="datetimetz", nullable=true) */ private $publishDate; /** * @var array * - * @Column(name="`IdxNews`", type="json_array", nullable=true) + * @ORM\Column(name="IdxNews", type="json_array", nullable=true) */ private $idxNews; /** * @var bool * - * @Column(name="`Highlight`", type="boolean", nullable=false) + * @ORM\Column(name="Highlight", type="boolean", nullable=false) */ private $highlight; /** * @var int * - * @Column(name="`Order`", type="integer", nullable=false) + * @ORM\Column(name="Order", type="integer", nullable=false) */ private $order; /** * @var bool * - * @Column(name="`Deleted`", type="boolean", nullable=false) + * @ORM\Column(name="Deleted", type="boolean", nullable=false) */ private $deleted; /** * @var bool * - * @Column(name="`Active`", type="boolean", nullable=false) + * @ORM\Column(name="Active", type="boolean", nullable=false) */ private $active; /** * @var bool * - * @Column(name="`UpdateToHighlighted`", type="boolean", nullable=true) + * @ORM\Column(name="UpdateToHighlighted", type="boolean", nullable=true) */ private $updateToHighlighted; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1707Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1707Test.php index 54b52a57bd1..48044132c79 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1707Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1707Test.php @@ -1,9 +1,13 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1509File::class), - $this->_em->getClassMetadata(DDC1509Picture::class), + $this->em->getClassMetadata(DDC1509File::class), + $this->em->getClassMetadata(DDC1509Picture::class), ] ); } catch (\Exception $ignored) { @@ -28,32 +32,35 @@ public function setUp() public function testPostLoadOnChild() { - $class = $this->_em->getClassMetadata(DDC1707Child::class); - $entity = new DDC1707Child(); + $class = $this->em->getClassMetadata(DDC1707Child::class); + $entity = new DDC1707Child(); + $event = new LifecycleEventArgs($entity, $this->em); + $invoker = new ListenersInvoker($this->em); + $invoke = $invoker->getSubscribedSystems($class, \Doctrine\ORM\Events::postLoad); - $class->invokeLifecycleCallbacks(Events::postLoad, $entity); + $invoker->invoke($class, \Doctrine\ORM\Events::postLoad, $entity, $event, $invoke); - $this->assertTrue($entity->postLoad); + self::assertTrue($entity->postLoad); } } /** - * @Entity - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorMap({"c": "DDC1707Child"}) - * @HasLifecycleCallbacks + * @ORM\Entity + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorMap({"c": "DDC1707Child"}) + * @ORM\HasLifecycleCallbacks */ abstract class DDC1707Base { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ protected $id; public $postLoad = false; /** - * @PostLoad + * @ORM\PostLoad */ public function onPostLoad() { @@ -61,7 +68,7 @@ public function onPostLoad() } } /** - * @Entity + * @ORM\Entity */ class DDC1707Child extends DDC1707Base { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1719Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1719Test.php index b3784ff8a7c..fc0c348f1ec 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1719Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1719Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1719SimpleEntity::class), + $this->em->getClassMetadata(DDC1719SimpleEntity::class), ] ); } @@ -22,9 +26,9 @@ protected function tearDown() { parent::tearDown(); - $this->_schemaTool->dropSchema( + $this->schemaTool->dropSchema( [ - $this->_em->getClassMetadata(DDC1719SimpleEntity::class), + $this->em->getClassMetadata(DDC1719SimpleEntity::class), ] ); } @@ -35,78 +39,78 @@ public function testCreateRetrieveUpdateDelete() $e2 = new DDC1719SimpleEntity('Foo 1'); // Create - $this->_em->persist($e1); - $this->_em->persist($e2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($e1); + $this->em->persist($e2); + $this->em->flush(); + $this->em->clear(); $e1Id = $e1->id; $e2Id = $e2->id; // Retrieve - $e1 = $this->_em->find(DDC1719SimpleEntity::class, $e1Id); - $e2 = $this->_em->find(DDC1719SimpleEntity::class, $e2Id); + $e1 = $this->em->find(DDC1719SimpleEntity::class, $e1Id); + $e2 = $this->em->find(DDC1719SimpleEntity::class, $e2Id); - $this->assertInstanceOf(DDC1719SimpleEntity::class, $e1); - $this->assertInstanceOf(DDC1719SimpleEntity::class, $e2); + self::assertInstanceOf(DDC1719SimpleEntity::class, $e1); + self::assertInstanceOf(DDC1719SimpleEntity::class, $e2); - $this->assertEquals($e1Id, $e1->id); - $this->assertEquals($e2Id, $e2->id); + self::assertEquals($e1Id, $e1->id); + self::assertEquals($e2Id, $e2->id); - $this->assertEquals('Bar 1', $e1->value); - $this->assertEquals('Foo 1', $e2->value); + self::assertEquals('Bar 1', $e1->value); + self::assertEquals('Foo 1', $e2->value); $e1->value = 'Bar 2'; $e2->value = 'Foo 2'; // Update - $this->_em->persist($e1); - $this->_em->persist($e2); - $this->_em->flush(); + $this->em->persist($e1); + $this->em->persist($e2); + $this->em->flush(); - $this->assertEquals('Bar 2', $e1->value); - $this->assertEquals('Foo 2', $e2->value); + self::assertEquals('Bar 2', $e1->value); + self::assertEquals('Foo 2', $e2->value); - $this->assertInstanceOf(DDC1719SimpleEntity::class, $e1); - $this->assertInstanceOf(DDC1719SimpleEntity::class, $e2); + self::assertInstanceOf(DDC1719SimpleEntity::class, $e1); + self::assertInstanceOf(DDC1719SimpleEntity::class, $e2); - $this->assertEquals($e1Id, $e1->id); - $this->assertEquals($e2Id, $e2->id); + self::assertEquals($e1Id, $e1->id); + self::assertEquals($e2Id, $e2->id); - $this->assertEquals('Bar 2', $e1->value); - $this->assertEquals('Foo 2', $e2->value); + self::assertEquals('Bar 2', $e1->value); + self::assertEquals('Foo 2', $e2->value); // Delete - $this->_em->remove($e1); - $this->_em->remove($e2); - $this->_em->flush(); + $this->em->remove($e1); + $this->em->remove($e2); + $this->em->flush(); - $e1 = $this->_em->find(DDC1719SimpleEntity::class, $e1Id); - $e2 = $this->_em->find(DDC1719SimpleEntity::class, $e2Id); + $e1 = $this->em->find(DDC1719SimpleEntity::class, $e1Id); + $e2 = $this->em->find(DDC1719SimpleEntity::class, $e2Id); - $this->assertNull($e1); - $this->assertNull($e2); + self::assertNull($e1); + self::assertNull($e2); } } /** - * @Entity - * @Table(name="`ddc-1719-simple-entity`") + * @ORM\Entity + * @ORM\Table(name="ddc-1719-simple-entity") */ class DDC1719SimpleEntity { /** - * @Id - * @Column(type="integer", name="`simple-entity-id`") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer", name="simple-entity-id") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @Column(type="string", name="`simple-entity-value`") + * @ORM\Column(type="string", name="simple-entity-value") */ public $value; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1734Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1734Test.php deleted file mode 100644 index cfca544ae81..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1734Test.php +++ /dev/null @@ -1,90 +0,0 @@ -useModelSet('cms'); - parent::setUp(); - } - - /** - * This test is DDC-1734 minus the serialization, i.e. it works - * - * @group DDC-1734 - */ - public function testMergeWorksOnNonSerializedProxies() - { - $group = new CmsGroup(); - - $group->setName('Foo'); - $this->_em->persist($group); - $this->_em->flush(); - $this->_em->clear(); - - $proxy = $this->getProxy($group); - - $this->assertInstanceOf(Proxy::class, $proxy); - $this->assertFalse($proxy->__isInitialized()); - - $this->_em->detach($proxy); - $this->_em->clear(); - - $proxy = $this->_em->merge($proxy); - - $this->assertEquals('Foo', $proxy->getName(), 'The entity is broken'); - } - - /** - * This test reproduces DDC-1734 which is: - * - A non-initialized proxy is detached and serialized (the identifier of the proxy is *not* serialized) - * - the object is deserialized and merged (to turn into an entity) - * - the entity is broken because it has no identifier and no field defined - * - * @group DDC-1734 - */ - public function testMergeWorksOnSerializedProxies() - { - $group = new CmsGroup(); - - $group->setName('Foo'); - $this->_em->persist($group); - $this->_em->flush(); - $this->_em->clear(); - - $proxy = $this->getProxy($group); - - $this->assertInstanceOf(Proxy::class, $proxy); - $this->assertFalse($proxy->__isInitialized()); - - $this->_em->detach($proxy); - $serializedProxy = serialize($proxy); - $this->_em->clear(); - - $unserializedProxy = $this->_em->merge(unserialize($serializedProxy)); - $this->assertEquals('Foo', $unserializedProxy->getName(), 'The entity is broken'); - } - - /** - * @param object $object - * - * @return \Doctrine\Common\Proxy\Proxy - */ - private function getProxy($object) - { - $metadataFactory = $this->_em->getMetadataFactory(); - $className = get_class($object); - $identifier = $metadataFactory->getMetadataFor($className)->getIdentifierValues($object); - - return $this->_em->getProxyFactory()->getProxy($className, $identifier); - } - -} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1757Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1757Test.php index 54245368a26..7e31f25dd4d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1757Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1757Test.php @@ -1,14 +1,17 @@ _em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); /* @var $qb \Doctrine\ORM\QueryBuilder */ $qb->select('_a') @@ -28,63 +31,63 @@ public function testFailingCase() } /** - * @Entity + * @ORM\Entity */ class DDC1757A { /** - * @Column(type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") + * @ORM\Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; } /** - * @Entity + * @ORM\Entity */ class DDC1757B { /** - * @Column(type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") + * @ORM\Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** - * @OneToOne(targetEntity="DDC1757C") + * @ORM\OneToOne(targetEntity="DDC1757C") */ private $c; } /** - * @Entity + * @ORM\Entity */ class DDC1757C { /** - * @Column(type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") + * @ORM\Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @OneToOne(targetEntity="DDC1757D") + * @ORM\OneToOne(targetEntity="DDC1757D") */ private $d; } /** - * @Entity + * @ORM\Entity */ class DDC1757D { /** - * @Column(type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") + * @ORM\Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1778Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1778Test.php index 09623f13535..74d0537a65f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1778Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1778Test.php @@ -1,5 +1,7 @@ phone->phonenumber = '0123456789'; $this->user->addPhonenumber($this->phone); - $this->_em->persist($this->user); - $this->_em->persist($this->phone); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($this->user); + $this->em->persist($this->phone); + $this->em->flush(); + $this->em->clear(); - $this->user = $this->_em->find(CmsUser::class, $this->user->getId()); - $this->phone = $this->_em->find(CmsPhonenumber::class, $this->phone->phonenumber); + $this->user = $this->em->find(CmsUser::class, $this->user->getId()); + $this->phone = $this->em->find(CmsPhonenumber::class, $this->phone->phonenumber); } public function testClear() { $clonedNumbers = clone $this->user->getPhonenumbers(); $clonedNumbers->clear(); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $this->user = $this->_em->find(CmsUser::class, $this->user->getId()); + $this->user = $this->em->find(CmsUser::class, $this->user->getId()); - $this->assertCount(1, $this->user->getPhonenumbers()); + self::assertCount(1, $this->user->getPhonenumbers()); } public function testRemove() { $clonedNumbers = clone $this->user->getPhonenumbers(); $clonedNumbers->remove(0); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $this->user = $this->_em->find(CmsUser::class, $this->user->getId()); + $this->user = $this->em->find(CmsUser::class, $this->user->getId()); - $this->assertCount(1, $this->user->getPhonenumbers()); + self::assertCount(1, $this->user->getPhonenumbers()); } public function testRemoveElement() { $clonedNumbers = clone $this->user->getPhonenumbers(); $clonedNumbers->removeElement($this->phone); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $this->user = $this->_em->find(CmsUser::class, $this->user->getId()); + $this->user = $this->em->find(CmsUser::class, $this->user->getId()); - $this->assertCount(1, $this->user->getPhonenumbers()); + self::assertCount(1, $this->user->getPhonenumbers()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1787Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1787Test.php index 17f28658a5d..8b6bad3477a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1787Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1787Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1787Foo::class), - $this->_em->getClassMetadata(DDC1787Bar::class), + $this->em->getClassMetadata(DDC1787Foo::class), + $this->em->getClassMetadata(DDC1787Bar::class), ] ); } @@ -23,29 +27,29 @@ public function testIssue() $bar = new DDC1787Bar; $bar2 = new DDC1787Bar; - $this->_em->persist($bar); - $this->_em->persist($bar2); - $this->_em->flush(); + $this->em->persist($bar); + $this->em->persist($bar2); + $this->em->flush(); - $this->assertSame(1, $bar->getVersion()); + self::assertSame(1, $bar->getVersion()); } } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="discr", type="string") - * @DiscriminatorMap({"bar" = "DDC1787Bar", "foo" = "DDC1787Foo"}) + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="discr", type="string") + * @ORM\DiscriminatorMap({"bar" = "DDC1787Bar", "foo" = "DDC1787Foo"}) */ class DDC1787Foo { /** - * @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** - * @Version @Column(type="integer") + * @ORM\Version @ORM\Column(type="integer") */ private $version; @@ -56,7 +60,7 @@ public function getVersion() } /** - * @Entity + * @ORM\Entity */ class DDC1787Bar extends DDC1787Foo { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1843Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1843Test.php index 4273a36b6af..b83e96653b0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1843Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1843Test.php @@ -1,5 +1,7 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(User::class), - $this->_em->getClassMetadata(Group::class), - $this->_em->getClassMetadata(Phone::class), - $this->_em->getClassMetadata(Address::class), + $this->em->getClassMetadata(User::class), + $this->em->getClassMetadata(Group::class), + $this->em->getClassMetadata(Phone::class), + $this->em->getClassMetadata(Address::class), ] ); } catch(\Exception $e) { @@ -37,18 +38,18 @@ public function testCreateRetrieveUpdateDelete() $e1 = new Group('Parent Bar 1'); $e2 = new Group('Parent Foo 2'); - $this->_em->persist($e1); - $this->_em->persist($e2); - $this->_em->flush(); + $this->em->persist($e1); + $this->em->persist($e2); + $this->em->flush(); $e3 = new Group('Bar 3', $e1); $e4 = new Group('Foo 4', $e2); // Create - $this->_em->persist($e3); - $this->_em->persist($e4); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($e3); + $this->em->persist($e4); + $this->em->flush(); + $this->em->clear(); $e1Id = $e1->id; $e2Id = $e2->id; @@ -56,26 +57,26 @@ public function testCreateRetrieveUpdateDelete() $e4Id = $e4->id; // Retrieve - $e1 = $this->_em->find(Group::class, $e1Id); - $e2 = $this->_em->find(Group::class, $e2Id); - $e3 = $this->_em->find(Group::class, $e3Id); - $e4 = $this->_em->find(Group::class, $e4Id); + $e1 = $this->em->find(Group::class, $e1Id); + $e2 = $this->em->find(Group::class, $e2Id); + $e3 = $this->em->find(Group::class, $e3Id); + $e4 = $this->em->find(Group::class, $e4Id); - $this->assertInstanceOf(Group::class, $e1); - $this->assertInstanceOf(Group::class, $e2); - $this->assertInstanceOf(Group::class, $e3); - $this->assertInstanceOf(Group::class, $e4); + self::assertInstanceOf(Group::class, $e1); + self::assertInstanceOf(Group::class, $e2); + self::assertInstanceOf(Group::class, $e3); + self::assertInstanceOf(Group::class, $e4); - $this->assertEquals($e1Id, $e1->id); - $this->assertEquals($e2Id, $e2->id); - $this->assertEquals($e3Id, $e3->id); - $this->assertEquals($e4Id, $e4->id); + self::assertEquals($e1Id, $e1->id); + self::assertEquals($e2Id, $e2->id); + self::assertEquals($e3Id, $e3->id); + self::assertEquals($e4Id, $e4->id); - $this->assertEquals('Parent Bar 1', $e1->name); - $this->assertEquals('Parent Foo 2', $e2->name); - $this->assertEquals('Bar 3', $e3->name); - $this->assertEquals('Foo 4', $e4->name); + self::assertEquals('Parent Bar 1', $e1->name); + self::assertEquals('Parent Foo 2', $e2->name); + self::assertEquals('Bar 3', $e3->name); + self::assertEquals('Foo 4', $e4->name); $e1->name = 'Parent Bar 11'; $e2->name = 'Parent Foo 22'; @@ -83,57 +84,57 @@ public function testCreateRetrieveUpdateDelete() $e4->name = 'Foo 44'; // Update - $this->_em->persist($e1); - $this->_em->persist($e2); - $this->_em->persist($e3); - $this->_em->persist($e4); - $this->_em->flush(); - - $this->assertEquals('Parent Bar 11', $e1->name); - $this->assertEquals('Parent Foo 22', $e2->name); - $this->assertEquals('Bar 33', $e3->name); - $this->assertEquals('Foo 44', $e4->name); - - $this->assertInstanceOf(Group::class, $e1); - $this->assertInstanceOf(Group::class, $e2); - $this->assertInstanceOf(Group::class, $e3); - $this->assertInstanceOf(Group::class, $e4); - - $this->assertEquals($e1Id, $e1->id); - $this->assertEquals($e2Id, $e2->id); - $this->assertEquals($e3Id, $e3->id); - $this->assertEquals($e4Id, $e4->id); - - $this->assertEquals('Parent Bar 11', $e1->name); - $this->assertEquals('Parent Foo 22', $e2->name); - $this->assertEquals('Bar 33', $e3->name); - $this->assertEquals('Foo 44', $e4->name); + $this->em->persist($e1); + $this->em->persist($e2); + $this->em->persist($e3); + $this->em->persist($e4); + $this->em->flush(); + + self::assertEquals('Parent Bar 11', $e1->name); + self::assertEquals('Parent Foo 22', $e2->name); + self::assertEquals('Bar 33', $e3->name); + self::assertEquals('Foo 44', $e4->name); + + self::assertInstanceOf(Group::class, $e1); + self::assertInstanceOf(Group::class, $e2); + self::assertInstanceOf(Group::class, $e3); + self::assertInstanceOf(Group::class, $e4); + + self::assertEquals($e1Id, $e1->id); + self::assertEquals($e2Id, $e2->id); + self::assertEquals($e3Id, $e3->id); + self::assertEquals($e4Id, $e4->id); + + self::assertEquals('Parent Bar 11', $e1->name); + self::assertEquals('Parent Foo 22', $e2->name); + self::assertEquals('Bar 33', $e3->name); + self::assertEquals('Foo 44', $e4->name); // Delete - $this->_em->remove($e4); - $this->_em->remove($e3); - $this->_em->remove($e2); - $this->_em->remove($e1); + $this->em->remove($e4); + $this->em->remove($e3); + $this->em->remove($e2); + $this->em->remove($e1); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $this->assertInstanceOf(Group::class, $e1); - $this->assertInstanceOf(Group::class, $e2); - $this->assertInstanceOf(Group::class, $e3); - $this->assertInstanceOf(Group::class, $e4); + self::assertInstanceOf(Group::class, $e1); + self::assertInstanceOf(Group::class, $e2); + self::assertInstanceOf(Group::class, $e3); + self::assertInstanceOf(Group::class, $e4); // Retrieve - $e1 = $this->_em->find(Group::class, $e1Id); - $e2 = $this->_em->find(Group::class, $e2Id); - $e3 = $this->_em->find(Group::class, $e3Id); - $e4 = $this->_em->find(Group::class, $e4Id); - - $this->assertNull($e1); - $this->assertNull($e2); - $this->assertNull($e3); - $this->assertNull($e4); + $e1 = $this->em->find(Group::class, $e1Id); + $e2 = $this->em->find(Group::class, $e2Id); + $e3 = $this->em->find(Group::class, $e3Id); + $e4 = $this->em->find(Group::class, $e4Id); + + self::assertNull($e1); + self::assertNull($e2); + self::assertNull($e3); + self::assertNull($e4); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1884Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1884Test.php index 938459ad465..b5dfc981236 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1884Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1884Test.php @@ -1,4 +1,6 @@ createCars(Car::class); list($john, $foo) = $this->createDrivers(Driver::class); - $this->_em->flush(); + $this->em->flush(); $ride1 = new Ride($john, $bimmer); $ride2 = new Ride($john, $merc); $ride3 = new Ride($john, $volvo); $ride4 = new Ride($foo, $merc); - $this->_em->persist($ride1); - $this->_em->persist($ride2); - $this->_em->persist($ride3); - $this->_em->persist($ride4); + $this->em->persist($ride1); + $this->em->persist($ride2); + $this->em->persist($ride3); + $this->em->persist($ride4); $ride5 = new PaidRide($john, $bimmer); $ride5->setFare(10.50); @@ -43,12 +45,12 @@ protected function setUp() $ride8 = new PaidRide($foo, $merc); $ride8->setFare(32.15); - $this->_em->persist($ride5); - $this->_em->persist($ride6); - $this->_em->persist($ride7); - $this->_em->persist($ride8); + $this->em->persist($ride5); + $this->em->persist($ride6); + $this->em->persist($ride7); + $this->em->persist($ride8); - $this->_em->flush(); + $this->em->flush(); } private function createCars($class) @@ -69,10 +71,10 @@ private function createCars($class) $volvo->setBrand('Volvo'); $volvo->setModel('XC90'); - $this->_em->persist($bimmer); - $this->_em->persist($crysler); - $this->_em->persist($merc); - $this->_em->persist($volvo); + $this->em->persist($bimmer); + $this->em->persist($crysler); + $this->em->persist($merc); + $this->em->persist($volvo); return [$bimmer, $crysler, $merc, $volvo]; } @@ -85,8 +87,8 @@ private function createDrivers($class) $foo = new $class; $foo->setName('Foo Bar'); - $this->_em->persist($foo); - $this->_em->persist($john); + $this->em->persist($foo); + $this->em->persist($john); return [$john, $foo]; } @@ -97,7 +99,7 @@ private function createDrivers($class) */ public function testSelectFromInverseSideWithCompositePkAndSolelyIdentifierColumnsUsingFetchJoins() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $result = $qb->select('d, dr, c') ->from(Driver::class, 'd') @@ -108,9 +110,9 @@ public function testSelectFromInverseSideWithCompositePkAndSolelyIdentifierColum ->getQuery() ->getArrayResult(); - $this->assertCount(1, $result); - $this->assertArrayHasKey('freeDriverRides', $result[0]); - $this->assertCount(3, $result[0]['freeDriverRides']); + self::assertCount(1, $result); + self::assertArrayHasKey('freeDriverRides', $result[0]); + self::assertCount(3, $result[0]['freeDriverRides']); } /** @@ -119,7 +121,7 @@ public function testSelectFromInverseSideWithCompositePkAndSolelyIdentifierColum */ public function testSelectFromInverseSideWithCompositePkUsingFetchJoins() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $result = $qb->select('d, dr, c') ->from(Driver::class, 'd') @@ -129,9 +131,9 @@ public function testSelectFromInverseSideWithCompositePkUsingFetchJoins() ->setParameter(1, 'John Doe') ->getQuery()->getArrayResult(); - $this->assertCount(1, $result); - $this->assertArrayHasKey('driverRides', $result[0]); - $this->assertCount(3, $result[0]['driverRides']); + self::assertCount(1, $result); + self::assertArrayHasKey('driverRides', $result[0]); + self::assertCount(3, $result[0]['driverRides']); } /** @@ -139,7 +141,7 @@ public function testSelectFromInverseSideWithCompositePkUsingFetchJoins() */ public function testSelectFromOwningSideUsingFetchJoins() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $result = $qb->select('r, d, c') ->from(PaidRide::class, 'r') @@ -149,8 +151,8 @@ public function testSelectFromOwningSideUsingFetchJoins() ->setParameter(1, 'John Doe') ->getQuery()->getArrayResult(); - $this->assertCount(3, $result); - $this->assertArrayHasKey('driver', $result[0]); - $this->assertArrayHasKey('car', $result[0]); + self::assertCount(3, $result); + self::assertArrayHasKey('driver', $result[0]); + self::assertArrayHasKey('car', $result[0]); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1885Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1885Test.php index 283340b820a..af0553c7bdb 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1885Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1885Test.php @@ -1,5 +1,7 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(User::class), - $this->_em->getClassMetadata(Group::class), - $this->_em->getClassMetadata(Address::class), + $this->em->getClassMetadata(User::class), + $this->em->getClassMetadata(Group::class), + $this->em->getClassMetadata(Address::class), ] ); } catch(\Exception $e) { @@ -41,9 +42,9 @@ protected function setUp() $this->user = $user; // Create - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); } @@ -58,117 +59,117 @@ public function testCreateRetrieveUpdateDelete() $g2Id = $g2->id; // Retrieve - $user = $this->_em->find(User::class, $u1Id); + $user = $this->em->find(User::class, $u1Id); - $this->assertInstanceOf(User::class, $user); - $this->assertEquals('FabioBatSilva', $user->name); - $this->assertEquals($u1Id, $user->id); + self::assertInstanceOf(User::class, $user); + self::assertEquals('FabioBatSilva', $user->name); + self::assertEquals($u1Id, $user->id); - $this->assertCount(2, $user->groups); + self::assertCount(2, $user->groups); $g1 = $user->getGroups()->get(0); $g2 = $user->getGroups()->get(1); - $this->assertInstanceOf(Group::class, $g1); - $this->assertInstanceOf(Group::class, $g2); + self::assertInstanceOf(Group::class, $g1); + self::assertInstanceOf(Group::class, $g2); $g1->name = 'Bar 11'; $g2->name = 'Foo 22'; // Update - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $user = $this->_em->find(User::class, $u1Id); + $user = $this->em->find(User::class, $u1Id); - $this->assertInstanceOf(User::class, $user); - $this->assertEquals('FabioBatSilva', $user->name); - $this->assertEquals($u1Id, $user->id); + self::assertInstanceOf(User::class, $user); + self::assertEquals('FabioBatSilva', $user->name); + self::assertEquals($u1Id, $user->id); // Delete - $this->_em->remove($user); + $this->em->remove($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $this->assertNull($this->_em->find(User::class, $u1Id)); - $this->assertNull($this->_em->find(Group::class, $g1Id)); - $this->assertNull($this->_em->find(Group::class, $g2Id)); + self::assertNull($this->em->find(User::class, $u1Id)); + self::assertNull($this->em->find(Group::class, $g1Id)); + self::assertNull($this->em->find(Group::class, $g2Id)); } public function testRemoveItem() { $user = $this->user; $u1Id = $user->id; - $user = $this->_em->find(User::class, $u1Id); + $user = $this->em->find(User::class, $u1Id); - $this->assertInstanceOf(User::class, $user); - $this->assertEquals('FabioBatSilva', $user->name); - $this->assertEquals($u1Id, $user->id); + self::assertInstanceOf(User::class, $user); + self::assertEquals('FabioBatSilva', $user->name); + self::assertEquals($u1Id, $user->id); - $this->assertCount(2, $user->groups); - $this->assertInstanceOf(Group::class, $user->getGroups()->get(0)); - $this->assertInstanceOf(Group::class, $user->getGroups()->get(1)); + self::assertCount(2, $user->groups); + self::assertInstanceOf(Group::class, $user->getGroups()->get(0)); + self::assertInstanceOf(Group::class, $user->getGroups()->get(1)); $user->getGroups()->remove(0); // Update - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $user = $this->_em->find(User::class, $u1Id); + $user = $this->em->find(User::class, $u1Id); - $this->assertInstanceOf(User::class, $user); - $this->assertEquals('FabioBatSilva', $user->name); - $this->assertEquals($u1Id, $user->id); + self::assertInstanceOf(User::class, $user); + self::assertEquals('FabioBatSilva', $user->name); + self::assertEquals($u1Id, $user->id); - $this->assertCount(1, $user->getGroups()); + self::assertCount(1, $user->getGroups()); } public function testClearAll() { $user = $this->user; $u1Id = $user->id; - $user = $this->_em->find(User::class, $u1Id); + $user = $this->em->find(User::class, $u1Id); - $this->assertInstanceOf(User::class, $user); - $this->assertEquals('FabioBatSilva', $user->name); - $this->assertEquals($u1Id, $user->id); + self::assertInstanceOf(User::class, $user); + self::assertEquals('FabioBatSilva', $user->name); + self::assertEquals($u1Id, $user->id); - $this->assertCount(2, $user->groups); - $this->assertInstanceOf(Group::class, $user->getGroups()->get(0)); - $this->assertInstanceOf(Group::class, $user->getGroups()->get(1)); + self::assertCount(2, $user->groups); + self::assertInstanceOf(Group::class, $user->getGroups()->get(0)); + self::assertInstanceOf(Group::class, $user->getGroups()->get(1)); $user->getGroups()->clear(); // Update - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $user = $this->_em->find(User::class, $u1Id); + $user = $this->em->find(User::class, $u1Id); - $this->assertInstanceOf(User::class, $user); - $this->assertEquals('FabioBatSilva', $user->name); - $this->assertEquals($u1Id, $user->id); + self::assertInstanceOf(User::class, $user); + self::assertEquals('FabioBatSilva', $user->name); + self::assertEquals($u1Id, $user->id); - $this->assertCount(0, $user->getGroups()); + self::assertCount(0, $user->getGroups()); } public function testCountExtraLazy() { $user = $this->user; $u1Id = $user->id; - $user = $this->_em->find(User::class, $u1Id); + $user = $this->em->find(User::class, $u1Id); - $this->assertInstanceOf(User::class, $user); - $this->assertEquals('FabioBatSilva', $user->name); - $this->assertEquals($u1Id, $user->id); + self::assertInstanceOf(User::class, $user); + self::assertEquals('FabioBatSilva', $user->name); + self::assertEquals($u1Id, $user->id); - $this->assertCount(2, $user->groups); - $this->assertInstanceOf(Group::class, $user->getGroups()->get(0)); - $this->assertInstanceOf(Group::class, $user->getGroups()->get(1)); + self::assertCount(2, $user->groups); + self::assertInstanceOf(Group::class, $user->getGroups()->get(0)); + self::assertInstanceOf(Group::class, $user->getGroups()->get(1)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1918Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1918Test.php index 4b0c7eb9151..ee099e611d7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1918Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1918Test.php @@ -1,5 +1,7 @@ name = "test"; - $this->_em->persist($group); + $this->em->persist($group); $groups[] = $group; } @@ -35,28 +37,28 @@ public function testLastPageCorrect() $user->status = "active"; $user->groups = $groups; - $this->_em->persist($user); + $this->em->persist($user); } - $this->_em->flush(); + $this->em->flush(); - $query = $this->_em->createQuery('SELECT u, g FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g'); + $query = $this->em->createQuery('SELECT u, g FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g'); $query->setFirstResult(6); $query->setMaxResults(3); $paginator = new Paginator($query, true); - $this->assertEquals(3, count(iterator_to_array($paginator))); + self::assertEquals(3, count(iterator_to_array($paginator))); $query->setFirstResult(8); $query->setMaxResults(3); $paginator = new Paginator($query, true); - $this->assertEquals(2, count(iterator_to_array($paginator))); + self::assertEquals(2, count(iterator_to_array($paginator))); $query->setFirstResult(10); $query->setMaxResults(3); $paginator = new Paginator($query, true); - $this->assertEquals(0, count(iterator_to_array($paginator))); + self::assertEquals(0, count(iterator_to_array($paginator))); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1925Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1925Test.php index ef7d6014bf6..98c0f4f72df 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1925Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1925Test.php @@ -1,8 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1925User::class), - $this->_em->getClassMetadata(DDC1925Product::class), + $this->em->getClassMetadata(DDC1925User::class), + $this->em->getClassMetadata(DDC1925Product::class), ] ); @@ -25,54 +28,54 @@ public function testIssue() $product = new DDC1925Product(); $product->setTitle("Test product"); - $this->_em->persist($user); - $this->_em->persist($product); - $this->_em->flush(); + $this->em->persist($user); + $this->em->persist($product); + $this->em->flush(); $product->addBuyer($user); - $this->_em->getUnitOfWork() + $this->em->getUnitOfWork() ->computeChangeSets(); - $this->_em->persist($product); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($product); + $this->em->flush(); + $this->em->clear(); /** @var DDC1925Product $persistedProduct */ - $persistedProduct = $this->_em->find(DDC1925Product::class, $product->getId()); + $persistedProduct = $this->em->find(DDC1925Product::class, $product->getId()); self::assertEquals($user, $persistedProduct->getBuyers()->first()); } } /** - * @Table - * @Entity + * @ORM\Table + * @ORM\Entity */ class DDC1925Product { /** * @var int $id * - * @Column(name="id", type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") + * @ORM\Column(name="id", type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string $title * - * @Column(name="title", type="string", length=255) + * @ORM\Column(name="title", type="string", length=255) */ private $title; /** - * @ManyToMany(targetEntity="DDC1925User") - * @JoinTable( + * @ORM\ManyToMany(targetEntity="DDC1925User") + * @ORM\JoinTable( * name="user_purchases", - * joinColumns={@JoinColumn(name="product_id", referencedColumnName="id")}, - * inverseJoinColumns={@JoinColumn(name="user_id", referencedColumnName="id")} + * joinColumns={@ORM\JoinColumn(name="product_id", referencedColumnName="id")}, + * inverseJoinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")} * ) */ private $buyers; @@ -129,24 +132,24 @@ public function addBuyer(DDC1925User $buyer) } /** - * @Table - * @Entity + * @ORM\Table + * @ORM\Entity */ class DDC1925User { /** * @var int * - * @Column(name="id", type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") + * @ORM\Column(name="id", type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * - * @Column(name="title", type="string", length=255) + * @ORM\Column(name="title", type="string", length=255) */ private $title; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC192Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC192Test.php index 532e0edfeb4..ab97ed27516 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC192Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC192Test.php @@ -1,8 +1,11 @@ _em->getClassMetadata(DDC192User::class), - $this->_em->getClassMetadata(DDC192Phonenumber::class), + $this->em->getClassMetadata(DDC192User::class), + $this->em->getClassMetadata(DDC192Phonenumber::class), ]; - $this->_schemaTool->createSchema($classes); + $this->schemaTool->createSchema($classes); - $tables = $this->_em->getConnection() + $tables = $this->em->getConnection() ->getSchemaManager() ->listTableNames(); @@ -31,45 +34,43 @@ public function testSchemaCreation() } /** - * @Entity - * @Table(name="ddc192_users") + * @ORM\Entity + * @ORM\Table(name="ddc192_users") */ class DDC192User { /** - * @Id - * @Column(name="id", type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @Column(name="name", type="string") + * @ORM\Column(name="name", type="string") */ public $name; } /** - * @Entity - * @Table(name="ddc192_phonenumbers") + * @ORM\Entity @ORM\Table(name="ddc192_phonenumbers") */ class DDC192Phonenumber { /** - * @Id - * @Column(name="phone", type="string", length=40) + * @ORM\Id + * @ORM\Column(name="phone", type="string", length=40) */ protected $phone; /** - * @Id - * @ManyToOne(targetEntity="DDC192User") - * @JoinColumn(name="userId", referencedColumnName="id") + * @ORM\Id + * @ORM\ManyToOne(targetEntity="DDC192User") + * @ORM\JoinColumn(name="userId", referencedColumnName="id") */ protected $User; - public function setPhone($value) { $this->phone = $value; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1995Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1995Test.php index fb32b99fe51..365fc1a960e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1995Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1995Test.php @@ -1,5 +1,7 @@ setDepartment('bar'); $employee->setSalary(1000); - $this->_em->persist($person); - $this->_em->persist($employee); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($person); + $this->em->persist($employee); + $this->em->flush(); + $this->em->clear(); $dql = 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF ?1'; - $class = $this->_em->getClassMetadata(CompanyEmployee::class); + $class = $this->em->getClassMetadata(CompanyEmployee::class); - $result = $this->_em->createQuery($dql) + $result = $this->em->createQuery($dql) ->setParameter(1, $class) ->getResult(); - $this->assertCount(1, $result); - $this->assertInstanceOf(CompanyEmployee::class, $result[0]); + self::assertCount(1, $result); + self::assertInstanceOf(CompanyEmployee::class, $result[0]); } public function testQueryCache() @@ -52,30 +54,30 @@ public function testQueryCache() $employee->setDepartment('bar'); $employee->setSalary(1000); - $this->_em->persist($person); - $this->_em->persist($employee); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($person); + $this->em->persist($employee); + $this->em->flush(); + $this->em->clear(); $dql = 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF :type'; - $class1 = $this->_em->getClassMetadata(CompanyEmployee::class); - $class2 = $this->_em->getClassMetadata(CompanyPerson::class); + $class1 = $this->em->getClassMetadata(CompanyEmployee::class); + $class2 = $this->em->getClassMetadata(CompanyPerson::class); - $result1 = $this->_em->createQuery($dql) + $result1 = $this->em->createQuery($dql) ->setParameter('type', $class1) ->useQueryCache(true) ->getResult(); - $result2 = $this->_em->createQuery($dql) + $result2 = $this->em->createQuery($dql) ->setParameter('type', $class2) ->useQueryCache(true) ->getResult(); - $this->assertCount(1, $result1); - $this->assertCount(1, $result2); + self::assertCount(1, $result1); + self::assertCount(1, $result2); - $this->assertInstanceOf(CompanyEmployee::class, $result1[0]); - $this->assertInstanceOf(CompanyPerson::class, $result2[0]); - $this->assertNotInstanceOf(CompanyEmployee::class, $result2[0]); + self::assertInstanceOf(CompanyEmployee::class, $result1[0]); + self::assertInstanceOf(CompanyPerson::class, $result2[0]); + self::assertNotInstanceOf(CompanyEmployee::class, $result2[0]); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1998Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1998Test.php index 74ea2fd8889..b94fce87070 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1998Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1998Test.php @@ -1,10 +1,13 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC1998Entity::class), + $this->em->getClassMetadata(DDC1998Entity::class), ] ); $entity = new DDC1998Entity(); $entity->id = new DDC1998Id("foo"); - $this->_em->persist($entity); - $this->_em->flush(); + $this->em->persist($entity); + $this->em->flush(); $entity->num++; - $this->_em->flush(); + $this->em->flush(); - $this->_em->remove($entity); - $this->_em->flush(); - $this->_em->clear(); + $this->em->remove($entity); + $this->em->flush(); + $this->em->clear(); - $found = $this->_em->find(DDC1998Entity::class, $entity->id); - $this->assertNull($found); + $found = $this->em->find(DDC1998Entity::class, $entity->id); + self::assertNull($found); - $found = $this->_em->find(DDC1998Entity::class, "foo"); - $this->assertNull($found); + $found = $this->em->find(DDC1998Entity::class, "foo"); + self::assertNull($found); - $this->assertEquals(0, count($this->_em->getRepository(DDC1998Entity::class)->findAll())); + self::assertEquals(0, count($this->em->getRepository(DDC1998Entity::class)->findAll())); } } /** - * @Entity + * @ORM\Entity */ class DDC1998Entity { /** - * @Id @Column(type="ddc1998") + * @ORM\Id @ORM\Column(type="ddc1998") */ public $id; /** - * @Column(type="integer") + * @ORM\Column(type="integer") */ public $num = 0; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC199Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC199Test.php index 2fb3acd33bd..8cd0538beeb 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC199Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC199Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC199ParentClass::class), - $this->_em->getClassMetadata(DDC199ChildClass::class), - $this->_em->getClassMetadata(DDC199RelatedClass::class) + $this->em->getClassMetadata(DDC199ParentClass::class), + $this->em->getClassMetadata(DDC199ChildClass::class), + $this->em->getClassMetadata(DDC199RelatedClass::class) ] ); } @@ -23,80 +26,80 @@ public function testPolymorphicLoading() $child = new DDC199ChildClass; $child->parentData = 'parentData'; $child->childData = 'childData'; - $this->_em->persist($child); + $this->em->persist($child); $related1 = new DDC199RelatedClass; $related1->relatedData = 'related1'; $related1->parent = $child; - $this->_em->persist($related1); + $this->em->persist($related1); $related2 = new DDC199RelatedClass; $related2->relatedData = 'related2'; $related2->parent = $child; - $this->_em->persist($related2); + $this->em->persist($related2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery('select e,r from Doctrine\Tests\ORM\Functional\Ticket\DDC199ParentClass e join e.relatedEntities r'); + $query = $this->em->createQuery('select e,r from Doctrine\Tests\ORM\Functional\Ticket\DDC199ParentClass e join e.relatedEntities r'); $result = $query->getResult(); - $this->assertEquals(1, count($result)); - $this->assertInstanceOf(DDC199ParentClass::class, $result[0]); - $this->assertTrue($result[0]->relatedEntities->isInitialized()); - $this->assertEquals(2, $result[0]->relatedEntities->count()); - $this->assertInstanceOf(DDC199RelatedClass::class, $result[0]->relatedEntities[0]); - $this->assertInstanceOf(DDC199RelatedClass::class, $result[0]->relatedEntities[1]); + self::assertEquals(1, count($result)); + self::assertInstanceOf(DDC199ParentClass::class, $result[0]); + self::assertTrue($result[0]->relatedEntities->isInitialized()); + self::assertEquals(2, $result[0]->relatedEntities->count()); + self::assertInstanceOf(DDC199RelatedClass::class, $result[0]->relatedEntities[0]); + self::assertInstanceOf(DDC199RelatedClass::class, $result[0]->relatedEntities[1]); } } /** - * @Entity @Table(name="ddc199_entities") - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorColumn(name="discr", type="string") - * @DiscriminatorMap({"parent" = "DDC199ParentClass", "child" = "DDC199ChildClass"}) + * @ORM\Entity @ORM\Table(name="ddc199_entities") + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorColumn(name="discr", type="string") + * @ORM\DiscriminatorMap({"parent" = "DDC199ParentClass", "child" = "DDC199ChildClass"}) */ class DDC199ParentClass { /** - * @Id @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $parentData; /** - * @OneToMany(targetEntity="DDC199RelatedClass", mappedBy="parent") + * @ORM\OneToMany(targetEntity="DDC199RelatedClass", mappedBy="parent") */ public $relatedEntities; } -/** @Entity */ +/** @ORM\Entity */ class DDC199ChildClass extends DDC199ParentClass { /** - * @Column + * @ORM\Column */ public $childData; } -/** @Entity @Table(name="ddc199_relatedclass") */ +/** @ORM\Entity @ORM\Table(name="ddc199_relatedclass") */ class DDC199RelatedClass { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @Column */ + /** @ORM\Column */ public $relatedData; /** - * @ManyToOne(targetEntity="DDC199ParentClass", inversedBy="relatedEntities") - * @JoinColumn(name="parent_id", referencedColumnName="id") + * @ORM\ManyToOne(targetEntity="DDC199ParentClass", inversedBy="relatedEntities") + * @ORM\JoinColumn(name="parent_id", referencedColumnName="id") */ public $parent; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2012Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2012Test.php index 3882408081e..917a02548f3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2012Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2012Test.php @@ -1,9 +1,12 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2012Item::class), - $this->_em->getClassMetadata(DDC2012ItemPerson::class), + $this->em->getClassMetadata(DDC2012Item::class), + $this->em->getClassMetadata(DDC2012ItemPerson::class), ] ); } @@ -32,47 +35,47 @@ public function testIssue() $item = new DDC2012ItemPerson(); $item->tsv = ['word1', 'word2', 'word3']; - $this->_em->persist($item); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($item); + $this->em->flush(); + $this->em->clear(); - $item = $this->_em->find(get_class($item), $item->id); + $item = $this->em->find(get_class($item), $item->id); - $this->assertArrayHasKey('convertToDatabaseValueSQL', DDC2012TsVectorType::$calls); - $this->assertArrayHasKey('convertToDatabaseValue', DDC2012TsVectorType::$calls); - $this->assertArrayHasKey('convertToPHPValue', DDC2012TsVectorType::$calls); + self::assertArrayHasKey('convertToDatabaseValueSQL', DDC2012TsVectorType::$calls); + self::assertArrayHasKey('convertToDatabaseValue', DDC2012TsVectorType::$calls); + self::assertArrayHasKey('convertToPHPValue', DDC2012TsVectorType::$calls); - $this->assertCount(1, DDC2012TsVectorType::$calls['convertToDatabaseValueSQL']); - $this->assertCount(1, DDC2012TsVectorType::$calls['convertToDatabaseValue']); - $this->assertCount(1, DDC2012TsVectorType::$calls['convertToPHPValue']); + self::assertCount(1, DDC2012TsVectorType::$calls['convertToDatabaseValueSQL']); + self::assertCount(1, DDC2012TsVectorType::$calls['convertToDatabaseValue']); + self::assertCount(1, DDC2012TsVectorType::$calls['convertToPHPValue']); - $this->assertInstanceOf(DDC2012Item::class, $item); - $this->assertEquals(['word1', 'word2', 'word3'], $item->tsv); + self::assertInstanceOf(DDC2012Item::class, $item); + self::assertEquals(['word1', 'word2', 'word3'], $item->tsv); $item->tsv = ['word1', 'word2']; - $this->_em->persist($item); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($item); + $this->em->flush(); + $this->em->clear(); - $item = $this->_em->find(get_class($item), $item->id); + $item = $this->em->find(get_class($item), $item->id); - $this->assertCount(2, DDC2012TsVectorType::$calls['convertToDatabaseValueSQL']); - $this->assertCount(2, DDC2012TsVectorType::$calls['convertToDatabaseValue']); - $this->assertCount(2, DDC2012TsVectorType::$calls['convertToPHPValue']); + self::assertCount(2, DDC2012TsVectorType::$calls['convertToDatabaseValueSQL']); + self::assertCount(2, DDC2012TsVectorType::$calls['convertToDatabaseValue']); + self::assertCount(2, DDC2012TsVectorType::$calls['convertToPHPValue']); - $this->assertInstanceOf(DDC2012Item::class, $item); - $this->assertEquals(['word1', 'word2'], $item->tsv); + self::assertInstanceOf(DDC2012Item::class, $item); + self::assertEquals(['word1', 'word2'], $item->tsv); } } /** - * @Table(name="ddc2010_item") - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="type_id", type="smallint") - * @DiscriminatorMap({ + * @ORM\Table(name="ddc2010_item") + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="type_id", type="smallint") + * @ORM\DiscriminatorMap({ * 1 = "DDC2012ItemPerson", * 2 = "DDC2012Item" * }) @@ -80,21 +83,21 @@ public function testIssue() class DDC2012Item { /** - * @Id - * @GeneratedValue - * @Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue + * @ORM\Column(type="integer") */ public $id; /** - * @Column(name="tsv", type="tsvector", nullable=true) + * @ORM\Column(name="tsv", type="tsvector", nullable=true) */ public $tsv; } /** - * @Table(name="ddc2010_item_person") - * @Entity + * @ORM\Table(name="ddc2010_item_person") + * @ORM\Entity */ class DDC2012ItemPerson extends DDC2012Item { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2074Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2074Test.php index ed77ba13468..65c4c76d896 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2074Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2074Test.php @@ -1,5 +1,7 @@ _em->getClassMetadata(ECommerceProduct::class); + $class = $this->em->getClassMetadata(ECommerceProduct::class); $product = new ECommerceProduct(); $category = new ECommerceCategory(); - $collection = new PersistentCollection($this->_em, $class, new ArrayCollection([$category])); - $collection->setOwner($product, $class->associationMappings['categories']); + $collection = new PersistentCollection($this->em, $class, new ArrayCollection([$category])); + $collection->setOwner($product, $class->getProperty('categories')); - $uow = $this->_em->getUnitOfWork(); + $uow = $this->em->getUnitOfWork(); $clonedCollection = clone $collection; $clonedCollection->clear(); - $this->assertEquals(0, count($uow->getScheduledCollectionDeletions())); + self::assertEquals(0, count($uow->getScheduledCollectionDeletions())); } public function testSavingClonedPersistentCollection() @@ -40,22 +42,22 @@ public function testSavingClonedPersistentCollection() $category->setName('foo'); $product->addCategory($category); - $this->_em->persist($product); - $this->_em->persist($category); - $this->_em->flush(); + $this->em->persist($product); + $this->em->persist($category); + $this->em->flush(); $newProduct = clone $product; - $this->_em->persist($newProduct); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($newProduct); + $this->em->flush(); + $this->em->clear(); - $product1 = $this->_em->find(ECommerceProduct::class, $product->getId()); - $product2 = $this->_em->find(ECommerceProduct::class, $newProduct->getId()); + $product1 = $this->em->find(ECommerceProduct::class, $product->getId()); + $product2 = $this->em->find(ECommerceProduct::class, $newProduct->getId()); - $this->assertCount(1, $product1->getCategories()); - $this->assertCount(1, $product2->getCategories()); + self::assertCount(1, $product1->getCategories()); + self::assertCount(1, $product2->getCategories()); - $this->assertSame($product1->getCategories()->get(0), $product2->getCategories()->get(0)); + self::assertSame($product1->getCategories()->get(0), $product2->getCategories()->get(0)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2084Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2084Test.php index eadbc1caf9d..8d0ee54a9a0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2084Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2084Test.php @@ -1,5 +1,7 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2084\MyEntity1'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2084\MyEntity2'), + $this->em->getClassMetadata(__NAMESPACE__ . '\DDC2084\MyEntity1'), + $this->em->getClassMetadata(__NAMESPACE__ . '\DDC2084\MyEntity2'), ] ); } catch (\Exception $exc) { @@ -27,13 +29,13 @@ public function loadFixture() $e2 = new DDC2084\MyEntity2('Foo'); $e1 = new DDC2084\MyEntity1($e2); - $this->_em->persist($e2); - $this->_em->flush(); + $this->em->persist($e2); + $this->em->flush(); - $this->_em->persist($e1); - $this->_em->flush(); + $this->em->persist($e1); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); return $e1; } @@ -42,11 +44,11 @@ public function testIssue() { $e1 = $this->loadFixture(); $e2 = $e1->getMyEntity2(); - $e = $this->_em->find(__NAMESPACE__ . '\DDC2084\MyEntity1', $e2); + $e = $this->em->find(__NAMESPACE__ . '\DDC2084\MyEntity1', $e2); - $this->assertInstanceOf(__NAMESPACE__ . '\DDC2084\MyEntity1', $e); - $this->assertInstanceOf(__NAMESPACE__ . '\DDC2084\MyEntity2', $e->getMyEntity2()); - $this->assertEquals('Foo', $e->getMyEntity2()->getValue()); + self::assertInstanceOf(__NAMESPACE__ . '\DDC2084\MyEntity1', $e); + self::assertInstanceOf(__NAMESPACE__ . '\DDC2084\MyEntity2', $e->getMyEntity2()); + self::assertEquals('Foo', $e->getMyEntity2()->getValue()); } /** @@ -55,22 +57,24 @@ public function testIssue() */ public function testinvalidIdentifierBindingEntityException() { - $this->_em->find(__NAMESPACE__ . '\DDC2084\MyEntity1', new DDC2084\MyEntity2('Foo')); + $this->em->find(__NAMESPACE__ . '\DDC2084\MyEntity1', new DDC2084\MyEntity2('Foo')); } } namespace Doctrine\Tests\ORM\Functional\Ticket\DDC2084; +use Doctrine\ORM\Annotation as ORM; + /** - * @Entity - * @Table(name="DDC2084_ENTITY1") + * @ORM\Entity + * @ORM\Table(name="DDC2084_ENTITY1") */ class MyEntity1 { /** - * @Id - * @OneToOne(targetEntity="MyEntity2") - * @JoinColumn(name="entity2_id", referencedColumnName="id", nullable=false) + * @ORM\Id + * @ORM\OneToOne(targetEntity="MyEntity2") + * @ORM\JoinColumn(name="entity2_id", referencedColumnName="id", nullable=false) */ private $entity2; @@ -91,20 +95,20 @@ public function getMyEntity2() } /** - * @Entity - * @Table(name="DDC2084_ENTITY2") + * @ORM\Entity + * @ORM\Table(name="DDC2084_ENTITY2") */ class MyEntity2 { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** - * @Column + * @ORM\Column */ private $value; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2090Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2090Test.php index 174fee2b288..dcc30185eed 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2090Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2090Test.php @@ -1,5 +1,7 @@ setDepartment("QA"); $employee2->setSalary(100); - $this->_em->persist($employee1); - $this->_em->persist($employee2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($employee1); + $this->em->persist($employee2); + $this->em->flush(); + $this->em->clear(); - $this->_em->createQueryBuilder() + $this->em->createQueryBuilder() ->update(CompanyEmployee::class, 'e') ->set('e.startDate', ':date') ->set('e.salary', ':salary') @@ -54,7 +56,7 @@ public function testIssue() ->useQueryCache(true) ->execute(); - $this->_em->createQueryBuilder() + $this->em->createQueryBuilder() ->update(CompanyEmployee::class, 'e') ->set('e.startDate', ':date') ->set('e.salary', ':salary') @@ -70,17 +72,17 @@ public function testIssue() ->useQueryCache(true) ->execute(); - $this->_em->clear(); + $this->em->clear(); - $e1 = $this->_em->find(CompanyEmployee::class, $employee1->getId()); - $e2 = $this->_em->find(CompanyEmployee::class, $employee2->getId()); + $e1 = $this->em->find(CompanyEmployee::class, $employee1->getId()); + $e2 = $this->em->find(CompanyEmployee::class, $employee2->getId()); - $this->assertEquals(101, $e1->getSalary()); - $this->assertEquals(102, $e2->getSalary()); - $this->assertEquals($date1, $e1->getStartDate()); - $this->assertEquals($date2, $e2->getStartDate()); + self::assertEquals(101, $e1->getSalary()); + self::assertEquals(102, $e2->getSalary()); + self::assertEquals($date1, $e1->getStartDate()); + self::assertEquals($date2, $e2->getStartDate()); - $this->_em->createQueryBuilder() + $this->em->createQueryBuilder() ->update(CompanyEmployee::class, 'e') ->set('e.startDate', '?1') ->set('e.salary', '?2') @@ -90,7 +92,7 @@ public function testIssue() ->useQueryCache(true) ->execute(); - $this->_em->createQueryBuilder() + $this->em->createQueryBuilder() ->update(CompanyEmployee::class, 'e') ->set('e.startDate', '?1') ->set('e.salary', '?2') @@ -101,14 +103,14 @@ public function testIssue() ->execute(); - $this->_em->clear(); + $this->em->clear(); - $e1 = $this->_em->find(CompanyEmployee::class, $employee1->getId()); - $e2 = $this->_em->find(CompanyEmployee::class, $employee2->getId()); + $e1 = $this->em->find(CompanyEmployee::class, $employee1->getId()); + $e2 = $this->em->find(CompanyEmployee::class, $employee2->getId()); - $this->assertEquals(101, $e1->getSalary()); - $this->assertEquals(102, $e2->getSalary()); - $this->assertEquals($date1, $e1->getStartDate()); - $this->assertEquals($date2, $e2->getStartDate()); + self::assertEquals(101, $e1->getSalary()); + self::assertEquals(102, $e2->getSalary()); + self::assertEquals($date1, $e1->getStartDate()); + self::assertEquals($date2, $e2->getStartDate()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2106Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2106Test.php deleted file mode 100644 index 4856852ecaa..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2106Test.php +++ /dev/null @@ -1,67 +0,0 @@ -_schemaTool->createSchema( - [ - $this->_em->getClassMetadata(DDC2106Entity::class), - ] - ); - } - - public function testDetachedEntityAsId() - { - // We want an uninitialized PersistentCollection $entity->children - $entity = new DDC2106Entity(); - $this->_em->persist($entity); - $this->_em->flush(); - $this->_em->detach($entity); - $entity = $this->_em->getRepository(DDC2106Entity::class)->findOneBy([]); - - // ... and a managed entity without id - $entityWithoutId = new DDC2106Entity(); - $this->_em->persist($entityWithoutId); - - $criteria = Criteria::create()->where(Criteria::expr()->eq('parent', $entityWithoutId)); - - self::assertCount(0, $entity->children->matching($criteria)); - } -} - -/** - * @Entity - */ -class DDC2106Entity -{ - /** - * @Id - * @GeneratedValue(strategy="IDENTITY") - * @Column(type="integer") - */ - public $id; - - /** @ManyToOne(targetEntity="DDC2106Entity", inversedBy="children") */ - public $parent; - - /** - * @OneToMany(targetEntity="DDC2106Entity", mappedBy="parent", cascade={"persist"}) - */ - public $children; - - public function __construct() - { - $this->children = new \Doctrine\Common\Collections\ArrayCollection; - } -} - diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC211Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC211Test.php index 9ac27f3cf94..0d04e3ec37c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC211Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC211Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC211User::class), - $this->_em->getClassMetadata(DDC211Group::class) + $this->em->getClassMetadata(DDC211User::class), + $this->em->getClassMetadata(DDC211Group::class) ] ); } public function testIssue() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $user = new DDC211User; $user->setName('John Doe'); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); $groupNames = ['group 1', 'group 2', 'group 3', 'group 4']; foreach ($groupNames as $name) { $group = new DDC211Group; $group->setName($name); - $this->_em->persist($group); - $this->_em->flush(); + $this->em->persist($group); + $this->em->flush(); if (!$user->getGroups()->contains($group)) { $user->getGroups()->add($group); $group->getUsers()->add($user); - $this->_em->flush(); + $this->em->flush(); } } - $this->assertEquals(4, $user->getGroups()->count()); + self::assertEquals(4, $user->getGroups()->count()); } } /** - * @Entity - * @Table(name="ddc211_users") + * @ORM\Entity + * @ORM\Table(name="ddc211_users") */ class DDC211User { /** - * @Id - * @Column(name="id", type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** - * @Column(name="name", type="string") + * @ORM\Column(name="name", type="string") */ protected $name; /** - * @ManyToMany(targetEntity="DDC211Group", inversedBy="users") - * @JoinTable(name="user_groups", - * joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")}, - * inverseJoinColumns={@JoinColumn(name="group_id", referencedColumnName="id")} + * @ORM\ManyToMany(targetEntity="DDC211Group", inversedBy="users") + * @ORM\JoinTable(name="user_groups", + * joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")}, + * inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id")} * ) */ protected $groups; @@ -85,25 +88,25 @@ public function getGroups() { return $this->groups; } } /** - * @Entity - * @Table(name="ddc211_groups") + * @ORM\Entity + * @ORM\Table(name="ddc211_groups") */ class DDC211Group { /** - * @Id - * @Column(name="id", type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** - * @Column(name="name", type="string") + * @ORM\Column(name="name", type="string") */ protected $name; /** - * @ManyToMany(targetEntity="DDC211User", mappedBy="groups") + * @ORM\ManyToMany(targetEntity="DDC211User", mappedBy="groups") */ protected $users; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2138Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2138Test.php index 960395e9c70..1e47a6f1a80 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2138Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2138Test.php @@ -1,10 +1,12 @@ _em; - $schemaTool = new SchemaTool($em); - - $classes = [ - $em->getClassMetadata(DDC2138User::class), - $em->getClassMetadata(DDC2138Structure::class), - $em->getClassMetadata(DDC2138UserFollowedObject::class), - $em->getClassMetadata(DDC2138UserFollowedStructure::class), - $em->getClassMetadata(DDC2138UserFollowedUser::class) - ]; - - $schema = $schemaTool->getSchemaFromMetadata($classes); - $this->assertTrue($schema->hasTable('users_followed_objects'), "Table users_followed_objects should exist."); + $schema = $this->schemaTool->getSchemaFromMetadata( + [ + $this->em->getClassMetadata(DDC2138User::class), + $this->em->getClassMetadata(DDC2138Structure::class), + $this->em->getClassMetadata(DDC2138UserFollowedObject::class), + $this->em->getClassMetadata(DDC2138UserFollowedStructure::class), + $this->em->getClassMetadata(DDC2138UserFollowedUser::class) + ] + ); + + self::assertTrue($schema->hasTable('users_followed_objects'), "Table users_followed_objects should exist."); /* @var $table \Doctrine\DBAL\Schema\Table */ $table = ($schema->getTable('users_followed_objects')); - $this->assertTrue($table->columnsAreIndexed(['object_id'])); - $this->assertTrue($table->columnsAreIndexed(['user_id'])); + + self::assertTrue($table->columnsAreIndexed(['object_id'])); + self::assertTrue($table->columnsAreIndexed(['user_id'])); + $foreignKeys = $table->getForeignKeys(); - $this->assertCount(1, $foreignKeys, 'user_id column has to have FK, but not object_id'); + + self::assertCount(1, $foreignKeys, 'user_id column has to have FK, but not object_id'); /* @var $fk \Doctrine\DBAL\Schema\ForeignKeyConstraint */ $fk = reset($foreignKeys); - $this->assertEquals('users', $fk->getForeignTableName()); + + self::assertEquals('users', $fk->getForeignTableName()); $localColumns = $fk->getLocalColumns(); - $this->assertContains('user_id', $localColumns); - $this->assertCount(1, $localColumns); + + self::assertContains('"user_id"', $localColumns); + self::assertCount(1, $localColumns); } } /** - * @Table(name="structures") - * @Entity + * @ORM\Table(name="structures") + * @ORM\Entity */ class DDC2138Structure { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** - * @Column(type="string", length=32, nullable=true) + * @ORM\Column(type="string", length=32, nullable=true) */ protected $name; } /** - * @Entity - * @Table(name="users_followed_objects") - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorColumn(name="object_type", type="smallint") - * @DiscriminatorMap({4 = "DDC2138UserFollowedUser", 3 = "DDC2138UserFollowedStructure"}) + * @ORM\Entity + * @ORM\Table(name="users_followed_objects") + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorColumn(name="object_type", type="smallint") + * @ORM\DiscriminatorMap({4 = "DDC2138UserFollowedUser", 3 = "DDC2138UserFollowedStructure"}) */ abstract class DDC2138UserFollowedObject { /** * @var int $id * - * @Column(name="id", type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") + * @ORM\Column(name="id", type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; @@ -95,20 +100,20 @@ public function getId() } /** - * @Entity + * @ORM\Entity */ class DDC2138UserFollowedStructure extends DDC2138UserFollowedObject { /** - * @ManyToOne(targetEntity="DDC2138User", inversedBy="followedStructures") - * @JoinColumn(name="user_id", referencedColumnName="id", nullable=false) + * @ORM\ManyToOne(targetEntity="DDC2138User", inversedBy="followedStructures") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) * @var User $user */ protected $user; /** - * @ManyToOne(targetEntity="DDC2138Structure") - * @JoinColumn(name="object_id", referencedColumnName="id", nullable=false) + * @ORM\ManyToOne(targetEntity="DDC2138Structure") + * @ORM\JoinColumn(name="object_id", referencedColumnName="id", nullable=false) * @var Structure $followedStructure */ private $followedStructure; @@ -146,20 +151,20 @@ public function getFollowedStructure() } /** - * @Entity + * @ORM\Entity */ class DDC2138UserFollowedUser extends DDC2138UserFollowedObject { /** - * @ManyToOne(targetEntity="DDC2138User", inversedBy="followedUsers") - * @JoinColumn(name="user_id", referencedColumnName="id", nullable=false) + * @ORM\ManyToOne(targetEntity="DDC2138User", inversedBy="followedUsers") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) * @var User $user */ protected $user; /** - * @ManyToOne(targetEntity="DDC2138User") - * @JoinColumn(name="object_id", referencedColumnName="id", nullable=false) + * @ORM\ManyToOne(targetEntity="DDC2138User") + * @ORM\JoinColumn(name="object_id", referencedColumnName="id", nullable=false) * @var User $user */ private $followedUser; @@ -198,32 +203,32 @@ public function getFollowedUser() } /** - * @Table(name="users") - * @Entity + * @ORM\Table(name="users") + * @ORM\Entity */ class DDC2138User { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** - * @Column(type="string", length=32, nullable=true) + * @ORM\Column(type="string", length=32, nullable=true) */ protected $name; /** * @var ArrayCollection $followedUsers - * @OneToMany(targetEntity="DDC2138UserFollowedUser", mappedBy="user", cascade={"persist"}, orphanRemoval=true) + * @ORM\OneToMany(targetEntity="DDC2138UserFollowedUser", mappedBy="user", cascade={"persist"}, orphanRemoval=true) */ protected $followedUsers; /** * @var ArrayCollection $followedStructures - * @OneToMany(targetEntity="DDC2138UserFollowedStructure", mappedBy="user", cascade={"persist"}, orphanRemoval=true) + * @ORM\OneToMany(targetEntity="DDC2138UserFollowedStructure", mappedBy="user", cascade={"persist"}, orphanRemoval=true) */ protected $followedStructures; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2175Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2175Test.php index d6b3c603b8f..bec87805974 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2175Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2175Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( - [ - $this->_em->getClassMetadata(DDC2175Entity::class), - ] + + $this->schemaTool->createSchema( + [$this->em->getClassMetadata(DDC2175Entity::class)] + ); + } + + protected function tearDown() + { + parent::tearDown(); + + $this->schemaTool->dropSchema( + [$this->em->getClassMetadata(DDC2175Entity::class)] ); } @@ -22,43 +34,43 @@ public function testIssue() $entity = new DDC2175Entity(); $entity->field = "foo"; - $this->_em->persist($entity); - $this->_em->flush(); + $this->em->persist($entity); + $this->em->flush(); - $this->assertEquals(1, $entity->version); + self::assertEquals(1, $entity->version); $entity->field = "bar"; - $this->_em->flush(); + $this->em->flush(); - $this->assertEquals(2, $entity->version); + self::assertEquals(2, $entity->version); $entity->field = "baz"; - $this->_em->flush(); + $this->em->flush(); - $this->assertEquals(3, $entity->version); + self::assertEquals(3, $entity->version); } } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorMap({"entity": "DDC2175Entity"}) + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorMap({"entity": "DDC2175Entity"}) */ class DDC2175Entity { /** - * @Id @GeneratedValue @Column(type="integer") + * @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ public $id; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $field; /** - * @Version - * @Column(type="integer") + * @ORM\Version + * @ORM\Column(type="integer") */ public $version; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2182Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2182Test.php index 590b7cd5f58..a6369c52d60 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2182Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2182Test.php @@ -1,50 +1,55 @@ _em->getConnection()->getDatabasePlatform()->getName() != 'mysql') { + if ($this->em->getConnection()->getDatabasePlatform()->getName() != 'mysql') { $this->markTestSkipped("This test is useful for all databases, but designed only for mysql."); } - $sql = $this->_schemaTool->getCreateSchemaSql( + $sql = $this->schemaTool->getCreateSchemaSql( [ - $this->_em->getClassMetadata(DDC2182OptionParent::class), - $this->_em->getClassMetadata(DDC2182OptionChild::class), + $this->em->getClassMetadata(DDC2182OptionParent::class), + $this->em->getClassMetadata(DDC2182OptionChild::class), ] ); - $this->assertEquals("CREATE TABLE DDC2182OptionParent (id INT UNSIGNED NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[0]); - $this->assertEquals("CREATE TABLE DDC2182OptionChild (id VARCHAR(255) NOT NULL, parent_id INT UNSIGNED DEFAULT NULL, INDEX IDX_B314D4AD727ACA70 (parent_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[1]); - $this->assertEquals("ALTER TABLE DDC2182OptionChild ADD CONSTRAINT FK_B314D4AD727ACA70 FOREIGN KEY (parent_id) REFERENCES DDC2182OptionParent (id)", $sql[2]); + self::assertEquals("CREATE TABLE DDC2182OptionParent (id INT UNSIGNED NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[0]); + self::assertEquals("CREATE TABLE DDC2182OptionChild (id VARCHAR(255) NOT NULL, parent_id INT UNSIGNED DEFAULT NULL, INDEX IDX_B314D4AD727ACA70 (parent_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[1]); + self::assertEquals("ALTER TABLE DDC2182OptionChild ADD CONSTRAINT FK_B314D4AD727ACA70 FOREIGN KEY (parent_id) REFERENCES DDC2182OptionParent (id)", $sql[2]); } } /** - * @Entity - * @Table + * @ORM\Entity + * @ORM\Table */ class DDC2182OptionParent { - /** @Id @Column(type="integer", options={"unsigned": true}) */ + /** @ORM\Id @ORM\Column(type="integer", options={"unsigned": true}) */ private $id; } /** - * @Entity - * @Table + * @ORM\Entity + * @ORM\Table */ class DDC2182OptionChild { - /** @Id @Column */ + /** @ORM\Id @ORM\Column */ private $id; /** - * @ManyToOne(targetEntity="DDC2182OptionParent") - * @JoinColumn(referencedColumnName="id") + * @ORM\ManyToOne(targetEntity="DDC2182OptionParent") + * @ORM\JoinColumn(referencedColumnName="id") */ private $parent; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2214Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2214Test.php index 87101fff1da..f8751e9ebd5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2214Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2214Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2214Foo::class), - $this->_em->getClassMetadata(DDC2214Bar::class), + $this->em->getClassMetadata(DDC2214Foo::class), + $this->em->getClassMetadata(DDC2214Bar::class), ] ); } @@ -32,42 +36,42 @@ public function testIssue() $foo->bar = $bar; - $this->_em->persist($foo); - $this->_em->persist($bar); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($foo); + $this->em->persist($bar); + $this->em->flush(); + $this->em->clear(); /* @var $foo \Doctrine\Tests\ORM\Functional\Ticket\DDC2214Foo */ - $foo = $this->_em->find(DDC2214Foo::class, $foo->id); + $foo = $this->em->find(DDC2214Foo::class, $foo->id); $bar = $foo->bar; - $logger = $this->_em->getConnection()->getConfiguration()->getSQLLogger(); + $logger = $this->em->getConnection()->getConfiguration()->getSQLLogger(); $related = $this - ->_em + ->em ->createQuery('SELECT b FROM '.__NAMESPACE__ . '\DDC2214Bar b WHERE b.id IN(:ids)') ->setParameter('ids', [$bar]) ->getResult(); $query = end($logger->queries); - $this->assertEquals(\Doctrine\DBAL\Connection::PARAM_INT_ARRAY, $query['types'][0]); + self::assertEquals(\Doctrine\DBAL\Connection::PARAM_INT_ARRAY, $query['types'][0]); } } -/** @Entity */ +/** @ORM\Entity */ class DDC2214Foo { - /** @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */ public $id; - /** @ManyToOne(targetEntity="DDC2214Bar") */ + /** @ORM\ManyToOne(targetEntity="DDC2214Bar") */ public $bar; } -/** @Entity */ +/** @ORM\Entity */ class DDC2214Bar { - /** @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2224Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2224Test.php index 3529fa35640..6f5bb42d26e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2224Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2224Test.php @@ -1,10 +1,13 @@ _em->createQuery($dql); + $query = $this->em->createQuery($dql); $query->setQueryCacheDriver(new ArrayCache()); $query->setParameter('field', 'test', 'DDC2224Type'); - $this->assertStringEndsWith('.field = FUNCTION(?)', $query->getSQL()); + + self::assertStringEndsWith('."field" = FUNCTION(?)', $query->getSQL()); return $query; } @@ -35,7 +39,8 @@ public function testIssue() public function testCacheMissWhenTypeChanges(Query $query) { $query->setParameter('field', 'test', 'string'); - $this->assertStringEndsWith('.field = ?', $query->getSQL()); + + self::assertStringEndsWith('."field" = ?', $query->getSQL()); } } @@ -72,17 +77,17 @@ public function convertToDatabaseValueSQL($sqlExpr, AbstractPlatform $platform) } /** - * @Entity + * @ORM\Entity */ class DDC2224Entity { /** - * @Id @GeneratedValue @Column(type="integer") + * @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ public $id; /** - * @Column(type="DDC2224Type") + * @ORM\Column(type="DDC2224Type") */ public $field; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2230Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2230Test.php index 4ced4df4dc7..3751f342df6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2230Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2230Test.php @@ -1,10 +1,13 @@ _schemaTool->createSchema( - [ - $this->_em->getClassMetadata(DDC2230User::class), - $this->_em->getClassMetadata(DDC2230Address::class), - ] - ); + $this->schemaTool->createSchema([ + $this->em->getClassMetadata(DDC2230User::class), + $this->em->getClassMetadata(DDC2230Address::class), + ]); } catch (ToolsException $e) {} } - public function testNotifyTrackingNotCalledOnUninitializedProxies() - { - $insertedUser = new DDC2230User(); - $insertedUser->address = new DDC2230Address(); - - $this->_em->persist($insertedUser); - $this->_em->persist($insertedUser->address); - $this->_em->flush(); - $this->_em->clear(); - - $user = $this->_em->find(DDC2230User::class, $insertedUser->id); - - $this->_em->clear(); - - $mergedUser = $this->_em->merge($user); - - /* @var $address Proxy */ - $address = $mergedUser->address; - - $this->assertInstanceOf(Proxy::class, $address); - $this->assertFalse($address->__isInitialized()); - } - public function testNotifyTrackingCalledOnProxyInitialization() { $insertedAddress = new DDC2230Address(); - $this->_em->persist($insertedAddress); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($insertedAddress); + $this->em->flush(); + $this->em->clear(); - $addressProxy = $this->_em->getReference(DDC2230Address::class, $insertedAddress->id); + $addressProxy = $this->em->getReference(DDC2230Address::class, $insertedAddress->id); /* @var $addressProxy Proxy|\Doctrine\Tests\ORM\Functional\Ticket\DDC2230Address */ - $this->assertFalse($addressProxy->__isInitialized()); - $this->assertNull($addressProxy->listener); + self::assertFalse($addressProxy->__isInitialized()); + self::assertNull($addressProxy->listener); $addressProxy->__load(); - $this->assertSame($this->_em->getUnitOfWork(), $addressProxy->listener); + self::assertSame($this->em->getUnitOfWork(), $addressProxy->listener); } } -/** @Entity */ +/** @ORM\Entity */ class DDC2230User { - /** @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @OneToOne(targetEntity="DDC2230Address") + * @ORM\OneToOne(targetEntity="DDC2230Address") */ public $address; } /** - * @Entity - * @ChangeTrackingPolicy("NOTIFY") + * @ORM\Entity + * @ORM\ChangeTrackingPolicy("NOTIFY") */ class DDC2230Address implements NotifyPropertyChanged { - /** @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2231Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2231Test.php index 6bfd8d823d0..bb9b25e2656 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2231Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2231Test.php @@ -1,10 +1,13 @@ _schemaTool->createSchema( - [ - $this->_em->getClassMetadata(DDC2231EntityY::class), - ] - ); + + $this->schemaTool->createSchema([ + $this->em->getClassMetadata(DDC2231EntityY::class), + ]); } public function testInjectObjectManagerInProxyIfInitializedInUow() { $y1 = new DDC2231EntityY; - $this->_em->persist($y1); + $this->em->persist($y1); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $y1ref = $this->_em->getReference(get_class($y1), $y1->id); + $y1ref = $this->em->getReference(get_class($y1), $y1->id); - $this->assertInstanceOf(Proxy::class, $y1ref); - $this->assertFalse($y1ref->__isInitialized__); + self::assertInstanceOf(Proxy::class, $y1ref); + self::assertFalse($y1ref->__isInitialized()); $id = $y1ref->doSomething(); - $this->assertTrue($y1ref->__isInitialized__); - $this->assertEquals($this->_em, $y1ref->om); + self::assertTrue($y1ref->__isInitialized()); + self::assertEquals($this->em, $y1ref->om); } } -/** @Entity @Table(name="ddc2231_y") */ -class DDC2231EntityY implements ObjectManagerAware +/** @ORM\Entity @ORM\Table(name="ddc2231_y") */ +class DDC2231EntityY implements EntityManagerAware { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; public $om; - public function injectObjectManager(ObjectManager $objectManager, ClassMetadata $classMetadata) + public function injectEntityManager(EntityManagerInterface $objectManager, ClassMetadata $classMetadata) : void { $this->om = $objectManager; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2252Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2252Test.php index e4b60196622..42d37226f22 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2252Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2252Test.php @@ -1,8 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2252User::class), - $this->_em->getClassMetadata(DDC2252Privilege::class), - $this->_em->getClassMetadata(DDC2252Membership::class), - $this->_em->getClassMetadata(DDC2252MerchantAccount::class), + $this->em->getClassMetadata(DDC2252User::class), + $this->em->getClassMetadata(DDC2252Privilege::class), + $this->em->getClassMetadata(DDC2252Membership::class), + $this->em->getClassMetadata(DDC2252MerchantAccount::class), ] ); @@ -44,16 +47,16 @@ public function loadFixtures() $this->membership->addPrivilege($this->privileges[1]); $this->membership->addPrivilege($this->privileges[2]); - $this->_em->persist($this->user); - $this->_em->persist($this->merchant); - $this->_em->persist($this->privileges[0]); - $this->_em->persist($this->privileges[1]); - $this->_em->persist($this->privileges[2]); - $this->_em->flush(); + $this->em->persist($this->user); + $this->em->persist($this->merchant); + $this->em->persist($this->privileges[0]); + $this->em->persist($this->privileges[1]); + $this->em->persist($this->privileges[2]); + $this->em->flush(); - $this->_em->persist($this->membership); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($this->membership); + $this->em->flush(); + $this->em->clear(); } public function testIssue() @@ -63,54 +66,54 @@ public function testIssue() 'userAccount' => $this->user->getUid(), ]; - $membership = $this->_em->find(DDC2252Membership::class, $identifier); + $membership = $this->em->find(DDC2252Membership::class, $identifier); - $this->assertInstanceOf(DDC2252Membership::class, $membership); - $this->assertCount(3, $membership->getPrivileges()); + self::assertInstanceOf(DDC2252Membership::class, $membership); + self::assertCount(3, $membership->getPrivileges()); $membership->getPrivileges()->remove(2); - $this->_em->persist($membership); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($membership); + $this->em->flush(); + $this->em->clear(); - $membership = $this->_em->find(DDC2252Membership::class, $identifier); + $membership = $this->em->find(DDC2252Membership::class, $identifier); - $this->assertInstanceOf(DDC2252Membership::class, $membership); - $this->assertCount(2, $membership->getPrivileges()); + self::assertInstanceOf(DDC2252Membership::class, $membership); + self::assertCount(2, $membership->getPrivileges()); $membership->getPrivileges()->clear(); - $this->_em->persist($membership); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($membership); + $this->em->flush(); + $this->em->clear(); - $membership = $this->_em->find(DDC2252Membership::class, $identifier); + $membership = $this->em->find(DDC2252Membership::class, $identifier); - $this->assertInstanceOf(DDC2252Membership::class, $membership); - $this->assertCount(0, $membership->getPrivileges()); + self::assertInstanceOf(DDC2252Membership::class, $membership); + self::assertCount(0, $membership->getPrivileges()); $membership->addPrivilege($privilege3 = new DDC2252Privilege); - $this->_em->persist($privilege3); - $this->_em->persist($membership); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($privilege3); + $this->em->persist($membership); + $this->em->flush(); + $this->em->clear(); - $membership = $this->_em->find(DDC2252Membership::class, $identifier); + $membership = $this->em->find(DDC2252Membership::class, $identifier); - $this->assertInstanceOf(DDC2252Membership::class, $membership); - $this->assertCount(1, $membership->getPrivileges()); + self::assertInstanceOf(DDC2252Membership::class, $membership); + self::assertCount(1, $membership->getPrivileges()); } } /** - * @Entity() - * @Table(name="ddc2252_acl_privilege") + * @ORM\Entity() + * @ORM\Table(name="ddc2252_acl_privilege") */ class DDC2252Privilege { /** - * @Id - * @GeneratedValue - * @Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue + * @ORM\Column(type="integer") */ protected $privilegeid; @@ -121,14 +124,14 @@ public function getPrivilegeid() } /** - * @Entity - * @Table(name="ddc2252_mch_account") + * @ORM\Entity + * @ORM\Table(name="ddc2252_mch_account") */ class DDC2252MerchantAccount { /** - * @Id - * @Column(type="integer") + * @ORM\Id + * @ORM\Column(type="integer") */ protected $accountid = 111; @@ -139,19 +142,19 @@ public function getAccountid() } /** - * @Entity - * @Table(name="ddc2252_user_account") + * @ORM\Entity + * @ORM\Table(name="ddc2252_user_account") */ class DDC2252User { /** - * @Id - * @Column(type="integer") + * @ORM\Id + * @ORM\Column(type="integer") */ protected $uid = 222; /** - * @OneToMany(targetEntity="DDC2252Membership", mappedBy="userAccount", cascade={"persist"}) - * @JoinColumn(name="uid", referencedColumnName="uid") + * @ORM\OneToMany(targetEntity="DDC2252Membership", mappedBy="userAccount", cascade={"persist"}) + * @ORM\JoinColumn(name="uid", referencedColumnName="uid") */ protected $memberships; @@ -177,35 +180,35 @@ public function addMembership(DDC2252Membership $membership) } /** - * @Entity - * @Table(name="ddc2252_mch_account_member") - * @HasLifecycleCallbacks + * @ORM\Entity + * @ORM\Table(name="ddc2252_mch_account_member") + * @ORM\HasLifecycleCallbacks */ class DDC2252Membership { /** - * @Id - * @ManyToOne(targetEntity="DDC2252User", inversedBy="memberships") - * @JoinColumn(name="uid", referencedColumnName="uid") + * @ORM\Id + * @ORM\ManyToOne(targetEntity="DDC2252User", inversedBy="memberships") + * @ORM\JoinColumn(name="uid", referencedColumnName="uid") */ protected $userAccount; /** - * @Id - * @ManyToOne(targetEntity="DDC2252MerchantAccount") - * @JoinColumn(name="mch_accountid", referencedColumnName="accountid") + * @ORM\Id + * @ORM\ManyToOne(targetEntity="DDC2252MerchantAccount") + * @ORM\JoinColumn(name="mch_accountid", referencedColumnName="accountid") */ protected $merchantAccount; /** - * @ManyToMany(targetEntity="DDC2252Privilege", indexBy="privilegeid") - * @JoinTable(name="ddc2252_user_mch_account_privilege", + * @ORM\ManyToMany(targetEntity="DDC2252Privilege", indexBy="privilegeid") + * @ORM\JoinTable(name="ddc2252_user_mch_account_privilege", * joinColumns={ - * @JoinColumn(name="mch_accountid", referencedColumnName="mch_accountid"), - * @JoinColumn(name="uid", referencedColumnName="uid") + * @ORM\JoinColumn(name="mch_accountid", referencedColumnName="mch_accountid"), + * @ORM\JoinColumn(name="uid", referencedColumnName="uid") * }, * inverseJoinColumns={ - * @JoinColumn(name="privilegeid", referencedColumnName="privilegeid") + * @ORM\JoinColumn(name="privilegeid", referencedColumnName="privilegeid") * } * ) */ diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2256Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2256Test.php index 02281a5e3a0..a70ffcd02ab 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2256Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2256Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2256User::class), - $this->_em->getClassMetadata(DDC2256Group::class) + $this->em->getClassMetadata(DDC2256User::class), + $this->em->getClassMetadata(DDC2256Group::class) ] ); } public function testIssue() { - $config = $this->_em->getConfiguration(); + $config = $this->em->getConfiguration(); $config->addEntityNamespace('MyNamespace', __NAMESPACE__); $user = new DDC2256User(); @@ -33,10 +36,10 @@ public function testIssue() $group->name = 'group'; $user->group = $group; - $this->_em->persist($user); - $this->_em->persist($group); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->persist($group); + $this->em->flush(); + $this->em->clear(); $sql = 'SELECT u.id, u.name, g.id as group_id, g.name as group_name FROM ddc2256_users u LEFT JOIN ddc2256_groups g ON u.group_id = g.id'; @@ -51,62 +54,62 @@ public function testIssue() $rsm->addFieldResult('g', 'group_id', 'id'); $rsm->addFieldResult('g', 'group_name', 'name'); - self::assertCount(1, $this->_em->createNativeQuery($sql, $rsm)->getResult()); + self::assertCount(1, $this->em->createNativeQuery($sql, $rsm)->getResult()); // Test ResultSetMappingBuilder. - $rsm = new ResultSetMappingBuilder($this->_em); + $rsm = new ResultSetMappingBuilder($this->em); $rsm->addRootEntityFromClassMetadata('MyNamespace:DDC2256User', 'u'); $rsm->addJoinedEntityFromClassMetadata('MyNamespace:DDC2256Group', 'g', 'u', 'group', ['id' => 'group_id', 'name' => 'group_name']); - self::assertCount(1, $this->_em->createNativeQuery($sql, $rsm)->getResult()); + self::assertCount(1, $this->em->createNativeQuery($sql, $rsm)->getResult()); } } /** - * @Entity - * @Table(name="ddc2256_users") + * @ORM\Entity + * @ORM\Table(name="ddc2256_users") */ class DDC2256User { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $name; /** - * @ManyToOne(targetEntity="DDC2256Group", inversedBy="users")A - * @JoinColumn(name="group_id") + * @ORM\ManyToOne(targetEntity="DDC2256Group", inversedBy="users")A + * @ORM\JoinColumn(name="group_id") */ public $group; } /** - * @Entity - * @Table(name="ddc2256_groups") + * @ORM\Entity + * @ORM\Table(name="ddc2256_groups") */ class DDC2256Group { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $name; /** - * @OneToMany(targetEntity="DDC2256User", mappedBy="group") + * @ORM\OneToMany(targetEntity="DDC2256User", mappedBy="group") */ public $users; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2306Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2306Test.php index 24807db029a..af3da3aa1d3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2306Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2306Test.php @@ -1,8 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2306Zone::class), - $this->_em->getClassMetadata(DDC2306User::class), - $this->_em->getClassMetadata(DDC2306Address::class), - $this->_em->getClassMetadata(DDC2306UserAddress::class), + $this->em->getClassMetadata(DDC2306Zone::class), + $this->em->getClassMetadata(DDC2306User::class), + $this->em->getClassMetadata(DDC2306Address::class), + $this->em->getClassMetadata(DDC2306UserAddress::class), ] ); } @@ -48,28 +51,28 @@ public function testIssue() $user->zone = $zone; $address->zone = $zone; - $this->_em->persist($zone); - $this->_em->persist($user); - $this->_em->persist($address); - $this->_em->persist($userAddress); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($zone); + $this->em->persist($user); + $this->em->persist($address); + $this->em->persist($userAddress); + $this->em->flush(); + $this->em->clear(); /* @var $address DDC2306Address */ - $address = $this->_em->find(DDC2306Address::class, $address->id); + $address = $this->em->find(DDC2306Address::class, $address->id); /* @var $user DDC2306User|Proxy */ $user = $address->users->first()->user; - $this->assertInstanceOf(Proxy::class, $user); - $this->assertInstanceOf(DDC2306User::class, $user); + self::assertInstanceOf(Proxy::class, $user); + self::assertInstanceOf(DDC2306User::class, $user); $userId = $user->id; - $this->assertNotNull($userId); + self::assertNotNull($userId); $user->__load(); - $this->assertEquals( + self::assertEquals( $userId, $user->id, 'As of DDC-1734, the identifier is NULL for un-managed proxies. The identifier should be an integer here' @@ -77,29 +80,29 @@ public function testIssue() } } -/** @Entity */ +/** @ORM\Entity */ class DDC2306Zone { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; } /** - * @Entity + * @ORM\Entity */ class DDC2306User { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; /** * @var DDC2306UserAddress[]|\Doctrine\Common\Collections\Collection * - * @OneToMany(targetEntity="DDC2306UserAddress", mappedBy="user") + * @ORM\OneToMany(targetEntity="DDC2306UserAddress", mappedBy="user") */ public $addresses; - /** @ManyToOne(targetEntity="DDC2306Zone", fetch="EAGER") */ + /** @ORM\ManyToOne(targetEntity="DDC2306Zone", fetch="EAGER") */ public $zone; /** Constructor */ @@ -108,20 +111,20 @@ public function __construct() { } } -/** @Entity */ +/** @ORM\Entity */ class DDC2306Address { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; /** * @var DDC2306UserAddress[]|\Doctrine\Common\Collections\Collection * - * @OneToMany(targetEntity="DDC2306UserAddress", mappedBy="address", orphanRemoval=true) + * @ORM\OneToMany(targetEntity="DDC2306UserAddress", mappedBy="address", orphanRemoval=true) */ public $users; - /** @ManyToOne(targetEntity="DDC2306Zone", fetch="EAGER") */ + /** @ORM\ManyToOne(targetEntity="DDC2306Zone", fetch="EAGER") */ public $zone; /** Constructor */ @@ -130,16 +133,16 @@ public function __construct() { } } -/** @Entity */ +/** @ORM\Entity */ class DDC2306UserAddress { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @ManyToOne(targetEntity="DDC2306User") */ + /** @ORM\ManyToOne(targetEntity="DDC2306User") */ public $user; - /** @ManyToOne(targetEntity="DDC2306Address", fetch="LAZY") */ + /** @ORM\ManyToOne(targetEntity="DDC2306Address", fetch="LAZY") */ public $address; /** Constructor */ diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2346Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2346Test.php index a1cac08eaf3..4e6aa8052ff 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2346Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2346Test.php @@ -1,9 +1,12 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2346Foo::class), - $this->_em->getClassMetadata(DDC2346Bar::class), - $this->_em->getClassMetadata(DDC2346Baz::class), + $this->em->getClassMetadata(DDC2346Foo::class), + $this->em->getClassMetadata(DDC2346Bar::class), + $this->em->getClassMetadata(DDC2346Baz::class), ] ); @@ -50,33 +53,33 @@ public function testIssue() $foo1->bars[] = $baz1; $foo1->bars[] = $baz2; - $this->_em->persist($foo1); - $this->_em->persist($foo2); - $this->_em->persist($baz1); - $this->_em->persist($baz2); + $this->em->persist($foo1); + $this->em->persist($foo2); + $this->em->persist($baz1); + $this->em->persist($baz2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $this->_em->getConnection()->getConfiguration()->setSQLLogger($this->logger); + $this->em->getConnection()->getConfiguration()->setSQLLogger($this->logger); - $fetchedBazs = $this->_em->getRepository(DDC2346Baz::class)->findAll(); + $fetchedBazs = $this->em->getRepository(DDC2346Baz::class)->findAll(); - $this->assertCount(2, $fetchedBazs); - $this->assertCount(2, $this->logger->queries, 'The total number of executed queries is 2, and not n+1'); + self::assertCount(2, $fetchedBazs); + self::assertCount(2, $this->logger->queries, 'The total number of executed queries is 2, and not n+1'); } } -/** @Entity */ +/** @ORM\Entity */ class DDC2346Foo { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; /** * @var DDC2346Bar[]|\Doctrine\Common\Collections\Collection * - * @OneToMany(targetEntity="DDC2346Bar", mappedBy="foo") + * @ORM\OneToMany(targetEntity="DDC2346Bar", mappedBy="foo") */ public $bars; @@ -87,23 +90,23 @@ public function __construct() { } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="discr", type="string") - * @DiscriminatorMap({"bar" = "DDC2346Bar", "baz" = "DDC2346Baz"}) + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="discr", type="string") + * @ORM\DiscriminatorMap({"bar" = "DDC2346Bar", "baz" = "DDC2346Baz"}) */ class DDC2346Bar { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @ManyToOne(targetEntity="DDC2346Foo", inversedBy="bars", fetch="EAGER") */ + /** @ORM\ManyToOne(targetEntity="DDC2346Foo", inversedBy="bars", fetch="EAGER") */ public $foo; } /** - * @Entity + * @ORM\Entity */ class DDC2346Baz extends DDC2346Bar { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2350Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2350Test.php index 1d3a4117ad0..df6c4c49efb 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2350Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2350Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2350User::class), - $this->_em->getClassMetadata(DDC2350Bug::class), + $this->em->getClassMetadata(DDC2350User::class), + $this->em->getClassMetadata(DDC2350Bug::class), ] ); } @@ -30,42 +33,42 @@ public function testEagerCollectionsAreOnlyRetrievedOnce() $bug2 = new DDC2350Bug(); $bug2->user = $user; - $this->_em->persist($user); - $this->_em->persist($bug1); - $this->_em->persist($bug2); - $this->_em->flush(); + $this->em->persist($user); + $this->em->persist($bug1); + $this->em->persist($bug2); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); $cnt = $this->getCurrentQueryCount(); - $user = $this->_em->find(DDC2350User::class, $user->id); + $user = $this->em->find(DDC2350User::class, $user->id); - $this->assertEquals($cnt + 1, $this->getCurrentQueryCount()); + self::assertEquals($cnt + 1, $this->getCurrentQueryCount()); - $this->assertEquals(2, count($user->reportedBugs)); + self::assertEquals(2, count($user->reportedBugs)); - $this->assertEquals($cnt + 1, $this->getCurrentQueryCount()); + self::assertEquals($cnt + 1, $this->getCurrentQueryCount()); } } /** - * @Entity + * @ORM\Entity */ class DDC2350User { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @OneToMany(targetEntity="DDC2350Bug", mappedBy="user", fetch="EAGER") */ + /** @ORM\OneToMany(targetEntity="DDC2350Bug", mappedBy="user", fetch="EAGER") */ public $reportedBugs; } /** - * @Entity + * @ORM\Entity */ class DDC2350Bug { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @ManyToOne(targetEntity="DDC2350User", inversedBy="reportedBugs") */ + /** @ORM\ManyToOne(targetEntity="DDC2350User", inversedBy="reportedBugs") */ public $user; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2359Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2359Test.php index 21a932ed36d..51530f776a0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2359Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2359Test.php @@ -1,34 +1,38 @@ createMock(MappingDriver::class); $mockMetadata = $this->createMock(ClassMetadata::class); - $entityManager = $this->createMock(EntityManager::class); + $entityManager = $this->createMock(EntityManagerInterface::class); /* @var $metadataFactory \Doctrine\ORM\Mapping\ClassMetadataFactory|\PHPUnit_Framework_MockObject_MockObject */ $metadataFactory = $this->getMockBuilder(ClassMetadataFactory::class) - ->setMethods(['newClassMetadataInstance', 'wakeupReflection']) + ->setMethods(['doLoadMetadata', 'wakeupReflection']) ->getMock(); $configuration = $this->getMockBuilder(Configuration::class) @@ -42,25 +46,44 @@ public function testIssue() ->method('getMetadataDriverImpl') ->will($this->returnValue($mockDriver)); - $entityManager->expects($this->any())->method('getConfiguration')->will($this->returnValue($configuration)); - $entityManager->expects($this->any())->method('getConnection')->will($this->returnValue($connection)); + $mockMetadata + ->expects($this->any()) + ->method('getDeclaredPropertiesIterator') + ->will($this->returnValue(new \ArrayIterator([]))); + + $entityManager + ->expects($this->any()) + ->method('getConfiguration') + ->will($this->returnValue($configuration)); + + $entityManager + ->expects($this->any()) + ->method('getConnection') + ->will($this->returnValue($connection)); + $entityManager ->expects($this->any()) ->method('getEventManager') ->will($this->returnValue($this->createMock(EventManager::class))); - $metadataFactory->expects($this->any())->method('newClassMetadataInstance')->will($this->returnValue($mockMetadata)); - $metadataFactory->expects($this->once())->method('wakeupReflection'); + $metadataFactory + ->expects($this->any()) + ->method('doLoadMetadata') + ->will($this->returnValue($mockMetadata)); + + $metadataFactory + ->expects($this->never()) + ->method('wakeupReflection'); $metadataFactory->setEntityManager($entityManager); - $this->assertSame($mockMetadata, $metadataFactory->getMetadataFor(DDC2359Foo::class)); + self::assertSame($mockMetadata, $metadataFactory->getMetadataFor(DDC2359Foo::class)); } } -/** @Entity */ +/** @ORM\Entity */ class DDC2359Foo { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC237Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC237Test.php index eac219c7280..6425042dd10 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC237Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC237Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC237EntityX::class), - $this->_em->getClassMetadata(DDC237EntityY::class), - $this->_em->getClassMetadata(DDC237EntityZ::class) + $this->em->getClassMetadata(DDC237EntityX::class), + $this->em->getClassMetadata(DDC237EntityY::class), + $this->em->getClassMetadata(DDC237EntityZ::class) ] ); } @@ -31,84 +34,84 @@ public function testUninitializedProxyIsInitializedOnFetchJoin() $x->y = $y; $z->y = $y; - $this->_em->persist($x); - $this->_em->persist($y); - $this->_em->persist($z); + $this->em->persist($x); + $this->em->persist($y); + $this->em->persist($z); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $x2 = $this->_em->find(get_class($x), $x->id); // proxy injected for Y - $this->assertInstanceOf(Proxy::class, $x2->y); - $this->assertFalse($x2->y->__isInitialized__); + $x2 = $this->em->find(get_class($x), $x->id); // proxy injected for Y + self::assertInstanceOf(Proxy::class, $x2->y); + self::assertFalse($x2->y->__isInitialized()); // proxy for Y is in identity map - $z2 = $this->_em->createQuery('select z,y from ' . get_class($z) . ' z join z.y y where z.id = ?1') + $z2 = $this->em->createQuery('select z,y from ' . get_class($z) . ' z join z.y y where z.id = ?1') ->setParameter(1, $z->id) ->getSingleResult(); - $this->assertInstanceOf(Proxy::class, $z2->y); - $this->assertTrue($z2->y->__isInitialized__); - $this->assertEquals('Y', $z2->y->data); - $this->assertEquals($y->id, $z2->y->id); + self::assertInstanceOf(Proxy::class, $z2->y); + self::assertTrue($z2->y->__isInitialized()); + self::assertEquals('Y', $z2->y->data); + self::assertEquals($y->id, $z2->y->id); // since the Y is the same, the instance from the identity map is // used, even if it is a proxy. - $this->assertNotSame($x, $x2); - $this->assertNotSame($z, $z2); - $this->assertSame($z2->y, $x2->y); - $this->assertInstanceOf(Proxy::class, $z2->y); + self::assertNotSame($x, $x2); + self::assertNotSame($z, $z2); + self::assertSame($z2->y, $x2->y); + self::assertInstanceOf(Proxy::class, $z2->y); } } /** - * @Entity @Table(name="ddc237_x") + * @ORM\Entity @ORM\Table(name="ddc237_x") */ class DDC237EntityX { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $data; /** - * @OneToOne(targetEntity="DDC237EntityY") - * @JoinColumn(name="y_id", referencedColumnName="id") + * @ORM\OneToOne(targetEntity="DDC237EntityY") + * @ORM\JoinColumn(name="y_id", referencedColumnName="id") */ public $y; } -/** @Entity @Table(name="ddc237_y") */ +/** @ORM\Entity @ORM\Table(name="ddc237_y") */ class DDC237EntityY { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $data; } -/** @Entity @Table(name="ddc237_z") */ +/** @ORM\Entity @ORM\Table(name="ddc237_z") */ class DDC237EntityZ { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $data; /** - * @OneToOne(targetEntity="DDC237EntityY") - * @JoinColumn(name="y_id", referencedColumnName="id") + * @ORM\OneToOne(targetEntity="DDC237EntityY") + * @ORM\JoinColumn(name="y_id", referencedColumnName="id") */ public $y; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2387Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2387Test.php index de4e2058955..ec7f4bdfcbc 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2387Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2387Test.php @@ -1,9 +1,11 @@ convertToClassMetadata([$product, $attributes], []); - $this->assertEquals(ClassMetadataInfo::GENERATOR_TYPE_NONE, $metadata['Ddc2387Attributes']->generatorType); - $this->assertEquals(ClassMetadataInfo::GENERATOR_TYPE_AUTO, $metadata['Ddc2387Product']->generatorType); + self::assertFalse($metadata['Ddc2387Attributes']->getProperty('productId')->hasValueGenerator()); + self::assertEquals(GeneratorType::AUTO, $metadata['Ddc2387Product']->getProperty('id')->getValueGenerator()->getType()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2409Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2409Test.php deleted file mode 100644 index 94d39b99446..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2409Test.php +++ /dev/null @@ -1,72 +0,0 @@ -useModelSet('cms'); - parent::setUp(); - } - - public function testIssue() - { - $em = $this->_em; - $uow = $em->getUnitOfWork(); - - $originalArticle = new CmsArticle(); - $originalUser = new CmsUser(); - - $originalArticle->topic = 'Unit Test'; - $originalArticle->text = 'How to write a test'; - - $originalUser->name = 'Doctrine Bot'; - $originalUser->username = 'DoctrineBot'; - $originalUser->status = 'active'; - - $originalUser->addArticle($originalArticle); - - $em->persist($originalUser); - $em->persist($originalArticle); - $em->flush(); - $em->clear(); - - $article = $em->find(CmsArticle::class, $originalArticle->id); - $user = new CmsUser(); - - $user->name = 'Doctrine Bot 2.0'; - $user->username = 'BotDoctrine2'; - $user->status = 'new'; - - $article->setAuthor($user); - - $this->assertEquals(UnitOfWork::STATE_DETACHED, $uow->getEntityState($originalArticle)); - $this->assertEquals(UnitOfWork::STATE_DETACHED, $uow->getEntityState($originalUser)); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $uow->getEntityState($article)); - $this->assertEquals(UnitOfWork::STATE_NEW, $uow->getEntityState($user)); - - $em->detach($user); - $em->detach($article); - - $userMerged = $em->merge($user); - $articleMerged = $em->merge($article); - - $this->assertEquals(UnitOfWork::STATE_NEW, $uow->getEntityState($user)); - $this->assertEquals(UnitOfWork::STATE_DETACHED, $uow->getEntityState($article)); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $uow->getEntityState($userMerged)); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $uow->getEntityState($articleMerged)); - - $this->assertNotSame($user, $userMerged); - $this->assertNotSame($article, $articleMerged); - $this->assertNotSame($userMerged, $articleMerged->user); - $this->assertSame($user, $articleMerged->user); - } -} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2415Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2415Test.php deleted file mode 100644 index fb1f0ec273a..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2415Test.php +++ /dev/null @@ -1,108 +0,0 @@ -_em->getConfiguration()->setMetadataDriverImpl(new StaticPHPDriver([])); - - $this->_schemaTool->createSchema( - [ - $this->_em->getClassMetadata(DDC2415ParentEntity::class), - $this->_em->getClassMetadata(DDC2415ChildEntity::class), - ] - ); - } - - public function testTicket() - { - $parentMetadata = $this->_em->getClassMetadata(DDC2415ParentEntity::class); - $childMetadata = $this->_em->getClassMetadata(DDC2415ChildEntity::class); - - $this->assertEquals($parentMetadata->generatorType, $childMetadata->generatorType); - $this->assertEquals($parentMetadata->customGeneratorDefinition, $childMetadata->customGeneratorDefinition); - $this->assertEquals(DDC2415Generator::class, $parentMetadata->customGeneratorDefinition['class']); - - $e1 = new DDC2415ChildEntity("ChildEntity 1"); - $e2 = new DDC2415ChildEntity("ChildEntity 2"); - - $this->_em->persist($e1); - $this->_em->persist($e2); - $this->_em->flush(); - $this->_em->clear(); - - $this->assertEquals(md5($e1->getName()), $e1->getId()); - $this->assertEquals(md5($e2->getName()), $e2->getId()); - } -} - -class DDC2415ParentEntity -{ - protected $id; - - public function getId() - { - return $this->id; - } - - public static function loadMetadata(ClassMetadataInfo $metadata) - { - $metadata->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'string', - ] - ); - - $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_CUSTOM); - $metadata->setCustomGeneratorDefinition(['class' => DDC2415Generator::class]); - - $metadata->isMappedSuperclass = true; - } -} - -class DDC2415ChildEntity extends DDC2415ParentEntity -{ - protected $name; - - public function __construct($name) - { - $this->name = $name; - } - - public function getName() - { - return $this->name; - } - - public static function loadMetadata(ClassMetadataInfo $metadata) - { - $metadata->mapField( - [ - 'fieldName' => 'name', - 'type' => 'string', - ] - ); - } -} - -class DDC2415Generator extends AbstractIdGenerator -{ - public function generate(EntityManager $em, $entity) - { - return md5($entity->getName()); - } -} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2494Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2494Test.php index 4aa30e95046..108351d97f1 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2494Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2494Test.php @@ -1,9 +1,12 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2494Currency::class), - $this->_em->getClassMetadata(DDC2494Campaign::class), + $this->em->getClassMetadata(DDC2494Currency::class), + $this->em->getClassMetadata(DDC2494Campaign::class), ] ); } @@ -31,66 +34,66 @@ public function testIssue() { $currency = new DDC2494Currency(1, 2); - $this->_em->persist($currency); - $this->_em->flush(); + $this->em->persist($currency); + $this->em->flush(); $campaign = new DDC2494Campaign($currency); - $this->_em->persist($campaign); - $this->_em->flush(); - $this->_em->close(); + $this->em->persist($campaign); + $this->em->flush(); + $this->em->close(); - $this->assertArrayHasKey('convertToDatabaseValue', DDC2494TinyIntType::$calls); - $this->assertCount(3, DDC2494TinyIntType::$calls['convertToDatabaseValue']); + self::assertArrayHasKey('convertToDatabaseValue', DDC2494TinyIntType::$calls); + self::assertCount(3, DDC2494TinyIntType::$calls['convertToDatabaseValue']); - $item = $this->_em->find(DDC2494Campaign::class, $campaign->getId()); + $item = $this->em->find(DDC2494Campaign::class, $campaign->getId()); - $this->assertInstanceOf(DDC2494Campaign::class, $item); - $this->assertInstanceOf(DDC2494Currency::class, $item->getCurrency()); + self::assertInstanceOf(DDC2494Campaign::class, $item); + self::assertInstanceOf(DDC2494Currency::class, $item->getCurrency()); $queryCount = $this->getCurrentQueryCount(); - $this->assertInstanceOf('\Doctrine\Common\Proxy\Proxy', $item->getCurrency()); - $this->assertFalse($item->getCurrency()->__isInitialized()); + self::assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $item->getCurrency()); + self::assertFalse($item->getCurrency()->__isInitialized()); - $this->assertArrayHasKey('convertToPHPValue', DDC2494TinyIntType::$calls); - $this->assertCount(1, DDC2494TinyIntType::$calls['convertToPHPValue']); + self::assertArrayHasKey('convertToPHPValue', DDC2494TinyIntType::$calls); + self::assertCount(1, DDC2494TinyIntType::$calls['convertToPHPValue']); - $this->assertInternalType('integer', $item->getCurrency()->getId()); - $this->assertCount(1, DDC2494TinyIntType::$calls['convertToPHPValue']); - $this->assertFalse($item->getCurrency()->__isInitialized()); + self::assertInternalType('integer', $item->getCurrency()->getId()); + self::assertCount(1, DDC2494TinyIntType::$calls['convertToPHPValue']); + self::assertFalse($item->getCurrency()->__isInitialized()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInternalType('integer', $item->getCurrency()->getTemp()); - $this->assertCount(3, DDC2494TinyIntType::$calls['convertToPHPValue']); - $this->assertTrue($item->getCurrency()->__isInitialized()); + self::assertInternalType('integer', $item->getCurrency()->getTemp()); + self::assertCount(3, DDC2494TinyIntType::$calls['convertToPHPValue']); + self::assertTrue($item->getCurrency()->__isInitialized()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } } /** - * @Table(name="ddc2494_currency") - * @Entity + * @ORM\Table(name="ddc2494_currency") + * @ORM\Entity */ class DDC2494Currency { /** - * @Id - * @Column(type="integer", type="ddc2494_tinyint") + * @ORM\Id + * @ORM\Column(type="integer", type="ddc2494_tinyint") */ protected $id; /** - * @Column(name="temp", type="ddc2494_tinyint", nullable=false) + * @ORM\Column(name="temp", type="ddc2494_tinyint", nullable=false) */ protected $temp; /** * @var \Doctrine\Common\Collections\Collection * - * @OneToMany(targetEntity="DDC2494Campaign", mappedBy="currency") + * @ORM\OneToMany(targetEntity="DDC2494Campaign", mappedBy="currency") */ protected $campaigns; @@ -117,23 +120,23 @@ public function getCampaigns() } /** - * @Table(name="ddc2494_campaign") - * @Entity + * @ORM\Table(name="ddc2494_campaign") + * @ORM\Entity */ class DDC2494Campaign { /** - * @Id - * @GeneratedValue - * @Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue + * @ORM\Column(type="integer") */ protected $id; /** * @var \Doctrine\Tests\ORM\Functional\Ticket\DDC2494Currency * - * @ManyToOne(targetEntity="DDC2494Currency", inversedBy="campaigns") - * @JoinColumn(name="currency_id", referencedColumnName="id", nullable=false) + * @ORM\ManyToOne(targetEntity="DDC2494Currency", inversedBy="campaigns") + * @ORM\JoinColumn(name="currency_id", referencedColumnName="id", nullable=false) */ protected $currency; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2519Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2519Test.php index cc12d044dc0..c105819c428 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2519Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2519Test.php @@ -1,5 +1,7 @@ _em->createQuery($dql)->getResult(); - - $this->assertCount(2, $result); - $this->assertInstanceOf(LegacyUserReference::class, $result[0]); - $this->assertInstanceOf(LegacyUserReference::class, $result[1]); - - $this->assertInstanceOf(LegacyUser::class, $result[0]->source()); - $this->assertInstanceOf(LegacyUser::class, $result[0]->target()); - $this->assertInstanceOf(LegacyUser::class, $result[1]->source()); - $this->assertInstanceOf(LegacyUser::class, $result[1]->target()); - - $this->assertInstanceOf(Proxy::class, $result[0]->source()); - $this->assertInstanceOf(Proxy::class, $result[0]->target()); - $this->assertInstanceOf(Proxy::class, $result[1]->source()); - $this->assertInstanceOf(Proxy::class, $result[1]->target()); - - $this->assertFalse($result[0]->target()->__isInitialized()); - $this->assertFalse($result[0]->source()->__isInitialized()); - $this->assertFalse($result[1]->target()->__isInitialized()); - $this->assertFalse($result[1]->source()->__isInitialized()); - - $this->assertNotNull($result[0]->source()->getId()); - $this->assertNotNull($result[0]->target()->getId()); - $this->assertNotNull($result[1]->source()->getId()); - $this->assertNotNull($result[1]->target()->getId()); + $dql = 'SELECT PARTIAL l.{source, target} FROM Doctrine\Tests\Models\Legacy\LegacyUserReference l'; + $result = $this->em->createQuery($dql)->getResult(); + + self::assertCount(2, $result); + self::assertInstanceOf(LegacyUserReference::class, $result[0]); + self::assertInstanceOf(LegacyUserReference::class, $result[1]); + + self::assertInstanceOf(LegacyUser::class, $result[0]->source()); + self::assertInstanceOf(LegacyUser::class, $result[0]->target()); + self::assertInstanceOf(LegacyUser::class, $result[1]->source()); + self::assertInstanceOf(LegacyUser::class, $result[1]->target()); + + self::assertInstanceOf(Proxy::class, $result[0]->source()); + self::assertInstanceOf(Proxy::class, $result[0]->target()); + self::assertInstanceOf(Proxy::class, $result[1]->source()); + self::assertInstanceOf(Proxy::class, $result[1]->target()); + + self::assertFalse($result[0]->target()->__isInitialized()); + self::assertFalse($result[0]->source()->__isInitialized()); + self::assertFalse($result[1]->target()->__isInitialized()); + self::assertFalse($result[1]->source()->__isInitialized()); + + self::assertNotNull($result[0]->source()->getId()); + self::assertNotNull($result[0]->target()->getId()); + self::assertNotNull($result[1]->source()->getId()); + self::assertNotNull($result[1]->target()->getId()); } public function loadFixture() { $user1 = new LegacyUser(); - $user1->_username = 'FabioBatSilva'; - $user1->_name = 'Fabio B. Silva'; - $user1->_status = 'active'; + $user1->username = 'FabioBatSilva'; + $user1->name = 'Fabio B. Silva'; + $user1->status = 'active'; $user2 = new LegacyUser(); - $user2->_username = 'doctrinebot'; - $user2->_name = 'Doctrine Bot'; - $user2->_status = 'active'; + $user2->username = 'doctrinebot'; + $user2->name = 'Doctrine Bot'; + $user2->status = 'active'; $user3 = new LegacyUser(); - $user3->_username = 'test'; - $user3->_name = 'Tester'; - $user3->_status = 'active'; + $user3->username = 'test'; + $user3->name = 'Tester'; + $user3->status = 'active'; - $this->_em->persist($user1); - $this->_em->persist($user2); - $this->_em->persist($user3); + $this->em->persist($user1); + $this->em->persist($user2); + $this->em->persist($user3); - $this->_em->flush(); + $this->em->flush(); - $this->_em->persist(new LegacyUserReference($user1, $user2, 'foo')); - $this->_em->persist(new LegacyUserReference($user1, $user3, 'bar')); + $this->em->persist(new LegacyUserReference($user1, $user2, 'foo')); + $this->em->persist(new LegacyUserReference($user1, $user3, 'bar')); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2575Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2575Test.php index e3652e55c04..9e8b2560eb4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2575Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2575Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2575Root::class), - $this->_em->getClassMetadata(DDC2575A::class), - $this->_em->getClassMetadata(DDC2575B::class), + $this->em->getClassMetadata(DDC2575Root::class), + $this->em->getClassMetadata(DDC2575A::class), + $this->em->getClassMetadata(DDC2575B::class), ] ); @@ -27,19 +31,19 @@ protected function setUp() $entityB1 = new DDC2575B(2); $entityA1 = new DDC2575A($entityRoot1, $entityB1); - $this->_em->persist($entityRoot1); - $this->_em->persist($entityA1); - $this->_em->persist($entityB1); + $this->em->persist($entityRoot1); + $this->em->persist($entityA1); + $this->em->persist($entityB1); $entityRoot2 = new DDC2575Root(3); $entityB2 = new DDC2575B(4); $entityA2 = new DDC2575A($entityRoot2, $entityB2); - $this->_em->persist($entityRoot2); - $this->_em->persist($entityA2); - $this->_em->persist($entityB2); + $this->em->persist($entityRoot2); + $this->em->persist($entityA2); + $this->em->persist($entityB2); - $this->_em->flush(); + $this->em->flush(); $this->rootsEntities[] = $entityRoot1; $this->rootsEntities[] = $entityRoot2; @@ -50,12 +54,12 @@ protected function setUp() $this->bEntities[] = $entityB1; $this->bEntities[] = $entityB2; - $this->_em->clear(); + $this->em->clear(); } public function testHydrationIssue() { - $repository = $this->_em->getRepository(DDC2575Root::class); + $repository = $this->em->getRepository(DDC2575Root::class); $qb = $repository->createQueryBuilder('r') ->select('r, a, b') ->leftJoin('r.aRelation', 'a') @@ -64,44 +68,44 @@ public function testHydrationIssue() $query = $qb->getQuery(); $result = $query->getResult(); - $this->assertCount(2, $result); + self::assertCount(2, $result); $row = $result[0]; - $this->assertNotNull($row->aRelation); - $this->assertEquals(1, $row->id); - $this->assertNotNull($row->aRelation->rootRelation); - $this->assertSame($row, $row->aRelation->rootRelation); - $this->assertNotNull($row->aRelation->bRelation); - $this->assertEquals(2, $row->aRelation->bRelation->id); + self::assertNotNull($row->aRelation); + self::assertEquals(1, $row->id); + self::assertNotNull($row->aRelation->rootRelation); + self::assertSame($row, $row->aRelation->rootRelation); + self::assertNotNull($row->aRelation->bRelation); + self::assertEquals(2, $row->aRelation->bRelation->id); $row = $result[1]; - $this->assertNotNull($row->aRelation); - $this->assertEquals(3, $row->id); - $this->assertNotNull($row->aRelation->rootRelation); - $this->assertSame($row, $row->aRelation->rootRelation); - $this->assertNotNull($row->aRelation->bRelation); - $this->assertEquals(4, $row->aRelation->bRelation->id); + self::assertNotNull($row->aRelation); + self::assertEquals(3, $row->id); + self::assertNotNull($row->aRelation->rootRelation); + self::assertSame($row, $row->aRelation->rootRelation); + self::assertNotNull($row->aRelation->bRelation); + self::assertEquals(4, $row->aRelation->bRelation->id); } } /** - * @Entity + * @ORM\Entity */ class DDC2575Root { /** - * @Id - * @Column(type="integer") + * @ORM\Id + * @ORM\Column(type="integer") */ public $id; /** - * @Column(type="integer") + * @ORM\Column(type="integer") */ public $sampleField; /** - * @OneToOne(targetEntity="DDC2575A", mappedBy="rootRelation") + * @ORM\OneToOne(targetEntity="DDC2575A", mappedBy="rootRelation") **/ public $aRelation; @@ -114,20 +118,20 @@ public function __construct($id, $value = 0) } /** - * @Entity + * @ORM\Entity */ class DDC2575A { /** - * @Id - * @OneToOne(targetEntity="DDC2575Root", inversedBy="aRelation") - * @JoinColumn(name="root_id", referencedColumnName="id", nullable=FALSE, onDelete="CASCADE") + * @ORM\Id + * @ORM\OneToOne(targetEntity="DDC2575Root", inversedBy="aRelation") + * @ORM\JoinColumn(name="root_id", referencedColumnName="id", nullable=FALSE, onDelete="CASCADE") */ public $rootRelation; /** - * @ManyToOne(targetEntity="DDC2575B") - * @JoinColumn(name="b_id", referencedColumnName="id", nullable=FALSE, onDelete="CASCADE") + * @ORM\ManyToOne(targetEntity="DDC2575B") + * @ORM\JoinColumn(name="b_id", referencedColumnName="id", nullable=FALSE, onDelete="CASCADE") */ public $bRelation; @@ -139,18 +143,18 @@ public function __construct(DDC2575Root $rootRelation, DDC2575B $bRelation) } /** - * @Entity + * @ORM\Entity */ class DDC2575B { /** - * @Id - * @Column(type="integer") + * @ORM\Id + * @ORM\Column(type="integer") */ public $id; /** - * @Column(type="integer") + * @ORM\Column(type="integer") */ public $sampleField; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2579Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2579Test.php index e7ba77759f4..fce3ec39029 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2579Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2579Test.php @@ -1,10 +1,13 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2579Entity::class), - $this->_em->getClassMetadata(DDC2579EntityAssoc::class), - $this->_em->getClassMetadata(DDC2579AssocAssoc::class), + $this->em->getClassMetadata(DDC2579Entity::class), + $this->em->getClassMetadata(DDC2579EntityAssoc::class), + $this->em->getClassMetadata(DDC2579AssocAssoc::class), ] ); } @@ -32,56 +35,56 @@ public function testIssue() $assoc = new DDC2579AssocAssoc($id); $assocAssoc = new DDC2579EntityAssoc($assoc); $entity = new DDC2579Entity($assocAssoc); - $repository = $this->_em->getRepository(DDC2579Entity::class); + $repository = $this->em->getRepository(DDC2579Entity::class); - $this->_em->persist($assoc); - $this->_em->persist($assocAssoc); - $this->_em->persist($entity); - $this->_em->flush(); + $this->em->persist($assoc); + $this->em->persist($assocAssoc); + $this->em->persist($entity); + $this->em->flush(); $entity->value++; - $this->_em->persist($entity); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($entity); + $this->em->flush(); + $this->em->clear(); $id = $entity->id; $value = $entity->value; $criteria = ['assoc' => $assoc, 'id' => $id]; $entity = $repository->findOneBy($criteria); - $this->assertInstanceOf(DDC2579Entity::class, $entity); - $this->assertEquals($value, $entity->value); + self::assertInstanceOf(DDC2579Entity::class, $entity); + self::assertEquals($value, $entity->value); - $this->_em->remove($entity); - $this->_em->flush(); - $this->_em->clear(); + $this->em->remove($entity); + $this->em->flush(); + $this->em->clear(); - $this->assertNull($repository->findOneBy($criteria)); - $this->assertCount(0, $repository->findAll()); + self::assertNull($repository->findOneBy($criteria)); + self::assertCount(0, $repository->findAll()); } } /** - * @Entity + * @ORM\Entity */ class DDC2579Entity { /** - * @Id - * @Column(type="ddc2579") + * @ORM\Id + * @ORM\Column(type="ddc2579") */ public $id; /** - * @Id - * @ManyToOne(targetEntity="DDC2579EntityAssoc") - * @JoinColumn(name="relation_id", referencedColumnName="association_id") + * @ORM\Id + * @ORM\ManyToOne(targetEntity="DDC2579EntityAssoc") + * @ORM\JoinColumn(name="relation_id", referencedColumnName="association_id") */ public $assoc; /** - * @Column(type="integer") + * @ORM\Column(type="integer") */ public $value; @@ -95,14 +98,14 @@ public function __construct(DDC2579EntityAssoc $assoc, $value = 0) } /** - * @Entity + * @ORM\Entity */ class DDC2579EntityAssoc { /** - * @Id - * @ManyToOne(targetEntity="DDC2579AssocAssoc") - * @JoinColumn(name="association_id", referencedColumnName="associationId") + * @ORM\Id + * @ORM\ManyToOne(targetEntity="DDC2579AssocAssoc") + * @ORM\JoinColumn(name="association_id", referencedColumnName="associationId") */ public $assocAssoc; @@ -113,13 +116,13 @@ public function __construct(DDC2579AssocAssoc $assocAssoc) } /** - * @Entity + * @ORM\Entity */ class DDC2579AssocAssoc { /** - * @Id - * @Column(type="ddc2579") + * @ORM\Id + * @ORM\Column(type="ddc2579") */ public $associationId; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC258Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC258Test.php index fb7ce673e3e..41f87ef8243 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC258Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC258Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC258Super::class), - $this->_em->getClassMetadata(DDC258Class1::class), - $this->_em->getClassMetadata(DDC258Class2::class), - $this->_em->getClassMetadata(DDC258Class3::class), + $this->em->getClassMetadata(DDC258Super::class), + $this->em->getClassMetadata(DDC258Class1::class), + $this->em->getClassMetadata(DDC258Class2::class), + $this->em->getClassMetadata(DDC258Class3::class), ] ); } @@ -24,7 +27,7 @@ protected function setUp() */ public function testIssue() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $c1 = new DDC258Class1(); $c1->title = "Foo"; @@ -39,33 +42,33 @@ public function testIssue() $c3->apples = "Baz"; $c3->bananas = "Baz"; - $this->_em->persist($c1); - $this->_em->persist($c2); - $this->_em->persist($c3); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($c1); + $this->em->persist($c2); + $this->em->persist($c3); + $this->em->flush(); + $this->em->clear(); - $e2 = $this->_em->find(DDC258Super::class, $c2->id); + $e2 = $this->em->find(DDC258Super::class, $c2->id); - $this->assertInstanceOf(DDC258Class2::class, $e2); - $this->assertEquals('Bar', $e2->title); - $this->assertEquals('Bar', $e2->description); - $this->assertEquals('Bar', $e2->text); + self::assertInstanceOf(DDC258Class2::class, $e2); + self::assertEquals('Bar', $e2->title); + self::assertEquals('Bar', $e2->description); + self::assertEquals('Bar', $e2->text); - $all = $this->_em->getRepository(DDC258Super::class)->findAll(); + $all = $this->em->getRepository(DDC258Super::class)->findAll(); foreach ($all as $obj) { if ($obj instanceof DDC258Class1) { - $this->assertEquals('Foo', $obj->title); - $this->assertEquals('Foo', $obj->description); + self::assertEquals('Foo', $obj->title); + self::assertEquals('Foo', $obj->description); } else if ($obj instanceof DDC258Class2) { - $this->assertTrue($e2 === $obj); - $this->assertEquals('Bar', $obj->title); - $this->assertEquals('Bar', $obj->description); - $this->assertEquals('Bar', $obj->text); + self::assertTrue($e2 === $obj); + self::assertEquals('Bar', $obj->title); + self::assertEquals('Bar', $obj->description); + self::assertEquals('Bar', $obj->text); } else if ($obj instanceof DDC258Class3) { - $this->assertEquals('Baz', $obj->apples); - $this->assertEquals('Baz', $obj->bananas); + self::assertEquals('Baz', $obj->apples); + self::assertEquals('Baz', $obj->bananas); } else { $this->fail('Instance of DDC258Class1, DDC258Class2 or DDC258Class3 expected.'); } @@ -74,54 +77,54 @@ public function testIssue() } /** - * @Entity - * @Table(name="DDC258Super") - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="type", type="string") - * @DiscriminatorMap({"class1" = "DDC258Class1", "class2" = "DDC258Class2", "class3"="DDC258Class3"}) + * @ORM\Entity + * @ORM\Table(name="DDC258Super") + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="type", type="string") + * @ORM\DiscriminatorMap({"class1" = "DDC258Class1", "class2" = "DDC258Class2", "class3"="DDC258Class3"}) */ abstract class DDC258Super { /** - * @Id @Column(name="id", type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; } /** - * @Entity + * @ORM\Entity */ class DDC258Class1 extends DDC258Super { /** - * @Column(name="title", type="string", length=150) + * @ORM\Column(name="title", type="string", length=150) */ public $title; /** - * @Column(name="content", type="string", length=500) + * @ORM\Column(name="content", type="string", length=500) */ public $description; } /** - * @Entity + * @ORM\Entity */ class DDC258Class2 extends DDC258Super { /** - * @Column(name="title", type="string", length=150) + * @ORM\Column(name="title", type="string", length=150) */ public $title; /** - * @Column(name="content", type="string", length=500) + * @ORM\Column(name="content", type="string", length=500) */ public $description; /** - * @Column(name="text", type="text") + * @ORM\Column(name="text", type="text") */ public $text; } @@ -129,17 +132,17 @@ class DDC258Class2 extends DDC258Super /** * An extra class to demonstrate why title and description aren't in Super * - * @Entity + * @ORM\Entity */ class DDC258Class3 extends DDC258Super { /** - * @Column(name="title", type="string", length=150) + * @ORM\Column(name="title", type="string", length=150) */ public $apples; /** - * @Column(name="content", type="string", length=500) + * @ORM\Column(name="content", type="string", length=500) */ public $bananas; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2645Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2645Test.php deleted file mode 100644 index d6a77f7db37..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2645Test.php +++ /dev/null @@ -1,53 +0,0 @@ -id = 123; - - $foo = new DDC2645Foo(1, $bar, 'Foo'); - $foo2 = new DDC2645Foo(1, $bar, 'Bar'); - - $this->_em->persist($bar); - $this->_em->persist($foo); - - $foo3 = $this->_em->merge($foo2); - - $this->assertSame($foo, $foo3); - $this->assertEquals('Bar', $foo->name); - } -} - -/** @Entity */ -class DDC2645Foo -{ - /** @Id @Column(type="integer") */ - private $id; - - /** @Id @ManyToOne(targetEntity="DDC2645Bar") */ - private $bar; - - /** @Column */ - public $name; - - public function __construct($id, $bar, $name) - { - $this->id = $id; - $this->bar = $bar; - $this->name = $name; - } -} - -/** @Entity */ -class DDC2645Bar -{ - /** @Id @Column(type="integer") @GeneratedValue(strategy="NONE") */ - public $id; -} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2655Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2655Test.php index 8a2dc166a84..af85010ee3f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2655Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2655Test.php @@ -1,5 +1,7 @@ _em->createQuery("SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'happy_doctrine_user'"); - $this->assertNull($query->getOneOrNullResult(Query::HYDRATE_SINGLE_SCALAR)); + $query = $this->em->createQuery("SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'happy_doctrine_user'"); + self::assertNull($query->getOneOrNullResult(Query::HYDRATE_SINGLE_SCALAR)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2660Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2660Test.php index 46380f754b2..98f951adfc7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2660Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2660Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2660Product::class), - $this->_em->getClassMetadata(DDC2660Customer::class), - $this->_em->getClassMetadata(DDC2660CustomerOrder::class) + $this->em->getClassMetadata(DDC2660Product::class), + $this->em->getClassMetadata(DDC2660Customer::class), + $this->em->getClassMetadata(DDC2660CustomerOrder::class) ] ); } catch(\Exception $e) { @@ -33,32 +36,32 @@ protected function setUp() $customer = new DDC2660Customer(); $order = new DDC2660CustomerOrder($product, $customer, 'name' . $i); - $this->_em->persist($product); - $this->_em->persist($customer); - $this->_em->flush(); + $this->em->persist($product); + $this->em->persist($customer); + $this->em->flush(); - $this->_em->persist($order); - $this->_em->flush(); + $this->em->persist($order); + $this->em->flush(); } - $this->_em->clear(); + $this->em->clear(); } public function testIssueWithExtraColumn() { $sql = "SELECT o.product_id, o.customer_id, o.name FROM ddc_2660_customer_order o"; - $rsm = new ResultSetMappingBuilder($this->_getEntityManager()); + $rsm = new ResultSetMappingBuilder($this->getEntityManager()); $rsm->addRootEntityFromClassMetadata(DDC2660CustomerOrder::class, 'c'); - $query = $this->_em->createNativeQuery($sql, $rsm); + $query = $this->em->createNativeQuery($sql, $rsm); $result = $query->getResult(); - $this->assertCount(5, $result); + self::assertCount(5, $result); foreach ($result as $order) { - $this->assertNotNull($order); - $this->assertInstanceOf(DDC2660CustomerOrder::class, $order); + self::assertNotNull($order); + self::assertInstanceOf(DDC2660CustomerOrder::class, $order); } } @@ -66,51 +69,51 @@ public function testIssueWithoutExtraColumn() { $sql = "SELECT o.product_id, o.customer_id FROM ddc_2660_customer_order o"; - $rsm = new ResultSetMappingBuilder($this->_getEntityManager()); + $rsm = new ResultSetMappingBuilder($this->getEntityManager()); $rsm->addRootEntityFromClassMetadata(DDC2660CustomerOrder::class, 'c'); - $query = $this->_em->createNativeQuery($sql, $rsm); + $query = $this->em->createNativeQuery($sql, $rsm); $result = $query->getResult(); - $this->assertCount(5, $result); + self::assertCount(5, $result); foreach ($result as $order) { - $this->assertNotNull($order); - $this->assertInstanceOf(DDC2660CustomerOrder::class, $order); + self::assertNotNull($order); + self::assertInstanceOf(DDC2660CustomerOrder::class, $order); } } } /** - * @Entity @Table(name="ddc_2660_product") + * @ORM\Entity @ORM\Table(name="ddc_2660_product") */ class DDC2660Product { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; } -/** @Entity @Table(name="ddc_2660_customer") */ +/** @ORM\Entity @ORM\Table(name="ddc_2660_customer") */ class DDC2660Customer { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; } -/** @Entity @Table(name="ddc_2660_customer_order") */ +/** @ORM\Entity @ORM\Table(name="ddc_2660_customer_order") */ class DDC2660CustomerOrder { /** - * @Id @ManyToOne(targetEntity="DDC2660Product") + * @ORM\Id @ORM\ManyToOne(targetEntity="DDC2660Product") */ public $product; /** - * @Id @ManyToOne(targetEntity="DDC2660Customer") + * @ORM\Id @ORM\ManyToOne(targetEntity="DDC2660Customer") */ public $customer; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $name; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2692Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2692Test.php index 1e9f05e4768..f324e680de3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2692Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2692Test.php @@ -1,8 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2692Foo::class), + $this->em->getClassMetadata(DDC2692Foo::class), ] ); } catch(\Exception $e) { return; } - $this->_em->clear(); + $this->em->clear(); } public function testIsListenerCalledOnlyOnceOnPreFlush() @@ -37,21 +40,21 @@ public function testIsListenerCalledOnlyOnceOnPreFlush() $listener->expects($this->once())->method('preFlush'); - $this->_em->getEventManager()->addEventSubscriber($listener); + $this->em->getEventManager()->addEventSubscriber($listener); - $this->_em->persist(new DDC2692Foo); - $this->_em->persist(new DDC2692Foo); + $this->em->persist(new DDC2692Foo); + $this->em->persist(new DDC2692Foo); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); } } /** - * @Entity @Table(name="ddc_2692_foo") + * @ORM\Entity @ORM\Table(name="ddc_2692_foo") */ class DDC2692Foo { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2759Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2759Test.php index 10d3e68ae91..12578ff2cac 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2759Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2759Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2759Qualification::class), - $this->_em->getClassMetadata(DDC2759Category::class), - $this->_em->getClassMetadata(DDC2759QualificationMetadata::class), - $this->_em->getClassMetadata(DDC2759MetadataCategory::class), + $this->em->getClassMetadata(DDC2759Qualification::class), + $this->em->getClassMetadata(DDC2759Category::class), + $this->em->getClassMetadata(DDC2759QualificationMetadata::class), + $this->em->getClassMetadata(DDC2759MetadataCategory::class), ] ); } catch(\Exception $e) { @@ -36,22 +40,22 @@ protected function setUp() $metadataCategory1 = new DDC2759MetadataCategory($qualificationMetadata, $category1); $metadataCategory2 = new DDC2759MetadataCategory($qualificationMetadata, $category2); - $this->_em->persist($qualification); - $this->_em->persist($qualificationMetadata); + $this->em->persist($qualification); + $this->em->persist($qualificationMetadata); - $this->_em->persist($category1); - $this->_em->persist($category2); + $this->em->persist($category1); + $this->em->persist($category2); - $this->_em->persist($metadataCategory1); - $this->_em->persist($metadataCategory2); + $this->em->persist($metadataCategory1); + $this->em->persist($metadataCategory2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); } public function testCorrectNumberOfAssociationsIsReturned() { - $repository = $this->_em->getRepository(DDC2759Qualification::class); + $repository = $this->em->getRepository(DDC2759Qualification::class); $builder = $repository->createQueryBuilder('q') ->select('q, qm, qmc') @@ -61,40 +65,40 @@ public function testCorrectNumberOfAssociationsIsReturned() $result = $builder->getQuery() ->getArrayResult(); - $this->assertCount(2, $result[0]['metadata']['metadataCategories']); + self::assertCount(2, $result[0]['metadata']['metadataCategories']); } } -/** @Entity @Table(name="ddc_2759_qualification") */ +/** @ORM\Entity @ORM\Table(name="ddc_2759_qualification") */ class DDC2759Qualification { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @OneToOne(targetEntity="DDC2759QualificationMetadata", mappedBy="content") */ + /** @ORM\OneToOne(targetEntity="DDC2759QualificationMetadata", mappedBy="content") */ public $metadata; } -/** @Entity @Table(name="ddc_2759_category") */ +/** @ORM\Entity @ORM\Table(name="ddc_2759_category") */ class DDC2759Category { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @OneToMany(targetEntity="DDC2759MetadataCategory", mappedBy="category") */ + /** @ORM\OneToMany(targetEntity="DDC2759MetadataCategory", mappedBy="category") */ public $metadataCategories; } -/** @Entity @Table(name="ddc_2759_qualification_metadata") */ +/** @ORM\Entity @ORM\Table(name="ddc_2759_qualification_metadata") */ class DDC2759QualificationMetadata { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @OneToOne(targetEntity="DDC2759Qualification", inversedBy="metadata") */ + /** @ORM\OneToOne(targetEntity="DDC2759Qualification", inversedBy="metadata") */ public $content; - /** @OneToMany(targetEntity="DDC2759MetadataCategory", mappedBy="metadata") */ + /** @ORM\OneToMany(targetEntity="DDC2759MetadataCategory", mappedBy="metadata") */ protected $metadataCategories; public function __construct(DDC2759Qualification $content) @@ -103,16 +107,16 @@ public function __construct(DDC2759Qualification $content) } } -/** @Entity @Table(name="ddc_2759_metadata_category") */ +/** @ORM\Entity @ORM\Table(name="ddc_2759_metadata_category") */ class DDC2759MetadataCategory { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @ManyToOne(targetEntity="DDC2759QualificationMetadata", inversedBy="metadataCategories") */ + /** @ORM\ManyToOne(targetEntity="DDC2759QualificationMetadata", inversedBy="metadataCategories") */ public $metadata; - /** @ManyToOne(targetEntity="DDC2759Category", inversedBy="metadataCategories") */ + /** @ORM\ManyToOne(targetEntity="DDC2759Category", inversedBy="metadataCategories") */ public $category; public function __construct(DDC2759QualificationMetadata $metadata, DDC2759Category $category) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2775Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2775Test.php index b84024f048d..b3542cf1897 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2775Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2775Test.php @@ -1,7 +1,10 @@ addAuthorization($authorization); $role->addAuthorization($authorization); - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); // Need to clear so that associations are lazy-loaded - $this->_em->clear(); + $this->em->clear(); - $user = $this->_em->find(User::class, $user->id); + $user = $this->em->find(User::class, $user->id); - $this->_em->remove($user); - $this->_em->flush(); + $this->em->remove($user); + $this->em->flush(); - self::assertEmpty($this->_em->getRepository(Authorization::class)->findAll()); + self::assertEmpty($this->em->getRepository(Authorization::class)->findAll()); // With the bug, the second flush throws an error because the cascade remove didn't work correctly - $this->_em->flush(); + $this->em->flush(); } } /** - * @Entity @Table(name="ddc2775_role") - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="role_type", type="string") - * @DiscriminatorMap({"admin"="AdminRole"}) + * @ORM\Entity + * @ORM\Table(name="ddc2775_role") + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="role_type", type="string") + * @ORM\DiscriminatorMap({"admin"="AdminRole"}) */ abstract class Role { /** - * @Id @Column(type="integer") - * @GeneratedValue + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue */ public $id; /** - * @ManyToOne(targetEntity="User", inversedBy="roles") + * @ORM\ManyToOne(targetEntity="User", inversedBy="roles") */ public $user; /** - * @OneToMany(targetEntity="Authorization", mappedBy="role", cascade={"all"}, orphanRemoval=true) + * @ORM\OneToMany(targetEntity="Authorization", mappedBy="role", cascade={"all"}, orphanRemoval=true) */ public $authorizations; @@ -87,51 +92,51 @@ public function addAuthorization(Authorization $authorization) } } -/** @Entity @Table(name="ddc2775_admin_role") */ +/** @ORM\Entity @ORM\Table(name="ddc2775_admin_role") */ class AdminRole extends Role { } /** - * @Entity @Table(name="ddc2775_authorizations") + * @ORM\Entity @ORM\Table(name="ddc2775_authorizations") */ class Authorization { /** - * @Id @Column(type="integer") - * @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue */ public $id; /** - * @ManyToOne(targetEntity="User", inversedBy="authorizations") + * @ORM\ManyToOne(targetEntity="User", inversedBy="authorizations") */ public $user; /** - * @ManyToOne(targetEntity="Role", inversedBy="authorizations") + * @ORM\ManyToOne(targetEntity="Role", inversedBy="authorizations") */ public $role; } /** - * @Entity @Table(name="ddc2775_users") + * @ORM\Entity @ORM\Table(name="ddc2775_users") */ class User { /** - * @Id @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @OneToMany(targetEntity="Role", mappedBy="user", cascade={"all"}, orphanRemoval=true) + * @ORM\OneToMany(targetEntity="Role", mappedBy="user", cascade={"all"}, orphanRemoval=true) */ public $roles; /** - * @OneToMany(targetEntity="Authorization", mappedBy="user", cascade={"all"}, orphanRemoval=true) + * @ORM\OneToMany(targetEntity="Authorization", mappedBy="user", cascade={"all"}, orphanRemoval=true) */ public $authorizations; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2780Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2780Test.php index 5539dfbbe5c..9469d725c4d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2780Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2780Test.php @@ -1,8 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2780User::class), - $this->_em->getClassMetadata(DDC2780Project::class) + $this->em->getClassMetadata(DDC2780User::class), + $this->em->getClassMetadata(DDC2780Project::class) ] ); } @@ -34,12 +37,12 @@ public function testIssue() $user->project = $project; - $this->_em->persist($project); - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($project); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); - $result = $this->_em->createQueryBuilder() + $result = $this->em->createQueryBuilder() ->select('user') ->from(DDC2780User::class, 'user') ->leftJoin('user.project', 'project') @@ -47,34 +50,40 @@ public function testIssue() ->getQuery() ->getOneOrNullResult(); - $this->assertInstanceOf(DDC2780User::class, $result); + self::assertInstanceOf(DDC2780User::class, $result); } } /** - * @Entity + * @ORM\Entity */ class DDC2780User { - /** @Id @Column(type="integer") @GeneratedValue */ + /** + * @ORM\Id @ORM\GeneratedValue + * @ORM\Column(type="integer") + */ public $id; /** - * @ManyToOne(targetEntity="DDC2780Project") + * @ORM\ManyToOne(targetEntity="DDC2780Project") * * @var DDC2780Project */ public $project; } -/** @Entity */ +/** @ORM\Entity */ class DDC2780Project { - /** @Id @Column(type="integer") @GeneratedValue */ + /** + * @ORM\Id @ORM\GeneratedValue + * @ORM\Column(type="integer") + */ public $id; /** - * @OneToMany(targetEntity="DDC2780User", mappedBy="project") + * @ORM\OneToMany(targetEntity="DDC2780User", mappedBy="project") * * @var DDC2780User[] */ diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2790Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2790Test.php index ee2668931c0..93d2aa69c4a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2790Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2790Test.php @@ -1,5 +1,7 @@ _em->getEventManager()->addEventListener(Events::onFlush, new OnFlushListener); + $this->em->getEventManager()->addEventListener(Events::onFlush, new OnFlushListener); $entity = new CmsUser; $entity->username = 'romanb'; $entity->name = 'Roman'; - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->from(get_class($entity), 'c'); $qb->select("count(c)"); $initial = intval($qb->getQuery()->getSingleScalarResult()); - $this->_em->persist($entity); - $this->_em->flush(); + $this->em->persist($entity); + $this->em->flush(); - $this->_em->remove($entity); + $this->em->remove($entity); // in Doctrine <2.5, this causes an UPDATE statement to be added before the DELETE statement // (and consequently also triggers preUpdate/postUpdate for the entity in question) $entity->name = 'Robin'; - $this->_em->flush($entity); + $this->em->flush(); - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->from(get_class($entity), 'c'); $qb->select("count(c)"); $count = intval($qb->getQuery()->getSingleScalarResult()); - $this->assertEquals($initial, $count); + self::assertEquals($initial, $count); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC279Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC279Test.php index f09e2e68ccd..dd647404e5f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC279Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC279Test.php @@ -1,18 +1,22 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC279EntityXAbstract::class), - $this->_em->getClassMetadata(DDC279EntityX::class), - $this->_em->getClassMetadata(DDC279EntityY::class), - $this->_em->getClassMetadata(DDC279EntityZ::class), + $this->em->getClassMetadata(DDC279EntityXAbstract::class), + $this->em->getClassMetadata(DDC279EntityX::class), + $this->em->getClassMetadata(DDC279EntityY::class), + $this->em->getClassMetadata(DDC279EntityZ::class), ] ); } @@ -33,14 +37,14 @@ public function testDDC279() $x->y = $y; $y->z = $z; - $this->_em->persist($x); - $this->_em->persist($y); - $this->_em->persist($z); + $this->em->persist($x); + $this->em->persist($y); + $this->em->persist($z); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $query = $this->_em->createQuery( + $query = $this->em->createQuery( 'SELECT x, y, z FROM Doctrine\Tests\ORM\Functional\Ticket\DDC279EntityX x '. 'INNER JOIN x.y y INNER JOIN y.z z WHERE x.id = ?1' )->setParameter(1, $x->id); @@ -50,84 +54,84 @@ public function testDDC279() $expected1 = 'Y'; $expected2 = 'Z'; - $this->assertEquals(1, count($result)); + self::assertEquals(1, count($result)); - $this->assertEquals($expected1, $result[0]->y->data); - $this->assertEquals($expected2, $result[0]->y->z->data); + self::assertEquals($expected1, $result[0]->y->data); + self::assertEquals($expected2, $result[0]->y->z->data); } } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="discr", type="string") - * @DiscriminatorMap({"DDC279EntityX" = "DDC279EntityX"}) + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="discr", type="string") + * @ORM\DiscriminatorMap({"DDC279EntityX" = "DDC279EntityX"}) */ abstract class DDC279EntityXAbstract { /** - * @Id - * @GeneratedValue - * @Column(name="id", type="integer") + * @ORM\Id + * @ORM\GeneratedValue + * @ORM\Column(name="id", type="integer") */ public $id; /** - * @column(type="string") + * @ORM\Column(type="string") */ public $data; } /** - * @Entity + * @ORM\Entity */ class DDC279EntityX extends DDC279EntityXAbstract { /** - * @OneToOne(targetEntity="DDC279EntityY") - * @JoinColumn(name="y_id", referencedColumnName="id") + * @ORM\OneToOne(targetEntity="DDC279EntityY") + * @ORM\JoinColumn(name="y_id", referencedColumnName="id") */ public $y; } /** - * @Entity + * @ORM\Entity */ class DDC279EntityY { /** - * @Id @GeneratedValue - * @Column(name="id", type="integer") + * @ORM\Id @ORM\GeneratedValue + * @ORM\Column(name="id", type="integer") */ public $id; /** - * @column(type="string") + * @ORM\Column(type="string") */ public $data; /** - * @OneToOne(targetEntity="DDC279EntityZ") - * @JoinColumn(name="z_id", referencedColumnName="id") + * @ORM\OneToOne(targetEntity="DDC279EntityZ") + * @ORM\JoinColumn(name="z_id", referencedColumnName="id") */ public $z; } /** - * @Entity + * @ORM\Entity */ class DDC279EntityZ { /** - * @Id @GeneratedValue - * @Column(name="id", type="integer") + * @ORM\Id @ORM\GeneratedValue + * @ORM\Column(name="id", type="integer") */ public $id; /** - * @column(type="string") + * @ORM\Column(type="string") */ public $data; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2825Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2825Test.php index 7aeba002a0a..189d7873ed8 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2825Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2825Test.php @@ -1,7 +1,10 @@ _em->getConnection()->getDatabasePlatform(); + $platform = $this->em->getConnection()->getDatabasePlatform(); if ( ! $platform->supportsSchemas() && ! $platform->canEmulateSchemas()) { $this->markTestSkipped("This test is only useful for databases that support schemas or can emulate them."); @@ -36,26 +39,30 @@ protected function setUp() */ public function testClassSchemaMappingsValidity($className, $expectedSchemaName, $expectedTableName) { - $classMetadata = $this->_em->getClassMetadata($className); - $platform = $this->_em->getConnection()->getDatabasePlatform(); - $quotedTableName = $this->_em->getConfiguration()->getQuoteStrategy()->getTableName($classMetadata, $platform); + $classMetadata = $this->em->getClassMetadata($className); + $platform = $this->em->getConnection()->getDatabasePlatform(); + $quotedTableName = $classMetadata->table->getQuotedQualifiedName($platform); // Check if table name and schema properties are defined in the class metadata - $this->assertEquals($expectedTableName, $classMetadata->table['name']); - $this->assertEquals($expectedSchemaName, $classMetadata->table['schema']); + self::assertEquals($expectedTableName, $classMetadata->table->getName()); + self::assertEquals($expectedSchemaName, $classMetadata->table->getSchema()); - if ($this->_em->getConnection()->getDatabasePlatform()->supportsSchemas()) { - $fullTableName = sprintf('%s.%s', $expectedSchemaName, $expectedTableName); + if ($platform->supportsSchemas()) { + $fullTableName = sprintf('"%s"."%s"', $expectedSchemaName, $expectedTableName); } else { - $fullTableName = sprintf('%s__%s', $expectedSchemaName, $expectedTableName); + $fullTableName = sprintf('"%s__%s"', $expectedSchemaName, $expectedTableName); } - $this->assertEquals($fullTableName, $quotedTableName); + self::assertEquals($fullTableName, $quotedTableName); + + $property = $classMetadata->getProperty($classMetadata->getSingleIdentifierFieldName()); + $sequencePrefix = $platform->getSequencePrefix($classMetadata->getTableName(), $classMetadata->getSchemaName()); + $idSequenceName = sprintf('%s_%s_seq', $sequencePrefix, $property->getColumnName()); // Checks sequence name validity - $this->assertEquals( - $fullTableName . '_' . $classMetadata->getSingleIdentifierColumnName() . '_seq', - $classMetadata->getSequenceName($platform) + self::assertEquals( + str_replace('"', '', $fullTableName) . '_' . $property->getColumnName() . '_seq', + $idSequenceName ); } @@ -66,17 +73,20 @@ public function testClassSchemaMappingsValidity($className, $expectedSchemaName, */ public function testPersistenceOfEntityWithSchemaMapping($className) { + $classMetadata = $this->em->getClassMetadata($className); + $repository = $this->em->getRepository($className); + try { - $this->_schemaTool->createSchema([$this->_em->getClassMetadata($className)]); + $this->schemaTool->createSchema([$classMetadata]); } catch (ToolsException $e) { // table already exists } - $this->_em->persist(new $className()); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist(new $className()); + $this->em->flush(); + $this->em->clear(); - $this->assertCount(1, $this->_em->getRepository($className)->findAll()); + self::assertCount(1, $repository->findAll()); } /** @@ -95,14 +105,14 @@ public function getTestedClasses() } /** - * @Entity - * @Table(name="myschema.order") + * @ORM\Entity + * @ORM\Table(name="order", schema="myschema") */ class DDC2825ClassWithImplicitlyDefinedSchemaAndQuotedTableName { /** - * @Id @GeneratedValue - * @Column(type="integer") + * @ORM\Id @ORM\GeneratedValue + * @ORM\Column(type="integer") * * @var integer */ diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2862Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2862Test.php index c4b2fb227bf..5bda88c400a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2862Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2862Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2862User::class), - $this->_em->getClassMetadata(DDC2862Driver::class), + $this->em->getClassMetadata(DDC2862User::class), + $this->em->getClassMetadata(DDC2862Driver::class), ] ); } catch (ToolsException $exc) { @@ -31,37 +34,37 @@ public function testIssue() $user1 = new DDC2862User('Foo'); $driver1 = new DDC2862Driver('Bar' , $user1); - $this->_em->persist($user1); - $this->_em->persist($driver1); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user1); + $this->em->persist($driver1); + $this->em->flush(); + $this->em->clear(); - $this->assertTrue($this->_em->getCache()->containsEntity(DDC2862User::class, ['id' => $user1->getId()])); - $this->assertTrue($this->_em->getCache()->containsEntity(DDC2862Driver::class, ['id' => $driver1->getId()])); + self::assertTrue($this->em->getCache()->containsEntity(DDC2862User::class, ['id' => $user1->getId()])); + self::assertTrue($this->em->getCache()->containsEntity(DDC2862Driver::class, ['id' => $driver1->getId()])); $queryCount = $this->getCurrentQueryCount(); - $driver2 = $this->_em->find(DDC2862Driver::class, $driver1->getId()); + $driver2 = $this->em->find(DDC2862Driver::class, $driver1->getId()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(DDC2862Driver::class, $driver2); - $this->assertInstanceOf(DDC2862User::class, $driver2->getUserProfile()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertInstanceOf(DDC2862Driver::class, $driver2); + self::assertInstanceOf(DDC2862User::class, $driver2->getUserProfile()); $driver2->setName('Franta'); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $this->assertTrue($this->_em->getCache()->containsEntity(DDC2862User::class, ['id' => $user1->getId()])); - $this->assertTrue($this->_em->getCache()->containsEntity(DDC2862Driver::class, ['id' => $driver1->getId()])); + self::assertTrue($this->em->getCache()->containsEntity(DDC2862User::class, ['id' => $user1->getId()])); + self::assertTrue($this->em->getCache()->containsEntity(DDC2862Driver::class, ['id' => $driver1->getId()])); $queryCount = $this->getCurrentQueryCount(); - $driver3 = $this->_em->find(DDC2862Driver::class, $driver1->getId()); + $driver3 = $this->em->find(DDC2862Driver::class, $driver1->getId()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(DDC2862Driver::class, $driver3); - $this->assertInstanceOf(DDC2862User::class, $driver3->getUserProfile()); - $this->assertEquals('Franta', $driver3->getName()); - $this->assertEquals('Foo', $driver3->getUserProfile()->getName()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertInstanceOf(DDC2862Driver::class, $driver3); + self::assertInstanceOf(DDC2862User::class, $driver3->getUserProfile()); + self::assertEquals('Franta', $driver3->getName()); + self::assertEquals('Foo', $driver3->getUserProfile()->getName()); } public function testIssueReopened() @@ -69,72 +72,72 @@ public function testIssueReopened() $user1 = new DDC2862User('Foo'); $driver1 = new DDC2862Driver('Bar' , $user1); - $this->_em->persist($user1); - $this->_em->persist($driver1); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user1); + $this->em->persist($driver1); + $this->em->flush(); + $this->em->clear(); - $this->_em->getCache()->evictEntityRegion(DDC2862User::class); - $this->_em->getCache()->evictEntityRegion(DDC2862Driver::class); + $this->em->getCache()->evictEntityRegion(DDC2862User::class); + $this->em->getCache()->evictEntityRegion(DDC2862Driver::class); - $this->assertFalse($this->_em->getCache()->containsEntity(DDC2862User::class, ['id' => $user1->getId()])); - $this->assertFalse($this->_em->getCache()->containsEntity(DDC2862Driver::class, ['id' => $driver1->getId()])); + self::assertFalse($this->em->getCache()->containsEntity(DDC2862User::class, ['id' => $user1->getId()])); + self::assertFalse($this->em->getCache()->containsEntity(DDC2862Driver::class, ['id' => $driver1->getId()])); $queryCount = $this->getCurrentQueryCount(); - $driver2 = $this->_em->find(DDC2862Driver::class, $driver1->getId()); + $driver2 = $this->em->find(DDC2862Driver::class, $driver1->getId()); - $this->assertInstanceOf(DDC2862Driver::class, $driver2); - $this->assertInstanceOf(DDC2862User::class, $driver2->getUserProfile()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertInstanceOf(DDC2862Driver::class, $driver2); + self::assertInstanceOf(DDC2862User::class, $driver2->getUserProfile()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->_em->clear(); + $this->em->clear(); - $this->assertFalse($this->_em->getCache()->containsEntity(DDC2862User::class, ['id' => $user1->getId()])); - $this->assertTrue($this->_em->getCache()->containsEntity(DDC2862Driver::class, ['id' => $driver1->getId()])); + self::assertFalse($this->em->getCache()->containsEntity(DDC2862User::class, ['id' => $user1->getId()])); + self::assertTrue($this->em->getCache()->containsEntity(DDC2862Driver::class, ['id' => $driver1->getId()])); $queryCount = $this->getCurrentQueryCount(); - $driver3 = $this->_em->find(DDC2862Driver::class, $driver1->getId()); + $driver3 = $this->em->find(DDC2862Driver::class, $driver1->getId()); - $this->assertInstanceOf(DDC2862Driver::class, $driver3); - $this->assertInstanceOf(DDC2862User::class, $driver3->getUserProfile()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertEquals('Foo', $driver3->getUserProfile()->getName()); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + self::assertInstanceOf(DDC2862Driver::class, $driver3); + self::assertInstanceOf(DDC2862User::class, $driver3->getUserProfile()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals('Foo', $driver3->getUserProfile()->getName()); + self::assertEquals($queryCount + 1, $this->getCurrentQueryCount()); $queryCount = $this->getCurrentQueryCount(); - $driver4 = $this->_em->find(DDC2862Driver::class, $driver1->getId()); + $driver4 = $this->em->find(DDC2862Driver::class, $driver1->getId()); - $this->assertInstanceOf(DDC2862Driver::class, $driver4); - $this->assertInstanceOf(DDC2862User::class, $driver4->getUserProfile()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertEquals('Foo', $driver4->getUserProfile()->getName()); - $this->assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertInstanceOf(DDC2862Driver::class, $driver4); + self::assertInstanceOf(DDC2862User::class, $driver4->getUserProfile()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); + self::assertEquals('Foo', $driver4->getUserProfile()->getName()); + self::assertEquals($queryCount, $this->getCurrentQueryCount()); } } /** - * @Entity - * @Table(name="ddc2862_drivers") - * @Cache("NONSTRICT_READ_WRITE") + * @ORM\Entity + * @ORM\Table(name="ddc2862_drivers") + * @ORM\Cache("NONSTRICT_READ_WRITE") */ class DDC2862Driver { /** - * @Id - * @GeneratedValue - * @Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue + * @ORM\Column(type="integer") */ protected $id; /** - * @Column(type="string") + * @ORM\Column(type="string") * @var string */ protected $name; /** - * @Cache() - * @OneToOne(targetEntity="DDC2862User") + * @ORM\Cache() + * @ORM\OneToOne(targetEntity="DDC2862User") * @var User */ protected $userProfile; @@ -188,21 +191,21 @@ public function getUserProfile() } /** - * @Entity - * @Table(name="ddc2862_users") - * @Cache("NONSTRICT_READ_WRITE") + * @ORM\Entity + * @ORM\Table(name="ddc2862_users") + * @ORM\Cache("NONSTRICT_READ_WRITE") */ class DDC2862User { /** - * @Id - * @GeneratedValue - * @Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue + * @ORM\Column(type="integer") */ protected $id; /** - * @Column(type="string") + * @ORM\Column(type="string") * @var string */ protected $name; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2895Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2895Test.php index 397c7acd380..12a80f3edac 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2895Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2895Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2895::class), + $this->em->getClassMetadata(DDC2895::class), ] ); } catch(\Exception $e) { @@ -25,9 +29,9 @@ public function setUp() public function testPostLoadOneToManyInheritance() { - $cm = $this->_em->getClassMetadata(DDC2895::class); + $cm = $this->em->getClassMetadata(DDC2895::class); - $this->assertEquals( + self::assertEquals( [ "prePersist" => ["setLastModifiedPreUpdate"], "preUpdate" => ["setLastModifiedPreUpdate"], @@ -37,33 +41,33 @@ public function testPostLoadOneToManyInheritance() $ddc2895 = new DDC2895(); - $this->_em->persist($ddc2895); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($ddc2895); + $this->em->flush(); + $this->em->clear(); /** @var DDC2895 $ddc2895 */ - $ddc2895 = $this->_em->find(get_class($ddc2895), $ddc2895->id); + $ddc2895 = $this->em->find(get_class($ddc2895), $ddc2895->id); - $this->assertNotNull($ddc2895->getLastModified()); + self::assertNotNull($ddc2895->getLastModified()); } } /** - * @MappedSuperclass - * @HasLifecycleCallbacks + * @ORM\MappedSuperclass + * @ORM\HasLifecycleCallbacks */ abstract class AbstractDDC2895 { /** - * @Column(name="last_modified", type="datetimetz", nullable=false) + * @ORM\Column(name="last_modified", type="datetimetz", nullable=false) * @var \DateTime */ protected $lastModified; /** - * @PrePersist - * @PreUpdate + * @ORM\PrePersist + * @ORM\PreUpdate */ public function setLastModifiedPreUpdate() { @@ -88,12 +92,12 @@ public function getLastModified() } /** - * @Entity - * @HasLifecycleCallbacks + * @ORM\Entity + * @ORM\HasLifecycleCallbacks */ class DDC2895 extends AbstractDDC2895 { - /** @Id @GeneratedValue @Column(type="integer") */ + /** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ public $id; /** diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2931Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2931Test.php index 927856a1c6e..ab918edc31a 100755 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2931Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2931Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2931User::class), + $this->em->getClassMetadata(DDC2931User::class), ] ); } catch (\Exception $e) { @@ -33,16 +36,16 @@ public function testIssue() $second->parent = $first; $third->parent = $second; - $this->_em->persist($first); - $this->_em->persist($second); - $this->_em->persist($third); + $this->em->persist($first); + $this->em->persist($second); + $this->em->persist($third); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $second = $this->_em->find(DDC2931User::class, $second->id); + $second = $this->em->find(DDC2931User::class, $second->id); - $this->assertSame(2, $second->getRank()); + self::assertSame(2, $second->getRank()); } public function testFetchJoinedEntitiesCanBeRefreshed() @@ -58,18 +61,18 @@ public function testFetchJoinedEntitiesCanBeRefreshed() $second->value = 2; $third->value = 3; - $this->_em->persist($first); - $this->_em->persist($second); - $this->_em->persist($third); + $this->em->persist($first); + $this->em->persist($second); + $this->em->persist($third); - $this->_em->flush(); + $this->em->flush(); $first->value = 4; $second->value = 5; $third->value = 6; $refreshedSecond = $this - ->_em + ->em ->createQuery( 'SELECT e, p, c FROM ' . __NAMESPACE__ . '\\DDC2931User e LEFT JOIN e.parent p LEFT JOIN e.child c WHERE e = :id' @@ -78,28 +81,28 @@ public function testFetchJoinedEntitiesCanBeRefreshed() ->setHint(Query::HINT_REFRESH, true) ->getResult(); - $this->assertCount(1, $refreshedSecond); - $this->assertSame(1, $first->value); - $this->assertSame(2, $second->value); - $this->assertSame(3, $third->value); + self::assertCount(1, $refreshedSecond); + self::assertSame(1, $first->value); + self::assertSame(2, $second->value); + self::assertSame(3, $third->value); } } -/** @Entity */ +/** @ORM\Entity */ class DDC2931User { - /** @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */ public $id; - /** @OneToOne(targetEntity="DDC2931User", inversedBy="child") */ + /** @ORM\OneToOne(targetEntity="DDC2931User", inversedBy="child") */ public $parent; - /** @OneToOne(targetEntity="DDC2931User", mappedBy="parent") */ + /** @ORM\OneToOne(targetEntity="DDC2931User", mappedBy="parent") */ public $child; - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ public $value = 0; /** diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2943Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2943Test.php index 553bc98f528..c81849f3bd1 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2943Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2943Test.php @@ -1,5 +1,7 @@ _em->persist(new Country("Brazil")); - $this->_em->persist(new Country("Canada")); - $this->_em->persist(new Country("Germany")); - $this->_em->persist(new Country("France")); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist(new Country("Brazil")); + $this->em->persist(new Country("Canada")); + $this->em->persist(new Country("Germany")); + $this->em->persist(new Country("France")); + $this->em->flush(); + $this->em->clear(); } public function testIssue() { $this->loadFixtures(); - $region = $this->_em->getCache()->getEntityCacheRegion(Country::class); + $region = $this->em->getCache()->getEntityCacheRegion(Country::class); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; - $query = $this->_em->createQuery($dql) + $query = $this->em->createQuery($dql) ->setCacheable(true) ->setFirstResult(0) ->setMaxResults(2); - $this->assertPaginatorQueryPut(new Paginator(clone $query), $region->getName(), 4, 2); + self::assertPaginatorQueryPut(new Paginator(clone $query), $region->getName(), 4, 2); - $this->_em->clear(); + $this->em->clear(); $this->secondLevelCacheLogger->clearStats(); - $this->assertPaginatorQueryHit(new Paginator(clone $query), $region->getName(), 4, 2); + self::assertPaginatorQueryHit(new Paginator(clone $query), $region->getName(), 4, 2); } public function testIssueNonFetchJoin() { $this->loadFixtures(); - $region = $this->_em->getCache()->getEntityCacheRegion(Country::class); + $region = $this->em->getCache()->getEntityCacheRegion(Country::class); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; - $query = $this->_em->createQuery($dql) + $query = $this->em->createQuery($dql) ->setCacheable(true) ->setFirstResult(0) ->setMaxResults(2); - $this->assertPaginatorQueryPut(new Paginator(clone $query, false), $region->getName(), 4, 2); + self::assertPaginatorQueryPut(new Paginator(clone $query, false), $region->getName(), 4, 2); - $this->_em->clear(); + $this->em->clear(); $this->secondLevelCacheLogger->clearStats(); - $this->assertPaginatorQueryHit(new Paginator(clone $query, false), $region->getName(), 4, 2); + self::assertPaginatorQueryHit(new Paginator(clone $query, false), $region->getName(), 4, 2); } public function assertPaginatorQueryPut(Paginator $paginator, $regionName, $count, $pageSize) { - $this->assertCount($count, $paginator); - $this->assertCount($pageSize, $paginator->getIterator()); + self::assertCount($count, $paginator); + self::assertCount($pageSize, $paginator->getIterator()); - $this->assertEquals(0, $this->secondLevelCacheLogger->getRegionHitCount(Cache::DEFAULT_QUERY_REGION_NAME)); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount(Cache::DEFAULT_QUERY_REGION_NAME)); - $this->assertEquals(0, $this->secondLevelCacheLogger->getRegionHitCount($regionName)); - $this->assertEquals($count, $this->secondLevelCacheLogger->getRegionPutCount($regionName)); + self::assertEquals(0, $this->secondLevelCacheLogger->getRegionHitCount(Cache::DEFAULT_QUERY_REGION_NAME)); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount(Cache::DEFAULT_QUERY_REGION_NAME)); + self::assertEquals(0, $this->secondLevelCacheLogger->getRegionHitCount($regionName)); + self::assertEquals($count, $this->secondLevelCacheLogger->getRegionPutCount($regionName)); } public function assertPaginatorQueryHit(Paginator $paginator, $regionName, $count, $pageSize) { - $this->assertCount($count, $paginator); - $this->assertCount($pageSize, $paginator->getIterator()); + self::assertCount($count, $paginator); + self::assertCount($pageSize, $paginator->getIterator()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount(Cache::DEFAULT_QUERY_REGION_NAME)); - $this->assertEquals(0, $this->secondLevelCacheLogger->getRegionPutCount(Cache::DEFAULT_QUERY_REGION_NAME)); - $this->assertEquals($pageSize, $this->secondLevelCacheLogger->getRegionHitCount($regionName)); - $this->assertEquals(0, $this->secondLevelCacheLogger->getRegionPutCount($regionName)); + self::assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount(Cache::DEFAULT_QUERY_REGION_NAME)); + self::assertEquals(0, $this->secondLevelCacheLogger->getRegionPutCount(Cache::DEFAULT_QUERY_REGION_NAME)); + self::assertEquals($pageSize, $this->secondLevelCacheLogger->getRegionHitCount($regionName)); + self::assertEquals(0, $this->secondLevelCacheLogger->getRegionPutCount($regionName)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2984Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2984Test.php index 69f4d01c0c5..239f42b1c22 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2984Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2984Test.php @@ -1,11 +1,14 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2984User::class), + $this->em->getClassMetadata(DDC2984User::class), ] ); } catch (\Exception $e) { @@ -39,38 +42,38 @@ public function testIssue() $user = new DDC2984User(new DDC2984DomainUserId('unique_id_within_a_vo')); $user->applyName('Alex'); - $this->_em->persist($user); - $this->_em->flush($user); + $this->em->persist($user); + $this->em->flush(); - $repository = $this->_em->getRepository(__NAMESPACE__ . "\DDC2984User"); + $repository = $this->em->getRepository(__NAMESPACE__ . "\DDC2984User"); $sameUser = $repository->find(new DDC2984DomainUserId('unique_id_within_a_vo')); //Until know, everything works as expected - $this->assertTrue($user->sameIdentityAs($sameUser)); + self::assertTrue($user->sameIdentityAs($sameUser)); - $this->_em->clear(); + $this->em->clear(); //After clearing the identity map, the UnitOfWork produces the warning described in DDC-2984 $equalUser = $repository->find(new DDC2984DomainUserId('unique_id_within_a_vo')); - $this->assertNotSame($user, $equalUser); - $this->assertTrue($user->sameIdentityAs($equalUser)); + self::assertNotSame($user, $equalUser); + self::assertTrue($user->sameIdentityAs($equalUser)); } } -/** @Entity @Table(name="users") */ +/** @ORM\Entity @ORM\Table(name="users") */ class DDC2984User { /** - * @Id @Column(type="ddc2984_domain_user_id") - * @GeneratedValue(strategy="NONE") + * @ORM\Id @ORM\Column(type="ddc2984_domain_user_id") + * @ORM\GeneratedValue(strategy="NONE") * * @var DDC2984DomainUserId */ private $userId; - /** @Column(type="string", length=50) */ + /** @ORM\Column(type="string", length=50) */ private $name; public function __construct(DDC2984DomainUserId $aUserId) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2996Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2996Test.php index 4a2436330f0..07f27f6c0a0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2996Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2996Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2996User::class), - $this->_em->getClassMetadata(DDC2996UserPreference::class), + $this->em->getClassMetadata(DDC2996User::class), + $this->em->getClassMetadata(DDC2996UserPreference::class), ] ); @@ -20,58 +24,58 @@ public function testIssue() $pref->user = new DDC2996User(); $pref->value = "foo"; - $this->_em->persist($pref); - $this->_em->persist($pref->user); - $this->_em->flush(); + $this->em->persist($pref); + $this->em->persist($pref->user); + $this->em->flush(); $pref->value = "bar"; - $this->_em->flush(); + $this->em->flush(); - $this->assertEquals(1, $pref->user->counter); + self::assertEquals(1, $pref->user->counter); - $this->_em->clear(); + $this->em->clear(); - $pref = $this->_em->find(DDC2996UserPreference::class, $pref->id); - $this->assertEquals(1, $pref->user->counter); + $pref = $this->em->find(DDC2996UserPreference::class, $pref->id); + self::assertEquals(1, $pref->user->counter); } } /** - * @Entity + * @ORM\Entity */ class DDC2996User { /** - * @Id @GeneratedValue @Column(type="integer") + * @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ public $id; /** - * @Column(type="integer") + * @ORM\Column(type="integer") */ public $counter = 0; } /** - * @Entity @HasLifecycleCallbacks + * @ORM\Entity @ORM\HasLifecycleCallbacks */ class DDC2996UserPreference { /** - * @Id @GeneratedValue @Column(type="integer") + * @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ public $id; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $value; /** - * @ManyToOne(targetEntity="DDC2996User") + * @ORM\ManyToOne(targetEntity="DDC2996User") */ public $user; /** - * @PreFlush + * @ORM\PreFlush */ public function preFlush($event) { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3033Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3033Test.php index b25686dce10..63195245469 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3033Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3033Test.php @@ -1,8 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC3033User::class), - $this->_em->getClassMetadata(DDC3033Product::class), + $this->em->getClassMetadata(DDC3033User::class), + $this->em->getClassMetadata(DDC3033Product::class), ] ); $user = new DDC3033User(); $user->name = "Test User"; - $this->_em->persist($user); + $this->em->persist($user); $user2 = new DDC3033User(); $user2->name = "Test User 2"; - $this->_em->persist($user2); + $this->em->persist($user2); $product = new DDC3033Product(); $product->title = "Test product"; $product->buyers[] = $user; - $this->_em->persist($product); - $this->_em->flush(); + $this->em->persist($product); + $this->em->flush(); $product->title = "Test Change title"; $product->buyers[] = $user2; - $this->_em->persist($product); - $this->_em->flush(); + $this->em->persist($product); + $this->em->flush(); $expect = [ 'title' => [ @@ -47,13 +50,13 @@ public function testIssue() ], ]; - $this->assertEquals($expect, $product->changeSet); + self::assertEquals($expect, $product->changeSet); } } /** - * @Table - * @Entity @HasLifecycleCallbacks + * @ORM\Table + * @ORM\Entity @ORM\HasLifecycleCallbacks */ class DDC3033Product { @@ -62,25 +65,25 @@ class DDC3033Product /** * @var int $id * - * @Column(name="id", type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") + * @ORM\Column(name="id", type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** * @var string $title * - * @Column(name="title", type="string", length=255) + * @ORM\Column(name="title", type="string", length=255) */ public $title; /** - * @ManyToMany(targetEntity="DDC3033User") - * @JoinTable( + * @ORM\ManyToMany(targetEntity="DDC3033User") + * @ORM\JoinTable( * name="user_purchases_3033", - * joinColumns={@JoinColumn(name="product_id", referencedColumnName="id")}, - * inverseJoinColumns={@JoinColumn(name="user_id", referencedColumnName="id")} + * joinColumns={@ORM\JoinColumn(name="product_id", referencedColumnName="id")}, + * inverseJoinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")} * ) */ public $buyers; @@ -94,14 +97,14 @@ public function __construct() } /** - * @PreUpdate + * @ORM\PreUpdate */ public function preUpdate(LifecycleEventArgs $eventArgs) { } /** - * @PostUpdate + * @ORM\PostUpdate */ public function postUpdate(LifecycleEventArgs $eventArgs) { @@ -116,24 +119,24 @@ public function postUpdate(LifecycleEventArgs $eventArgs) } /** - * @Table - * @Entity @HasLifecycleCallbacks + * @ORM\Table + * @ORM\Entity @ORM\HasLifecycleCallbacks */ class DDC3033User { /** * @var int * - * @Column(name="id", type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") + * @ORM\Column(name="id", type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** * @var string * - * @Column(name="title", type="string", length=255) + * @ORM\Column(name="title", type="string", length=255) */ public $name; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3042Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3042Test.php index 940989bb713..e41b070c2fd 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3042Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3042Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC3042Foo::class), - $this->_em->getClassMetadata(DDC3042Bar::class), + $this->em->getClassMetadata(DDC3042Foo::class), + $this->em->getClassMetadata(DDC3042Bar::class), ] ); } public function testSQLGenerationDoesNotProvokeAliasCollisions() { - $this->assertStringNotMatchesFormat( + self::assertStringNotMatchesFormat( '%sfield11%sfield11%s', $this - ->_em + ->em ->createQuery( 'SELECT f, b FROM ' . __NAMESPACE__ . '\DDC3042Foo f JOIN ' . __NAMESPACE__ . '\DDC3042Bar b WITH 1 = 1' ) @@ -36,39 +39,39 @@ public function testSQLGenerationDoesNotProvokeAliasCollisions() } /** - * @Entity + * @ORM\Entity */ class DDC3042Foo { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $field; - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ public $field1; - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ public $field2; - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ public $field3; - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ public $field4; - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ public $field5; - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ public $field6; - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ public $field7; - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ public $field8; - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ public $field9; - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ public $field10; } /** - * @Entity + * @ORM\Entity */ class DDC3042Bar { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $field; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3068Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3068Test.php index 90a3f3ed80e..4c5b4612bce 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3068Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3068Test.php @@ -1,5 +1,7 @@ foo = new Driver(); $this->foo->setName('Foo Bar'); - $this->_em->persist($this->foo); + $this->em->persist($this->foo); $this->merc = new Car(); $this->merc->setBrand('Mercedes'); $this->merc->setModel('C-Class'); - $this->_em->persist($this->merc); + $this->em->persist($this->merc); - $this->_em->flush(); + $this->em->flush(); $ride = new Ride($this->foo, $this->merc); - $this->_em->persist($ride); + $this->em->persist($ride); - $this->_em->flush(); + $this->em->flush(); } public function testFindUsingAnArrayOfObjectAsPrimaryKey() { - $ride1 = $this->_em->find(Ride::class, [ + $ride1 = $this->em->find(Ride::class, [ 'driver' => $this->foo->getId(), 'car' => $this->merc->getBrand() ] ); - $this->assertInstanceOf(Ride::class, $ride1); + self::assertInstanceOf(Ride::class, $ride1); - $ride2 = $this->_em->find(Ride::class, [ + $ride2 = $this->em->find(Ride::class, [ 'driver' => $this->foo, 'car' => $this->merc ] ); - $this->assertInstanceOf(Ride::class, $ride2); - $this->assertSame($ride1, $ride2); + self::assertInstanceOf(Ride::class, $ride2); + self::assertSame($ride1, $ride2); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC309Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC309Test.php index 15454b48269..30ae2c1c863 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC309Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC309Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC309Country::class), - $this->_em->getClassMetadata(DDC309User::class), + $this->em->getClassMetadata(DDC309Country::class), + $this->em->getClassMetadata(DDC309User::class), ] ); } @@ -24,53 +27,53 @@ public function testTwoIterateHydrations() $u1 = new DDC309User(); $u2 = new DDC309User(); - $this->_em->persist($c1); - $this->_em->persist($c2); - $this->_em->persist($u1); - $this->_em->persist($u2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($c1); + $this->em->persist($c2); + $this->em->persist($u1); + $this->em->persist($u2); + $this->em->flush(); + $this->em->clear(); - $q = $this->_em->createQuery('SELECT c FROM Doctrine\Tests\ORM\Functional\Ticket\DDC309Country c')->iterate(); + $q = $this->em->createQuery('SELECT c FROM Doctrine\Tests\ORM\Functional\Ticket\DDC309Country c')->iterate(); $c = $q->next(); - $this->assertEquals(1, $c[0]->id); + self::assertEquals(1, $c[0]->id); - $r = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\ORM\Functional\Ticket\DDC309User u')->iterate(); + $r = $this->em->createQuery('SELECT u FROM Doctrine\Tests\ORM\Functional\Ticket\DDC309User u')->iterate(); $u = $r->next(); // This line breaks - $this->assertEquals(1, $u[0]->id); + self::assertEquals(1, $u[0]->id); $c = $q->next(); $u = $r->next(); - $this->assertEquals(2, $c[0]->id); - $this->assertEquals(2, $u[0]->id); + self::assertEquals(2, $c[0]->id); + self::assertEquals(2, $u[0]->id); } } /** - * @Entity + * @ORM\Entity */ class DDC309Country { /** - * @Id - * @Column(name="id", type="integer") - * @GeneratedValue + * @ORM\Id + * @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue */ public $id; } /** - * @Entity + * @ORM\Entity */ class DDC309User { /** - * @Id - * @Column(name="id", type="integer") - * @GeneratedValue + * @ORM\Id + * @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3103Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3103Test.php index fe8329345ca..8426c5131e3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3103Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3103Test.php @@ -1,8 +1,14 @@ markTestSkipped('Embeddables are ommitted for now'); + + $driver = $this->createAnnotationDriver(); + + $metadataBuildingContext = new ClassMetadataBuildingContext( + $this->createMock(ClassMetadataFactory::class), + $this->createMock(ReflectionService::class) + ); + + $classMetadata = new ClassMetadata(DDC3103ArticleId::class, $metadataBuildingContext); - $this->createAnnotationDriver()->loadMetadataForClass(DDC3103ArticleId::class, $classMetadata); + $driver->loadMetadataForClass(DDC3103ArticleId::class, $classMetadata, $metadataBuildingContext); - $this->assertTrue( + self::assertTrue( $classMetadata->isEmbeddedClass, 'The isEmbeddedClass property should be true from the mapping data.' ); - $this->assertTrue( + self::assertTrue( unserialize(serialize($classMetadata))->isEmbeddedClass, 'The isEmbeddedClass property should still be true after serialization and unserialization.' ); @@ -31,13 +46,13 @@ public function testIssue() } /** - * @Embeddable + * @ORM\Embeddable */ class DDC3103ArticleId { /** * @var string - * @Column(name="name", type="string", length=255) + * @ORM\Column(name="name", type="string", length=255) */ protected $nameValue; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3123Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3123Test.php index 515aa9febc7..c80b87f8af0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3123Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3123Test.php @@ -1,5 +1,7 @@ _em->getUnitOfWork(); + $uow = $this->em->getUnitOfWork(); $user->name = 'Marco'; $user->username = 'ocramius'; - $this->_em->persist($user); + $this->em->persist($user); $uow->scheduleExtraUpdate($user, ['name' => 'changed name']); $listener = $this->getMockBuilder(\stdClass::class) @@ -39,8 +41,8 @@ public function testIssue() $test->assertAttributeEmpty('extraUpdates', $uow, 'ExtraUpdates are reset before postFlush'); })); - $this->_em->getEventManager()->addEventListener(Events::postFlush, $listener); + $this->em->getEventManager()->addEventListener(Events::postFlush, $listener); - $this->_em->flush(); + $this->em->flush(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3160Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3160Test.php index c0ed69dd0e4..433ca733d46 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3160Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3160Test.php @@ -1,5 +1,7 @@ _em->getEventManager()->addEventListener(Events::onFlush, $listener); + $this->em->getEventManager()->addEventListener(Events::onFlush, $listener); $user = new CmsUser; $user->username = 'romanb'; $user->name = 'Roman'; $user->status = 'Dev'; - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); - $this->_em->refresh($user); + $this->em->refresh($user); - $this->assertEquals('romanc', $user->username); - $this->assertEquals(1, $listener->inserts); - $this->assertEquals(0, $listener->updates); + self::assertEquals('romanc', $user->username); + self::assertEquals(1, $listener->inserts); + self::assertEquals(0, $listener->updates); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3170Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3170Test.php index 45a49b7a6d0..00b7b87bb5d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3170Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3170Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC3170AbstractEntityJoined::class), - $this->_em->getClassMetadata(DDC3170ProductJoined::class), - $this->_em->getClassMetadata(DDC3170AbstractEntitySingleTable::class), - $this->_em->getClassMetadata(DDC3170ProductSingleTable::class), + $this->em->getClassMetadata(DDC3170AbstractEntityJoined::class), + $this->em->getClassMetadata(DDC3170ProductJoined::class), + $this->em->getClassMetadata(DDC3170AbstractEntitySingleTable::class), + $this->em->getClassMetadata(DDC3170ProductSingleTable::class), ] ); } @@ -41,12 +44,12 @@ public function testIssue() $productJoined = new DDC3170ProductJoined(); $productSingleTable = new DDC3170ProductSingleTable(); - $this->_em->persist($productJoined); - $this->_em->persist($productSingleTable); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($productJoined); + $this->em->persist($productSingleTable); + $this->em->flush(); + $this->em->clear(); - $result = $this->_em->createQueryBuilder() + $result = $this->em->createQueryBuilder() ->select('p') ->from(DDC3170ProductJoined::class, 'p') ->getQuery() @@ -55,7 +58,7 @@ public function testIssue() self::assertCount(1, $result); self::assertContainsOnly(DDC3170ProductJoined::class, $result); - $result = $this->_em->createQueryBuilder() + $result = $this->em->createQueryBuilder() ->select('p') ->from(DDC3170ProductSingleTable::class, 'p') ->getQuery() @@ -67,38 +70,38 @@ public function testIssue() } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="type", type="string") - * @DiscriminatorMap({"product" = "DDC3170ProductJoined"}) + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="type", type="string") + * @ORM\DiscriminatorMap({"product" = "DDC3170ProductJoined"}) */ abstract class DDC3170AbstractEntityJoined { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; } /** - * @Entity + * @ORM\Entity */ class DDC3170ProductJoined extends DDC3170AbstractEntityJoined { } /** - * @Entity - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorColumn(name="type", type="string") - * @DiscriminatorMap({"product" = "DDC3170ProductSingleTable"}) + * @ORM\Entity + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorColumn(name="type", type="string") + * @ORM\DiscriminatorMap({"product" = "DDC3170ProductSingleTable"}) */ abstract class DDC3170AbstractEntitySingleTable { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; } /** - * @Entity + * @ORM\Entity */ class DDC3170ProductSingleTable extends DDC3170AbstractEntitySingleTable { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3192Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3192Test.php index 1262bce4521..4534cf40eb8 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3192Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3192Test.php @@ -1,10 +1,12 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC3192Currency::class), - $this->_em->getClassMetadata(DDC3192Transaction::class), + $this->em->getClassMetadata(DDC3192Currency::class), + $this->em->getClassMetadata(DDC3192Transaction::class), ] ); } @@ -37,24 +39,24 @@ public function testIssue() { $currency = new DDC3192Currency('BYR'); - $this->_em->persist($currency); - $this->_em->flush(); + $this->em->persist($currency); + $this->em->flush(); $amount = 50; $transaction = new DDC3192Transaction($amount, $currency); - $this->_em->persist($transaction); - $this->_em->flush(); - $this->_em->close(); + $this->em->persist($transaction); + $this->em->flush(); + $this->em->close(); - $resultByPersister = $this->_em->find(DDC3192Transaction::class, $transaction->id); + $resultByPersister = $this->em->find(DDC3192Transaction::class, $transaction->id); // This works: DDC2494 makes persister set type mapping info to ResultSetMapping - $this->assertEquals('BYR', $resultByPersister->currency->code); + self::assertEquals('BYR', $resultByPersister->currency->code); - $this->_em->close(); + $this->em->close(); - $query = $this->_em->createQuery(); + $query = $this->em->createQuery(); $query->setDQL('SELECT t FROM ' . DDC3192Transaction::class . ' t WHERE t.id = ?1'); $query->setParameter(1, $transaction->id); @@ -62,26 +64,26 @@ public function testIssue() // This is fixed here: before the fix it used to return 974. // because unlike the BasicEntityPersister, SQLWalker doesn't set type info - $this->assertEquals('BYR', $resultByQuery->currency->code); + self::assertEquals('BYR', $resultByQuery->currency->code); } } /** - * @Table(name="ddc3192_currency") - * @Entity + * @ORM\Table(name="ddc3192_currency") + * @ORM\Entity */ class DDC3192Currency { /** - * @Id - * @Column(type="ddc3192_currency_code") + * @ORM\Id + * @ORM\Column(type="ddc3192_currency_code") */ public $code; /** * @var \Doctrine\Common\Collections\Collection * - * @OneToMany(targetEntity="DDC3192Transaction", mappedBy="currency") + * @ORM\OneToMany(targetEntity="DDC3192Transaction", mappedBy="currency") */ public $transactions; @@ -92,30 +94,30 @@ public function __construct($code) } /** - * @Table(name="ddc3192_transaction") - * @Entity + * @ORM\Table(name="ddc3192_transaction") + * @ORM\Entity */ class DDC3192Transaction { /** - * @Id - * @GeneratedValue - * @Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue + * @ORM\Column(type="integer") */ public $id; /** * @var int * - * @Column(type="integer") + * @ORM\Column(type="integer") */ public $amount; /** * @var \Doctrine\Tests\ORM\Functional\Ticket\DDC3192Currency * - * @ManyToOne(targetEntity="DDC3192Currency", inversedBy="transactions") - * @JoinColumn(name="currency_id", referencedColumnName="code", nullable=false) + * @ORM\ManyToOne(targetEntity="DDC3192Currency", inversedBy="transactions") + * @ORM\JoinColumn(name="currency_id", referencedColumnName="code", nullable=false) */ public $currency; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3223Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3223Test.php index 0f98adca1fa..c8bf4f697fc 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3223Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3223Test.php @@ -1,7 +1,10 @@ profileStatus = $profileStatus; - $this->_em->persist($profileStatus); - $this->_em->persist($participant); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($profileStatus); + $this->em->persist($participant); + $this->em->flush(); + $this->em->clear(); - $participant = $this->_em->find(Participant::class, $participant->id); + $participant = $this->em->find(Participant::class, $participant->id); $profileStatus = clone $participant->profileStatus; - $this->assertSame(1, $profileStatus->getId(), 'The identifier on the cloned instance is an integer'); + self::assertSame(1, $profileStatus->getId(), 'The identifier on the cloned instance is an integer'); } } -/** @Entity @Table(name="ddc3223_journalist") */ +/** @ORM\Entity @ORM\Table(name="ddc3223_journalist") */ class Journalist extends Participant { } /** - * @Entity @Table(name="ddc3223_participant") - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="discr", type="string") - * @DiscriminatorMap({ + * @ORM\Entity @ORM\Table(name="ddc3223_participant") + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="discr", type="string") + * @ORM\DiscriminatorMap({ * "journalist" = "Journalist", * "participant" = "Participant", * }) */ class Participant { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @ManyToOne(targetEntity="ProfileStatus") */ + /** @ORM\ManyToOne(targetEntity="ProfileStatus") */ public $profileStatus; } /** - * @Entity @Table(name="ddc3223_status") - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorColumn(name="discr", type="string") - * @DiscriminatorMap({ + * @ORM\Entity @ORM\Table(name="ddc3223_status") + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorColumn(name="discr", type="string") + * @ORM\DiscriminatorMap({ * "profile" = "ProfileStatus", * "status" = "Status", * }) */ class Status { - /** @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */ private $id; public function getId() @@ -89,7 +92,7 @@ public function getId() } /** - * @Entity + * @ORM\Entity */ class ProfileStatus extends Status { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3300Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3300Test.php index 17de7d217e1..182bd5d327c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3300Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3300Test.php @@ -1,7 +1,11 @@ addResolveTargetEntity( DDC3300BossInterface::class, - DDC3300Boss::class, - [] + DDC3300Boss::class ); $resolveTargetEntity->addResolveTargetEntity( DDC3300EmployeeInterface::class, - DDC3300Employee::class, - [] + DDC3300Employee::class ); - $this->_em->getEventManager()->addEventSubscriber($resolveTargetEntity); + $this->em->getEventManager()->addEventSubscriber($resolveTargetEntity); - $this->_schemaTool->createSchema( - [ - $this->_em->getClassMetadata(DDC3300Person::class), - ] - ); + $this->schemaTool->createSchema([ + $this->em->getClassMetadata(DDC3300Person::class), + ]); $boss = new DDC3300Boss(); $employee = new DDC3300Employee(); - $this->_em->persist($boss); - $this->_em->persist($employee); + $this->em->persist($boss); + $this->em->persist($employee); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $this->assertEquals($boss, $this->_em->find(DDC3300BossInterface::class, $boss->id)); - $this->assertEquals($employee, $this->_em->find(DDC3300EmployeeInterface::class, $employee->id)); + self::assertEquals($boss, $this->em->find(DDC3300BossInterface::class, $boss->id)); + self::assertEquals($employee, $this->em->find(DDC3300EmployeeInterface::class, $employee->id)); } } /** - * @Entity - * @InheritanceType("SINGLE_TABLE") - * @DdiscriminatorColumn(name="discr", type="string") - * @DiscriminatorMap({ + * @ORM\Entity + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorColumn(name="discr", type="string") + * @ORM\DiscriminatorMap({ * "boss" = "Doctrine\Tests\ORM\Functional\Ticket\DDC3300BossInterface", * "employee" = "Doctrine\Tests\ORM\Functional\Ticket\DDC3300EmployeeInterface" * }) */ abstract class DDC3300Person { - /** @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */ public $id; } @@ -66,7 +66,7 @@ interface DDC3300BossInterface { } -/** @Entity */ +/** @ORM\Entity */ class DDC3300Boss extends DDC3300Person implements DDC3300BossInterface { } @@ -75,7 +75,7 @@ interface DDC3300EmployeeInterface { } -/** @Entity */ +/** @ORM\Entity */ class DDC3300Employee extends DDC3300Person implements DDC3300EmployeeInterface { } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3303Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3303Test.php index b40f99ff9d6..8de7255985f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3303Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3303Test.php @@ -1,6 +1,10 @@ _schemaTool->createSchema([$this->_em->getClassMetadata(DDC3303Employee::class)]); + $this->schemaTool->createSchema([$this->em->getClassMetadata(DDC3303Employee::class)]); } /** * @group 4097 * @group 4277 * @group 5867 + * @group embedded * * When using an embedded field in an inheritance, private properties should also be inherited. */ @@ -27,21 +32,21 @@ public function testEmbeddedObjectsAreAlsoInherited() 'Doctrine Inc' ); - $this->_em->persist($employee); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($employee); + $this->em->flush(); + $this->em->clear(); - self::assertEquals($employee, $this->_em->find(DDC3303Employee::class, 'John Doe')); + self::assertEquals($employee, $this->em->find(DDC3303Employee::class, 'John Doe')); } } -/** @MappedSuperclass */ +/** @ORM\MappedSuperclass */ abstract class DDC3303Person { - /** @Id @GeneratedValue(strategy="NONE") @Column(type="string") @var string */ + /** @ORM\Id @ORM\GeneratedValue(strategy="NONE") @ORM\Column(type="string") @var string */ private $name; - /** @Embedded(class="DDC3303Address") @var DDC3303Address */ + /** @ORM\Embedded(class="DDC3303Address") @var DDC3303Address */ private $address; public function __construct($name, DDC3303Address $address) @@ -52,17 +57,17 @@ public function __construct($name, DDC3303Address $address) } /** - * @Embeddable + * @ORM\Embeddable */ class DDC3303Address { - /** @Column(type="string") @var string */ + /** @ORM\Column(type="string") @var string */ private $street; - /** @Column(type="integer") @var int */ + /** @ORM\Column(type="integer") @var int */ private $number; - /** @Column(type="string") @var string */ + /** @ORM\Column(type="string") @var string */ private $city; public function __construct($street, $number, $city) @@ -74,12 +79,12 @@ public function __construct($street, $number, $city) } /** - * @Entity - * @Table(name="ddc3303_employee") + * @ORM\Entity + * @ORM\Table(name="ddc3303_employee") */ class DDC3303Employee extends DDC3303Person { - /** @Column(type="string") @var string */ + /** @ORM\Column(type="string") @var string */ private $company; public function __construct($name, DDC3303Address $address, $company) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC331Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC331Test.php index 5ec8ad730ae..12f47664a8b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC331Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC331Test.php @@ -1,5 +1,7 @@ _em->createQuery('SELECT e.name FROM Doctrine\Tests\Models\Company\CompanyEmployee e'); - $this->assertEquals( - strtolower('SELECT c0_.name AS name_0 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id LEFT JOIN company_managers c2_ ON c1_.id = c2_.id'), - strtolower($q->getSQL()) + $q = $this->em->createQuery('SELECT e.name FROM Doctrine\Tests\Models\Company\CompanyEmployee e'); + + self::assertSQLEquals( + 'SELECT t0."name" AS c0 FROM "company_employees" t1 INNER JOIN "company_persons" t0 ON t1."id" = t0."id" LEFT JOIN "company_managers" t2 ON t1."id" = t2."id"', + $q->getSQL() ); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3330Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3330Test.php index a03c3172cfd..7b9af23715a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3330Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3330Test.php @@ -1,9 +1,12 @@ createBuildingAndHalls(); $this->createBuildingAndHalls(); - $this->_em->clear(); + $this->em->clear(); - $query = $this->_em->createQuery( + $query = $this->em->createQuery( 'SELECT b, h'. ' FROM Doctrine\Tests\ORM\Functional\Ticket\DDC3330_Building b'. ' LEFT JOIN b.halls h'. @@ -42,7 +45,7 @@ public function testIssueCollectionOrderWithPaginator() $paginator = new Paginator($query, true); - $this->assertEquals(3, count(iterator_to_array($paginator)), 'Count is not correct for pagination'); + self::assertEquals(3, count(iterator_to_array($paginator)), 'Count is not correct for pagination'); } /** @@ -58,24 +61,24 @@ private function createBuildingAndHalls() $building->addHall($hall); } - $this->_em->persist($building); - $this->_em->flush(); + $this->em->persist($building); + $this->em->flush(); } } /** - * @Entity @Table(name="ddc3330_building") + * @ORM\Entity @ORM\Table(name="ddc3330_building") */ class DDC3330_Building { /** - * @Id @Column(type="integer") - * @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue */ public $id; /** - * @OneToMany(targetEntity="DDC3330_Hall", mappedBy="building", cascade={"persist"}) + * @ORM\OneToMany(targetEntity="DDC3330_Hall", mappedBy="building", cascade={"persist"}) */ public $halls; @@ -87,23 +90,23 @@ public function addHall(DDC3330_Hall $hall) } /** - * @Entity @Table(name="ddc3330_hall") + * @ORM\Entity @ORM\Table(name="ddc3330_hall") */ class DDC3330_Hall { /** - * @Id @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @ManyToOne(targetEntity="DDC3330_Building", inversedBy="halls") + * @ORM\ManyToOne(targetEntity="DDC3330_Building", inversedBy="halls") */ public $building; /** - * @Column(type="string", length=100) + * @ORM\Column(type="string", length=100) */ public $name; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3346Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3346Test.php index 3865767604e..14d615d0c71 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3346Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3346Test.php @@ -1,5 +1,7 @@ _em->getRepository(DDC3346Author::class)->findOneBy( + $author = $this->em->getRepository(DDC3346Author::class)->findOneBy( ['username' => 'bwoogy'] ); - $this->assertCount(2, $author->articles); + self::assertCount(2, $author->articles); } public function testFindLimitedWithEagerFetchWillNotHydrateLimitedCollection() { /* @var DDC3346Author[] $authors */ - $authors = $this->_em->getRepository(DDC3346Author::class)->findBy( + $authors = $this->em->getRepository(DDC3346Author::class)->findBy( ['username' => 'bwoogy'], null, 1 ); - $this->assertCount(1, $authors); - $this->assertCount(2, $authors[0]->articles); + self::assertCount(1, $authors); + self::assertCount(2, $authors[0]->articles); } public function testFindWithEagerFetchAndOffsetWillNotHydrateLimitedCollection() { /* @var DDC3346Author[] $authors */ - $authors = $this->_em->getRepository(DDC3346Author::class)->findBy( + $authors = $this->em->getRepository(DDC3346Author::class)->findBy( ['username' => 'bwoogy'], null, null, 0 // using an explicitly defined offset ); - $this->assertCount(1, $authors); - $this->assertCount(2, $authors[0]->articles); + self::assertCount(1, $authors); + self::assertCount(2, $authors[0]->articles); } private function loadAuthorFixture() @@ -68,10 +70,10 @@ private function loadAuthorFixture() $user->articles[] = $article1; $user->articles[] = $article2; - $this->_em->persist($user); - $this->_em->persist($article1); - $this->_em->persist($article2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->persist($article1); + $this->em->persist($article2); + $this->em->flush(); + $this->em->clear(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC345Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC345Test.php index 20b4236c304..d82855395d4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC345Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC345Test.php @@ -1,18 +1,22 @@ _em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_schemaTool->createSchema( + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC345User::class), - $this->_em->getClassMetadata(DDC345Group::class), - $this->_em->getClassMetadata(DDC345Membership::class), + $this->em->getClassMetadata(DDC345User::class), + $this->em->getClassMetadata(DDC345Group::class), + $this->em->getClassMetadata(DDC345Membership::class), ] ); } @@ -22,19 +26,19 @@ public function testTwoIterateHydrations() // Create User $user = new DDC345User; $user->name = 'Test User'; - $this->_em->persist($user); // $em->flush() does not change much here + $this->em->persist($user); // $em->flush() does not change much here // Create Group $group = new DDC345Group; $group->name = 'Test Group'; - $this->_em->persist($group); // $em->flush() does not change much here + $this->em->persist($group); // $em->flush() does not change much here $membership = new DDC345Membership; $membership->group = $group; $membership->user = $user; $membership->state = 'active'; - //$this->_em->persist($membership); // COMMENT OUT TO SEE BUG + //$this->em->persist($membership); // COMMENT OUT TO SEE BUG /* This should be not necessary, but without, its PrePersist is called twice, $membership seems to be persisted twice, but all properties but the @@ -44,30 +48,30 @@ public function testTwoIterateHydrations() $user->Memberships->add($membership); $group->Memberships->add($membership); - $this->_em->flush(); + $this->em->flush(); - $this->assertEquals(1, $membership->prePersistCallCount); - $this->assertEquals(0, $membership->preUpdateCallCount); - $this->assertInstanceOf('DateTime', $membership->updated); + self::assertEquals(1, $membership->prePersistCallCount); + self::assertEquals(0, $membership->preUpdateCallCount); + self::assertInstanceOf('DateTime', $membership->updated); } } /** - * @Entity + * @ORM\Entity */ class DDC345User { /** - * @Id - * @Column(type="integer") - * @GeneratedValue + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue */ public $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $name; - /** @OneToMany(targetEntity="DDC345Membership", mappedBy="user", cascade={"persist"}) */ + /** @ORM\OneToMany(targetEntity="DDC345Membership", mappedBy="user", cascade={"persist"}) */ public $Memberships; public function __construct() @@ -77,21 +81,21 @@ public function __construct() } /** - * @Entity + * @ORM\Entity */ class DDC345Group { /** - * @Id - * @Column(type="integer") - * @GeneratedValue + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue */ public $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $name; - /** @OneToMany(targetEntity="DDC345Membership", mappedBy="group", cascade={"persist"}) */ + /** @ORM\OneToMany(targetEntity="DDC345Membership", mappedBy="group", cascade={"persist"}) */ public $Memberships; @@ -102,43 +106,43 @@ public function __construct() } /** - * @Entity - * @HasLifecycleCallbacks - * @Table(name="ddc345_memberships", uniqueConstraints={ - * @UniqueConstraint(name="ddc345_memship_fks", columns={"user_id","group_id"}) + * @ORM\Entity + * @ORM\HasLifecycleCallbacks + * @ORM\Table(name="ddc345_memberships", uniqueConstraints={ + * @ORM\UniqueConstraint(name="ddc345_memship_fks", columns={"user_id","group_id"}) * }) */ class DDC345Membership { /** - * @Id - * @Column(type="integer") - * @GeneratedValue + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue */ public $id; /** - * @OneToOne(targetEntity="DDC345User", inversedBy="Memberships") - * @JoinColumn(name="user_id", referencedColumnName="id", nullable=false) + * @ORM\OneToOne(targetEntity="DDC345User", inversedBy="Memberships") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) */ public $user; /** - * @OneToOne(targetEntity="DDC345Group", inversedBy="Memberships") - * @JoinColumn(name="group_id", referencedColumnName="id", nullable=false) + * @ORM\OneToOne(targetEntity="DDC345Group", inversedBy="Memberships") + * @ORM\JoinColumn(name="group_id", referencedColumnName="id", nullable=false) */ public $group; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $state; - /** @Column(type="datetime") */ + /** @ORM\Column(type="datetime") */ public $updated; public $prePersistCallCount = 0; public $preUpdateCallCount = 0; - /** @PrePersist */ + /** @ORM\PrePersist */ public function doStuffOnPrePersist() { //echo "***** PrePersist\n"; @@ -146,7 +150,7 @@ public function doStuffOnPrePersist() $this->updated = new \DateTime; } - /** @PreUpdate */ + /** @ORM\PreUpdate */ public function doStuffOnPreUpdate() { //echo "***** PreUpdate\n"; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC353Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC353Test.php index dcb782bd4f8..1373ab778cd 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC353Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC353Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC353File::class), - $this->_em->getClassMetadata(DDC353Picture::class), + $this->em->getClassMetadata(DDC353File::class), + $this->em->getClassMetadata(DDC353Picture::class), ] ); } catch(\Exception $ignored) {} @@ -26,19 +29,19 @@ public function testWorkingCase() $picture = new DDC353Picture; $picture->setFile($file); - $em = $this->_em; + $em = $this->em; $em->persist($picture); $em->flush(); $em->clear(); $fileId = $file->getFileId(); - $this->assertTrue($fileId > 0); + self::assertTrue($fileId > 0); $file = $em->getReference(DDC353File::class, $fileId); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $em->getUnitOfWork()->getEntityState($file), "Reference Proxy should be marked MANAGED."); + self::assertEquals(UnitOfWork::STATE_MANAGED, $em->getUnitOfWork()->getEntityState($file), "Reference Proxy should be marked MANAGED."); $picture = $em->find(DDC353Picture::class, $picture->getPictureId()); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $em->getUnitOfWork()->getEntityState($picture->getFile()), "Lazy Proxy should be marked MANAGED."); + self::assertEquals(UnitOfWork::STATE_MANAGED, $em->getUnitOfWork()->getEntityState($picture->getFile()), "Lazy Proxy should be marked MANAGED."); $em->remove($picture); $em->flush(); @@ -51,7 +54,7 @@ public function testFailingCase() $picture = new DDC353Picture; $picture->setFile($file); - $em = $this->_em; + $em = $this->em; $em->persist($picture); $em->flush(); $em->clear(); @@ -59,10 +62,10 @@ public function testFailingCase() $fileId = $file->getFileId(); $pictureId = $picture->getPictureId(); - $this->assertTrue($fileId > 0); + self::assertTrue($fileId > 0); $picture = $em->find(DDC353Picture::class, $pictureId); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $em->getUnitOfWork()->getEntityState($picture->getFile()), "Lazy Proxy should be marked MANAGED."); + self::assertEquals(UnitOfWork::STATE_MANAGED, $em->getUnitOfWork()->getEntityState($picture->getFile()), "Lazy Proxy should be marked MANAGED."); $em->remove($picture); $em->flush(); @@ -70,20 +73,20 @@ public function testFailingCase() } /** - * @Entity + * @ORM\Entity */ class DDC353Picture { /** - * @Column(name="picture_id", type="integer") - * @Id @GeneratedValue + * @ORM\Column(name="picture_id", type="integer") + * @ORM\Id @ORM\GeneratedValue */ private $pictureId; /** - * @ManyToOne(targetEntity="DDC353File", cascade={"persist", "remove"}) - * @JoinColumns({ - * @JoinColumn(name="file_id", referencedColumnName="file_id") + * @ORM\ManyToOne(targetEntity="DDC353File", cascade={"persist", "remove"}) + * @ORM\JoinColumns({ + * @ORM\JoinColumn(name="file_id", referencedColumnName="file_id") * }) */ private $file; @@ -130,14 +133,14 @@ public function getFile() } /** - * @Entity + * @ORM\Entity */ class DDC353File { /** - * @Column(name="file_id", type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") + * @ORM\Column(name="file_id", type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") */ public $fileId; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3582Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3582Test.php index 17b4bed85e4..7e773e723ea 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3582Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3582Test.php @@ -1,32 +1,39 @@ _schemaTool->createSchema([$this->_em->getClassMetadata(DDC3582Entity::class)]); - $this->_em->persist(new DDC3582Entity('foo')); - $this->_em->flush(); - $this->_em->clear(); + $this->schemaTool->createSchema([$this->em->getClassMetadata(DDC3582Entity::class)]); + $this->em->persist(new DDC3582Entity('foo')); + $this->em->flush(); + $this->em->clear(); /** @var DDC3582Entity $entity */ - $entity = $this->_em->find(DDC3582Entity::class, 'foo'); + $entity = $this->em->find(DDC3582Entity::class, 'foo'); - $this->assertInstanceOf(DDC3582Embeddable1::class, $entity->embeddable1); - $this->assertInstanceOf(DDC3582Embeddable2::class, $entity->embeddable1->embeddable2); - $this->assertInstanceOf(DDC3582Embeddable3::class, $entity->embeddable1->embeddable2->embeddable3); + self::assertInstanceOf(DDC3582Embeddable1::class, $entity->embeddable1); + self::assertInstanceOf(DDC3582Embeddable2::class, $entity->embeddable1->embeddable2); + self::assertInstanceOf(DDC3582Embeddable3::class, $entity->embeddable1->embeddable2->embeddable3); } } -/** @Entity */ +/** @ORM\Entity */ class DDC3582Entity { - /** @Column @Id */ + /** @ORM\Column @ORM\Id */ private $id; - /** @Embedded(class="DDC3582Embeddable1") @var DDC3582Embeddable1 */ + /** @ORM\Embedded(class="DDC3582Embeddable1") @var DDC3582Embeddable1 */ public $embeddable1; public function __construct($id) @@ -36,27 +43,27 @@ public function __construct($id) } } -/** @Embeddable */ +/** @ORM\Embeddable */ class DDC3582Embeddable1 { - /** @Embedded(class="DDC3582Embeddable2") @var DDC3582Embeddable2 */ + /** @ORM\Embedded(class="DDC3582Embeddable2") @var DDC3582Embeddable2 */ public $embeddable2; public function __construct() { $this->embeddable2 = new DDC3582Embeddable2(); } } -/** @Embeddable */ +/** @ORM\Embeddable */ class DDC3582Embeddable2 { - /** @Embedded(class="DDC3582Embeddable3") @var DDC3582Embeddable3 */ + /** @ORM\Embedded(class="DDC3582Embeddable3") @var DDC3582Embeddable3 */ public $embeddable3; public function __construct() { $this->embeddable3 = new DDC3582Embeddable3(); } } -/** @Embeddable */ +/** @ORM\Embeddable */ class DDC3582Embeddable3 { - /** @Column */ + /** @ORM\Column */ public $embeddedValue = 'foo'; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3597Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3597Test.php index 6d59fd6f70c..da90db66b5a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3597Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3597Test.php @@ -1,5 +1,7 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC3597Root::class), - $this->_em->getClassMetadata(DDC3597Media::class), - $this->_em->getClassMetadata(DDC3597Image::class) + $this->em->getClassMetadata(DDC3597Root::class), + $this->em->getClassMetadata(DDC3597Media::class), + $this->em->getClassMetadata(DDC3597Image::class) ] ); } @@ -32,22 +34,22 @@ public function testSaveImageEntity() { $imageEntity->getDimension()->setWidth(300); $imageEntity->getDimension()->setHeight(500); - $this->_em->persist($imageEntity); - $this->_em->flush(); //before this fix, it will fail with a exception + $this->em->persist($imageEntity); + $this->em->flush(); //before this fix, it will fail with a exception - $this->_em->clear(); + $this->em->clear(); //request entity - $imageEntity = $this->_em->find(DDC3597Image::class, $imageEntity->getId()); - $this->assertInstanceOf(DDC3597Image::class, $imageEntity); + $imageEntity = $this->em->find(DDC3597Image::class, $imageEntity->getId()); + self::assertInstanceOf(DDC3597Image::class, $imageEntity); //cleanup - $this->_em->remove($imageEntity); - $this->_em->flush(); - $this->_em->clear(); + $this->em->remove($imageEntity); + $this->em->flush(); + $this->em->clear(); //check delete - $imageEntity = $this->_em->find(DDC3597Image::class, $imageEntity->getId()); - $this->assertNull($imageEntity); + $imageEntity = $this->em->find(DDC3597Image::class, $imageEntity->getId()); + self::assertNull($imageEntity); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php index 01f42bb930f..609866181b5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php @@ -1,9 +1,12 @@ _em->getClassMetadata(DDC3634Entity::class); + $metadata = $this->em->getClassMetadata(DDC3634Entity::class); - if ( ! $metadata->idGenerator->isPostInsertGenerator()) { + if ( ! $metadata->getValueGenerationPlan()->containsDeferred()) { $this->markTestSkipped('Need a post-insert ID generator in order to make this test work correctly'); } try { - $this->_schemaTool->createSchema([ + $this->schemaTool->createSchema([ $metadata, - $this->_em->getClassMetadata(DDC3634JTIBaseEntity::class), - $this->_em->getClassMetadata(DDC3634JTIChildEntity::class), + $this->em->getClassMetadata(DDC3634JTIBaseEntity::class), + $this->em->getClassMetadata(DDC3634JTIChildEntity::class), ]); } catch (ToolsException $e) { // schema already in place @@ -38,8 +42,8 @@ public function testSavesVeryLargeIntegerAutoGeneratedValue() $veryLargeId = PHP_INT_MAX . PHP_INT_MAX; $entityManager = EntityManager::create( - new DDC3634LastInsertIdMockingConnection($veryLargeId, $this->_em->getConnection()), - $this->_em->getConfiguration() + new DDC3634LastInsertIdMockingConnection($veryLargeId, $this->em->getConnection()), + $this->em->getConfiguration() ); $entity = new DDC3634Entity(); @@ -47,52 +51,52 @@ public function testSavesVeryLargeIntegerAutoGeneratedValue() $entityManager->persist($entity); $entityManager->flush(); - $this->assertSame($veryLargeId, $entity->id); + self::assertSame($veryLargeId, $entity->id); } public function testSavesIntegerAutoGeneratedValueAsString() { $entity = new DDC3634Entity(); - $this->_em->persist($entity); - $this->_em->flush(); + $this->em->persist($entity); + $this->em->flush(); - $this->assertInternalType('string', $entity->id); + self::assertInternalType('string', $entity->id); } public function testSavesIntegerAutoGeneratedValueAsStringWithJoinedInheritance() { $entity = new DDC3634JTIChildEntity(); - $this->_em->persist($entity); - $this->_em->flush(); + $this->em->persist($entity); + $this->em->flush(); - $this->assertInternalType('string', $entity->id); + self::assertInternalType('string', $entity->id); } } -/** @Entity */ +/** @ORM\Entity */ class DDC3634Entity { - /** @Id @Column(type="bigint") @GeneratedValue(strategy="AUTO") */ + /** @ORM\Id @ORM\Column(type="bigint") @ORM\GeneratedValue(strategy="AUTO") */ public $id; } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorMap({ + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorMap({ * DDC3634JTIBaseEntity::class = DDC3634JTIBaseEntity::class, * DDC3634JTIChildEntity::class = DDC3634JTIChildEntity::class, * }) */ class DDC3634JTIBaseEntity { - /** @Id @Column(type="bigint") @GeneratedValue(strategy="AUTO") */ + /** @ORM\Id @ORM\Column(type="bigint") @ORM\GeneratedValue(strategy="AUTO") */ public $id; } -/** @Entity */ +/** @ORM\Entity */ class DDC3634JTIChildEntity extends DDC3634JTIBaseEntity { } @@ -341,7 +345,7 @@ public function getNestTransactionsWithSavepoints() return $this->forwardCall(); } - protected function _getNestedTransactionSavePointName() + protected function getNestedTransactionSavePointName() { return $this->forwardCall(); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3644Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3644Test.php index 968c44d721b..3e7ce7ba896 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3644Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3644Test.php @@ -1,10 +1,12 @@ name = 'Guilherme Blanco'; $user->setAddresses($addresses); - $this->_em->persist($user); - $this->_em->persist($current); - $this->_em->persist($previous); - $this->_em->persist($initial); + $this->em->persist($user); + $this->em->persist($current); + $this->em->persist($previous); + $this->em->persist($initial); - $this->_em->flush(); + $this->em->flush(); $userId = $user->id; unset($current, $previous, $initial, $addresses, $user); - $this->_em->clear(); + $this->em->clear(); // Replace entire collection (this should trigger OneToManyPersister::remove()) $current = new DDC3644Address('Toronto, ON, Canada'); $addresses = new ArrayCollection([$current]); - $user = $this->_em->find(DDC3644User::class, $userId); + $user = $this->em->find(DDC3644User::class, $userId); $user->setAddresses($addresses); - $this->_em->persist($user); - $this->_em->persist($current); + $this->em->persist($user); + $this->em->persist($current); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); // We should only have 1 item in the collection list now - $user = $this->_em->find(DDC3644User::class, $userId); + $user = $this->em->find(DDC3644User::class, $userId); - $this->assertCount(1, $user->addresses); + self::assertCount(1, $user->addresses); // We should only have 1 item in the addresses table too - $repository = $this->_em->getRepository(DDC3644Address::class); + $repository = $this->em->getRepository(DDC3644Address::class); $addresses = $repository->findAll(); - $this->assertCount(1, $addresses); + self::assertCount(1, $addresses); } /** @@ -92,67 +94,67 @@ public function testIssueWithJoinedEntity() $user->name = 'Guilherme Blanco'; $user->setPets($pets); - $this->_em->persist($user); - $this->_em->persist($actual); - $this->_em->persist($past); + $this->em->persist($user); + $this->em->persist($actual); + $this->em->persist($past); - $this->_em->flush(); + $this->em->flush(); $userId = $user->id; unset($actual, $past, $pets, $user); - $this->_em->clear(); + $this->em->clear(); // Replace entire collection (this should trigger OneToManyPersister::remove()) $actual = new DDC3644Pet('Valentina'); $pets = new ArrayCollection([$actual]); - $user = $this->_em->find(DDC3644User::class, $userId); + $user = $this->em->find(DDC3644User::class, $userId); $user->setPets($pets); - $this->_em->persist($user); - $this->_em->persist($actual); + $this->em->persist($user); + $this->em->persist($actual); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); // We should only have 1 item in the collection list now - $user = $this->_em->find(DDC3644User::class, $userId); + $user = $this->em->find(DDC3644User::class, $userId); - $this->assertCount(1, $user->pets); + self::assertCount(1, $user->pets); // We should only have 1 item in the pets table too - $repository = $this->_em->getRepository(DDC3644Pet::class); + $repository = $this->em->getRepository(DDC3644Pet::class); $pets = $repository->findAll(); - $this->assertCount(1, $pets); + self::assertCount(1, $pets); } } /** - * @Entity + * @ORM\Entity */ class DDC3644User { /** - * @Id - * @GeneratedValue - * @Column(type="integer", name="hash_id") + * @ORM\Id + * @ORM\GeneratedValue + * @ORM\Column(type="integer", name="hash_id") */ public $id; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $name; /** - * @OneToMany(targetEntity="DDC3644Address", mappedBy="user", orphanRemoval=true) + * @ORM\OneToMany(targetEntity="DDC3644Address", mappedBy="user", orphanRemoval=true) */ public $addresses = []; /** - * @OneToMany(targetEntity="DDC3644Pet", mappedBy="owner", orphanRemoval=true) + * @ORM\OneToMany(targetEntity="DDC3644Pet", mappedBy="owner", orphanRemoval=true) */ public $pets = []; @@ -180,25 +182,25 @@ public function setPets(Collection $pets) } /** - * @Entity + * @ORM\Entity */ class DDC3644Address { /** - * @Id - * @GeneratedValue - * @Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue + * @ORM\Column(type="integer") */ public $id; /** - * @ManyToOne(targetEntity="DDC3644User", inversedBy="addresses") - * @JoinColumn(referencedColumnName="hash_id") + * @ORM\ManyToOne(targetEntity="DDC3644User", inversedBy="addresses") + * @ORM\JoinColumn(referencedColumnName="hash_id") */ public $user; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $address; @@ -209,22 +211,22 @@ public function __construct($address) } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="discriminator", type="string") - * @DiscriminatorMap({"pet" = "DDC3644Pet"}) + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="discriminator", type="string") + * @ORM\DiscriminatorMap({"pet" = "DDC3644Pet"}) */ abstract class DDC3644Animal { /** - * @Id - * @GeneratedValue - * @Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue + * @ORM\Column(type="integer") */ public $id; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $name; @@ -235,13 +237,13 @@ public function __construct($name) } /** - * @Entity + * @ORM\Entity */ class DDC3644Pet extends DDC3644Animal { /** - * @ManyToOne(targetEntity="DDC3644User", inversedBy="pets") - * @JoinColumn(referencedColumnName="hash_id") + * @ORM\ManyToOne(targetEntity="DDC3644User", inversedBy="pets") + * @ORM\JoinColumn(referencedColumnName="hash_id") */ public $owner; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3699Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3699Test.php deleted file mode 100644 index fd284e5b11d..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3699Test.php +++ /dev/null @@ -1,102 +0,0 @@ -useModelSet('ddc3699'); - - parent::setUp(); - } - - /** - * @group DDC-3699 - */ - public function testMergingParentClassFieldsDoesNotStopMergingScalarFieldsForToOneUninitializedAssociations() - { - $id = 1; - - $child = new DDC3699Child(); - - $child->id = $id; - $child->childField = 'childValue'; - $child->parentField = 'parentValue'; - - $relation = new DDC3699RelationOne(); - - $relation->id = $id; - $relation->child = $child ; - $child->oneRelation = $relation; - - $this->_em->persist($relation); - $this->_em->persist($child); - $this->_em->flush(); - $this->_em->clear(); - - // fixtures loaded - /* @var $unManagedChild DDC3699Child */ - $unManagedChild = $this->_em->find(DDC3699Child::class, $id); - - $this->_em->detach($unManagedChild); - - // make it managed again - $this->_em->find(DDC3699Child::class, $id); - - $unManagedChild->childField = 'modifiedChildValue'; - $unManagedChild->parentField = 'modifiedParentValue'; - - /* @var $mergedChild DDC3699Child */ - $mergedChild = $this->_em->merge($unManagedChild); - - $this->assertSame($mergedChild->childField, 'modifiedChildValue'); - $this->assertSame($mergedChild->parentField, 'modifiedParentValue'); - } - - /** - * @group DDC-3699 - */ - public function testMergingParentClassFieldsDoesNotStopMergingScalarFieldsForToManyUninitializedAssociations() - { - $id = 2; - - $child = new DDC3699Child(); - - $child->id = $id; - $child->childField = 'childValue'; - $child->parentField = 'parentValue'; - - $relation = new DDC3699RelationMany(); - - $relation->id = $id; - $relation->child = $child ; - $child->relations[] = $relation; - - $this->_em->persist($relation); - $this->_em->persist($child); - $this->_em->flush(); - $this->_em->clear(); - - /* @var $unmanagedChild DDC3699Child */ - $unmanagedChild = $this->_em->find(DDC3699Child::class, $id); - $this->_em->detach($unmanagedChild); - - // make it managed again - $this->_em->find(DDC3699Child::class, $id); - - $unmanagedChild->childField = 'modifiedChildValue'; - $unmanagedChild->parentField = 'modifiedParentValue'; - - /* @var $mergedChild DDC3699Child */ - $mergedChild = $this->_em->merge($unmanagedChild); - - $this->assertSame($mergedChild->childField, 'modifiedChildValue'); - $this->assertSame($mergedChild->parentField, 'modifiedParentValue'); - } -} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3711Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3711Test.php deleted file mode 100644 index bd2b1ba9bc6..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3711Test.php +++ /dev/null @@ -1,30 +0,0 @@ - - */ -class DDC3711Test extends YamlMappingDriverTest -{ - public function testCompositeKeyForJoinTableInManyToManyCreation() - { - $yamlDriver = $this->_loadDriver(); - - $em = $this->_getTestEntityManager(); - $em->getConfiguration()->setMetadataDriverImpl($yamlDriver); - $factory = new \Doctrine\ORM\Mapping\ClassMetadataFactory(); - $factory->setEntityManager($em); - - $entityA = new ClassMetadata(DDC3711EntityA::class); - $entityA = $factory->getMetadataFor(DDC3711EntityA::class); - - $this->assertEquals(['link_a_id1' => "id1", 'link_a_id2' => "id2"], $entityA->associationMappings['entityB']['relationToSourceKeyColumns']); - $this->assertEquals(['link_b_id1' => "id1", 'link_b_id2' => "id2"], $entityA->associationMappings['entityB']['relationToTargetKeyColumns']); - } -} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3719Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3719Test.php index f5f60c0b0d3..e6b2b32136c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3719Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3719Test.php @@ -1,5 +1,7 @@ setSalary(666); $manager->setTitle('Boss'); $manager->setDepartment('Marketing'); - $this->_em->persist($manager); + $this->em->persist($manager); $contractA = new CompanyFlexContract(); $contractA->markCompleted(); $contractA->addManager($manager); - $this->_em->persist($contractA); + $this->em->persist($contractA); $contractB = new CompanyFlexContract(); $contractB->addManager($manager); - $this->_em->persist($contractB); + $this->em->persist($contractB); - $this->_em->flush(); - $this->_em->refresh($manager); + $this->em->flush(); + $this->em->refresh($manager); $contracts = $manager->managedContracts; static::assertCount(2, $contracts); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC371Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC371Test.php index 3fe5c4b80d3..ed1e78c97e2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC371Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC371Test.php @@ -1,6 +1,10 @@ _em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_schemaTool->createSchema( + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC371Parent::class), - $this->_em->getClassMetadata(DDC371Child::class) + $this->em->getClassMetadata(DDC371Parent::class), + $this->em->getClassMetadata(DDC371Child::class) ] ); } @@ -33,41 +37,41 @@ public function testIssue() $child->parent = $parent; $parent->children->add($child); - $this->_em->persist($parent); - $this->_em->persist($child); + $this->em->persist($parent); + $this->em->persist($child); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $children = $this->_em->createQuery('select c,p from '.__NAMESPACE__.'\DDC371Child c ' + $children = $this->em->createQuery('select c,p from '.__NAMESPACE__.'\DDC371Child c ' . 'left join c.parent p where c.id = 1 and p.id = 1') ->setHint(Query::HINT_REFRESH, true) ->getResult(); - $this->assertEquals(1, count($children)); - $this->assertNotInstanceOf(Proxy::class, $children[0]->parent); - $this->assertFalse($children[0]->parent->children->isInitialized()); - $this->assertEquals(0, $children[0]->parent->children->unwrap()->count()); + self::assertEquals(1, count($children)); + self::assertNotInstanceOf(Proxy::class, $children[0]->parent); + self::assertFalse($children[0]->parent->children->isInitialized()); + self::assertEquals(0, $children[0]->parent->children->unwrap()->count()); } } -/** @Entity */ +/** @ORM\Entity */ class DDC371Child { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ private $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $data; - /** @ManyToOne(targetEntity="DDC371Parent", inversedBy="children") @JoinColumn(name="parentId") */ + /** @ORM\ManyToOne(targetEntity="DDC371Parent", inversedBy="children") @ORM\JoinColumn(name="parentId") */ public $parent; } -/** @Entity */ +/** @ORM\Entity */ class DDC371Parent { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ private $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $data; - /** @OneToMany(targetEntity="DDC371Child", mappedBy="parent") */ + /** @ORM\OneToMany(targetEntity="DDC371Child", mappedBy="parent") */ public $children; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3785Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3785Test.php index 984cda551ba..6d18984c346 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3785Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3785Test.php @@ -1,10 +1,13 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC3785_Asset::class), - $this->_em->getClassMetadata(DDC3785_AssetId::class), - $this->_em->getClassMetadata(DDC3785_Attribute::class) + $this->em->getClassMetadata(DDC3785_Asset::class), + $this->em->getClassMetadata(DDC3785_AssetId::class), + $this->em->getClassMetadata(DDC3785_Attribute::class) ] ); } catch(\Exception $e) { @@ -27,6 +30,7 @@ protected function setUp() } /** + * @group embedded * @group DDC-3785 */ public function testOwningValueObjectIdIsCorrectlyTransformedWhenRemovingOrphanedChildEntities() @@ -38,40 +42,41 @@ public function testOwningValueObjectIdIsCorrectlyTransformedWhenRemovingOrphane $attribute2 = new DDC3785_Attribute('foo2', 'bar2') ]; - $this->_em->persist($asset = new DDC3785_Asset($id, $attributes)); - $this->_em->flush(); + $this->em->persist($asset = new DDC3785_Asset($id, $attributes)); + $this->em->flush(); $asset->getAttributes() ->removeElement($attribute1); $idToBeRemoved = $attribute1->id; - $this->_em->persist($asset); - $this->_em->flush(); + $this->em->persist($asset); + $this->em->flush(); - self::assertNull($this->_em->find(DDC3785_Attribute::class, $idToBeRemoved)); - self::assertNotNull($this->_em->find(DDC3785_Attribute::class, $attribute2->id)); + self::assertNull($this->em->find(DDC3785_Attribute::class, $idToBeRemoved)); + self::assertNotNull($this->em->find(DDC3785_Attribute::class, $attribute2->id)); } } /** - * @Entity - * @Table(name="asset") + * @ORM\Entity + * @ORM\Table(name="asset") */ class DDC3785_Asset { /** - * @Id @GeneratedValue(strategy="NONE") @Column(type="ddc3785_asset_id") + * @ORM\Id @ORM\GeneratedValue(strategy="NONE") @ORM\Column(type="ddc3785_asset_id") */ private $id; /** - * @ManyToMany(targetEntity="DDC3785_Attribute", cascade={"persist"}, orphanRemoval=true) - * @JoinTable(name="asset_attributes", - * joinColumns={@JoinColumn(name="asset_id", referencedColumnName="id")}, - * inverseJoinColumns={@JoinColumn(name="attribute_id", referencedColumnName="id")} - * ) - **/ + * @ORM\ManyToMany(targetEntity="DDC3785_Attribute", cascade={"persist"}, orphanRemoval=true) + * @ORM\JoinTable( + * name="asset_attributes", + * joinColumns={@ORM\JoinColumn(name="asset_id", referencedColumnName="id")}, + * inverseJoinColumns={@ORM\JoinColumn(name="attribute_id", referencedColumnName="id")} + * ) + */ private $attributes; public function __construct(DDC3785_AssetId $id, $attributes = []) @@ -96,22 +101,22 @@ public function getAttributes() } /** - * @Entity - * @Table(name="attribute") + * @ORM\Entity + * @ORM\Table(name="attribute") */ class DDC3785_Attribute { - /** - * @Id @Column(type="integer") - * @GeneratedValue + /** + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue */ public $id; - /** @Column(type = "string") */ - private $name; + /** @ORM\Column(type = "string") */ + private $name; - /** @Column(type = "string") */ - private $value; + /** @ORM\Column(type = "string") */ + private $value; public function __construct($name, $value) { @@ -120,10 +125,10 @@ public function __construct($name, $value) } } -/** @Embeddable */ +/** @ORM\Embeddable */ class DDC3785_AssetId { - /** @Column(type = "guid") */ + /** @ORM\Column(type = "guid") */ private $id; public function __construct($id) @@ -133,7 +138,7 @@ public function __construct($id) public function __toString() { - return $this->id; + return (string) $this->id; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC381Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC381Test.php index bbfd6974e21..343c51e5120 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC381Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC381Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC381Entity::class), + $this->em->getClassMetadata(DDC381Entity::class), ] ); } catch(\Exception $e) { @@ -23,12 +27,12 @@ public function testCallUnserializedProxyMethods() { $entity = new DDC381Entity(); - $this->_em->persist($entity); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($entity); + $this->em->flush(); + $this->em->clear(); $persistedId = $entity->getId(); - $entity = $this->_em->getReference(DDC381Entity::class, $persistedId); + $entity = $this->em->getReference(DDC381Entity::class, $persistedId); // explicitly load proxy (getId() does not trigger reload of proxy) $id = $entity->getOtherMethod(); @@ -36,17 +40,17 @@ public function testCallUnserializedProxyMethods() $data = serialize($entity); $entity = unserialize($data); - $this->assertEquals($persistedId, $entity->getId()); + self::assertEquals($persistedId, $entity->getId()); } } /** - * @Entity + * @ORM\Entity */ class DDC381Entity { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ protected $id; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3967Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3967Test.php index 72a9cfe168a..96407898a21 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3967Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3967Test.php @@ -1,5 +1,7 @@ loadFixturesCountries(); - $this->_em->getCache()->evictEntityRegion(Country::class); - $this->_em->clear(); + $this->em->getCache()->evictEntityRegion(Country::class); + $this->em->clear(); } public function testIdentifierCachedWithProperType() @@ -22,14 +24,14 @@ public function testIdentifierCachedWithProperType() $id = $country->getId(); // First time, loaded from database - $this->_em->find(Country::class, "$id"); - $this->_em->clear(); + $this->em->find(Country::class, "$id"); + $this->em->clear(); // Second time, loaded from cache /** @var Country $country */ - $country = $this->_em->find(Country::class, "$id"); + $country = $this->em->find(Country::class, "$id"); // Identifier type should be integer - $this->assertSame($country->getId(), $id); + self::assertSame($country->getId(), $id); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC4003Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC4003Test.php index 6764bc9bf75..1d57887da05 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC4003Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC4003Test.php @@ -1,5 +1,7 @@ attractions[0]->getId(); - $repository = $this->_em->getRepository(Bar::class); + $repository = $this->em->getRepository(Bar::class); /** * This instance is fresh new, no QueryCache, so the full entity gets loaded from DB. @@ -30,8 +32,8 @@ public function test_reads_through_repository_same_data_that_it_wrote_in_cache() // Let's change it so that we can compare its state $bar->setName($newName = uniqid()); - $this->_em->persist($bar); - $this->_em->flush(); + $this->em->persist($bar); + $this->em->flush(); /** * Flush did 2 important things for us: @@ -44,7 +46,7 @@ public function test_reads_through_repository_same_data_that_it_wrote_in_cache() $repository->findOneBy(['id' => $id]); // Lets clear EM so that we don't hit IdentityMap at all. - $this->_em->clear(); + $this->em->clear(); /** * Here's the failing step: @@ -56,6 +58,6 @@ public function test_reads_through_repository_same_data_that_it_wrote_in_cache() */ $cached = $repository->findOneBy(['id' => $id]); - $this->assertEquals($newName, $cached->getName()); + self::assertEquals($newName, $cached->getName()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC422Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC422Test.php index 6ace5e74943..0a8d9e6eb64 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC422Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC422Test.php @@ -1,7 +1,10 @@ _em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_schemaTool->createSchema( + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC422Guest::class), - $this->_em->getClassMetadata(DDC422Customer::class), - $this->_em->getClassMetadata(DDC422Contact::class) + $this->em->getClassMetadata(DDC422Guest::class), + $this->em->getClassMetadata(DDC422Customer::class), + $this->em->getClassMetadata(DDC422Contact::class) ] ); } @@ -25,42 +28,42 @@ protected function setUp() public function testIssue() { $customer = new DDC422Customer; - $this->_em->persist($customer); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($customer); + $this->em->flush(); + $this->em->clear(); - $customer = $this->_em->find(get_class($customer), $customer->id); + $customer = $this->em->find(get_class($customer), $customer->id); - $this->assertInstanceOf(PersistentCollection::class, $customer->contacts); - $this->assertFalse($customer->contacts->isInitialized()); + self::assertInstanceOf(PersistentCollection::class, $customer->contacts); + self::assertFalse($customer->contacts->isInitialized()); $contact = new DDC422Contact; $customer->contacts->add($contact); - $this->assertTrue($customer->contacts->isDirty()); - $this->assertFalse($customer->contacts->isInitialized()); - $this->_em->flush(); + self::assertTrue($customer->contacts->isDirty()); + self::assertFalse($customer->contacts->isInitialized()); + $this->em->flush(); - $this->assertEquals(1, $this->_em->getConnection()->fetchColumn("select count(*) from ddc422_customers_contacts")); + self::assertEquals(1, $this->em->getConnection()->fetchColumn("select count(*) from ddc422_customers_contacts")); } } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="discr", type="string") - * @DiscriminatorMap({"guest" = "DDC422Guest", "customer" = "DDC422Customer"}) + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="discr", type="string") + * @ORM\DiscriminatorMap({"guest" = "DDC422Guest", "customer" = "DDC422Customer"}) */ class DDC422Guest { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; } -/** @Entity */ +/** @ORM\Entity */ class DDC422Customer extends DDC422Guest { /** - * @ManyToMany(targetEntity="DDC422Contact", cascade={"persist","remove"}) - * @JoinTable(name="ddc422_customers_contacts", - * joinColumns={@JoinColumn(name="customer_id", referencedColumnName="id", onDelete="cascade" )}, - * inverseJoinColumns={@JoinColumn(name="contact_id", referencedColumnName="id", onDelete="cascade" )} + * @ORM\ManyToMany(targetEntity="DDC422Contact", cascade={"persist","remove"}) + * @ORM\JoinTable(name="ddc422_customers_contacts", + * joinColumns={@ORM\JoinColumn(name="customer_id", referencedColumnName="id", onDelete="cascade" )}, + * inverseJoinColumns={@ORM\JoinColumn(name="contact_id", referencedColumnName="id", onDelete="cascade" )} * ) */ public $contacts; @@ -70,9 +73,9 @@ public function __construct() { } } -/** @Entity */ +/** @ORM\Entity */ class DDC422Contact { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC425Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC425Test.php index 8d91119a200..d5be11a9e2b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC425Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC425Test.php @@ -1,16 +1,20 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC425Entity::class), + $this->em->getClassMetadata(DDC425Entity::class), ] ); } @@ -20,23 +24,23 @@ protected function setUp() */ public function testIssue() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $num = $this->_em->createQuery('DELETE '.__NAMESPACE__.'\DDC425Entity e WHERE e.someDatetimeField > ?1') + $num = $this->em->createQuery('DELETE '.__NAMESPACE__.'\DDC425Entity e WHERE e.someDatetimeField > ?1') ->setParameter(1, new DateTime, Type::DATETIME) ->getResult(); - $this->assertEquals(0, $num); + self::assertEquals(0, $num); } } -/** @Entity */ +/** @ORM\Entity */ class DDC425Entity { /** - * @Id @Column(type="integer") - * @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue */ public $id; - /** @Column(type="datetime") */ + /** @ORM\Column(type="datetime") */ public $someDatetimeField; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC440Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC440Test.php index 30d2ca6b9cd..2054f2d9437 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC440Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC440Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC440Phone::class), - $this->_em->getClassMetadata(DDC440Client::class) + $this->em->getClassMetadata(DDC440Phone::class), + $this->em->getClassMetadata(DDC440Client::class) ] ); } catch (\Exception $e) { @@ -25,8 +29,6 @@ protected function setUp() */ public function testOriginalEntityDataEmptyWhenProxyLoadedFromTwoAssociations() { - - /* The key of the problem is that the first phone is fetched via two association, main_phone and phones. * * You will notice that the original_entity_datas are not loaded for the first phone. (They are for the second) @@ -52,13 +54,13 @@ public function testOriginalEntityDataEmptyWhenProxyLoadedFromTwoAssociations() $client->setMainPhone($phone); - $this->_em->persist($client); - $this->_em->flush(); + $this->em->persist($client); + $this->em->flush(); $id = $client->getId(); - $this->_em->clear(); + $this->em->clear(); - $uw = $this->_em->getUnitOfWork(); - $client = $this->_em->find(DDC440Client::class, $id); + $uw = $this->em->getUnitOfWork(); + $client = $this->em->find(DDC440Client::class, $id); $clientPhones = $client->getPhones(); $p1 = $clientPhones[1]; @@ -67,41 +69,41 @@ public function testOriginalEntityDataEmptyWhenProxyLoadedFromTwoAssociations() // Test the first phone. The assertion actually failed because original entity data is not set properly. // This was because it is also set as MainPhone and that one is created as a proxy, not the // original object when the find on Client is called. However loading proxies did not work correctly. - $this->assertInstanceOf(DDC440Phone::class, $p1); + self::assertInstanceOf(DDC440Phone::class, $p1); $originalData = $uw->getOriginalEntityData($p1); - $this->assertEquals($phone->getNumber(), $originalData['number']); + self::assertEquals($phone->getNumber(), $originalData['number']); //If you comment out previous test, this one should pass - $this->assertInstanceOf(DDC440Phone::class, $p2); + self::assertInstanceOf(DDC440Phone::class, $p2); $originalData = $uw->getOriginalEntityData($p2); - $this->assertEquals($phone2->getNumber(), $originalData['number']); + self::assertEquals($phone2->getNumber(), $originalData['number']); } } /** - * @Entity - * @Table(name="phone") + * @ORM\Entity + * @ORM\Table(name="phone") */ class DDC440Phone { /** - * @Column(name="id", type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") + * @ORM\Column(name="id", type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** - * @ManyToOne(targetEntity="DDC440Client",inversedBy="phones") - * @JoinColumns({ - * @JoinColumn(name="client_id", referencedColumnName="id") + * @ORM\ManyToOne(targetEntity="DDC440Client",inversedBy="phones") + * @ORM\JoinColumns({ + * @ORM\JoinColumn(name="client_id", referencedColumnName="id") * }) */ protected $client; /** - * @Column(name="phonenumber", type="string") + * @ORM\Column(name="phonenumber", type="string") */ protected $number; @@ -141,32 +143,32 @@ public function setId($value) } /** - * @Entity - * @Table(name="client") + * @ORM\Entity + * @ORM\Table(name="client") */ class DDC440Client { /** - * @Column(name="id", type="integer") - * @Id - * @GeneratedValue(strategy="AUTO") + * @ORM\Column(name="id", type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** - * @OneToOne(targetEntity="DDC440Phone", fetch="EAGER") - * @JoinColumns({ - * @JoinColumn(name="main_phone_id", referencedColumnName="id",onDelete="SET NULL") + * @ORM\OneToOne(targetEntity="DDC440Phone", fetch="EAGER") + * @ORM\JoinColumns({ + * @ORM\JoinColumn(name="main_phone_id", referencedColumnName="id",onDelete="SET NULL") * }) */ protected $main_phone; /** - * @OneToMany(targetEntity="DDC440Phone", mappedBy="client", cascade={"persist", "remove"}, fetch="EAGER", indexBy="id") - * @OrderBy({"number"="ASC"}) + * @ORM\OneToMany(targetEntity="DDC440Phone", mappedBy="client", cascade={"persist", "remove"}, fetch="EAGER", indexBy="id") + * @ORM\OrderBy({"number"="ASC"}) */ protected $phones; /** - * @Column(name="name", type="string") + * @ORM\Column(name="name", type="string") */ protected $name; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC444Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC444Test.php index 41d7e1270ec..f9f337e0fde 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC444Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC444Test.php @@ -1,16 +1,20 @@ _em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_schemaTool->createSchema( + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC444User::class), + $this->em->getClassMetadata(DDC444User::class), ] ); } @@ -22,54 +26,54 @@ public function testExplicitPolicy() $u = new $classname; $u->name = "Initial value"; - $this->_em->persist($u); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($u); + $this->em->flush(); + $this->em->clear(); - $q = $this->_em->createQuery("SELECT u FROM $classname u"); + $q = $this->em->createQuery("SELECT u FROM $classname u"); $u = $q->getSingleResult(); - $this->assertEquals("Initial value", $u->name); + self::assertEquals("Initial value", $u->name); $u->name = "Modified value"; // This should be NOOP as the change hasn't been persisted - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $u = $this->_em->createQuery("SELECT u FROM $classname u"); + $u = $this->em->createQuery("SELECT u FROM $classname u"); $u = $q->getSingleResult(); - $this->assertEquals("Initial value", $u->name); + self::assertEquals("Initial value", $u->name); $u->name = "Modified value"; - $this->_em->persist($u); + $this->em->persist($u); // Now we however persisted it, and this should have updated our friend - $this->_em->flush(); + $this->em->flush(); - $q = $this->_em->createQuery("SELECT u FROM $classname u"); + $q = $this->em->createQuery("SELECT u FROM $classname u"); $u = $q->getSingleResult(); - $this->assertEquals("Modified value", $u->name); + self::assertEquals("Modified value", $u->name); } } /** - * @Entity @Table(name="ddc444") - * @ChangeTrackingPolicy("DEFERRED_EXPLICIT") + * @ORM\Entity @ORM\Table(name="ddc444") + * @ORM\ChangeTrackingPolicy("DEFERRED_EXPLICIT") */ class DDC444User { /** - * @Id @Column(name="id", type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @Column(name="name", type="string") + * @ORM\Column(name="name", type="string") */ public $name; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC448Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC448Test.php index 31e03e33732..60698289c06 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC448Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC448Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC448MainTable::class), - $this->_em->getClassMetadata(DDC448ConnectedClass::class), - $this->_em->getClassMetadata(DDC448SubTable::class), + $this->em->getClassMetadata(DDC448MainTable::class), + $this->em->getClassMetadata(DDC448ConnectedClass::class), + $this->em->getClassMetadata(DDC448SubTable::class), ] ); } public function testIssue() { - $q = $this->_em->createQuery("select b from ".__NAMESPACE__."\\DDC448SubTable b where b.connectedClassId = ?1"); - $this->assertEquals( - strtolower('SELECT d0_.id AS id_0, d0_.discr AS discr_1, d0_.connectedClassId AS connectedClassId_2 FROM SubTable s1_ INNER JOIN DDC448MainTable d0_ ON s1_.id = d0_.id WHERE d0_.connectedClassId = ?'), - strtolower($q->getSQL()) + $q = $this->em->createQuery("select b from ".__NAMESPACE__."\\DDC448SubTable b where b.connectedClassId = ?1"); + + self::assertSQLEquals( + 'SELECT t0."id" AS c0, t0."discr" AS c1, t0."connectedClassId" AS c2 FROM "SubTable" t1 INNER JOIN "DDC448MainTable" t0 ON t1."id" = t0."id" WHERE t0."connectedClassId" = ?', + $q->getSQL() ); } } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="discr", type="smallint") - * @DiscriminatorMap({ + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="discr", type="smallint") + * @ORM\DiscriminatorMap({ * "0" = "DDC448MainTable", * "1" = "DDC448SubTable" * }) @@ -40,37 +44,37 @@ public function testIssue() class DDC448MainTable { /** - * @Id - * @Column(name="id", type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** - * @ManyToOne(targetEntity="DDC448ConnectedClass", cascade={"all"}, fetch="EAGER") - * @JoinColumn(name="connectedClassId", referencedColumnName="id", onDelete="CASCADE", nullable=true) + * @ORM\ManyToOne(targetEntity="DDC448ConnectedClass", cascade={"all"}, fetch="EAGER") + * @ORM\JoinColumn(name="connectedClassId", referencedColumnName="id", onDelete="CASCADE", nullable=true) */ private $connectedClassId; } /** - * @Entity - * @Table(name="connectedClass") - * @HasLifecycleCallbacks + * @ORM\Entity + * @ORM\Table(name="connectedClass") + * @ORM\HasLifecycleCallbacks */ class DDC448ConnectedClass { /** - * @Id - * @Column(name="id", type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; // connected with DDC448MainTable } /** - * @Entity - * @Table(name="SubTable") + * @ORM\Entity + * @ORM\Table(name="SubTable") */ class DDC448SubTable extends DDC448MainTable { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC493Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC493Test.php index 536a8b49b52..3d1365fe881 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC493Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC493Test.php @@ -1,69 +1,74 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC493Customer::class), - $this->_em->getClassMetadata(DDC493Distributor::class), - $this->_em->getClassMetadata(DDC493Contact::class) + $this->em->getClassMetadata(DDC493Customer::class), + $this->em->getClassMetadata(DDC493Distributor::class), + $this->em->getClassMetadata(DDC493Contact::class) ] ); } public function testIssue() { - $q = $this->_em->createQuery("select u, c.data from ".__NAMESPACE__."\\DDC493Distributor u JOIN u.contact c"); - $this->assertEquals( - strtolower('SELECT d0_.id AS id_0, d1_.data AS data_1, d0_.discr AS discr_2, d0_.contact AS contact_3 FROM DDC493Distributor d2_ INNER JOIN DDC493Customer d0_ ON d2_.id = d0_.id INNER JOIN DDC493Contact d1_ ON d0_.contact = d1_.id'), - strtolower($q->getSQL()) + $q = $this->em->createQuery("select u, c.data from ".__NAMESPACE__."\\DDC493Distributor u JOIN u.contact c"); + + self::assertSQLEquals( + 'SELECT t0."id" AS c0, t1."data" AS c1, t0."discr" AS c2, t0."contact" AS c3 FROM "DDC493Distributor" t2 INNER JOIN "DDC493Customer" t0 ON t2."id" = t0."id" INNER JOIN "DDC493Contact" t1 ON t0."contact" = t1."id"', + $q->getSQL() ); } } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="discr", type="string") - * @DiscriminatorMap({"distributor" = "DDC493Distributor", "customer" = "DDC493Customer"}) + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="discr", type="string") + * @ORM\DiscriminatorMap({"distributor" = "DDC493Distributor", "customer" = "DDC493Customer"}) */ class DDC493Customer { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @OneToOne(targetEntity="DDC493Contact", cascade={"remove","persist"}) - * @JoinColumn(name="contact", referencedColumnName="id") + * @ORM\OneToOne(targetEntity="DDC493Contact", cascade={"remove","persist"}) + * @ORM\JoinColumn(name="contact", referencedColumnName="id") */ public $contact; } /** - * @Entity + * @ORM\Entity */ class DDC493Distributor extends DDC493Customer { } /** - * @Entity + * @ORM\Entity */ class DDC493Contact { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $data; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC501Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC501Test.php deleted file mode 100644 index 5b2996aab2f..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC501Test.php +++ /dev/null @@ -1,120 +0,0 @@ -useModelSet('cms'); - parent::setUp(); - } - - public function testMergeUnitializedManyToManyAndOneToManyCollections() - { - // Create User - $user = $this->createAndPersistUser(); - $this->_em->flush(); - - $this->assertTrue($this->_em->contains($user)); - $this->_em->clear(); - $this->assertFalse($this->_em->contains($user)); - - unset($user); - - // Reload User from DB *without* any associations (i.e. an uninitialized PersistantCollection) - $userReloaded = $this->loadUserFromEntityManager(); - - $this->assertTrue($this->_em->contains($userReloaded)); - $this->_em->clear(); - $this->assertFalse($this->_em->contains($userReloaded)); - - // freeze and unfreeze - $userClone = unserialize(serialize($userReloaded)); - $this->assertInstanceOf(CmsUser::class, $userClone); - - // detached user can't know about his phonenumbers - $this->assertEquals(0, count($userClone->getPhonenumbers())); - $this->assertFalse($userClone->getPhonenumbers()->isInitialized(), "User::phonenumbers should not be marked initialized."); - - // detached user can't know about his groups either - $this->assertEquals(0, count($userClone->getGroups())); - $this->assertFalse($userClone->getGroups()->isInitialized(), "User::groups should not be marked initialized."); - - // Merge back and flush - $userClone = $this->_em->merge($userClone); - - // Back in managed world I would expect to have my phonenumbers back but they aren't! - // Remember I didn't touch (and probably didn't need) them at all while in detached mode. - $this->assertEquals(4, count($userClone->getPhonenumbers()), 'Phonenumbers are not available anymore'); - - // This works fine as long as cmUser::groups doesn't cascade "merge" - $this->assertEquals(2, count($userClone->getGroups())); - - $this->_em->flush(); - $this->_em->clear(); - - $this->assertFalse($this->_em->contains($userClone)); - - // Reload user from DB - $userFromEntityManager = $this->loadUserFromEntityManager(); - - //Strange: Now the phonenumbers are back again - $this->assertEquals(4, count($userFromEntityManager->getPhonenumbers())); - - // This works fine as long as cmUser::groups doesn't cascade "merge" - // Otherwise group memberships are physically deleted now! - $this->assertEquals(2, count($userClone->getGroups())); - } - - protected function createAndPersistUser() - { - $user = new CmsUser(); - $user->name = 'Luka'; - $user->username = 'lukacho'; - $user->status = 'developer'; - - foreach([1111,2222,3333,4444] as $number) { - $phone = new CmsPhonenumber; - $phone->phonenumber = $number; - $user->addPhonenumber($phone); - } - - foreach(['Moshers', 'Headbangers'] as $groupName) { - $group = new CmsGroup; - $group->setName($groupName); - $user->addGroup($group); - } - - $this->_em->persist($user); - - return $user; - } - - /** - * @return Doctrine\Tests\Models\CMS\CmsUser - */ - protected function loadUserFromEntityManager() - { - return $this->_em - ->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name like :name') - ->setParameter('name', 'Luka') - ->getSingleResult(); - } - -} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC512Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC512Test.php index 6f3c3cfb01b..697a9eb72c3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC512Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC512Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC512Customer::class), - $this->_em->getClassMetadata(DDC512OfferItem::class), - $this->_em->getClassMetadata(DDC512Item::class), + $this->em->getClassMetadata(DDC512Customer::class), + $this->em->getClassMetadata(DDC512OfferItem::class), + $this->em->getClassMetadata(DDC512Item::class), ] ); } @@ -23,39 +26,39 @@ public function testIssue() $customer1 = new DDC512Customer(); $item = new DDC512OfferItem(); $customer1->item = $item; - $this->_em->persist($customer1); + $this->em->persist($customer1); $customer2 = new DDC512Customer(); - $this->_em->persist($customer2); + $this->em->persist($customer2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $q = $this->_em->createQuery("select u,i from ".__NAMESPACE__."\\DDC512Customer u left join u.item i"); + $q = $this->em->createQuery("select u,i from ".__NAMESPACE__."\\DDC512Customer u left join u.item i"); $result = $q->getResult(); - $this->assertEquals(2, count($result)); - $this->assertInstanceOf(DDC512Customer::class, $result[0]); - $this->assertInstanceOf(DDC512Customer::class, $result[1]); + self::assertEquals(2, count($result)); + self::assertInstanceOf(DDC512Customer::class, $result[0]); + self::assertInstanceOf(DDC512Customer::class, $result[1]); if ($result[0]->id == $customer1->id) { - $this->assertInstanceOf(DDC512OfferItem::class, $result[0]->item); - $this->assertEquals($item->id, $result[0]->item->id); - $this->assertNull($result[1]->item); + self::assertInstanceOf(DDC512OfferItem::class, $result[0]->item); + self::assertEquals($item->id, $result[0]->item->id); + self::assertNull($result[1]->item); } else { - $this->assertInstanceOf(DDC512OfferItem::class, $result[1]->item); - $this->assertNull($result[0]->item); + self::assertInstanceOf(DDC512OfferItem::class, $result[1]->item); + self::assertNull($result[0]->item); } } } /** - * @Entity + * @ORM\Entity */ class DDC512Customer { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; @@ -63,31 +66,31 @@ class DDC512Customer { * NOTE that we can currently not name the join column the same as the field * (item = item), this currently confuses Doctrine. * - * @OneToOne(targetEntity="DDC512OfferItem", cascade={"remove","persist"}) - * @JoinColumn(name="item_id", referencedColumnName="id") + * @ORM\OneToOne(targetEntity="DDC512OfferItem", cascade={"remove","persist"}) + * @ORM\JoinColumn(name="item_id", referencedColumnName="id") */ public $item; } /** - * @Entity + * @ORM\Entity */ class DDC512OfferItem extends DDC512Item { } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="discr", type="string") - * @DiscriminatorMap({"item" = "DDC512Item", "offerItem" = "DDC512OfferItem"}) + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="discr", type="string") + * @ORM\DiscriminatorMap({"item" = "DDC512Item", "offerItem" = "DDC512OfferItem"}) */ class DDC512Item { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC513Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC513Test.php index 800c442a398..aa110e29e4f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC513Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC513Test.php @@ -1,71 +1,76 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC513OfferItem::class), - $this->_em->getClassMetadata(DDC513Item::class), - $this->_em->getClassMetadata(DDC513Price::class), + $this->em->getClassMetadata(DDC513OfferItem::class), + $this->em->getClassMetadata(DDC513Item::class), + $this->em->getClassMetadata(DDC513Price::class), ] ); } public function testIssue() { - $q = $this->_em->createQuery("select u from ".__NAMESPACE__."\\DDC513OfferItem u left join u.price p"); - $this->assertEquals( - strtolower('SELECT d0_.id AS id_0, d0_.discr AS discr_1, d0_.price AS price_2 FROM DDC513OfferItem d1_ INNER JOIN DDC513Item d0_ ON d1_.id = d0_.id LEFT JOIN DDC513Price d2_ ON d0_.price = d2_.id'), - strtolower($q->getSQL()) + $q = $this->em->createQuery("select u from ".__NAMESPACE__."\\DDC513OfferItem u left join u.price p"); + + self::assertSQLEquals( + 'SELECT t0."id" AS c0, t0."discr" AS c1, t0."price" AS c2 FROM "DDC513OfferItem" t1 INNER JOIN "DDC513Item" t0 ON t1."id" = t0."id" LEFT JOIN "DDC513Price" t2 ON t0."price" = t2."id"', + $q->getSQL() ); } } /** - * @Entity + * @ORM\Entity */ class DDC513OfferItem extends DDC513Item { } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="discr", type="string") - * @DiscriminatorMap({"item" = "DDC513Item", "offerItem" = "DDC513OfferItem"}) + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="discr", type="string") + * @ORM\DiscriminatorMap({"item" = "DDC513Item", "offerItem" = "DDC513OfferItem"}) */ class DDC513Item { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @OneToOne(targetEntity="DDC513Price", cascade={"remove","persist"}) - * @JoinColumn(name="price", referencedColumnName="id") + * @ORM\OneToOne(targetEntity="DDC513Price", cascade={"remove","persist"}) + * @ORM\JoinColumn(name="price", referencedColumnName="id") */ public $price; } /** - * @Entity + * @ORM\Entity */ class DDC513Price { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $data; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC518Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC518Test.php deleted file mode 100644 index 073bb335188..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC518Test.php +++ /dev/null @@ -1,35 +0,0 @@ -useModelSet('cms'); - parent::setUp(); - } - - public function testMergeWithRelatedNew() - { - $article = new \Doctrine\Tests\Models\CMS\CmsArticle(); - $article->text = "foo"; - $article->topic = "bar"; - - $this->_em->persist($article); - $this->_em->flush(); - $this->_em->detach($article); - $this->_em->clear(); - - $user = new \Doctrine\Tests\Models\CMS\CmsUser(); - $user->username = "beberlei"; - $user->name = "Benjamin Eberlei"; - $user->status = "active"; - $article->user = $user; - - $this->_em->persist($user); - $managedArticle = $this->_em->merge($article); - - $this->assertSame($article->user, $managedArticle->user); - } -} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC522Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC522Test.php index dc6fa208179..a8a431d513d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC522Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC522Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC522Customer::class), - $this->_em->getClassMetadata(DDC522Cart::class), - $this->_em->getClassMetadata(DDC522ForeignKeyTest::class) + $this->em->getClassMetadata(DDC522Customer::class), + $this->em->getClassMetadata(DDC522Cart::class), + $this->em->getClassMetadata(DDC522ForeignKeyTest::class) ] ); } catch(\Exception $e) { @@ -33,35 +36,41 @@ public function testJoinColumnWithSameNameAsAssociationField() { $cust = new DDC522Customer; $cust->name = "name"; + $cart = new DDC522Cart; $cart->total = 0; $cust->cart = $cart; $cart->customer = $cust; - $this->_em->persist($cust); - $this->_em->persist($cart); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($cust); + $this->em->persist($cart); + $this->em->flush(); + $this->em->clear(); + + $cart = $this->em + ->createQuery('select ca, c from ' . DDC522Cart::class . ' ca join ca.customer c') + ->getSingleResult() + ; - $r = $this->_em->createQuery('select ca,c from ' . DDC522Cart::class . ' ca join ca.customer c') - ->getResult(); + self::assertInstanceOf(DDC522Cart::class, $cart); + self::assertInstanceOf(DDC522Customer::class, $cart->customer); + self::assertNotInstanceOf(Proxy::class, $cart->customer); + self::assertEquals('name', $cart->customer->name); - $this->assertInstanceOf(DDC522Cart::class, $r[0]); - $this->assertInstanceOf(DDC522Customer::class, $r[0]->customer); - $this->assertNotInstanceOf(Proxy::class, $r[0]->customer); - $this->assertEquals('name', $r[0]->customer->name); + $cartId = $cart->id; $fkt = new DDC522ForeignKeyTest(); - $fkt->cartId = $r[0]->id; // ignored for persistence - $fkt->cart = $r[0]; // must be set properly - $this->_em->persist($fkt); - $this->_em->flush(); - $this->_em->clear(); - - $fkt2 = $this->_em->find(get_class($fkt), $fkt->id); - $this->assertEquals($fkt->cart->id, $fkt2->cartId); - $this->assertInstanceOf(Proxy::class, $fkt2->cart); - $this->assertFalse($fkt2->cart->__isInitialized__); + $fkt->cart = $cart; // must be set properly + + $this->em->persist($fkt); + $this->em->flush(); + $this->em->clear(); + + $fkt2 = $this->em->find(get_class($fkt), $fkt->id); + + self::assertEquals($fkt->cart->id, $cartId); + self::assertInstanceOf(Proxy::class, $fkt2->cart); + self::assertFalse($fkt2->cart->__isInitialized()); } /** @@ -74,59 +83,75 @@ public function testJoinColumnWithNullSameNameAssociationField() $fkCust->name = 'name'; $fkCust->cart = null; - $this->_em->persist($fkCust); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($fkCust); + $this->em->flush(); + $this->em->clear(); $expected = clone $fkCust; + // removing dynamic field (which is not persisted) unset($expected->name); - self::assertEquals($expected, $this->_em->find(DDC522ForeignKeyTest::class, $fkCust->id)); + self::assertEquals($expected, $this->em->find(DDC522ForeignKeyTest::class, $fkCust->id)); } } -/** @Entity */ +/** + * @ORM\Entity + */ class DDC522Customer { - /** @Id @Column(type="integer") @GeneratedValue */ + /** + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue + */ public $id; - /** @Column */ + /** @ORM\Column */ public $name; - /** @OneToOne(targetEntity="DDC522Cart", mappedBy="customer") */ + /** @ORM\OneToOne(targetEntity="DDC522Cart", mappedBy="customer") */ public $cart; } -/** @Entity */ +/** + * @ORM\Entity + */ class DDC522Cart { - /** @Id @Column(type="integer") @GeneratedValue */ + /** + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue + */ public $id; - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ public $total; /** - * @OneToOne(targetEntity="DDC522Customer", inversedBy="cart") - * @JoinColumn(name="customer", referencedColumnName="id") + * @ORM\OneToOne(targetEntity="DDC522Customer", inversedBy="cart") + * @ORM\JoinColumn(name="customer", referencedColumnName="id") */ public $customer; } -/** @Entity */ +/** + * @ORM\Entity + */ class DDC522ForeignKeyTest { - /** @Id @Column(type="integer") @GeneratedValue */ + /** + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue + */ public $id; - /** @Column(type="integer", name="cart_id", nullable=true) */ - public $cartId; - /** - * @OneToOne(targetEntity="DDC522Cart") - * @JoinColumn(name="cart_id", referencedColumnName="id") + * @ORM\OneToOne(targetEntity="DDC522Cart") + * @ORM\JoinColumn(name="cart_id", referencedColumnName="id") */ public $cart; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC531Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC531Test.php index 33d88c6be1f..1f423bc11ee 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC531Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC531Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC531Item::class), - $this->_em->getClassMetadata(DDC531SubItem::class), + $this->em->getClassMetadata(DDC531Item::class), + $this->em->getClassMetadata(DDC531SubItem::class), ] ); } @@ -23,46 +26,46 @@ public function testIssue() $item2 = new DDC531Item; $item2->parent = $item1; $item1->getChildren()->add($item2); - $this->_em->persist($item1); - $this->_em->persist($item2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($item1); + $this->em->persist($item2); + $this->em->flush(); + $this->em->clear(); - $item3 = $this->_em->find(DDC531Item::class, $item2->id); // Load child item first (id 2) + $item3 = $this->em->find(DDC531Item::class, $item2->id); // Load child item first (id 2) // parent will already be loaded, cannot be lazy because it has mapped subclasses and we would not // know which proxy type to put in. - $this->assertInstanceOf(DDC531Item::class, $item3->parent); - $this->assertNotInstanceOf(Proxy::class, $item3->parent); - $item4 = $this->_em->find(DDC531Item::class, $item1->id); // Load parent item (id 1) - $this->assertNull($item4->parent); - $this->assertNotNull($item4->getChildren()); - $this->assertTrue($item4->getChildren()->contains($item3)); // lazy-loads children + self::assertInstanceOf(DDC531Item::class, $item3->parent); + self::assertNotInstanceOf(Proxy::class, $item3->parent); + $item4 = $this->em->find(DDC531Item::class, $item1->id); // Load parent item (id 1) + self::assertNull($item4->parent); + self::assertNotNull($item4->getChildren()); + self::assertTrue($item4->getChildren()->contains($item3)); // lazy-loads children } } /** - * @Entity - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorColumn(name="type", type="integer") - * @DiscriminatorMap({"0" = "DDC531Item", "1" = "DDC531SubItem"}) + * @ORM\Entity + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorColumn(name="type", type="integer") + * @ORM\DiscriminatorMap({"0" = "DDC531Item", "1" = "DDC531SubItem"}) */ class DDC531Item { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @OneToMany(targetEntity="DDC531Item", mappedBy="parent") + * @ORM\OneToMany(targetEntity="DDC531Item", mappedBy="parent") */ protected $children; /** - * @ManyToOne(targetEntity="DDC531Item", inversedBy="children") - * @JoinColumn(name="parentId", referencedColumnName="id") + * @ORM\ManyToOne(targetEntity="DDC531Item", inversedBy="children") + * @ORM\JoinColumn(name="parentId", referencedColumnName="id") */ public $parent; @@ -83,7 +86,7 @@ public function getChildren() } /** - * @Entity + * @ORM\Entity */ class DDC531SubItem extends DDC531Item { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC5684Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC5684Test.php index e525ae1342b..3f5972b3492 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC5684Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC5684Test.php @@ -1,9 +1,12 @@ _schemaTool->createSchema([$this->_em->getClassMetadata(DDC5684Object::class)]); + $this->schemaTool->createSchema([$this->em->getClassMetadata(DDC5684Object::class)]); } protected function tearDown() { - $this->_schemaTool->dropSchema([$this->_em->getClassMetadata(DDC5684Object::class)]); + $this->schemaTool->dropSchema([$this->em->getClassMetadata(DDC5684Object::class)]); parent::tearDown(); } @@ -37,24 +40,24 @@ protected function tearDown() public function testAutoIncrementIdWithCustomType() { $object = new DDC5684Object(); - $this->_em->persist($object); - $this->_em->flush(); + $this->em->persist($object); + $this->em->flush(); - $this->assertInstanceOf(DDC5684ObjectId::class, $object->id); + self::assertInstanceOf(DDC5684ObjectId::class, $object->id); } public function testFetchObjectWithAutoIncrementedCustomType() { $object = new DDC5684Object(); - $this->_em->persist($object); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($object); + $this->em->flush(); + $this->em->clear(); $rawId = $object->id->value; - $object = $this->_em->find(DDC5684Object::class, new DDC5684ObjectId($rawId)); + $object = $this->em->find(DDC5684Object::class, new DDC5684ObjectId($rawId)); - $this->assertInstanceOf(DDC5684ObjectId::class, $object->id); - $this->assertEquals($rawId, $object->id->value); + self::assertInstanceOf(DDC5684ObjectId::class, $object->id); + self::assertEquals($rawId, $object->id->value); } } @@ -97,15 +100,15 @@ public function __toString() } /** - * @Entity - * @Table(name="ticket_5684_objects") + * @ORM\Entity + * @ORM\Table(name="ticket_5684_objects") */ class DDC5684Object { /** - * @Id - * @Column(type=Doctrine\Tests\ORM\Functional\Ticket\DDC5684ObjectIdType::class) - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type=Doctrine\Tests\ORM\Functional\Ticket\DDC5684ObjectIdType::class) + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC588Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC588Test.php index 7361bc4f403..6663ecab7fb 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC588Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC588Test.php @@ -1,16 +1,20 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC588Site::class), + $this->em->getClassMetadata(DDC588Site::class), ] ); } @@ -19,29 +23,30 @@ public function testIssue() { $site = new DDC588Site('Foo'); - $this->_em->persist($site); - $this->_em->flush(); + $this->em->persist($site); + $this->em->flush(); + // Following should not result in exception - $this->_em->refresh($site); + $this->em->refresh($site); $this->addToAssertionCount(1); } } /** - * @Entity + * @ORM\Entity */ class DDC588Site { /** - * @Id - * @Column(type="integer", name="site_id") - * @GeneratedValue + * @ORM\Id + * @ORM\Column(type="integer", name="site_id") + * @ORM\GeneratedValue */ public $id; /** - * @Column(type="string", length=45) + * @ORM\Column(type="string", length=45) */ protected $name = null; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC599Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC599Test.php index 842ccdd1a73..260ac5b2d0a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC599Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC599Test.php @@ -1,21 +1,23 @@ _em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); try { - $this->_schemaTool->createSchema( - [ - $this->_em->getClassMetadata(DDC599Item::class), - $this->_em->getClassMetadata(DDC599Subitem::class), - $this->_em->getClassMetadata(DDC599Child::class), - ] - ); + $this->schemaTool->createSchema([ + $this->em->getClassMetadata(DDC599Item::class), + $this->em->getClassMetadata(DDC599Subitem::class), + $this->em->getClassMetadata(DDC599Child::class), + ]); } catch (\Exception $ignored) {} } @@ -26,68 +28,68 @@ public function testCascadeRemoveOnInheritanceHierarchy() $child = new DDC599Child; $child->parent = $item; $item->getChildren()->add($child); - $this->_em->persist($item); - $this->_em->persist($child); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($item); + $this->em->persist($child); + $this->em->flush(); + $this->em->clear(); - $item = $this->_em->find(DDC599Item::class, $item->id); + $item = $this->em->find(DDC599Item::class, $item->id); - $this->_em->remove($item); - $this->_em->flush(); // Should not fail + $this->em->remove($item); + $this->em->flush(); // Should not fail - $this->assertFalse($this->_em->contains($item)); + self::assertFalse($this->em->contains($item)); $children = $item->getChildren(); - $this->assertFalse($this->_em->contains($children[0])); + self::assertFalse($this->em->contains($children[0])); - $this->_em->clear(); + $this->em->clear(); $item2 = new DDC599Subitem; $item2->elem = "bar"; - $this->_em->persist($item2); - $this->_em->flush(); + $this->em->persist($item2); + $this->em->flush(); $child2 = new DDC599Child; $child2->parent = $item2; $item2->getChildren()->add($child2); - $this->_em->persist($child2); - $this->_em->flush(); + $this->em->persist($child2); + $this->em->flush(); - $this->_em->remove($item2); - $this->_em->flush(); // should not fail + $this->em->remove($item2); + $this->em->flush(); // should not fail - $this->assertFalse($this->_em->contains($item)); + self::assertFalse($this->em->contains($item)); $children = $item->getChildren(); - $this->assertFalse($this->_em->contains($children[0])); + self::assertFalse($this->em->contains($children[0])); } public function testCascadeRemoveOnChildren() { - $class = $this->_em->getClassMetadata(DDC599Subitem::class); + $class = $this->em->getClassMetadata(DDC599Subitem::class); - $this->assertArrayHasKey('children', $class->associationMappings); - $this->assertTrue($class->associationMappings['children']['isCascadeRemove']); + self::assertArrayHasKey('children', iterator_to_array($class->getDeclaredPropertiesIterator())); + self::assertContains('remove', $class->getProperty('children')->getCascade()); } } /** - * @Entity - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorColumn(name="type", type="integer") - * @DiscriminatorMap({"0" = "DDC599Item", "1" = "DDC599Subitem"}) + * @ORM\Entity + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorColumn(name="type", type="integer") + * @ORM\DiscriminatorMap({"0" = "DDC599Item", "1" = "DDC599Subitem"}) */ class DDC599Item { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @OneToMany(targetEntity="DDC599Child", mappedBy="parent", cascade={"remove"}) + * @ORM\OneToMany(targetEntity="DDC599Child", mappedBy="parent", cascade={"remove"}) */ protected $children; @@ -103,31 +105,31 @@ public function getChildren() } /** - * @Entity + * @ORM\Entity */ class DDC599Subitem extends DDC599Item { /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $elem; } /** - * @Entity + * @ORM\Entity */ class DDC599Child { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @ManyToOne(targetEntity="DDC599Item", inversedBy="children") - * @JoinColumn(name="parentId", referencedColumnName="id") + * @ORM\ManyToOne(targetEntity="DDC599Item", inversedBy="children") + * @ORM\JoinColumn(name="parentId", referencedColumnName="id") */ public $parent; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC618Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC618Test.php index 5e359863e91..cf497fe362a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC618Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC618Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC618Author::class), - $this->_em->getClassMetadata(DDC618Book::class) + $this->em->getClassMetadata(DDC618Author::class), + $this->em->getClassMetadata(DDC618Book::class) ] ); @@ -22,7 +26,7 @@ protected function setUp() $author = new DDC618Author(); $author->id = 10; $author->name = 'Joe'; - $this->_em->persist($author); + $this->em->persist($author); // Create author 11/Alice with two books 21/AliceA and 23/AliceB $author = new DDC618Author(); @@ -32,10 +36,10 @@ protected function setUp() $author->addBook('Reloaded'); $author->addBook('Test'); - $this->_em->persist($author); + $this->em->persist($author); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); } catch(\Exception $e) { } @@ -44,25 +48,25 @@ protected function setUp() public function testIndexByHydrateObject() { $dql = 'SELECT A FROM Doctrine\Tests\ORM\Functional\Ticket\DDC618Author A INDEX BY A.name ORDER BY A.name ASC'; - $result = $this->_em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT); + $result = $this->em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT); - $joe = $this->_em->find(DDC618Author::class, 10); - $alice = $this->_em->find(DDC618Author::class, 11); + $joe = $this->em->find(DDC618Author::class, 10); + $alice = $this->em->find(DDC618Author::class, 11); - $this->assertArrayHasKey('Joe', $result, "INDEX BY A.name should return an index by the name of 'Joe'."); - $this->assertArrayHasKey('Alice', $result, "INDEX BY A.name should return an index by the name of 'Alice'."); + self::assertArrayHasKey('Joe', $result, "INDEX BY A.name should return an index by the name of 'Joe'."); + self::assertArrayHasKey('Alice', $result, "INDEX BY A.name should return an index by the name of 'Alice'."); } public function testIndexByHydrateArray() { $dql = 'SELECT A FROM Doctrine\Tests\ORM\Functional\Ticket\DDC618Author A INDEX BY A.name ORDER BY A.name ASC'; - $result = $this->_em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); + $result = $this->em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); - $joe = $this->_em->find(DDC618Author::class, 10); - $alice = $this->_em->find(DDC618Author::class, 11); + $joe = $this->em->find(DDC618Author::class, 10); + $alice = $this->em->find(DDC618Author::class, 11); - $this->assertArrayHasKey('Joe', $result, "INDEX BY A.name should return an index by the name of 'Joe'."); - $this->assertArrayHasKey('Alice', $result, "INDEX BY A.name should return an index by the name of 'Alice'."); + self::assertArrayHasKey('Joe', $result, "INDEX BY A.name should return an index by the name of 'Joe'."); + self::assertArrayHasKey('Alice', $result, "INDEX BY A.name should return an index by the name of 'Alice'."); } /** @@ -72,21 +76,21 @@ public function testIndexByJoin() { $dql = 'SELECT A, B FROM Doctrine\Tests\ORM\Functional\Ticket\DDC618Author A '. 'INNER JOIN A.books B INDEX BY B.title ORDER BY A.name ASC'; - $result = $this->_em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT); + $result = $this->em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT); - $this->assertEquals(3, count($result[0]->books)); // Alice, Joe doesn't appear because he has no books. - $this->assertEquals('Alice', $result[0]->name); - $this->assertTrue( isset($result[0]->books["In Wonderland"] ), "Indexing by title should have books by title."); - $this->assertTrue( isset($result[0]->books["Reloaded"] ), "Indexing by title should have books by title."); - $this->assertTrue( isset($result[0]->books["Test"] ), "Indexing by title should have books by title."); + self::assertEquals(3, count($result[0]->books)); // Alice, Joe doesn't appear because he has no books. + self::assertEquals('Alice', $result[0]->name); + self::assertTrue( isset($result[0]->books["In Wonderland"] ), "Indexing by title should have books by title."); + self::assertTrue( isset($result[0]->books["Reloaded"] ), "Indexing by title should have books by title."); + self::assertTrue( isset($result[0]->books["Test"] ), "Indexing by title should have books by title."); - $result = $this->_em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); + $result = $this->em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); - $this->assertEquals(3, count($result[0]['books'])); // Alice, Joe doesn't appear because he has no books. - $this->assertEquals('Alice', $result[0]['name']); - $this->assertTrue( isset($result[0]['books']["In Wonderland"] ), "Indexing by title should have books by title."); - $this->assertTrue( isset($result[0]['books']["Reloaded"] ), "Indexing by title should have books by title."); - $this->assertTrue( isset($result[0]['books']["Test"] ), "Indexing by title should have books by title."); + self::assertEquals(3, count($result[0]['books'])); // Alice, Joe doesn't appear because he has no books. + self::assertEquals('Alice', $result[0]['name']); + self::assertTrue( isset($result[0]['books']["In Wonderland"] ), "Indexing by title should have books by title."); + self::assertTrue( isset($result[0]['books']["Reloaded"] ), "Indexing by title should have books by title."); + self::assertTrue( isset($result[0]['books']["Test"] ), "Indexing by title should have books by title."); } /** @@ -96,16 +100,16 @@ public function testIndexByToOneJoinSilentlyIgnored() { $dql = 'SELECT B, A FROM Doctrine\Tests\ORM\Functional\Ticket\DDC618Book B '. 'INNER JOIN B.author A INDEX BY A.name ORDER BY A.name ASC'; - $result = $this->_em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT); + $result = $this->em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT); - $this->assertInstanceOf(DDC618Book::class, $result[0]); - $this->assertInstanceOf(DDC618Author::class, $result[0]->author); + self::assertInstanceOf(DDC618Book::class, $result[0]); + self::assertInstanceOf(DDC618Author::class, $result[0]->author); $dql = 'SELECT B, A FROM Doctrine\Tests\ORM\Functional\Ticket\DDC618Book B '. 'INNER JOIN B.author A INDEX BY A.name ORDER BY A.name ASC'; - $result = $this->_em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); + $result = $this->em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); - $this->assertEquals("Alice", $result[0]['author']['name']); + self::assertEquals("Alice", $result[0]['author']['name']); } /** @@ -115,34 +119,34 @@ public function testCombineIndexBy() { $dql = 'SELECT A, B FROM Doctrine\Tests\ORM\Functional\Ticket\DDC618Author A INDEX BY A.id '. 'INNER JOIN A.books B INDEX BY B.title ORDER BY A.name ASC'; - $result = $this->_em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT); + $result = $this->em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT); - $this->assertArrayHasKey(11, $result); // Alice + self::assertArrayHasKey(11, $result); // Alice - $this->assertEquals(3, count($result[11]->books)); // Alice, Joe doesn't appear because he has no books. - $this->assertEquals('Alice', $result[11]->name); - $this->assertTrue( isset($result[11]->books["In Wonderland"] ), "Indexing by title should have books by title."); - $this->assertTrue( isset($result[11]->books["Reloaded"] ), "Indexing by title should have books by title."); - $this->assertTrue( isset($result[11]->books["Test"] ), "Indexing by title should have books by title."); + self::assertEquals(3, count($result[11]->books)); // Alice, Joe doesn't appear because he has no books. + self::assertEquals('Alice', $result[11]->name); + self::assertTrue( isset($result[11]->books["In Wonderland"] ), "Indexing by title should have books by title."); + self::assertTrue( isset($result[11]->books["Reloaded"] ), "Indexing by title should have books by title."); + self::assertTrue( isset($result[11]->books["Test"] ), "Indexing by title should have books by title."); } } /** - * @Entity + * @ORM\Entity */ class DDC618Author { /** - * @Id - * @Column(type="integer") + * @ORM\Id + * @ORM\Column(type="integer") */ public $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $name; /** - * @OneToMany(targetEntity="DDC618Book", mappedBy="author", cascade={"persist"}) + * @ORM\OneToMany(targetEntity="DDC618Book", mappedBy="author", cascade={"persist"}) */ public $books; @@ -159,20 +163,20 @@ public function addBook($title) } /** - * @Entity + * @ORM\Entity */ class DDC618Book { /** - * @Id @GeneratedValue - * @Column(type="integer") + * @ORM\Id @ORM\GeneratedValue + * @ORM\Column(type="integer") */ public $id; - /** @column(type="string") */ + /** @ORM\Column(type="string") */ public $title; - /** @ManyToOne(targetEntity="DDC618Author", inversedBy="books") */ + /** @ORM\ManyToOne(targetEntity="DDC618Author", inversedBy="books") */ public $author; function __construct($title, $author) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC633Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC633Test.php index 2ed53ed354f..dcdba191e0a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC633Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC633Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC633Patient::class), - $this->_em->getClassMetadata(DDC633Appointment::class), + $this->em->getClassMetadata(DDC633Patient::class), + $this->em->getClassMetadata(DDC633Appointment::class), ] ); } catch(\Exception $e) { @@ -33,16 +36,16 @@ public function testOneToOneEager() $app->patient = $pat; $pat->appointment = $app; - $this->_em->persist($app); - $this->_em->persist($pat); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($app); + $this->em->persist($pat); + $this->em->flush(); + $this->em->clear(); - $eagerAppointment = $this->_em->find(DDC633Appointment::class, $app->id); + $eagerAppointment = $this->em->find(DDC633Appointment::class, $app->id); // Eager loading of one to one leads to fetch-join - $this->assertNotInstanceOf(Proxy::class, $eagerAppointment->patient); - $this->assertTrue($this->_em->contains($eagerAppointment->patient)); + self::assertNotInstanceOf(Proxy::class, $eagerAppointment->patient); + self::assertTrue($this->em->contains($eagerAppointment->patient)); } /** @@ -57,46 +60,46 @@ public function testDQLDeferredEagerLoad() $app->patient = $pat; $pat->appointment = $app; - $this->_em->persist($app); - $this->_em->persist($pat); + $this->em->persist($app); + $this->em->persist($pat); } - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $appointments = $this->_em->createQuery("SELECT a FROM " . __NAMESPACE__ . "\DDC633Appointment a")->getResult(); + $appointments = $this->em->createQuery("SELECT a FROM " . __NAMESPACE__ . "\DDC633Appointment a")->getResult(); foreach ($appointments AS $eagerAppointment) { - $this->assertInstanceOf(Proxy::class, $eagerAppointment->patient); - $this->assertTrue($eagerAppointment->patient->__isInitialized__, "Proxy should already be initialized due to eager loading!"); + self::assertInstanceOf(Proxy::class, $eagerAppointment->patient); + self::assertTrue($eagerAppointment->patient->__isInitialized(), "Proxy should already be initialized due to eager loading!"); } } } /** - * @Entity + * @ORM\Entity */ class DDC633Appointment { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; /** - * @OneToOne(targetEntity="DDC633Patient", inversedBy="appointment", fetch="EAGER") + * @ORM\OneToOne(targetEntity="DDC633Patient", inversedBy="appointment", fetch="EAGER") */ public $patient; } /** - * @Entity + * @ORM\Entity */ class DDC633Patient { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; /** - * @OneToOne(targetEntity="DDC633Appointment", mappedBy="patient") + * @ORM\OneToOne(targetEntity="DDC633Appointment", mappedBy="patient") */ public $appointment; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC6460Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC6460Test.php index 9868c7d1c00..01a7f94d96f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC6460Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC6460Test.php @@ -1,16 +1,16 @@ _em + $isFieldMapped = $this->em ->getClassMetadata(DDC6460Entity::class) ->hasField('embedded'); - $this->assertTrue($isFieldMapped); + self::assertTrue($isFieldMapped); } /** @@ -49,63 +49,64 @@ public function testInlineEmbeddableProxyInitialization() $entity->id = 1; $entity->embedded = new DDC6460Embeddable(); $entity->embedded->field = 'test'; - $this->_em->persist($entity); + + $this->em->persist($entity); $second = new DDC6460ParentEntity(); $second->id = 1; $second->lazyLoaded = $entity; - $this->_em->persist($second); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($second); + $this->em->flush(); + $this->em->clear(); - $secondEntityWithLazyParameter = $this->_em->getRepository(DDC6460ParentEntity::class)->findOneById(1); + $secondEntityWithLazyParameter = $this->em->getRepository(DDC6460ParentEntity::class)->findOneById(1); - $this->assertInstanceOf(Proxy::class, $secondEntityWithLazyParameter->lazyLoaded); - $this->assertInstanceOf(DDC6460Entity::class, $secondEntityWithLazyParameter->lazyLoaded); - $this->assertFalse($secondEntityWithLazyParameter->lazyLoaded->__isInitialized()); - $this->assertEquals($secondEntityWithLazyParameter->lazyLoaded->embedded, $entity->embedded); - $this->assertTrue($secondEntityWithLazyParameter->lazyLoaded->__isInitialized()); + self::assertInstanceOf(Proxy::class, $secondEntityWithLazyParameter->lazyLoaded); + self::assertInstanceOf(DDC6460Entity::class, $secondEntityWithLazyParameter->lazyLoaded); + self::assertFalse($secondEntityWithLazyParameter->lazyLoaded->__isInitialized()); + self::assertEquals($secondEntityWithLazyParameter->lazyLoaded->embedded, $entity->embedded); + self::assertTrue($secondEntityWithLazyParameter->lazyLoaded->__isInitialized()); } } /** - * @Embeddable() + * @ORM\Embeddable() */ class DDC6460Embeddable { - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $field; } /** - * @Entity() + * @ORM\Entity() */ class DDC6460Entity { /** - * @Id - * @GeneratedValue(strategy = "NONE") - * @Column(type = "integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy = "NONE") + * @ORM\Column(type = "integer") */ public $id; - /** @Embedded(class = "DDC6460Embeddable") */ + /** @ORM\Embedded(class = "DDC6460Embeddable") */ public $embedded; } /** - * @Entity() + * @ORM\Entity() */ class DDC6460ParentEntity { /** - * @Id - * @GeneratedValue(strategy = "NONE") - * @Column(type = "integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy = "NONE") + * @ORM\Column(type = "integer") */ public $id; - /** @ManyToOne(targetEntity = "DDC6460Entity", fetch="EXTRA_LAZY", cascade={"persist"}) */ + /** @ORM\ManyToOne(targetEntity = "DDC6460Entity", fetch="EXTRA_LAZY", cascade={"persist"}) */ public $lazyLoaded; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC656Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC656Test.php index 1f94a3953a9..eb542000f45 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC656Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC656Test.php @@ -1,16 +1,20 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC656Entity::class) + $this->em->getClassMetadata(DDC656Entity::class) ] ); } catch(\Exception $e) { @@ -23,42 +27,42 @@ public function testRecomputeSingleEntityChangeSet_PreservesFieldOrder() $entity = new DDC656Entity(); $entity->setName('test1'); $entity->setType('type1'); - $this->_em->persist($entity); + $this->em->persist($entity); - $this->_em->getUnitOfWork()->computeChangeSet($this->_em->getClassMetadata(get_class($entity)), $entity); - $data1 = $this->_em->getUnitOfWork()->getEntityChangeSet($entity); + $this->em->getUnitOfWork()->computeChangeSet($this->em->getClassMetadata(get_class($entity)), $entity); + $data1 = $this->em->getUnitOfWork()->getEntityChangeSet($entity); $entity->setType('type2'); - $this->_em->getUnitOfWork()->recomputeSingleEntityChangeSet($this->_em->getClassMetadata(get_class($entity)), $entity); - $data2 = $this->_em->getUnitOfWork()->getEntityChangeSet($entity); + $this->em->getUnitOfWork()->recomputeSingleEntityChangeSet($this->em->getClassMetadata(get_class($entity)), $entity); + $data2 = $this->em->getUnitOfWork()->getEntityChangeSet($entity); - $this->assertEquals(array_keys($data1), array_keys($data2)); + self::assertEquals(array_keys($data1), array_keys($data2)); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $persistedEntity = $this->_em->find(get_class($entity), $entity->specificationId); - $this->assertEquals('type2', $persistedEntity->getType()); - $this->assertEquals('test1', $persistedEntity->getName()); + $persistedEntity = $this->em->find(get_class($entity), $entity->specificationId); + self::assertEquals('type2', $persistedEntity->getType()); + self::assertEquals('test1', $persistedEntity->getName()); } } /** - * @Entity + * @ORM\Entity */ class DDC656Entity { /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $name; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $type; /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $specificationId; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC657Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC657Test.php index 759464a5f0e..63fd44ca562 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC657Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC657Test.php @@ -1,5 +1,7 @@ _em->createQuery('SELECT d FROM ' . DateTimeModel::class . ' d'); + $query = $this->em->createQuery('SELECT d FROM ' . DateTimeModel::class . ' d'); $datetime = $query->setMaxResults(1)->getSingleResult(); - $this->assertInstanceOf(DateTimeModel::class, $datetime); + self::assertInstanceOf(DateTimeModel::class, $datetime); - $this->assertInstanceOf('DateTime', $datetime->datetime); - $this->assertInstanceOf('DateTime', $datetime->time); - $this->assertInstanceOf('DateTime', $datetime->date); + self::assertInstanceOf('DateTime', $datetime->datetime); + self::assertInstanceOf('DateTime', $datetime->time); + self::assertInstanceOf('DateTime', $datetime->date); } public function testScalarResult() { - $query = $this->_em->createQuery('SELECT d.id, d.time, d.date, d.datetime FROM ' . DateTimeModel::class . ' d ORDER BY d.date ASC'); + $query = $this->em->createQuery('SELECT d.id, d.time, d.date, d.datetime FROM ' . DateTimeModel::class . ' d ORDER BY d.date ASC'); $result = $query->getScalarResult(); - $this->assertCount(2,$result); + self::assertCount(2,$result); - $this->assertContains('11:11:11', $result[0]['time']); - $this->assertContains('2010-01-01', $result[0]['date']); - $this->assertContains('2010-01-01 11:11:11', $result[0]['datetime']); + self::assertContains('11:11:11', $result[0]['time']); + self::assertContains('2010-01-01', $result[0]['date']); + self::assertContains('2010-01-01 11:11:11', $result[0]['datetime']); - $this->assertContains('12:12:12', $result[1]['time']); - $this->assertContains('2010-02-02', $result[1]['date']); - $this->assertContains('2010-02-02 12:12:12', $result[1]['datetime']); + self::assertContains('12:12:12', $result[1]['time']); + self::assertContains('2010-02-02', $result[1]['date']); + self::assertContains('2010-02-02 12:12:12', $result[1]['datetime']); } public function testaTicketEntityArrayResult() { - $query = $this->_em->createQuery('SELECT d FROM ' . DateTimeModel::class . ' d ORDER BY d.date ASC'); + $query = $this->em->createQuery('SELECT d FROM ' . DateTimeModel::class . ' d ORDER BY d.date ASC'); $result = $query->getArrayResult(); - $this->assertCount(2,$result); + self::assertCount(2,$result); - $this->assertInstanceOf('DateTime', $result[0]['datetime']); - $this->assertInstanceOf('DateTime', $result[0]['time']); - $this->assertInstanceOf('DateTime', $result[0]['date']); + self::assertInstanceOf('DateTime', $result[0]['datetime']); + self::assertInstanceOf('DateTime', $result[0]['time']); + self::assertInstanceOf('DateTime', $result[0]['date']); - $this->assertInstanceOf('DateTime', $result[1]['datetime']); - $this->assertInstanceOf('DateTime', $result[1]['time']); - $this->assertInstanceOf('DateTime', $result[1]['date']); + self::assertInstanceOf('DateTime', $result[1]['datetime']); + self::assertInstanceOf('DateTime', $result[1]['time']); + self::assertInstanceOf('DateTime', $result[1]['date']); } public function testTicketSingleResult() { - $query = $this->_em->createQuery('SELECT d.id, d.time, d.date, d.datetime FROM ' . DateTimeModel::class . ' d ORDER BY d.date ASC'); + $query = $this->em->createQuery('SELECT d.id, d.time, d.date, d.datetime FROM ' . DateTimeModel::class . ' d ORDER BY d.date ASC'); $datetime = $query->setMaxResults(1)->getSingleResult(); - $this->assertTrue(is_array($datetime)); + self::assertTrue(is_array($datetime)); - $this->assertInstanceOf('DateTime', $datetime['datetime']); - $this->assertInstanceOf('DateTime', $datetime['time']); - $this->assertInstanceOf('DateTime', $datetime['date']); + self::assertInstanceOf('DateTime', $datetime['datetime']); + self::assertInstanceOf('DateTime', $datetime['time']); + self::assertInstanceOf('DateTime', $datetime['date']); } public function testTicketResult() { - $query = $this->_em->createQuery('SELECT d.id, d.time, d.date, d.datetime FROM ' . DateTimeModel::class . ' d ORDER BY d.date ASC'); + $query = $this->em->createQuery('SELECT d.id, d.time, d.date, d.datetime FROM ' . DateTimeModel::class . ' d ORDER BY d.date ASC'); $result = $query->getResult(); - $this->assertCount(2,$result); + self::assertCount(2,$result); - $this->assertInstanceOf('DateTime', $result[0]['time']); - $this->assertInstanceOf('DateTime', $result[0]['date']); - $this->assertInstanceOf('DateTime', $result[0]['datetime']); + self::assertInstanceOf('DateTime', $result[0]['time']); + self::assertInstanceOf('DateTime', $result[0]['date']); + self::assertInstanceOf('DateTime', $result[0]['datetime']); - $this->assertEquals('2010-01-01 11:11:11', $result[0]['datetime']->format('Y-m-d G:i:s')); + self::assertEquals('2010-01-01 11:11:11', $result[0]['datetime']->format('Y-m-d G:i:s')); - $this->assertInstanceOf('DateTime', $result[1]['time']); - $this->assertInstanceOf('DateTime', $result[1]['date']); - $this->assertInstanceOf('DateTime', $result[1]['datetime']); + self::assertInstanceOf('DateTime', $result[1]['time']); + self::assertInstanceOf('DateTime', $result[1]['date']); + self::assertInstanceOf('DateTime', $result[1]['datetime']); - $this->assertEquals('2010-02-02 12:12:12', $result[1]['datetime']->format('Y-m-d G:i:s')); + self::assertEquals('2010-02-02 12:12:12', $result[1]['datetime']->format('Y-m-d G:i:s')); } public function loadFixtures() @@ -108,9 +110,9 @@ public function loadFixtures() $dateTime2->time = new \DateTime('2010-02-02 12:12:12', $timezone); $dateTime2->datetime= new \DateTime('2010-02-02 12:12:12', $timezone); - $this->_em->persist($dateTime1); - $this->_em->persist($dateTime2); + $this->em->persist($dateTime1); + $this->em->persist($dateTime2); - $this->_em->flush(); + $this->em->flush(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC698Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC698Test.php index f21d6de6936..d48eef5a75f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC698Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC698Test.php @@ -1,17 +1,21 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC698Role::class), - $this->_em->getClassMetadata(DDC698Privilege::class) + $this->em->getClassMetadata(DDC698Role::class), + $this->em->getClassMetadata(DDC698Privilege::class) ] ); } catch(\Exception $e) { @@ -21,43 +25,41 @@ protected function setUp() public function testTicket() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('p', 'r') ->from(__NAMESPACE__ . '\DDC698Privilege', 'p') ->leftJoin('p.roles', 'r'); - $sql = $qb->getQuery()->getSQL(); - - $this->assertEquals( - strtolower('SELECT p0_.privilegeID AS privilegeID_0, p0_.name AS name_1, r1_.roleID AS roleID_2, r1_.name AS name_3, r1_.shortName AS shortName_4 FROM Privileges p0_ LEFT JOIN RolePrivileges r2_ ON p0_.privilegeID = r2_.privilegeID LEFT JOIN Roles r1_ ON r1_.roleID = r2_.roleID'), - strtolower($sql) + self::assertSQLEquals( + 'SELECT t0."privilegeID" AS c0, t0."name" AS c1, t1."roleID" AS c2, t1."name" AS c3, t1."shortName" AS c4 FROM "Privileges" t0 LEFT JOIN "RolePrivileges" t2 ON t0."privilegeID" = t2."privilegeID" LEFT JOIN "Roles" t1 ON t1."roleID" = t2."roleID"', + $qb->getQuery()->getSQL() ); } } /** * - * @Table(name="Roles") - * @Entity + * @ORM\Table(name="Roles") + * @ORM\Entity */ class DDC698Role { /** - * @Id @Column(name="roleID", type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(name="roleID", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") * */ protected $roleID; /** - * @Column(name="name", type="string", length=45) + * @ORM\Column(name="name", type="string", length=45) * * */ protected $name; /** - * @Column(name="shortName", type="string", length=45) + * @ORM\Column(name="shortName", type="string", length=45) * * */ @@ -66,10 +68,10 @@ class DDC698Role /** - * @ManyToMany(targetEntity="DDC698Privilege", inversedBy="roles") - * @JoinTable(name="RolePrivileges", - * joinColumns={@JoinColumn(name="roleID", referencedColumnName="roleID")}, - * inverseJoinColumns={@JoinColumn(name="privilegeID", referencedColumnName="privilegeID")} + * @ORM\ManyToMany(targetEntity="DDC698Privilege", inversedBy="roles") + * @ORM\JoinTable(name="RolePrivileges", + * joinColumns={@ORM\JoinColumn(name="roleID", referencedColumnName="roleID")}, + * inverseJoinColumns={@ORM\JoinColumn(name="privilegeID", referencedColumnName="privilegeID")} * ) */ protected $privilege; @@ -79,27 +81,27 @@ class DDC698Role /** * - * @Table(name="Privileges") - * @Entity() + * @ORM\Table(name="Privileges") + * @ORM\Entity() */ class DDC698Privilege { /** - * @Id @Column(name="privilegeID", type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(name="privilegeID", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") * */ protected $privilegeID; /** - * @Column(name="name", type="string", length=45) + * @ORM\Column(name="name", type="string", length=45) * * */ protected $name; /** - * @ManyToMany(targetEntity="DDC698Role", mappedBy="privilege") + * @ORM\ManyToMany(targetEntity="DDC698Role", mappedBy="privilege") */ protected $roles; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC719Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC719Test.php index c6f1a2254cb..5453a3ce008 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC719Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC719Test.php @@ -1,41 +1,45 @@ _em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_schemaTool->createSchema( + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC719Group::class), + $this->em->getClassMetadata(DDC719Group::class), ] ); } public function testIsEmptySqlGeneration() { - $q = $this->_em->createQuery('SELECT g, c FROM Doctrine\Tests\ORM\Functional\Ticket\DDC719Group g LEFT JOIN g.children c WHERE g.parents IS EMPTY'); - - $referenceSQL = 'SELECT g0_.name AS name_0, g0_.description AS description_1, g0_.id AS id_2, g1_.name AS name_3, g1_.description AS description_4, g1_.id AS id_5 FROM groups g0_ LEFT JOIN groups_groups g2_ ON g0_.id = g2_.parent_id LEFT JOIN groups g1_ ON g1_.id = g2_.child_id WHERE (SELECT COUNT(*) FROM groups_groups g3_ WHERE g3_.child_id = g0_.id) = 0'; + $q = $this->em->createQuery( + 'SELECT g, c FROM Doctrine\Tests\ORM\Functional\Ticket\DDC719Group g LEFT JOIN g.children c WHERE g.parents IS EMPTY' + ); - $this->assertEquals( - strtolower($referenceSQL), - strtolower($q->getSQL()) + self::assertSQLEquals( + 'SELECT t0."id" AS c0, t0."name" AS c1, t0."description" AS c2, t1."id" AS c3, t1."name" AS c4, t1."description" AS c5 FROM "groups" t0 LEFT JOIN "groups_groups" t2 ON t0."id" = t2."parent_id" LEFT JOIN "groups" t1 ON t1."id" = t2."child_id" WHERE (SELECT COUNT(*) FROM "groups_groups" t3 WHERE t3."child_id" = t0."id") = 0', + $q->getSQL() ); } } /** - * @MappedSuperclass + * @ORM\MappedSuperclass */ class Entity { /** - * @Id @GeneratedValue - * @Column(type="integer") + * @ORM\Id @ORM\GeneratedValue + * @ORM\Column(type="integer") */ protected $id; @@ -43,27 +47,27 @@ public function getId() { return $this->id; } } /** - * @Entity - * @Table(name="groups") + * @ORM\Entity + * @ORM\Table(name="groups") */ class DDC719Group extends Entity { - /** @Column(type="string", nullable=false) */ + /** @ORM\Column(type="string", nullable=false) */ protected $name; - /** @Column(type="string", nullable=true) */ + /** @ORM\Column(type="string", nullable=true) */ protected $description; /** - * @ManyToMany(targetEntity="DDC719Group", inversedBy="parents") - * @JoinTable(name="groups_groups", - * joinColumns={@JoinColumn(name="parent_id", referencedColumnName="id")}, - * inverseJoinColumns={@JoinColumn(name="child_id", referencedColumnName="id")} + * @ORM\ManyToMany(targetEntity="DDC719Group", inversedBy="parents") + * @ORM\JoinTable(name="groups_groups", + * joinColumns={@ORM\JoinColumn(name="parent_id", referencedColumnName="id")}, + * inverseJoinColumns={@ORM\JoinColumn(name="child_id", referencedColumnName="id")} * ) */ protected $children = NULL; /** - * @ManyToMany(targetEntity="DDC719Group", mappedBy="children") + * @ORM\ManyToMany(targetEntity="DDC719Group", mappedBy="children") */ protected $parents = NULL; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC729Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC729Test.php deleted file mode 100644 index af4c9634c12..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC729Test.php +++ /dev/null @@ -1,185 +0,0 @@ -_em); - $schemaTool->createSchema( - [ - $this->_em->getClassMetadata(DDC729A::class), - $this->_em->getClassMetadata(DDC729B::class), - ] - ); - } catch(\Exception $e) { - - } - } - - public function testMergeManyToMany() - { - $a = new DDC729A(); - $b = new DDC729B(); - $a->related[] = $b; - - $this->_em->persist($a); - $this->_em->persist($b); - $this->_em->flush(); - $this->_em->clear(); - $aId = $a->id; - - $a = new DDC729A(); - $a->id = $aId; - - $this->assertInstanceOf(ArrayCollection::class, $a->related); - - $a = $this->_em->merge($a); - - $this->assertInstanceOf(PersistentCollection::class, $a->related); - - $this->assertFalse($a->related->isInitialized(), "Collection should not be marked initialized."); - $this->assertFalse($a->related->isDirty(), "Collection should not be marked as dirty."); - - $this->_em->flush(); - $this->_em->clear(); - - $a = $this->_em->find(DDC729A::class, $aId); - $this->assertEquals(1, count($a->related)); - } - - public function testUnidirectionalMergeManyToMany() - { - $a = new DDC729A(); - $b1 = new DDC729B(); - $b2 = new DDC729B(); - $a->related[] = $b1; - - $this->_em->persist($a); - $this->_em->persist($b1); - $this->_em->persist($b2); - $this->_em->flush(); - $this->_em->clear(); - $aId = $a->id; - - $a = new DDC729A(); - $a->id = $aId; - - $a = $this->_em->merge($a); - - $a->related->set(0, $this->_em->merge($b1)); - - $a->related->set(1, $this->_em->merge($b2)); - - $this->_em->flush(); - $this->_em->clear(); - - $a = $this->_em->find(DDC729A::class, $aId); - $this->assertEquals(2, count($a->related)); - } - - public function testBidirectionalMergeManyToMany() - { - $a = new DDC729A(); - $b1 = new DDC729B(); - $b2 = new DDC729B(); - $a->related[] = $b1; - - $this->_em->persist($a); - $this->_em->persist($b1); - $this->_em->persist($b2); - $this->_em->flush(); - $this->_em->clear(); - $aId = $a->id; - - $a = new DDC729A(); - $a->id = $aId; - - $a = $this->_em->merge($a); - - $a->related->set(0, $this->_em->merge($b1)); - $b1->related->set(0, $a); - - $a->related->set(1, $this->_em->merge($b2)); - $b2->related->set(0, $a); - - $this->_em->flush(); - $this->_em->clear(); - - $a = $this->_em->find(DDC729A::class, $aId); - $this->assertEquals(2, count($a->related)); - } - - public function testBidirectionalMultiMergeManyToMany() - { - $a = new DDC729A(); - $b1 = new DDC729B(); - $b2 = new DDC729B(); - $a->related[] = $b1; - - $this->_em->persist($a); - $this->_em->persist($b1); - $this->_em->persist($b2); - $this->_em->flush(); - $this->_em->clear(); - $aId = $a->id; - - $a = new DDC729A(); - $a->id = $aId; - - $a = $this->_em->merge($a); - - $a->related->set(0, $this->_em->merge($b1)); - $b1->related->set(0, $this->_em->merge($a)); - - $a->related->set(1, $this->_em->merge($b2)); - $b2->related->set(0, $this->_em->merge($a)); - - $this->_em->flush(); - $this->_em->clear(); - - $a = $this->_em->find(DDC729A::class, $aId); - $this->assertEquals(2, count($a->related)); - } -} - -/** - * @Entity - */ -class DDC729A -{ - /** @Id @GeneratedValue @Column(type="integer") */ - public $id; - - /** @ManyToMany(targetEntity="DDC729B", inversedBy="related") */ - public $related; - - public function __construct() - { - $this->related = new \Doctrine\Common\Collections\ArrayCollection(); - } -} - -/** - * @Entity - */ -class DDC729B -{ - /** @Id @GeneratedValue @Column(type="integer") */ - public $id; - - /** @ManyToMany(targetEntity="DDC729B", mappedBy="related") */ - public $related; - - public function __construct() - { - $this->related = new \Doctrine\Common\Collections\ArrayCollection(); - } -} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC735Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC735Test.php index afae6973bf7..34827e2737d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC735Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC735Test.php @@ -1,8 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC735Product::class), - $this->_em->getClassMetadata(DDC735Review::class) + $this->em->getClassMetadata(DDC735Product::class), + $this->em->getClassMetadata(DDC735Review::class) ] ); } catch(\Exception $e) { @@ -28,43 +31,43 @@ public function testRemoveElement_AppliesOrphanRemoval() $review = new DDC735Review($product); // Persist and flush - $this->_em->persist($product); - $this->_em->flush(); + $this->em->persist($product); + $this->em->flush(); // Now you see it - $this->assertEquals(1, count($product->getReviews())); + self::assertEquals(1, count($product->getReviews())); // Remove the review $reviewId = $review->getId(); $product->removeReview($review); - $this->_em->flush(); + $this->em->flush(); // Now you don't - $this->assertEquals(0, count($product->getReviews()), 'count($reviews) should be 0 after removing its only Review'); + self::assertEquals(0, count($product->getReviews()), 'count($reviews) should be 0 after removing its only Review'); // Refresh - $this->_em->refresh($product); + $this->em->refresh($product); // It should still be 0 - $this->assertEquals(0, count($product->getReviews()), 'count($reviews) should still be 0 after the refresh'); + self::assertEquals(0, count($product->getReviews()), 'count($reviews) should still be 0 after the refresh'); // Review should also not be available anymore - $this->assertNull($this->_em->find(DDC735Review::class, $reviewId)); + self::assertNull($this->em->find(DDC735Review::class, $reviewId)); } } /** - * @Entity + * @ORM\Entity */ class DDC735Product { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ protected $id; /** - * @OneToMany( + * @ORM\OneToMany( * targetEntity="DDC735Review", * mappedBy="product", * cascade={"persist"}, @@ -95,17 +98,17 @@ public function removeReview(DDC735Review $review) } /** - * @Entity + * @ORM\Entity */ class DDC735Review { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ protected $id; /** - * @ManyToOne(targetEntity="DDC735Product", inversedBy="reviews") + * @ORM\ManyToOne(targetEntity="DDC735Product", inversedBy="reviews") */ protected $product; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php index 932731bf6f5..f6c03cb86fa 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php @@ -1,5 +1,7 @@ setPayment('cash'); $cart->setCustomer($cust); - $this->_em->persist($cust); - $this->_em->persist($cart); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($cust); + $this->em->persist($cart); + $this->em->flush(); + $this->em->clear(); - $result = $this->_em->createQuery("select c, c.name, ca, ca.payment from Doctrine\Tests\Models\ECommerce\ECommerceCart ca join ca.customer c") + $result = $this->em->createQuery("select c, c.name, ca, ca.payment from Doctrine\Tests\Models\ECommerce\ECommerceCart ca join ca.customer c") ->getSingleResult(/*\Doctrine\ORM\Query::HYDRATE_ARRAY*/); $cart2 = $result[0]; unset($result[0]); - $this->assertInstanceOf(ECommerceCart::class, $cart2); - $this->assertNotInstanceOf(Proxy::class, $cart2->getCustomer()); - $this->assertInstanceOf(ECommerceCustomer::class, $cart2->getCustomer()); - $this->assertEquals(['name' => 'roman', 'payment' => 'cash'], $result); + self::assertInstanceOf(ECommerceCart::class, $cart2); + self::assertNotInstanceOf(Proxy::class, $cart2->getCustomer()); + self::assertInstanceOf(ECommerceCustomer::class, $cart2->getCustomer()); + self::assertEquals(['name' => 'roman', 'payment' => 'cash'], $result); } /** @@ -59,19 +61,19 @@ public function testDqlTreeWalkerReordering() $cart->setPayment('cash'); $cart->setCustomer($cust); - $this->_em->persist($cust); - $this->_em->persist($cart); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($cust); + $this->em->persist($cart); + $this->em->flush(); + $this->em->clear(); $dql = "select c, c.name, ca, ca.payment from Doctrine\Tests\Models\ECommerce\ECommerceCart ca join ca.customer c"; - $result = $this->_em->createQuery($dql) + $result = $this->em->createQuery($dql) ->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [DisableFetchJoinTreeWalker::class]) ->getResult(); /* @var $cart2 ECommerceCart */ $cart2 = $result[0][0]; - $this->assertInstanceOf(Proxy::class, $cart2->getCustomer()); + self::assertInstanceOf(Proxy::class, $cart2->getCustomer()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC742Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC742Test.php index 8adcb08795e..c33aca6ced2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC742Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC742Test.php @@ -1,9 +1,12 @@ _em->getMetadataFactory()->setCacheDriver(new FilesystemCache($testDir)); + $this->em->getMetadataFactory()->setCacheDriver(new FilesystemCache($testDir)); try { - $this->_schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC742User::class), - $this->_em->getClassMetadata(DDC742Comment::class) + $this->em->getClassMetadata(DDC742User::class), + $this->em->getClassMetadata(DDC742Comment::class) ] ); } catch(\Exception $e) { } // make sure classes will be deserialized from caches - $this->_em->getMetadataFactory()->setMetadataFor(DDC742User::class, null); - $this->_em->getMetadataFactory()->setMetadataFor(DDC742Comment::class, null); + $this->em->getMetadataFactory()->setMetadataFor(DDC742User::class, null); + $this->em->getMetadataFactory()->setMetadataFor(DDC742Comment::class, null); } public function testIssue() @@ -57,49 +60,50 @@ public function testIssue() $user->favoriteComments->add($comment1); $user->favoriteComments->add($comment2); - $this->_em->persist($user); - $this->_em->persist($comment1); - $this->_em->persist($comment2); - $this->_em->persist($comment3); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->persist($comment1); + $this->em->persist($comment2); + $this->em->persist($comment3); + $this->em->flush(); + $this->em->clear(); + + $user = $this->em->find(DDC742User::class, $user->id); + $user->favoriteComments->add($this->em->find(DDC742Comment::class, $comment3->id)); - $user = $this->_em->find(DDC742User::class, $user->id); - $user->favoriteComments->add($this->_em->find(DDC742Comment::class, $comment3->id)); + $this->em->flush(); - $this->_em->flush(); $this->addToAssertionCount(1); } } /** - * @Entity - * @Table(name="ddc742_users") + * @ORM\Entity + * @ORM\Table(name="ddc742_users") */ class DDC742User { /** * User Id * - * @Id - * @GeneratedValue(strategy="AUTO") - * @Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") + * @ORM\Column(type="integer") * @var int */ public $id; /** - * @Column(length=100, type="string") + * @ORM\Column(length=100, type="string") * @var string */ public $title; /** - * @ManyToMany(targetEntity="DDC742Comment", cascade={"persist"}, fetch="EAGER") - * @JoinTable( + * @ORM\ManyToMany(targetEntity="DDC742Comment", cascade={"persist"}, fetch="EAGER") + * @ORM\JoinTable( * name="user_comments", - * joinColumns={@JoinColumn(name="user_id",referencedColumnName="id")}, - * inverseJoinColumns={@JoinColumn(name="comment_id", referencedColumnName="id")} + * joinColumns={@ORM\JoinColumn(name="user_id",referencedColumnName="id")}, + * inverseJoinColumns={@ORM\JoinColumn(name="comment_id", referencedColumnName="id")} * ) * * @var \Doctrine\ORM\PersistentCollection @@ -108,23 +112,23 @@ class DDC742User } /** - * @Entity - * @Table(name="ddc742_comments") + * @ORM\Entity + * @ORM\Table(name="ddc742_comments") */ class DDC742Comment { /** * User Id * - * @Id - * @GeneratedValue(strategy="AUTO") - * @Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue(strategy="AUTO") + * @ORM\Column(type="integer") * @var int */ public $id; /** - * @Column(length=100, type="string") + * @ORM\Column(length=100, type="string") * @var string */ public $content; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC748Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC748Test.php index cfafc66dd64..ebb0ff3ed79 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC748Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC748Test.php @@ -1,5 +1,7 @@ text = "foo"; $article->topic = "bar"; - $this->_em->persist($user); - $this->_em->persist($article); - $this->_em->flush(); + $this->em->persist($user); + $this->em->persist($article); + $this->em->flush(); - $this->assertInstanceOf(Collection::class, $user->articles); - $this->_em->refresh($article); - $this->assertTrue($article !== $user->articles, "The article should not be replaced on the inverse side of the relation."); - $this->assertInstanceOf(Collection::class, $user->articles); + self::assertInstanceOf(Collection::class, $user->articles); + $this->em->refresh($article); + self::assertTrue($article !== $user->articles, "The article should not be replaced on the inverse side of the relation."); + self::assertInstanceOf(Collection::class, $user->articles); } public function testRefreshOneToOne() @@ -51,12 +53,12 @@ public function testRefreshOneToOne() $address->zip = 12345; $address->setUser($user); - $this->_em->persist($user); - $this->_em->persist($address); - $this->_em->flush(); + $this->em->persist($user); + $this->em->persist($address); + $this->em->flush(); - $this->_em->refresh($address); - $this->assertSame($user, $address->user); - $this->assertSame($user->address, $address); + $this->em->refresh($address); + self::assertSame($user, $address->user); + self::assertSame($user->address, $address); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC758Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC758Test.php deleted file mode 100644 index a5707f233e3..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC758Test.php +++ /dev/null @@ -1,182 +0,0 @@ -markTestSkipped('Destroys testsuite'); - $this->useModelSet("cms"); - - parent::setUp(); - } - - /** - * Helper method to set cascade to merge only - */ - private function setCascadeMergeFor($class) - { - $metadata = $this->_em->getMetadataFactory()->getMetadataFor($class); - foreach ($metadata->associationMappings as $key => $associationMapping) { - $metadata->associationMappings[$key]["isCascadePersist"] = false; - $metadata->associationMappings[$key]["isCascadeMerge"] = true; - $metadata->associationMappings[$key]["isCascadeRemove"] = false; - $metadata->associationMappings[$key]["isCascadeDetach"] = false; - } - } - - /** - * Test that changing associations on detached entities and then cascade merging them - * causes the database to be updated with the new associations. - * This specifically tests adding new associations. - */ - public function testManyToManyMergeAssociationAdds() - { - $this->setCascadeMergeFor(CmsUser::class); - $this->setCascadeMergeFor(CmsGroup::class); - - // Put entities in the database - $cmsUser = new CmsUser(); - $cmsUser->username = "dave"; - $cmsUser->name = "Dave Keen"; - $cmsUser->status = "testing"; - - $group1 = new CmsGroup(); - $group1->name = "Group 1"; - - $group2 = new CmsGroup(); - $group2->name = "Group 2"; - - $this->_em->persist($cmsUser); - $this->_em->persist($group1); - $this->_em->persist($group2); - $this->_em->flush(); - - $cmsUserId = $cmsUser->id; - $group1Id = $group1->id; - $group2Id = $group2->id; - - $this->_em->clear(); - - // Now create detached versions of the entities with some new associations. - $cmsUser = new CmsUser(); - $cmsUser->id = $cmsUserId; - $cmsUser->username = "dave"; - $cmsUser->name = "Dave Keen"; - $cmsUser->status = "testing"; - $cmsUser->groups = new ArrayCollection(); - - $group1 = new CmsGroup(); - $group1->id = $group1Id; - $group1->name = "Group 1"; - $group1->users = new ArrayCollection(); - - $group2 = new CmsGroup(); - $group2->id = $group2Id; - $group2->name = "Group 2"; - $group2->users = new ArrayCollection(); - - $cmsUser->addGroup($group1); - $cmsUser->addGroup($group2); - - // Cascade merge of cmsUser followed by a flush should add in the bidirectional new many-to-many associations between the user and the groups - $this->_em->merge($cmsUser); - $this->_em->flush(); - - $this->_em->clear(); - - $cmsUsers = $this->_em->getRepository(CmsUser::class)->findAll(); - $cmsGroups = $this->_em->getRepository(CmsGroup::class)->findAll(); - - // Check the entities are in the database - $this->assertEquals(1, sizeof($cmsUsers)); - $this->assertEquals(2, sizeof($cmsGroups)); - - // Check the associations between the entities are now in the database - $this->assertEquals(2, sizeof($cmsUsers[0]->groups)); - $this->assertEquals(1, sizeof($cmsGroups[0]->users)); - $this->assertEquals(1, sizeof($cmsGroups[1]->users)); - - $this->assertSame($cmsUsers[0]->groups[0], $cmsGroups[0]); - $this->assertSame($cmsUsers[0]->groups[1], $cmsGroups[1]); - $this->assertSame($cmsGroups[0]->users[0], $cmsUsers[0]); - $this->assertSame($cmsGroups[1]->users[0], $cmsUsers[0]); - } - - /** - * Test that changing associations on detached entities and then cascade merging them causes the - * database to be updated with the new associations. - */ - public function testManyToManyMergeAssociationRemoves() - { - $this->setCascadeMergeFor(CmsUser::class); - $this->setCascadeMergeFor(CmsGroup::class); - - $cmsUser = new CmsUser(); - $cmsUser->username = "dave"; - $cmsUser->name = "Dave Keen"; - $cmsUser->status = "testing"; - - $group1 = new CmsGroup(); - $group1->name = "Group 1"; - - $group2 = new CmsGroup(); - $group2->name = "Group 2"; - - $cmsUser->addGroup($group1); - $cmsUser->addGroup($group2); - - $this->_em->persist($cmsUser); - $this->_em->persist($group1); - $this->_em->persist($group2); - $this->_em->flush(); - - $cmsUserId = $cmsUser->id; - $group1Id = $group1->id; - $group2Id = $group2->id; - - $this->_em->clear(); - - // Now create detached versions of the entities with NO associations. - $cmsUser = new CmsUser(); - $cmsUser->id = $cmsUserId; - $cmsUser->username = "dave"; - $cmsUser->name = "Dave Keen"; - $cmsUser->status = "testing"; - $cmsUser->groups = new ArrayCollection(); - - $group1 = new CmsGroup(); - $group1->id = $group1Id; - $group1->name = "Group 1"; - $group1->users = new ArrayCollection(); - - $group2 = new CmsGroup(); - $group2->id = $group2Id; - $group2->name = "Group 2"; - $group2->users = new ArrayCollection(); - - // Cascade merge of cmsUser followed by a flush should result in the association array collection being empty - $this->_em->merge($cmsUser); - $this->_em->flush(); - - $this->_em->clear(); - - $cmsUsers = $this->_em->getRepository(CmsUser::class)->findAll(); - $cmsGroups = $this->_em->getRepository(CmsGroup::class)->findAll(); - - // Check the entities are in the database - $this->assertEquals(1, sizeof($cmsUsers)); - $this->assertEquals(2, sizeof($cmsGroups)); - - // Check the associations between the entities are now in the database - $this->assertEquals(0, sizeof($cmsUsers[0]->groups)); - $this->assertEquals(0, sizeof($cmsGroups[0]->users)); - $this->assertEquals(0, sizeof($cmsGroups[1]->users)); - } -} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC767Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC767Test.php index 8420db13275..12b1b721bc6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC767Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC767Test.php @@ -1,5 +1,7 @@ addGroup($group1); $user->addGroup($group2); - $this->_em->persist($user); - $this->_em->persist($group1); - $this->_em->persist($group2); - $this->_em->persist($group3); + $this->em->persist($user); + $this->em->persist($group1); + $this->em->persist($group2); + $this->em->persist($group3); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); /* @var $pUser CmsUser */ - $pUser = $this->_em->find(get_class($user), $user->id); + $pUser = $this->em->find(get_class($user), $user->id); - $this->assertNotNull($pUser, "User not retrieved from database."); + self::assertNotNull($pUser, "User not retrieved from database."); $groups = [$group2->id, $group3->id]; try { - $this->_em->beginTransaction(); + $this->em->beginTransaction(); $pUser->groups->clear(); - $this->_em->flush(); + $this->em->flush(); // Add new foreach ($groups as $groupId) { - $pUser->addGroup($this->_em->find(get_class($group1), $groupId)); + $pUser->addGroup($this->em->find(get_class($group1), $groupId)); } - $this->_em->flush(); - $this->_em->commit(); + $this->em->flush(); + $this->em->commit(); } catch(\Exception $e) { - $this->_em->rollback(); + $this->em->rollback(); } } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC809Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC809Test.php index 4c6464a188b..087a240535a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC809Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC809Test.php @@ -1,20 +1,24 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC809Variant::class), - $this->_em->getClassMetadata(DDC809SpecificationValue::class) + $this->em->getClassMetadata(DDC809Variant::class), + $this->em->getClassMetadata(DDC809SpecificationValue::class) ] ); - $conn = $this->_em->getConnection(); + $conn = $this->em->getConnection(); $conn->insert('specification_value_test', ['specification_value_id' => 94589]); $conn->insert('specification_value_test', ['specification_value_id' => 94593]); $conn->insert('specification_value_test', ['specification_value_id' => 94606]); @@ -41,38 +45,38 @@ public function setUp() */ public function testIssue() { - $result = $this->_em->createQueryBuilder() + $result = $this->em->createQueryBuilder() ->select('Variant, SpecificationValue') ->from(DDC809Variant::class, 'Variant') ->leftJoin('Variant.SpecificationValues', 'SpecificationValue') ->getQuery() ->getResult(); - $this->assertEquals(4, count($result[0]->getSpecificationValues()), "Works in test-setup."); - $this->assertEquals(4, count($result[1]->getSpecificationValues()), "Only returns 2 in the case of the hydration bug."); + self::assertEquals(4, count($result[0]->getSpecificationValues()), "Works in test-setup."); + self::assertEquals(4, count($result[1]->getSpecificationValues()), "Only returns 2 in the case of the hydration bug."); } } /** - * @Table(name="variant_test") - * @Entity + * @ORM\Table(name="variant_test") + * @ORM\Entity */ class DDC809Variant { /** - * @Column(name="variant_id", type="integer") - * @Id + * @ORM\Column(name="variant_id", type="integer") + * @ORM\Id */ protected $variantId; /** - * @ManyToMany(targetEntity="DDC809SpecificationValue", inversedBy="Variants") - * @JoinTable(name="var_spec_value_test", + * @ORM\ManyToMany(targetEntity="DDC809SpecificationValue", inversedBy="Variants") + * @ORM\JoinTable(name="var_spec_value_test", * joinColumns={ - * @JoinColumn(name="variant_id", referencedColumnName="variant_id") + * @ORM\JoinColumn(name="variant_id", referencedColumnName="variant_id") * }, * inverseJoinColumns={ - * @JoinColumn(name="specification_value_id", referencedColumnName="specification_value_id") + * @ORM\JoinColumn(name="specification_value_id", referencedColumnName="specification_value_id") * } * ) */ @@ -85,21 +89,21 @@ public function getSpecificationValues() } /** - * @Table(name="specification_value_test") - * @Entity + * @ORM\Table(name="specification_value_test") + * @ORM\Entity */ class DDC809SpecificationValue { /** - * @Column(name="specification_value_id", type="integer") - * @Id + * @ORM\Column(name="specification_value_id", type="integer") + * @ORM\Id */ protected $specificationValueId; /** - * @var Variant + * @var DDC809Variant * - * @ManyToMany(targetEntity="DDC809Variant", mappedBy="SpecificationValues") + * @ORM\ManyToMany(targetEntity="DDC809Variant", mappedBy="SpecificationValues") */ protected $Variants; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC812Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC812Test.php index 5b37a47923c..59a4ee9aeaa 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC812Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC812Test.php @@ -1,5 +1,7 @@ _em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $article = new CmsArticle; $article->topic = "hello"; $article->text = "talk talk talk"; @@ -28,19 +30,19 @@ public function testFetchJoinInitializesPreviouslyUninitializedCollectionOfManag $comment->text = "stuff!"; $comment->article = $article; - $this->_em->persist($article); - $this->_em->persist($comment); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($article); + $this->em->persist($comment); + $this->em->flush(); + $this->em->clear(); - $article2 = $this->_em->find(get_class($article), $article->id); + $article2 = $this->em->find(get_class($article), $article->id); - $article2Again = $this->_em->createQuery( + $article2Again = $this->em->createQuery( "select a, c from Doctrine\Tests\Models\CMS\CmsArticle a join a.comments c where a.id = ?1") ->setParameter(1, $article->id) ->getSingleResult(); - $this->assertTrue($article2Again === $article2); - $this->assertTrue($article2Again->comments->isInitialized()); + self::assertTrue($article2Again === $article2); + self::assertTrue($article2Again->comments->isInitialized()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC832Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC832Test.php index fdae13585fc..36eda3fe963 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC832Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC832Test.php @@ -1,27 +1,31 @@ _em->getConnection()->getDatabasePlatform(); + $platform = $this->em->getConnection()->getDatabasePlatform(); if ($platform->getName() === 'oracle') { $this->markTestSkipped('Doesnt run on Oracle.'); } - $this->_em->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger()); + $this->em->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger()); try { - $this->_schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC832JoinedIndex::class), - $this->_em->getClassMetadata(DDC832JoinedTreeIndex::class), - $this->_em->getClassMetadata(DDC832Like::class), + $this->em->getClassMetadata(DDC832JoinedIndex::class), + $this->em->getClassMetadata(DDC832JoinedTreeIndex::class), + $this->em->getClassMetadata(DDC832Like::class), ] ); } catch(\Exception $e) { @@ -31,9 +35,10 @@ public function setUp() public function tearDown() { /* @var $sm \Doctrine\DBAL\Schema\AbstractSchemaManager */ - $platform = $this->_em->getConnection()->getDatabasePlatform(); + $platform = $this->em->getConnection()->getDatabasePlatform(); + + $sm = $this->em->getConnection()->getSchemaManager(); - $sm = $this->_em->getConnection()->getSchemaManager(); $sm->dropTable($platform->quoteIdentifier('TREE_INDEX')); $sm->dropTable($platform->quoteIdentifier('INDEX')); $sm->dropTable($platform->quoteIdentifier('LIKE')); @@ -44,15 +49,15 @@ public function tearDown() */ public function testQuotedTableBasicUpdate() { - $like = new DDC832Like('test'); - $this->_em->persist($like); - $this->_em->flush(); + $like = new DDC832Like("test"); + $this->em->persist($like); + $this->em->flush(); - $like->word = 'test2'; - $this->_em->flush(); - $this->_em->clear(); + $like->word = "test2"; + $this->em->flush(); + $this->em->clear(); - self::assertEquals($like, $this->_em->find(DDC832Like::class, $like->id)); + self::assertEquals($like, $this->em->find(DDC832Like::class, $like->id)); } /** @@ -60,17 +65,17 @@ public function testQuotedTableBasicUpdate() */ public function testQuotedTableBasicRemove() { - $like = new DDC832Like('test'); - $this->_em->persist($like); - $this->_em->flush(); + $like = new DDC832Like("test"); + $this->em->persist($like); + $this->em->flush(); $idToBeRemoved = $like->id; - $this->_em->remove($like); - $this->_em->flush(); - $this->_em->clear(); + $this->em->remove($like); + $this->em->flush(); + $this->em->clear(); - self::assertNull($this->_em->find(DDC832Like::class, $idToBeRemoved)); + self::assertNull($this->em->find(DDC832Like::class, $idToBeRemoved)); } /** @@ -78,15 +83,15 @@ public function testQuotedTableBasicRemove() */ public function testQuotedTableJoinedUpdate() { - $index = new DDC832JoinedIndex('test'); - $this->_em->persist($index); - $this->_em->flush(); + $index = new DDC832JoinedIndex("test"); + $this->em->persist($index); + $this->em->flush(); - $index->name = 'asdf'; - $this->_em->flush(); - $this->_em->clear(); + $index->name = "asdf"; + $this->em->flush(); + $this->em->clear(); - self::assertEquals($index, $this->_em->find(DDC832JoinedIndex::class, $index->id)); + self::assertEquals($index, $this->em->find(DDC832JoinedIndex::class, $index->id)); } /** @@ -94,17 +99,17 @@ public function testQuotedTableJoinedUpdate() */ public function testQuotedTableJoinedRemove() { - $index = new DDC832JoinedIndex('test'); - $this->_em->persist($index); - $this->_em->flush(); + $index = new DDC832JoinedIndex("test"); + $this->em->persist($index); + $this->em->flush(); $idToBeRemoved = $index->id; - $this->_em->remove($index); - $this->_em->flush(); - $this->_em->clear(); + $this->em->remove($index); + $this->em->flush(); + $this->em->clear(); - self::assertNull($this->_em->find(DDC832JoinedIndex::class, $idToBeRemoved)); + self::assertNull($this->em->find(DDC832JoinedIndex::class, $idToBeRemoved)); } /** @@ -112,15 +117,15 @@ public function testQuotedTableJoinedRemove() */ public function testQuotedTableJoinedChildUpdate() { - $index = new DDC832JoinedTreeIndex('test', 1, 2); - $this->_em->persist($index); - $this->_em->flush(); + $index = new DDC832JoinedTreeIndex("test", 1, 2); + $this->em->persist($index); + $this->em->flush(); - $index->name = 'asdf'; - $this->_em->flush(); - $this->_em->clear(); + $index->name = "asdf"; + $this->em->flush(); + $this->em->clear(); - self::assertEquals($index, $this->_em->find(DDC832JoinedTreeIndex::class, $index->id)); + self::assertEquals($index, $this->em->find(DDC832JoinedTreeIndex::class, $index->id)); } /** @@ -128,37 +133,37 @@ public function testQuotedTableJoinedChildUpdate() */ public function testQuotedTableJoinedChildRemove() { - $index = new DDC832JoinedTreeIndex('test', 1, 2); - $this->_em->persist($index); - $this->_em->flush(); + $index = new DDC832JoinedTreeIndex("test", 1, 2); + $this->em->persist($index); + $this->em->flush(); $idToBeRemoved = $index->id; - $this->_em->remove($index); - $this->_em->flush(); - $this->_em->clear(); + $this->em->remove($index); + $this->em->flush(); + $this->em->clear(); - self::assertNull($this->_em->find(DDC832JoinedTreeIndex::class, $idToBeRemoved)); + self::assertNull($this->em->find(DDC832JoinedTreeIndex::class, $idToBeRemoved)); } } /** - * @Entity - * @Table(name="`LIKE`") + * @ORM\Entity + * @ORM\Table(name="LIKE") */ class DDC832Like { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $word; /** - * @version - * @Column(type="integer") + * @ORM\Version + * @ORM\Column(type="integer") */ public $version; @@ -169,25 +174,25 @@ public function __construct($word) } /** - * @Entity - * @Table(name="`INDEX`") - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="discr", type="string") - * @DiscriminatorMap({"like" = "DDC832JoinedIndex", "fuzzy" = "DDC832JoinedTreeIndex"}) + * @ORM\Entity + * @ORM\Table(name="INDEX") + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="discr", type="string") + * @ORM\DiscriminatorMap({"like" = "DDC832JoinedIndex", "fuzzy" = "DDC832JoinedTreeIndex"}) */ class DDC832JoinedIndex { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $name; /** - * @version - * @Column(type="integer") + * @ORM\Version + * @ORM\Column(type="integer") */ public $version; @@ -198,15 +203,15 @@ public function __construct($name) } /** - * @Entity - * @Table(name="`TREE_INDEX`") + * @ORM\Entity + * @ORM\Table(name="TREE_INDEX") */ class DDC832JoinedTreeIndex extends DDC832JoinedIndex { - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ public $lft; - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ public $rgt; public function __construct($name, $lft, $rgt) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC837Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC837Test.php index 4721a6b18be..ce4b0898465 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC837Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC837Test.php @@ -1,19 +1,23 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC837Super::class), - $this->_em->getClassMetadata(DDC837Class1::class), - $this->_em->getClassMetadata(DDC837Class2::class), - $this->_em->getClassMetadata(DDC837Class3::class), - $this->_em->getClassMetadata(DDC837Aggregate::class), + $this->em->getClassMetadata(DDC837Super::class), + $this->em->getClassMetadata(DDC837Class1::class), + $this->em->getClassMetadata(DDC837Class2::class), + $this->em->getClassMetadata(DDC837Class3::class), + $this->em->getClassMetadata(DDC837Aggregate::class), ] ); } @@ -23,7 +27,7 @@ protected function setUp() */ public function testIssue() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); + //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $c1 = new DDC837Class1(); $c1->title = "Foo"; @@ -42,47 +46,47 @@ public function testIssue() $c3->apples = "Baz"; $c3->bananas = "Baz"; - $this->_em->persist($c1); - $this->_em->persist($aggregate1); - $this->_em->persist($c2); - $this->_em->persist($aggregate2); - $this->_em->persist($c3); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($c1); + $this->em->persist($aggregate1); + $this->em->persist($c2); + $this->em->persist($aggregate2); + $this->em->persist($c3); + $this->em->flush(); + $this->em->clear(); // Test Class1 - $e1 = $this->_em->find(DDC837Super::class, $c1->id); + $e1 = $this->em->find(DDC837Super::class, $c1->id); - $this->assertInstanceOf(DDC837Class1::class, $e1); - $this->assertEquals('Foo', $e1->title); - $this->assertEquals('Foo', $e1->description); - $this->assertInstanceOf(DDC837Aggregate::class, $e1->aggregate); - $this->assertEquals('test1', $e1->aggregate->getSysname()); + self::assertInstanceOf(DDC837Class1::class, $e1); + self::assertEquals('Foo', $e1->title); + self::assertEquals('Foo', $e1->description); + self::assertInstanceOf(DDC837Aggregate::class, $e1->aggregate); + self::assertEquals('test1', $e1->aggregate->getSysname()); // Test Class 2 - $e2 = $this->_em->find(DDC837Super::class, $c2->id); + $e2 = $this->em->find(DDC837Super::class, $c2->id); - $this->assertInstanceOf(DDC837Class2::class, $e2); - $this->assertEquals('Bar', $e2->title); - $this->assertEquals('Bar', $e2->description); - $this->assertEquals('Bar', $e2->text); - $this->assertInstanceOf(DDC837Aggregate::class, $e2->aggregate); - $this->assertEquals('test2', $e2->aggregate->getSysname()); + self::assertInstanceOf(DDC837Class2::class, $e2); + self::assertEquals('Bar', $e2->title); + self::assertEquals('Bar', $e2->description); + self::assertEquals('Bar', $e2->text); + self::assertInstanceOf(DDC837Aggregate::class, $e2->aggregate); + self::assertEquals('test2', $e2->aggregate->getSysname()); - $all = $this->_em->getRepository(DDC837Super::class)->findAll(); + $all = $this->em->getRepository(DDC837Super::class)->findAll(); foreach ($all as $obj) { if ($obj instanceof DDC837Class1) { - $this->assertEquals('Foo', $obj->title); - $this->assertEquals('Foo', $obj->description); + self::assertEquals('Foo', $obj->title); + self::assertEquals('Foo', $obj->description); } else if ($obj instanceof DDC837Class2) { - $this->assertTrue($e2 === $obj); - $this->assertEquals('Bar', $obj->title); - $this->assertEquals('Bar', $obj->description); - $this->assertEquals('Bar', $obj->text); + self::assertTrue($e2 === $obj); + self::assertEquals('Bar', $obj->title); + self::assertEquals('Bar', $obj->description); + self::assertEquals('Bar', $obj->text); } else if ($obj instanceof DDC837Class3) { - $this->assertEquals('Baz', $obj->apples); - $this->assertEquals('Baz', $obj->bananas); + self::assertEquals('Baz', $obj->apples); + self::assertEquals('Baz', $obj->bananas); } else { $this->fail('Instance of DDC837Class1, DDC837Class2 or DDC837Class3 expected.'); } @@ -91,64 +95,64 @@ public function testIssue() } /** - * @Entity - * @Table(name="DDC837Super") - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="type", type="string") - * @DiscriminatorMap({"class1" = "DDC837Class1", "class2" = "DDC837Class2", "class3"="DDC837Class3"}) + * @ORM\Entity + * @ORM\Table(name="DDC837Super") + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="type", type="string") + * @ORM\DiscriminatorMap({"class1" = "DDC837Class1", "class2" = "DDC837Class2", "class3"="DDC837Class3"}) */ abstract class DDC837Super { /** - * @Id @Column(name="id", type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; } /** - * @Entity + * @ORM\Entity */ class DDC837Class1 extends DDC837Super { /** - * @Column(name="title", type="string", length=150) + * @ORM\Column(name="title", type="string", length=150) */ public $title; /** - * @Column(name="content", type="string", length=500) + * @ORM\Column(name="content", type="string", length=500) */ public $description; /** - * @OneToOne(targetEntity="DDC837Aggregate") + * @ORM\OneToOne(targetEntity="DDC837Aggregate") */ public $aggregate; } /** - * @Entity + * @ORM\Entity */ class DDC837Class2 extends DDC837Super { /** - * @Column(name="title", type="string", length=150) + * @ORM\Column(name="title", type="string", length=150) */ public $title; /** - * @Column(name="content", type="string", length=500) + * @ORM\Column(name="content", type="string", length=500) */ public $description; /** - * @Column(name="text", type="text") + * @ORM\Column(name="text", type="text") */ public $text; /** - * @OneToOne(targetEntity="DDC837Aggregate") + * @ORM\OneToOne(targetEntity="DDC837Aggregate") */ public $aggregate; } @@ -156,34 +160,34 @@ class DDC837Class2 extends DDC837Super /** * An extra class to demonstrate why title and description aren't in Super * - * @Entity + * @ORM\Entity */ class DDC837Class3 extends DDC837Super { /** - * @Column(name="title", type="string", length=150) + * @ORM\Column(name="title", type="string", length=150) */ public $apples; /** - * @Column(name="content", type="string", length=500) + * @ORM\Column(name="content", type="string", length=500) */ public $bananas; } /** - * @Entity + * @ORM\Entity */ class DDC837Aggregate { /** - * @Id @Column(name="id", type="integer") - * @GeneratedValue + * @ORM\Id @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue */ public $id; /** - * @Column(name="sysname", type="string") + * @ORM\Column(name="sysname", type="string") */ protected $sysname; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC849Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC849Test.php index 1844b316f37..1e9ce9318f6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC849Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC849Test.php @@ -1,5 +1,7 @@ user->addGroup($this->group1); $this->user->addGroup($this->group2); - $this->_em->persist($this->user); - $this->_em->persist($this->group1); - $this->_em->persist($this->group2); + $this->em->persist($this->user); + $this->em->persist($this->group1); + $this->em->persist($this->group2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $this->user = $this->_em->find(CmsUser::class, $this->user->getId()); + $this->user = $this->em->find(CmsUser::class, $this->user->getId()); } public function testRemoveContains() @@ -44,25 +46,25 @@ public function testRemoveContains() $group1 = $this->user->groups[0]; $group2 = $this->user->groups[1]; - $this->assertTrue($this->user->groups->contains($group1)); - $this->assertTrue($this->user->groups->contains($group2)); + self::assertTrue($this->user->groups->contains($group1)); + self::assertTrue($this->user->groups->contains($group2)); $this->user->groups->removeElement($group1); $this->user->groups->remove(1); - $this->assertFalse($this->user->groups->contains($group1)); - $this->assertFalse($this->user->groups->contains($group2)); + self::assertFalse($this->user->groups->contains($group1)); + self::assertFalse($this->user->groups->contains($group2)); } public function testClearCount() { $this->user->addGroup(new CmsGroup); - $this->assertEquals(3, count($this->user->groups)); + self::assertEquals(3, count($this->user->groups)); $this->user->groups->clear(); - $this->assertEquals(0, $this->user->groups->count()); - $this->assertEquals(0, count($this->user->groups)); + self::assertEquals(0, $this->user->groups->count()); + self::assertEquals(0, count($this->user->groups)); } public function testClearContains() @@ -70,12 +72,12 @@ public function testClearContains() $group1 = $this->user->groups[0]; $group2 = $this->user->groups[1]; - $this->assertTrue($this->user->groups->contains($group1)); - $this->assertTrue($this->user->groups->contains($group2)); + self::assertTrue($this->user->groups->contains($group1)); + self::assertTrue($this->user->groups->contains($group2)); $this->user->groups->clear(); - $this->assertFalse($this->user->groups->contains($group1)); - $this->assertFalse($this->user->groups->contains($group2)); + self::assertFalse($this->user->groups->contains($group1)); + self::assertFalse($this->user->groups->contains($group2)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC881Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC881Test.php index 3df61f7165c..b1571ff2e4c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC881Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC881Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC881User::class), - $this->_em->getClassMetadata(DDC881Phonenumber::class), - $this->_em->getClassMetadata(DDC881Phonecall::class), + $this->em->getClassMetadata(DDC881User::class), + $this->em->getClassMetadata(DDC881Phonenumber::class), + $this->em->getClassMetadata(DDC881Phonecall::class), ] ); } catch (\Exception $e) { @@ -34,87 +37,88 @@ public function testIssue() /* Create two test users: albert and alfons */ $albert = new DDC881User; $albert->setName("albert"); - $this->_em->persist($albert); + $this->em->persist($albert); $alfons = new DDC881User; $alfons->setName("alfons"); - $this->_em->persist($alfons); + $this->em->persist($alfons); - $this->_em->flush(); + $this->em->flush(); /* Assign two phone numbers to each user */ $phoneAlbert1 = new DDC881PhoneNumber(); $phoneAlbert1->setUser($albert); $phoneAlbert1->setId(1); $phoneAlbert1->setPhoneNumber("albert home: 012345"); - $this->_em->persist($phoneAlbert1); + $this->em->persist($phoneAlbert1); $phoneAlbert2 = new DDC881PhoneNumber(); $phoneAlbert2->setUser($albert); $phoneAlbert2->setId(2); $phoneAlbert2->setPhoneNumber("albert mobile: 67890"); - $this->_em->persist($phoneAlbert2); + $this->em->persist($phoneAlbert2); $phoneAlfons1 = new DDC881PhoneNumber(); $phoneAlfons1->setId(1); $phoneAlfons1->setUser($alfons); $phoneAlfons1->setPhoneNumber("alfons home: 012345"); - $this->_em->persist($phoneAlfons1); + $this->em->persist($phoneAlfons1); $phoneAlfons2 = new DDC881PhoneNumber(); $phoneAlfons2->setId(2); $phoneAlfons2->setUser($alfons); $phoneAlfons2->setPhoneNumber("alfons mobile: 67890"); - $this->_em->persist($phoneAlfons2); + $this->em->persist($phoneAlfons2); /* We call alfons and albert once on their mobile numbers */ $call1 = new DDC881PhoneCall(); $call1->setPhoneNumber($phoneAlfons2); - $this->_em->persist($call1); + $this->em->persist($call1); $call2 = new DDC881PhoneCall(); $call2->setPhoneNumber($phoneAlbert2); - $this->_em->persist($call2); + $this->em->persist($call2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); // fetch-join that foreign-key/primary-key entity association $dql = "SELECT c, p FROM " . DDC881PhoneCall::class . " c JOIN c.phonenumber p"; - $calls = $this->_em->createQuery($dql)->getResult(); + $calls = $this->em->createQuery($dql)->getResult(); - $this->assertEquals(2, count($calls)); - $this->assertNotInstanceOf(Proxy::class, $calls[0]->getPhoneNumber()); - $this->assertNotInstanceOf(Proxy::class, $calls[1]->getPhoneNumber()); + self::assertEquals(2, count($calls)); + self::assertNotInstanceOf(Proxy::class, $calls[0]->getPhoneNumber()); + self::assertNotInstanceOf(Proxy::class, $calls[1]->getPhoneNumber()); $dql = "SELECT p, c FROM " . DDC881PhoneNumber::class . " p JOIN p.calls c"; - $numbers = $this->_em->createQuery($dql)->getResult(); + $numbers = $this->em->createQuery($dql)->getResult(); - $this->assertEquals(2, count($numbers)); - $this->assertInstanceOf(PersistentCollection::class, $numbers[0]->getCalls()); - $this->assertTrue($numbers[0]->getCalls()->isInitialized()); + self::assertEquals(2, count($numbers)); + self::assertInstanceOf(PersistentCollection::class, $numbers[0]->getCalls()); + self::assertTrue($numbers[0]->getCalls()->isInitialized()); } } /** - * @Entity + * @ORM\Entity */ class DDC881User { - /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; + /** - * @Column(type="string") + * @ORM\Column(type="string") */ private $name; + /** - * @OneToMany(targetEntity="DDC881PhoneNumber",mappedBy="id") + * @ORM\OneToMany(targetEntity="DDC881PhoneNumber",mappedBy="id") */ private $phoneNumbers; @@ -130,28 +134,27 @@ public function setName($name) } /** - * @Entity + * @ORM\Entity */ class DDC881PhoneNumber { - /** - * @Id - * @Column(type="integer") + * @ORM\Id + * @ORM\Column(type="integer") */ private $id; /** - * @Id - * @ManyToOne(targetEntity="DDC881User",cascade={"all"}) + * @ORM\Id + * @ORM\ManyToOne(targetEntity="DDC881User",cascade={"all"}) */ private $user; /** - * @Column(type="string") + * @ORM\Column(type="string") */ private $phonenumber; /** - * @OneToMany(targetEntity="DDC881PhoneCall", mappedBy="phonenumber") + * @ORM\OneToMany(targetEntity="DDC881PhoneCall", mappedBy="phonenumber") */ private $calls; @@ -182,27 +185,26 @@ public function getCalls() } /** - * @Entity + * @ORM\Entity */ class DDC881PhoneCall { - /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** - * @ManyToOne(targetEntity="DDC881PhoneNumber", inversedBy="calls", cascade={"all"}) - * @JoinColumns({ - * @JoinColumn(name="phonenumber_id", referencedColumnName="id"), - * @JoinColumn(name="user_id", referencedColumnName="user_id") + * @ORM\ManyToOne(targetEntity="DDC881PhoneNumber", inversedBy="calls", cascade={"all"}) + * @ORM\JoinColumns({ + * @ORM\JoinColumn(name="phonenumber_id", referencedColumnName="id"), + * @ORM\JoinColumn(name="user_id", referencedColumnName="user_id") * }) */ private $phonenumber; /** - * @Column(type="string",nullable=true) + * @ORM\Column(type="string",nullable=true) */ private $callDate; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC933Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC933Test.php index f6216a16237..11813f0d59f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC933Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC933Test.php @@ -1,5 +1,7 @@ _em->getConnection()->getDatabasePlatform()->getName() === 'sqlite') { + if ($this->em->getConnection()->getDatabasePlatform()->getName() === 'sqlite') { self::markTestSkipped('It should not run on in-memory databases'); } @@ -31,12 +33,12 @@ public function testLockCTIClass() $manager->setTitle('Vice President of This Test'); $manager->setDepartment("Foo"); - $this->_em->persist($manager); - $this->_em->flush(); + $this->em->persist($manager); + $this->em->flush(); - $this->_em->beginTransaction(); - $this->_em->lock($manager, LockMode::PESSIMISTIC_READ); - $this->_em->rollback(); + $this->em->beginTransaction(); + $this->em->lock($manager, LockMode::PESSIMISTIC_READ); + $this->em->rollback(); // if lock hasn't been released we'd have an exception here $this->assertManagerCanBeUpdatedOnAnotherConnection($manager->getId(), 'Master of This Test'); @@ -55,7 +57,7 @@ public function testLockCTIClass() */ private function assertManagerCanBeUpdatedOnAnotherConnection(int $id, string $newName) { - $em = $this->_getEntityManager(TestUtil::getConnection()); + $em = $this->getEntityManager(TestUtil::getConnection()); /** @var CompanyManager $manager */ $manager = $em->find(CompanyManager::class, $id); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC949Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC949Test.php index 8c3162df364..9fca5db0131 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC949Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC949Test.php @@ -1,5 +1,7 @@ booleanField = false; - $this->_em->persist($true); - $this->_em->persist($false); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($true); + $this->em->persist($false); + $this->em->flush(); + $this->em->clear(); - $true = $this->_em->getRepository(BooleanModel::class)->findOneBy(['booleanField' => true]); - $false = $this->_em->getRepository(BooleanModel::class)->findOneBy(['booleanField' => false]); + $true = $this->em->getRepository(BooleanModel::class)->findOneBy(['booleanField' => true]); + $false = $this->em->getRepository(BooleanModel::class)->findOneBy(['booleanField' => false]); - $this->assertInstanceOf(BooleanModel::class, $true, "True model not found"); - $this->assertTrue($true->booleanField, "True Boolean Model should be true."); + self::assertInstanceOf(BooleanModel::class, $true, "True model not found"); + self::assertTrue($true->booleanField, "True Boolean Model should be true."); - $this->assertInstanceOf(BooleanModel::class, $false, "False model not found"); - $this->assertFalse($false->booleanField, "False Boolean Model should be false."); + self::assertInstanceOf(BooleanModel::class, $false, "False model not found"); + self::assertFalse($false->booleanField, "False Boolean Model should be false."); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC960Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC960Test.php index 730a70bce8c..7459e53957c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC960Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC960Test.php @@ -1,7 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC960Root::class), - $this->_em->getClassMetadata(DDC960Child::class) + $this->em->getClassMetadata(DDC960Root::class), + $this->em->getClassMetadata(DDC960Child::class) ] ); } catch(\Exception $e) { @@ -27,21 +30,21 @@ protected function setUp() public function testUpdateRootVersion() { $child = new DDC960Child('Test'); - $this->_em->persist($child); - $this->_em->flush(); + $this->em->persist($child); + $this->em->flush(); $child->setName("Test2"); - $this->_em->flush(); + $this->em->flush(); - $this->assertEquals(2, $child->getVersion()); + self::assertEquals(2, $child->getVersion()); } } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorMap({ + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorMap({ * "root" = "DDC960Root", * "child" = "DDC960Child" * }) @@ -49,12 +52,12 @@ public function testUpdateRootVersion() class DDC960Root { /** - * @Id @GeneratedValue @Column(type="integer") + * @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ private $id; /** - * @Column(type="integer") @Version + * @ORM\Column(type="integer") @ORM\Version */ private $version; @@ -70,12 +73,12 @@ public function getVersion() } /** - * @Entity + * @ORM\Entity */ class DDC960Child extends DDC960Root { /** - * @column(type="string") + * @ORM\Column(type="string") * @var string */ private $name; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC992Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC992Test.php index 77780486bd4..6558bc20ca2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC992Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC992Test.php @@ -1,8 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC992Role::class), - $this->_em->getClassMetadata(DDC992Parent::class), - $this->_em->getClassMetadata(DDC992Child::class), + $this->em->getClassMetadata(DDC992Role::class), + $this->em->getClassMetadata(DDC992Parent::class), + $this->em->getClassMetadata(DDC992Child::class), ] ); } catch(\Exception $e) { @@ -35,16 +38,16 @@ public function testIssue() $role->extendedBy[] = $child; $child->extends[] = $role; - $this->_em->persist($role); - $this->_em->persist($child); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($role); + $this->em->persist($child); + $this->em->flush(); + $this->em->clear(); - $child = $this->_em->getRepository(get_class($role))->find($child->roleID); + $child = $this->em->getRepository(get_class($role))->find($child->roleID); $parents = count($child->extends); - $this->assertEquals(1, $parents); + self::assertEquals(1, $parents); foreach ($child->extends AS $parent) { - $this->assertEquals($role->getRoleID(), $parent->getRoleID()); + self::assertEquals($role->getRoleID(), $parent->getRoleID()); } } @@ -55,50 +58,50 @@ public function testOneToManyChild() $child->parent = $parent; $parent->childs[] = $child; - $this->_em->persist($parent); - $this->_em->persist($child); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($parent); + $this->em->persist($child); + $this->em->flush(); + $this->em->clear(); - $parentRepository = $this->_em->getRepository(get_class($parent)); - $childRepository = $this->_em->getRepository(get_class($child)); + $parentRepository = $this->em->getRepository(get_class($parent)); + $childRepository = $this->em->getRepository(get_class($child)); $parent = $parentRepository->find($parent->id); - $this->assertEquals(1, count($parent->childs)); - $this->assertEquals(0, count($parent->childs[0]->childs())); + self::assertEquals(1, count($parent->childs)); + self::assertEquals(0, count($parent->childs[0]->childs())); $child = $parentRepository->findOneBy(["id" => $child->id]); - $this->assertSame($parent->childs[0], $child); + self::assertSame($parent->childs[0], $child); - $this->_em->clear(); + $this->em->clear(); $child = $parentRepository->find($child->id); - $this->assertEquals(0, count($child->childs)); + self::assertEquals(0, count($child->childs)); - $this->_em->clear(); + $this->em->clear(); $child = $childRepository->find($child->id); - $this->assertEquals(0, count($child->childs)); + self::assertEquals(0, count($child->childs)); } } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorMap({"child" = "DDC992Child", "parent" = "DDC992Parent"}) + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorMap({"child" = "DDC992Child", "parent" = "DDC992Parent"}) */ class DDC992Parent { - /** @Id @GeneratedValue @Column(type="integer") */ + /** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ public $id; - /** @ManyToOne(targetEntity="DDC992Parent", inversedBy="childs") */ + /** @ORM\ManyToOne(targetEntity="DDC992Parent", inversedBy="childs") */ public $parent; - /** @OneToMany(targetEntity="DDC992Child", mappedBy="parent") */ + /** @ORM\OneToMany(targetEntity="DDC992Child", mappedBy="parent") */ public $childs; } /** - * @Entity + * @ORM\Entity */ class DDC992Child extends DDC992Parent { @@ -109,7 +112,7 @@ public function childs() } /** - * @Entity + * @ORM\Entity */ class DDC992Role { @@ -119,23 +122,23 @@ public function getRoleID() } /** - * @Id @Column(name="roleID", type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(name="roleID", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $roleID; /** - * @Column (name="name", type="string", length=45) + * @ORM\Column (name="name", type="string", length=45) */ public $name; /** - * @ManyToMany (targetEntity="DDC992Role", mappedBy="extends") + * @ORM\ManyToMany (targetEntity="DDC992Role", mappedBy="extends") */ public $extendedBy; /** - * @ManyToMany (targetEntity="DDC992Role", inversedBy="extendedBy") - * @JoinTable (name="RoleRelations", - * joinColumns={@JoinColumn(name="roleID", referencedColumnName="roleID")}, - * inverseJoinColumns={@JoinColumn(name="extendsRoleID", referencedColumnName="roleID")} + * @ORM\ManyToMany (targetEntity="DDC992Role", inversedBy="extendedBy") + * @ORM\JoinTable (name="RoleRelations", + * joinColumns={@ORM\JoinColumn(name="roleID", referencedColumnName="roleID")}, + * inverseJoinColumns={@ORM\JoinColumn(name="extendsRoleID", referencedColumnName="roleID")} * ) */ public $extends; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH2947Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH2947Test.php index 0b21b57f065..2f4d96b5c03 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH2947Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH2947Test.php @@ -1,8 +1,11 @@ _schemaTool->createSchema([$this->_em->getClassMetadata(GH2947Car::class)]); + $this->schemaTool->createSchema( + [ + $this->em->getClassMetadata(GH2947Car::class) + ] + ); } public function testIssue() @@ -43,7 +50,7 @@ public function testIssue() private function createQuery() { - return $this->_em->createQueryBuilder() + return $this->em->createQueryBuilder() ->select('car') ->from(GH2947Car::class, 'car') ->getQuery() @@ -52,14 +59,14 @@ private function createQuery() private function createData() { - $this->_em->persist(new GH2947Car('BMW')); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist(new GH2947Car('BMW')); + $this->em->flush(); + $this->em->clear(); } private function updateData() { - $this->_em->createQueryBuilder() + $this->em->createQueryBuilder() ->update(GH2947Car::class, 'car') ->set('car.brand', ':newBrand') ->where('car.brand = :oldBrand') @@ -71,15 +78,15 @@ private function updateData() } /** - * @Entity - * @Table(name="GH2947_car") + * @ORM\Entity + * @ORM\Table(name="GH2947_car") */ class GH2947Car { /** - * @Id - * @Column(type="string", length=25) - * @GeneratedValue(strategy="NONE") + * @ORM\Id + * @ORM\Column(type="string", length=25) + * @ORM\GeneratedValue(strategy="NONE") */ public $brand; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5562Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5562Test.php index 824c4378add..3ce02f0ee6a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5562Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5562Test.php @@ -1,10 +1,10 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(GH5562User::class), - $this->_em->getClassMetadata(GH5562Manager::class), - $this->_em->getClassMetadata(GH5562Merchant::class), + $this->em->getClassMetadata(GH5562User::class), + $this->em->getClassMetadata(GH5562Manager::class), + $this->em->getClassMetadata(GH5562Merchant::class), ] ); } @@ -38,76 +38,76 @@ public function testCacheShouldBeUpdatedWhenAssociationChanges() $merchant->name = 'Merchant'; - $this->_em->persist($merchant); - $this->_em->persist($manager); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($merchant); + $this->em->persist($manager); + $this->em->flush(); + $this->em->clear(); - $merchant = $this->_em->find(GH5562Merchant::class, $merchant->id); + $merchant = $this->em->find(GH5562Merchant::class, $merchant->id); $merchant->name = mt_rand(); $merchant->manager->username = 'usernameUPDATE'; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); - $merchant = $this->_em->find(GH5562Merchant::class, $merchant->id); + $merchant = $this->em->find(GH5562Merchant::class, $merchant->id); self::assertEquals('usernameUPDATE', $merchant->manager->username); } } /** - * @Entity - * @Cache(usage="NONSTRICT_READ_WRITE") + * @ORM\Entity + * @ORM\Cache(usage="NONSTRICT_READ_WRITE") */ class GH5562Merchant { /** * @var integer * - * @Id - * @Column(name="id", type="integer") - * @GeneratedValue(strategy="IDENTITY") + * @ORM\Id + * @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue(strategy="IDENTITY") */ public $id; /** * @var GH5562Manager * - * @OneToOne(targetEntity=GH5562Manager::class, mappedBy="merchant") - * @Cache(usage="NONSTRICT_READ_WRITE") + * @ORM\OneToOne(targetEntity=GH5562Manager::class, mappedBy="merchant") + * @ORM\Cache(usage="NONSTRICT_READ_WRITE") */ public $manager; /** * @var string * - * @Column(name="name", type="string", length=255, nullable=false) + * @ORM\Column(name="name", type="string", length=255, nullable=false) */ public $name; } /** - * @Entity - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorMap({"MANAGER" = GH5562Manager::class}) + * @ORM\Entity + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorMap({"MANAGER" = GH5562Manager::class}) */ abstract class GH5562User { /** * @var integer * - * @Id - * @Column(name="id", type="integer") - * @GeneratedValue(strategy="IDENTITY") + * @ORM\Id + * @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue(strategy="IDENTITY") */ public $id; } /** - * @Entity - * @Cache(usage="NONSTRICT_READ_WRITE") + * @ORM\Entity + * @ORM\Cache(usage="NONSTRICT_READ_WRITE") */ class GH5562Manager extends GH5562User { @@ -115,14 +115,14 @@ class GH5562Manager extends GH5562User /** * @var string * - * @Column + * @ORM\Column */ public $username; /** * @var GH5562Merchant * - * @OneToOne(targetEntity=GH5562Merchant::class, inversedBy="manager") + * @ORM\OneToOne(targetEntity=GH5562Merchant::class, inversedBy="manager") */ public $merchant; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5762Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5762Test.php index b7a748ddc46..3faa640b3b9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5762Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5762Test.php @@ -1,8 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(GH5762Driver::class), - $this->_em->getClassMetadata(GH5762DriverRide::class), - $this->_em->getClassMetadata(GH5762Car::class), + $this->em->getClassMetadata(GH5762Driver::class), + $this->em->getClassMetadata(GH5762DriverRide::class), + $this->em->getClassMetadata(GH5762Car::class), ] ); } @@ -51,7 +54,7 @@ private function fetchData() { $this->createData(); - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('d, dr, c') ->from(GH5762Driver::class, 'd') ->leftJoin('d.driverRides', 'dr') @@ -77,45 +80,45 @@ private function createData() $ride4 = new GH5762DriverRide($driver, $car4); $ride5 = new GH5762DriverRide($driver, $car5); - $this->_em->persist($car1); - $this->_em->persist($car2); - $this->_em->persist($car3); - $this->_em->persist($car4); - $this->_em->persist($car5); + $this->em->persist($car1); + $this->em->persist($car2); + $this->em->persist($car3); + $this->em->persist($car4); + $this->em->persist($car5); - $this->_em->persist($driver); + $this->em->persist($driver); - $this->_em->persist($ride1); - $this->_em->persist($ride2); - $this->_em->persist($ride3); - $this->_em->persist($ride4); - $this->_em->persist($ride5); + $this->em->persist($ride1); + $this->em->persist($ride2); + $this->em->persist($ride3); + $this->em->persist($ride4); + $this->em->persist($ride5); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); } } /** - * @Entity - * @Table(name="driver") + * @ORM\Entity + * @ORM\Table(name="driver") */ class GH5762Driver { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="NONE") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="NONE") */ public $id; /** - * @Column(type="string", length=255); + * @ORM\Column(type="string", length=255); */ public $name; /** - * @OneToMany(targetEntity="GH5762DriverRide", mappedBy="driver") + * @ORM\OneToMany(targetEntity="GH5762DriverRide", mappedBy="driver") */ public $driverRides; @@ -128,22 +131,22 @@ public function __construct($id, $name) } /** - * @Entity - * @Table(name="driver_ride") + * @ORM\Entity + * @ORM\Table(name="driver_ride") */ class GH5762DriverRide { /** - * @Id - * @ManyToOne(targetEntity="GH5762Driver", inversedBy="driverRides") - * @JoinColumn(name="driver_id", referencedColumnName="id") + * @ORM\Id + * @ORM\ManyToOne(targetEntity="GH5762Driver", inversedBy="driverRides") + * @ORM\JoinColumn(name="driver_id", referencedColumnName="id") */ public $driver; /** - * @Id - * @ManyToOne(targetEntity="GH5762Car", inversedBy="carRides") - * @JoinColumn(name="car", referencedColumnName="brand") + * @ORM\Id + * @ORM\ManyToOne(targetEntity="GH5762Car", inversedBy="carRides") + * @ORM\JoinColumn(name="car", referencedColumnName="brand") */ public $car; @@ -158,26 +161,26 @@ function __construct(GH5762Driver $driver, GH5762Car $car) } /** - * @Entity - * @Table(name="car") + * @ORM\Entity + * @ORM\Table(name="car") */ class GH5762Car { /** - * @Id - * @Column(type="string", length=25) - * @GeneratedValue(strategy="NONE") + * @ORM\Id + * @ORM\Column(type="string", length=25) + * @ORM\GeneratedValue(strategy="NONE") */ public $brand; /** - * @Column(type="string", length=255); + * @ORM\Column(type="string", length=255); */ public $model; /** - * @OneToMany(targetEntity="GH5762DriverRide", mappedBy="car") + * @ORM\OneToMany(targetEntity="GH5762DriverRide", mappedBy="car") */ public $carRides; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5804Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5804Test.php index 77d4fbc878e..15b820785e9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5804Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5804Test.php @@ -4,8 +4,9 @@ use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Types\Type; -use Doctrine\ORM\EntityManager; -use Doctrine\ORM\Id\AbstractIdGenerator; +use Doctrine\ORM\Annotation as ORM; +use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Sequencing\Generator; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -19,8 +20,8 @@ protected function setUp() Type::addType(GH5804Type::NAME, GH5804Type::class); - $this->_schemaTool->createSchema( - [$this->_em->getClassMetadata(GH5804Article::class)] + $this->schemaTool->createSchema( + [$this->em->getClassMetadata(GH5804Article::class)] ); } @@ -28,28 +29,36 @@ public function testTextColumnSaveAndRetrieve2() { $firstArticle = new GH5804Article; $firstArticle->text = 'Max'; - $this->_em->persist($firstArticle); - $this->_em->flush(); + $this->em->persist($firstArticle); + $this->em->flush(); self::assertSame(1, $firstArticle->version); $firstArticle->text = 'Moritz'; - $this->_em->persist($firstArticle); - $this->_em->flush(); + $this->em->persist($firstArticle); + $this->em->flush(); self::assertSame(2, $firstArticle->version); } } -final class GH5804Generator extends AbstractIdGenerator +final class GH5804Generator implements Generator { /** * {@inheritdoc} */ - public function generate(EntityManager $em, $entity) + public function generate(EntityManagerInterface $em, $entity) { return 'test5804'; } + + /** + * {@inheritdoc} + */ + public function isPostInsertGenerator() + { + return false; + } } final class GH5804Type extends Type @@ -83,26 +92,26 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) } /** - * @Entity + * @ORM\Entity */ class GH5804Article { /** - * @Id - * @Column(type="GH5804Type") - * @GeneratedValue(strategy="CUSTOM") - * @CustomIdGenerator(class=\Doctrine\Tests\ORM\Functional\Ticket\GH5804Generator::class) + * @ORM\Id + * @ORM\Column(type="GH5804Type") + * @ORM\GeneratedValue(strategy="CUSTOM") + * @ORM\CustomIdGenerator(class=\Doctrine\Tests\ORM\Functional\Ticket\GH5804Generator::class) */ public $id; /** - * @Version - * @Column(type="integer") + * @ORM\Version + * @ORM\Column(type="integer") */ public $version; /** - * @Column(type="text") + * @ORM\Column(type="text") */ public $text; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5887Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5887Test.php index f19dd5924b5..bc3f2b23db8 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5887Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5887Test.php @@ -1,10 +1,13 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(GH5887Cart::class), - $this->_em->getClassMetadata(GH5887Customer::class), + $this->em->getClassMetadata(GH5887Cart::class), + $this->em->getClassMetadata(GH5887Customer::class), ] ); + + $this->markTestIncomplete('Requires updates to SqlWalker'); } public function testLazyLoadsForeignEntitiesInOneToOneRelationWhileHavingCustomIdObject() @@ -37,14 +42,12 @@ public function testLazyLoadsForeignEntitiesInOneToOneRelationWhileHavingCustomI $cart->setId($cartId); $cart->setCustomer($customer); - $this->_em->persist($customer); - $this->_em->persist($cart); - $this->_em->flush(); - - // Clearing cached entities - $this->_em->clear(); + $this->em->persist($customer); + $this->em->persist($cart); + $this->em->flush(); + $this->em->clear(); - $customerRepository = $this->_em->getRepository(GH5887Customer::class); + $customerRepository = $this->em->getRepository(GH5887Customer::class); /** @var GH5887Customer $customer */ $customer = $customerRepository->createQueryBuilder('c') ->where('c.id = :id') @@ -52,21 +55,21 @@ public function testLazyLoadsForeignEntitiesInOneToOneRelationWhileHavingCustomI ->getQuery() ->getOneOrNullResult(); - $this->assertInstanceOf(GH5887Cart::class, $customer->getCart()); + self::assertInstanceOf(GH5887Cart::class, $customer->getCart()); } } /** - * @Entity + * @ORM\Entity */ class GH5887Cart { /** * @var int * - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="NONE") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="NONE") */ private $id; @@ -75,8 +78,8 @@ class GH5887Cart * * @var GH5887Customer * - * @OneToOne(targetEntity="GH5887Customer", inversedBy="cart") - * @JoinColumn(name="customer_id", referencedColumnName="id") + * @ORM\OneToOne(targetEntity="GH5887Customer", inversedBy="cart") + * @ORM\JoinColumn(name="customer_id", referencedColumnName="id") */ private $customer; @@ -117,16 +120,16 @@ public function setCustomer(GH5887Customer $customer) } /** - * @Entity + * @ORM\Entity */ class GH5887Customer { /** * @var GH5887CustomIdObject * - * @Id - * @Column(type="GH5887CustomIdObject") - * @GeneratedValue(strategy="NONE") + * @ORM\Id + * @ORM\Column(type="GH5887CustomIdObject") + * @ORM\GeneratedValue(strategy="NONE") */ private $id; @@ -135,7 +138,7 @@ class GH5887Customer * * @var GH5887Cart * - * @OneToOne(targetEntity="GH5887Cart", mappedBy="customer") + * @ORM\OneToOne(targetEntity="GH5887Cart", mappedBy="customer") */ private $cart; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6141Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6141Test.php index 00ae936a4b1..56475dc15f8 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6141Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6141Test.php @@ -1,9 +1,13 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(GH6141Person::class), - $this->_em->getClassMetadata(GH6141Boss::class), - $this->_em->getClassMetadata(GH6141Employee::class), + $this->em->getClassMetadata(GH6141Person::class), + $this->em->getClassMetadata(GH6141Boss::class), + $this->em->getClassMetadata(GH6141Employee::class), ] ); } @@ -36,13 +40,13 @@ public function testEnumDiscriminatorsShouldBeConvertedToString() $boss = new GH6141Boss('John'); $employee = new GH6141Employee('Bob'); - $this->_em->persist($boss); - $this->_em->persist($employee); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($boss); + $this->em->persist($employee); + $this->em->flush(); + $this->em->clear(); // Using DQL here to make sure that we'll use ObjectHydrator instead of SimpleObjectHydrator - $query = $this->_em->createQueryBuilder() + $query = $this->em->createQueryBuilder() ->select('person') ->from(GH6141Person::class, 'person') ->where('person.name = :name') @@ -160,10 +164,10 @@ public function __toString() } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorColumn(name="discr", type="gh6141people") - * @DiscriminatorMap({ + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorColumn(name="discr", type="gh6141people") + * @ORM\DiscriminatorMap({ * Doctrine\Tests\ORM\Functional\Ticket\GH6141People::BOSS = GH6141Boss::class, * Doctrine\Tests\ORM\Functional\Ticket\GH6141People::EMPLOYEE = GH6141Employee::class * }) @@ -171,14 +175,14 @@ public function __toString() abstract class GH6141Person { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $name; @@ -191,12 +195,12 @@ public function __construct($name) } } -/** @Entity */ +/** @ORM\Entity */ class GH6141Boss extends GH6141Person { } -/** @Entity */ +/** @ORM\Entity */ class GH6141Employee extends GH6141Person { } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6362Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6362Test.php index 576fbd0eb86..366f43bbfe7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6362Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6362Test.php @@ -1,11 +1,15 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(GH6362Start::class), - $this->_em->getClassMetadata(GH6362Base::class), - $this->_em->getClassMetadata(GH6362Child::class), - $this->_em->getClassMetadata(GH6362Join::class), + $this->em->getClassMetadata(GH6362Start::class), + $this->em->getClassMetadata(GH6362Base::class), + $this->em->getClassMetadata(GH6362Child::class), + $this->em->getClassMetadata(GH6362Join::class), ] ); } @@ -45,10 +49,10 @@ public function testInheritanceJoinAlias() $rsm->addFieldResult('c', 'id_2', 'id'); $rsm->addFieldResult('d', 'id_3', 'id'); - $rsm->addMetaResult('a', 'bases_id_4', 'bases_id', false, 'integer'); - $rsm->addMetaResult('b', 'type_5', 'type'); - $rsm->addMetaResult('c', 'type_6', 'type'); - $rsm->addMetaResult('d', 'child_id_7', 'child_id', false, 'integer'); + $rsm->addMetaResult('a', 'bases_id_4', 'bases_id', false, Type::getType('integer')); + $rsm->addMetaResult('b', 'type_5', 'type', false, Type::getType('string')); + $rsm->addMetaResult('c', 'type_6', 'type', false, Type::getType('string')); + $rsm->addMetaResult('d', 'child_id_7', 'child_id', false, Type::getType('integer')); $rsm->setDiscriminatorColumn('b', 'type_5'); $rsm->setDiscriminatorColumn('c', 'type_6'); @@ -67,78 +71,78 @@ public function testInheritanceJoinAlias() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertInstanceOf(GH6362Start::class, $result[0]['base']); - $this->assertInstanceOf(GH6362Child::class, $result[1][0]); + self::assertInstanceOf(GH6362Start::class, $result[0]['base']); + self::assertInstanceOf(GH6362Child::class, $result[1][0]); } } /** - * @Entity + * @ORM\Entity */ class GH6362Start { /** - * @Column(type="integer") - * @Id - * @GeneratedValue + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue */ protected $id; /** - * @ManyToOne(targetEntity="GH6362Base", inversedBy="starts") + * @ORM\ManyToOne(targetEntity="GH6362Base", inversedBy="starts") */ private $bases; } /** - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorColumn(name="type", type="string") - * @DiscriminatorMap({"child" = "GH6362Child"}) - * @Entity + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorColumn(name="type", type="string") + * @ORM\DiscriminatorMap({"child" = "GH6362Child"}) + * @ORM\Entity */ abstract class GH6362Base { /** - * @Column(type="integer") - * @Id - * @GeneratedValue + * @ORM\Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue */ protected $id; /** - * @OneToMany(targetEntity="GH6362Start", mappedBy="bases") + * @ORM\OneToMany(targetEntity="GH6362Start", mappedBy="bases") */ private $starts; } /** - * @Entity + * @ORM\Entity */ class GH6362Child extends GH6362Base { /** - * @OneToMany(targetEntity="GH6362Join", mappedBy="child") + * @ORM\OneToMany(targetEntity="GH6362Join", mappedBy="child") */ private $joins; } /** - * @Entity + * @ORM\Entity */ class GH6362Join { /** - * @Column(type="integer") - * @Id - * @GeneratedValue + * @ORM\Column(type="integer") + * @ORM\Id + * @ORM\GeneratedValue */ private $id; /** - * @ManyToOne(targetEntity="GH6362Child", inversedBy="joins") + * @ORM\ManyToOne(targetEntity="GH6362Child", inversedBy="joins") */ private $child; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6402Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6402Test.php index 85bf43ea0c3..86151fcc364 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6402Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6402Test.php @@ -1,5 +1,7 @@ createAddress(); - $address = $this->_em->find(Address::class, $id); + $address = $this->em->find(Address::class, $id); + self::assertNotNull($address->user); } @@ -34,7 +37,7 @@ public function testQuery() { $id = $this->createAddress(); - $addresses = $this->_em->createQuery('SELECT a FROM ' . Address::class . ' a WHERE a.id = :id') + $addresses = $this->em->createQuery('SELECT a FROM ' . Address::class . ' a WHERE a.id = :id') ->setParameter('id', $id) ->getResult(); @@ -46,7 +49,8 @@ public function testFindWithSubClass() { $id = $this->createFullAddress(); - $address = $this->_em->find(FullAddress::class, $id); + $address = $this->em->find(FullAddress::class, $id); + self::assertNotNull($address->user); } @@ -54,7 +58,7 @@ public function testQueryWithSubClass() { $id = $this->createFullAddress(); - $addresses = $this->_em->createQuery('SELECT a FROM ' . FullAddress::class . ' a WHERE a.id = :id') + $addresses = $this->em->createQuery('SELECT a FROM ' . FullAddress::class . ' a WHERE a.id = :id') ->setParameter('id', $id) ->getResult(); @@ -89,8 +93,8 @@ private function persistAddress(Address $address) $user->name = "foo"; $user->setAddress($address); - $this->_em->persist($user); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($user); + $this->em->flush(); + $this->em->clear(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Issue5989Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Issue5989Test.php index cf601b99aed..99ef7de657d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/Issue5989Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Issue5989Test.php @@ -1,5 +1,7 @@ tags = $managerTags; - $this->_em->persist($manager); + $this->em->persist($manager); $employee = new Issue5989Employee(); $employeeTags =['tag2', 'tag3']; $employee->tags = $employeeTags; - $this->_em->persist($employee); + $this->em->persist($employee); - $this->_em->flush(); + $this->em->flush(); $managerId = $manager->id; $employeeId = $employee->id; // clear entity manager so that $repository->find actually fetches them and uses the hydrator // instead of just returning the existing managed entities - $this->_em->clear(); + $this->em->clear(); - $repository = $this->_em->getRepository(Issue5989Person::class); + $repository = $this->em->getRepository(Issue5989Person::class); $manager = $repository->find($managerId); $employee = $repository->find($employeeId); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket2481Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket2481Test.php index ebedf0c869f..d85c3b847f1 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket2481Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket2481Test.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(Ticket2481Product::class) + $this->em->getClassMetadata(Ticket2481Product::class) ] ); } catch (\Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } - $this->_conn = $this->_em->getConnection(); + $this->conn = $this->em->getConnection(); } public function testEmptyInsert() { $test = new Ticket2481Product(); - $this->_em->persist($test); - $this->_em->flush(); + $this->em->persist($test); + $this->em->flush(); - $this->assertTrue($test->id > 0); + self::assertTrue($test->id > 0); } } /** - * @Entity - * @Table(name="ticket_2481_products") + * @ORM\Entity + * @ORM\Table(name="ticket_2481_products") */ class Ticket2481Product { /** - * @Id @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket69.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket69.php index ccc8bce120c..c89b521bc7a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket69.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket69.php @@ -1,7 +1,11 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(Lemma::class), - $this->_em->getClassMetadata(Relation::class), - $this->_em->getClassMetadata(RelationType::class) + $this->em->getClassMetadata(Lemma::class), + $this->em->getClassMetadata(Relation::class), + $this->em->getClassMetadata(RelationType::class) ] ); } catch (\Exception $e) { @@ -66,39 +70,39 @@ public function testIssue() $lemma1->addRelation($relation2); $lemma1->addRelation($relation3); - $this->_em->persist($type1); - $this->_em->persist($type2); - $this->_em->persist($lemma1); - $this->_em->persist($lemma2); - $this->_em->persist($lemma3); - $this->_em->persist($lemma4); + $this->em->persist($type1); + $this->em->persist($type2); + $this->em->persist($lemma1); + $this->em->persist($lemma2); + $this->em->persist($lemma3); + $this->em->persist($lemma4); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); //end setup // test One To Many - $query = $this->_em->createQuery("SELECT l FROM Doctrine\Tests\ORM\Functional\Ticket\Lemma l Where l.lemma = 'foo'"); + $query = $this->em->createQuery("SELECT l FROM Doctrine\Tests\ORM\Functional\Ticket\Lemma l Where l.lemma = 'foo'"); $res = $query->getResult(); $lemma = $res[0]; - $this->assertEquals('foo', $lemma->getLemma()); - $this->assertInstanceOf(Lemma::class, $lemma); + self::assertEquals('foo', $lemma->getLemma()); + self::assertInstanceOf(Lemma::class, $lemma); $relations = $lemma->getRelations(); foreach($relations as $relation) { - $this->assertInstanceOf(Relation::class, $relation); - $this->assertTrue($relation->getType()->getType() != ''); + self::assertInstanceOf(Relation::class, $relation); + self::assertTrue($relation->getType()->getType() != ''); } - $this->_em->clear(); + $this->em->clear(); } } /** - * @Entity - * @Table(name="lemma") + * @ORM\Entity + * @ORM\Table(name="lemma") */ class Lemma { @@ -106,23 +110,23 @@ class Lemma { /** * @var int - * @Id - * @Column(type="integer", name="lemma_id") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer", name="lemma_id") + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * * @var string - * @Column(type="string", name="lemma_name", unique=true, length=255) + * @ORM\Column(type="string", name="lemma_name", unique=true, length=255) */ private $lemma; /** * @var kateglo\application\utilities\collections\ArrayCollection - * @OneToMany(targetEntity="Relation", mappedBy="parent", cascade={"persist"}) + * @ORM\OneToMany(targetEntity="Relation", mappedBy="parent", cascade={"persist"}) */ private $relations; @@ -193,8 +197,8 @@ public function getRelations() { /** * - * @Entity - * @Table(name="relation") + * @ORM\Entity + * @ORM\Table(name="relation") */ class Relation { @@ -202,30 +206,30 @@ class Relation { /** * @var int - * @Id - * @Column(type="integer", name="relation_id") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer", name="relation_id") + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var Lemma - * @ManyToOne(targetEntity="Lemma", inversedBy="relations") - * @JoinColumn(name="relation_parent_id", referencedColumnName="lemma_id") + * @ORM\ManyToOne(targetEntity="Lemma", inversedBy="relations") + * @ORM\JoinColumn(name="relation_parent_id", referencedColumnName="lemma_id") */ private $parent; /** * @var Lemma - * @OneToOne(targetEntity="Lemma") - * @JoinColumn(name="relation_child_id", referencedColumnName="lemma_id") + * @ORM\OneToOne(targetEntity="Lemma") + * @ORM\JoinColumn(name="relation_child_id", referencedColumnName="lemma_id") */ private $child; /** * @var RelationType - * @ManyToOne(targetEntity="RelationType", inversedBy="relations") - * @JoinColumn(name="relation_type_id", referencedColumnName="relation_type_id") + * @ORM\ManyToOne(targetEntity="RelationType", inversedBy="relations") + * @ORM\JoinColumn(name="relation_type_id", referencedColumnName="relation_type_id") */ private $type; @@ -309,8 +313,8 @@ public function removeType() { /** * - * @Entity - * @Table(name="relation_type") + * @ORM\Entity + * @ORM\Table(name="relation_type") */ class RelationType { @@ -319,29 +323,29 @@ class RelationType { /** * * @var int - * @Id - * @Column(type="integer", name="relation_type_id") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer", name="relation_type_id") + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * * @var string - * @Column(type="string", name="relation_type_name", unique=true, length=255) + * @ORM\Column(type="string", name="relation_type_name", unique=true, length=255) */ private $type; /** * * @var string - * @Column(type="string", name="relation_type_abbreviation", unique=true, length=255) + * @ORM\Column(type="string", name="relation_type_abbreviation", unique=true, length=255) */ private $abbreviation; /** * @var kateglo\application\utilities\collections\ArrayCollection - * @OneToMany(targetEntity="Relation", mappedBy="type", cascade={"persist"}) + * @ORM\OneToMany(targetEntity="Relation", mappedBy="type", cascade={"persist"}) */ private $relations; diff --git a/tests/Doctrine/Tests/ORM/Functional/TypeTest.php b/tests/Doctrine/Tests/ORM/Functional/TypeTest.php index 9dd99777a04..30284611a08 100644 --- a/tests/Doctrine/Tests/ORM/Functional/TypeTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/TypeTest.php @@ -1,5 +1,7 @@ decimal = 0.15; $decimal->highScale = 0.1515; - $this->_em->persist($decimal); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($decimal); + $this->em->flush(); + $this->em->clear(); $dql = 'SELECT d FROM ' . DecimalModel::class . ' d'; - $decimal = $this->_em->createQuery($dql)->getSingleResult(); + $decimal = $this->em->createQuery($dql)->getSingleResult(); - $this->assertSame('0.15', $decimal->decimal); - $this->assertSame('0.1515', $decimal->highScale); + self::assertSame('0.15', $decimal->decimal); + self::assertSame('0.1515', $decimal->highScale); } /** @@ -45,24 +47,24 @@ public function testBoolean() $bool = new BooleanModel(); $bool->booleanField = true; - $this->_em->persist($bool); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($bool); + $this->em->flush(); + $this->em->clear(); $dql = 'SELECT b FROM ' . BooleanModel::class . ' b WHERE b.booleanField = true'; - $bool = $this->_em->createQuery($dql)->getSingleResult(); + $bool = $this->em->createQuery($dql)->getSingleResult(); - $this->assertTrue($bool->booleanField); + self::assertTrue($bool->booleanField); $bool->booleanField = false; - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $dql = 'SELECT b FROM ' . BooleanModel::class . ' b WHERE b.booleanField = false'; - $bool = $this->_em->createQuery($dql)->getSingleResult(); + $bool = $this->em->createQuery($dql)->getSingleResult(); - $this->assertFalse($bool->booleanField); + self::assertFalse($bool->booleanField); } public function testArray() @@ -71,14 +73,14 @@ public function testArray() $serialize->array["foo"] = "bar"; $serialize->array["bar"] = "baz"; - $this->_em->persist($serialize); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($serialize); + $this->em->flush(); + $this->em->clear(); $dql = 'SELECT s FROM ' . SerializationModel::class . ' s'; - $serialize = $this->_em->createQuery($dql)->getSingleResult(); + $serialize = $this->em->createQuery($dql)->getSingleResult(); - $this->assertSame(["foo" => "bar", "bar" => "baz"], $serialize->array); + self::assertSame(["foo" => "bar", "bar" => "baz"], $serialize->array); } public function testObject() @@ -86,14 +88,14 @@ public function testObject() $serialize = new SerializationModel(); $serialize->object = new \stdClass(); - $this->_em->persist($serialize); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($serialize); + $this->em->flush(); + $this->em->clear(); $dql = 'SELECT s FROM ' . SerializationModel::class . ' s'; - $serialize = $this->_em->createQuery($dql)->getSingleResult(); + $serialize = $this->em->createQuery($dql)->getSingleResult(); - $this->assertInstanceOf('stdClass', $serialize->object); + self::assertInstanceOf('stdClass', $serialize->object); } public function testDate() @@ -101,14 +103,14 @@ public function testDate() $dateTime = new DateTimeModel(); $dateTime->date = new \DateTime('2009-10-01', new \DateTimeZone('Europe/Berlin')); - $this->_em->persist($dateTime); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($dateTime); + $this->em->flush(); + $this->em->clear(); - $dateTimeDb = $this->_em->find(DateTimeModel::class, $dateTime->id); + $dateTimeDb = $this->em->find(DateTimeModel::class, $dateTime->id); - $this->assertInstanceOf(\DateTime::class, $dateTimeDb->date); - $this->assertSame('2009-10-01', $dateTimeDb->date->format('Y-m-d')); + self::assertInstanceOf(\DateTime::class, $dateTimeDb->date); + self::assertEquals('2009-10-01', $dateTimeDb->date->format('Y-m-d')); } public function testDateTime() @@ -116,19 +118,21 @@ public function testDateTime() $dateTime = new DateTimeModel(); $dateTime->datetime = new \DateTime('2009-10-02 20:10:52', new \DateTimeZone('Europe/Berlin')); - $this->_em->persist($dateTime); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($dateTime); + $this->em->flush(); + $this->em->clear(); - $dateTimeDb = $this->_em->find(DateTimeModel::class, $dateTime->id); + $dateTimeDb = $this->em->find(DateTimeModel::class, $dateTime->id); - $this->assertInstanceOf(\DateTime::class, $dateTimeDb->datetime); - $this->assertSame('2009-10-02 20:10:52', $dateTimeDb->datetime->format('Y-m-d H:i:s')); + self::assertInstanceOf(\DateTime::class, $dateTimeDb->datetime); + self::assertEquals('2009-10-02 20:10:52', $dateTimeDb->datetime->format('Y-m-d H:i:s')); - $articles = $this->_em->getRepository(DateTimeModel::class) - ->findBy(['datetime' => new \DateTime()]); + $articles = $this->em + ->getRepository(DateTimeModel::class) + ->findBy(['datetime' => new \DateTime("now")]) + ; - $this->assertEmpty($articles); + self::assertEmpty($articles); } public function testDqlQueryBindDateTimeInstance() @@ -138,16 +142,17 @@ public function testDqlQueryBindDateTimeInstance() $dateTime = new DateTimeModel(); $dateTime->datetime = $date; - $this->_em->persist($dateTime); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($dateTime); + $this->em->flush(); + $this->em->clear(); - $dateTimeDb = $this->_em->createQuery('SELECT d FROM Doctrine\Tests\Models\Generic\DateTimeModel d WHERE d.datetime = ?1') - ->setParameter(1, $date, DBALType::DATETIME) - ->getSingleResult(); + $dateTimeDb = $this->em + ->createQuery('SELECT d FROM Doctrine\Tests\Models\Generic\DateTimeModel d WHERE d.datetime = ?1') + ->setParameter(1, $date, DBALType::DATETIME) + ->getSingleResult(); - $this->assertInstanceOf(\DateTime::class, $dateTimeDb->datetime); - $this->assertSame('2009-10-02 20:10:52', $dateTimeDb->datetime->format('Y-m-d H:i:s')); + self::assertInstanceOf(\DateTime::class, $dateTimeDb->datetime); + self::assertSame('2009-10-02 20:10:52', $dateTimeDb->datetime->format('Y-m-d H:i:s')); } public function testDqlQueryBuilderBindDateTimeInstance() @@ -157,19 +162,20 @@ public function testDqlQueryBuilderBindDateTimeInstance() $dateTime = new DateTimeModel(); $dateTime->datetime = $date; - $this->_em->persist($dateTime); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($dateTime); + $this->em->flush(); + $this->em->clear(); - $dateTimeDb = $this->_em->createQueryBuilder() - ->select('d') - ->from(DateTimeModel::class, 'd') - ->where('d.datetime = ?1') - ->setParameter(1, $date, DBALType::DATETIME) - ->getQuery()->getSingleResult(); + $dateTimeDb = $this->em->createQueryBuilder() + ->select('d') + ->from(DateTimeModel::class, 'd') + ->where('d.datetime = ?1') + ->setParameter(1, $date, DBALType::DATETIME) + ->getQuery() + ->getSingleResult(); - $this->assertInstanceOf(\DateTime::class, $dateTimeDb->datetime); - $this->assertSame('2009-10-02 20:10:52', $dateTimeDb->datetime->format('Y-m-d H:i:s')); + self::assertInstanceOf(\DateTime::class, $dateTimeDb->datetime); + self::assertSame('2009-10-02 20:10:52', $dateTimeDb->datetime->format('Y-m-d H:i:s')); } public function testTime() @@ -177,13 +183,13 @@ public function testTime() $dateTime = new DateTimeModel(); $dateTime->time = new \DateTime('2010-01-01 19:27:20'); - $this->_em->persist($dateTime); - $this->_em->flush(); - $this->_em->clear(); + $this->em->persist($dateTime); + $this->em->flush(); + $this->em->clear(); - $dateTimeDb = $this->_em->find(DateTimeModel::class, $dateTime->id); + $dateTimeDb = $this->em->find(DateTimeModel::class, $dateTime->id); - $this->assertInstanceOf(\DateTime::class, $dateTimeDb->time); - $this->assertSame('19:27:20', $dateTimeDb->time->format('H:i:s')); + self::assertInstanceOf(\DateTime::class, $dateTime->time); + self::assertSame('19:27:20', $dateTime->time->format('H:i:s')); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/TypeValueSqlTest.php b/tests/Doctrine/Tests/ORM/Functional/TypeValueSqlTest.php index 3af954cfd97..0dc8c0155b9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/TypeValueSqlTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/TypeValueSqlTest.php @@ -1,5 +1,7 @@ lowerCaseString = 'foo'; - $this->_em->persist($entity); - $this->_em->flush(); + $this->em->persist($entity); + $this->em->flush(); $id = $entity->id; - $this->_em->clear(); + $this->em->clear(); - $entity = $this->_em->find('\Doctrine\Tests\Models\CustomType\CustomTypeUpperCase', $id); + $entity = $this->em->find('\Doctrine\Tests\Models\CustomType\CustomTypeUpperCase', $id); - $this->assertEquals('foo', $entity->lowerCaseString, 'Entity holds lowercase string'); - $this->assertEquals('FOO', $this->_em->getConnection()->fetchColumn("select lowerCaseString from customtype_uppercases where id=".$entity->id.""), 'Database holds uppercase string'); + self::assertEquals('foo', $entity->lowerCaseString, 'Entity holds lowercase string'); + self::assertEquals('FOO', $this->em->getConnection()->fetchColumn("select lowerCaseString from customtype_uppercases where id=".$entity->id.""), 'Database holds uppercase string'); } /** @@ -58,31 +60,31 @@ public function testUpperCaseStringTypeWhenColumnNameIsDefined() $entity->lowerCaseString = 'Some Value'; $entity->namedLowerCaseString = 'foo'; - $this->_em->persist($entity); - $this->_em->flush(); + $this->em->persist($entity); + $this->em->flush(); $id = $entity->id; - $this->_em->clear(); + $this->em->clear(); - $entity = $this->_em->find('\Doctrine\Tests\Models\CustomType\CustomTypeUpperCase', $id); - $this->assertEquals('foo', $entity->namedLowerCaseString, 'Entity holds lowercase string'); - $this->assertEquals('FOO', $this->_em->getConnection()->fetchColumn("select named_lower_case_string from customtype_uppercases where id=".$entity->id.""), 'Database holds uppercase string'); + $entity = $this->em->find('\Doctrine\Tests\Models\CustomType\CustomTypeUpperCase', $id); + self::assertEquals('foo', $entity->namedLowerCaseString, 'Entity holds lowercase string'); + self::assertEquals('FOO', $this->em->getConnection()->fetchColumn("select named_lower_case_string from customtype_uppercases where id=".$entity->id.""), 'Database holds uppercase string'); $entity->namedLowerCaseString = 'bar'; - $this->_em->persist($entity); - $this->_em->flush(); + $this->em->persist($entity); + $this->em->flush(); $id = $entity->id; - $this->_em->clear(); + $this->em->clear(); - $entity = $this->_em->find('\Doctrine\Tests\Models\CustomType\CustomTypeUpperCase', $id); - $this->assertEquals('bar', $entity->namedLowerCaseString, 'Entity holds lowercase string'); - $this->assertEquals('BAR', $this->_em->getConnection()->fetchColumn("select named_lower_case_string from customtype_uppercases where id=".$entity->id.""), 'Database holds uppercase string'); + $entity = $this->em->find('\Doctrine\Tests\Models\CustomType\CustomTypeUpperCase', $id); + self::assertEquals('bar', $entity->namedLowerCaseString, 'Entity holds lowercase string'); + self::assertEquals('BAR', $this->em->getConnection()->fetchColumn("select named_lower_case_string from customtype_uppercases where id=".$entity->id.""), 'Database holds uppercase string'); } public function testTypeValueSqlWithAssociations() @@ -97,22 +99,22 @@ public function testTypeValueSqlWithAssociations() $parent->addMyFriend($friend1); $parent->addMyFriend($friend2); - $this->_em->persist($parent); - $this->_em->persist($friend1); - $this->_em->persist($friend2); - $this->_em->flush(); + $this->em->persist($parent); + $this->em->persist($friend1); + $this->em->persist($friend2); + $this->em->flush(); $parentId = $parent->id; - $this->_em->clear(); + $this->em->clear(); - $entity = $this->_em->find(CustomTypeParent::class, $parentId); + $entity = $this->em->find(CustomTypeParent::class, $parentId); - $this->assertTrue($entity->customInteger < 0, 'Fetched customInteger negative'); - $this->assertEquals(1, $this->_em->getConnection()->fetchColumn("select customInteger from customtype_parents where id=".$entity->id.""), 'Database has stored customInteger positive'); + self::assertTrue($entity->customInteger < 0, 'Fetched customInteger negative'); + self::assertEquals(1, $this->em->getConnection()->fetchColumn("select customInteger from customtype_parents where id=".$entity->id.""), 'Database has stored customInteger positive'); - $this->assertNotNull($parent->child, 'Child attached'); - $this->assertCount(2, $entity->getMyFriends(), '2 friends attached'); + self::assertNotNull($parent->child, 'Child attached'); + self::assertCount(2, $entity->getMyFriends(), '2 friends attached'); } public function testSelectDQL() @@ -121,23 +123,23 @@ public function testSelectDQL() $parent->customInteger = -1; $parent->child = new CustomTypeChild(); - $this->_em->persist($parent); - $this->_em->flush(); + $this->em->persist($parent); + $this->em->flush(); $parentId = $parent->id; - $this->_em->clear(); + $this->em->clear(); - $query = $this->_em->createQuery("SELECT p, p.customInteger, c from Doctrine\Tests\Models\CustomType\CustomTypeParent p JOIN p.child c where p.id = " . $parentId); + $query = $this->em->createQuery("SELECT p, p.customInteger, c from Doctrine\Tests\Models\CustomType\CustomTypeParent p JOIN p.child c where p.id = " . $parentId); $result = $query->getResult(); - $this->assertEquals(1, count($result)); - $this->assertInstanceOf(CustomTypeParent::class, $result[0][0]); - $this->assertEquals(-1, $result[0][0]->customInteger); + self::assertEquals(1, count($result)); + self::assertInstanceOf(CustomTypeParent::class, $result[0][0]); + self::assertEquals(-1, $result[0][0]->customInteger); - $this->assertEquals(-1, $result[0]['customInteger']); + self::assertEquals(-1, $result[0]['customInteger']); - $this->assertEquals('foo', $result[0][0]->child->lowerCaseString); + self::assertEquals('foo', $result[0][0]->child->lowerCaseString); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/UUIDGeneratorTest.php b/tests/Doctrine/Tests/ORM/Functional/UUIDGeneratorTest.php index ff352ba1f11..a1e9ad92d76 100644 --- a/tests/Doctrine/Tests/ORM/Functional/UUIDGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/UUIDGeneratorTest.php @@ -1,5 +1,9 @@ _em->getConnection()->getDatabasePlatform()->getName() != 'mysql') { + if ($this->em->getConnection()->getDatabasePlatform()->getName() != 'mysql') { $this->markTestSkipped('Currently restricted to MySQL platform.'); } - $this->_schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(UUIDEntity::class) + $this->em->getClassMetadata(UUIDEntity::class) ] ); } @@ -26,18 +30,18 @@ public function testGenerateUUID() { $entity = new UUIDEntity(); - $this->_em->persist($entity); - $this->assertNotNull($entity->getId()); - $this->assertTrue(strlen($entity->getId()) > 0); + $this->em->persist($entity); + self::assertNotNull($entity->getId()); + self::assertTrue(strlen($entity->getId()) > 0); } } /** - * @Entity + * @ORM\Entity */ class UUIDEntity { - /** @Id @Column(type="string") @GeneratedValue(strategy="UUID") */ + /** @ORM\Id @ORM\Column(type="string") @ORM\GeneratedValue(strategy="UUID") */ private $id; /** * Get id. diff --git a/tests/Doctrine/Tests/ORM/Functional/UnitOfWorkLifecycleTest.php b/tests/Doctrine/Tests/ORM/Functional/UnitOfWorkLifecycleTest.php index 8c4c500e728..d11f4707825 100644 --- a/tests/Doctrine/Tests/ORM/Functional/UnitOfWorkLifecycleTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/UnitOfWorkLifecycleTest.php @@ -1,5 +1,7 @@ username = "beberlei"; $user->name = "Benjamin"; $user->status = "active"; - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); $this->expectException(ORMInvalidArgumentException::class); $this->expectExceptionMessage('A managed+dirty entity Doctrine\Tests\Models\CMS\CmsUser'); - $this->_em->getUnitOfWork()->scheduleForInsert($user); + $this->em->getUnitOfWork()->scheduleForInsert($user); } public function testScheduleInsertDeleted() @@ -35,15 +37,15 @@ public function testScheduleInsertDeleted() $user->username = "beberlei"; $user->name = "Benjamin"; $user->status = "active"; - $this->_em->persist($user); - $this->_em->flush(); + $this->em->persist($user); + $this->em->flush(); - $this->_em->remove($user); + $this->em->remove($user); $this->expectException(ORMInvalidArgumentException::class); $this->expectExceptionMessage('Removed entity Doctrine\Tests\Models\CMS\CmsUser'); - $this->_em->getUnitOfWork()->scheduleForInsert($user); + $this->em->getUnitOfWork()->scheduleForInsert($user); } public function testScheduleInsertTwice() @@ -53,12 +55,12 @@ public function testScheduleInsertTwice() $user->name = "Benjamin"; $user->status = "active"; - $this->_em->getUnitOfWork()->scheduleForInsert($user); + $this->em->getUnitOfWork()->scheduleForInsert($user); $this->expectException(ORMInvalidArgumentException::class); $this->expectExceptionMessage('Entity Doctrine\Tests\Models\CMS\CmsUser'); - $this->_em->getUnitOfWork()->scheduleForInsert($user); + $this->em->getUnitOfWork()->scheduleForInsert($user); } public function testAddToIdentityMapWithoutIdentity() @@ -68,7 +70,7 @@ public function testAddToIdentityMapWithoutIdentity() $this->expectException(ORMInvalidArgumentException::class); $this->expectExceptionMessage("The given entity of type 'Doctrine\Tests\Models\CMS\CmsUser' (Doctrine\Tests\Models\CMS\CmsUser@"); - $this->_em->getUnitOfWork()->registerManaged($user, [], []); + $this->em->getUnitOfWork()->registerManaged($user, [], []); } public function testMarkReadOnlyNonManaged() @@ -78,6 +80,6 @@ public function testMarkReadOnlyNonManaged() $this->expectException(ORMInvalidArgumentException::class); $this->expectExceptionMessage('Only managed entities can be marked or checked as read only. But Doctrine\Tests\Models\CMS\CmsUser@'); - $this->_em->getUnitOfWork()->markReadOnly($user); + $this->em->getUnitOfWork()->markReadOnly($user); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdForeignKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdForeignKeyTest.php index 108ba743737..e5e757bd149 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdForeignKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdForeignKeyTest.php @@ -1,5 +1,7 @@ associatedEntities->add($owning); $owning->associatedEntities->add($inversed); - $this->_em->persist($auxiliary); - $this->_em->persist($inversed); - $this->_em->persist($owning); - - $this->_em->flush(); - $this->_em->clear(); - } - - public static function tearDownAfterClass() - { - $conn = static::$_sharedConn; + $this->em->persist($auxiliary); + $this->em->persist($inversed); + $this->em->persist($owning); - $conn->executeUpdate('DROP TABLE vct_xref_manytomany_compositeid_foreignkey'); - $conn->executeUpdate('DROP TABLE vct_owning_manytomany_compositeid_foreignkey'); - $conn->executeUpdate('DROP TABLE vct_inversed_manytomany_compositeid_foreignkey'); - $conn->executeUpdate('DROP TABLE vct_auxiliary'); + $this->em->flush(); + $this->em->clear(); } public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() { - $conn = $this->_em->getConnection(); + $conn = $this->em->getConnection(); - $this->assertEquals('nop', $conn->fetchColumn('SELECT id4 FROM vct_auxiliary LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT id4 FROM vct_auxiliary LIMIT 1')); - $this->assertEquals('qrs', $conn->fetchColumn('SELECT id1 FROM vct_inversed_manytomany_compositeid_foreignkey LIMIT 1')); - $this->assertEquals('nop', $conn->fetchColumn('SELECT foreign_id FROM vct_inversed_manytomany_compositeid_foreignkey LIMIT 1')); + self::assertEquals('qrs', $conn->fetchColumn('SELECT id1 FROM vct_inversed_manytomany_compositeid_foreignkey LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT foreign_id FROM vct_inversed_manytomany_compositeid_foreignkey LIMIT 1')); - $this->assertEquals('tuv', $conn->fetchColumn('SELECT id2 FROM vct_owning_manytomany_compositeid_foreignkey LIMIT 1')); + self::assertEquals('tuv', $conn->fetchColumn('SELECT id2 FROM vct_owning_manytomany_compositeid_foreignkey LIMIT 1')); - $this->assertEquals('qrs', $conn->fetchColumn('SELECT associated_id FROM vct_xref_manytomany_compositeid_foreignkey LIMIT 1')); - $this->assertEquals('nop', $conn->fetchColumn('SELECT associated_foreign_id FROM vct_xref_manytomany_compositeid_foreignkey LIMIT 1')); - $this->assertEquals('tuv', $conn->fetchColumn('SELECT owning_id FROM vct_xref_manytomany_compositeid_foreignkey LIMIT 1')); + self::assertEquals('qrs', $conn->fetchColumn('SELECT associated_id FROM vct_xref_manytomany_compositeid_foreignkey LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT associated_foreign_id FROM vct_xref_manytomany_compositeid_foreignkey LIMIT 1')); + self::assertEquals('tuv', $conn->fetchColumn('SELECT owning_id FROM vct_xref_manytomany_compositeid_foreignkey LIMIT 1')); } - /** - * @depends testThatTheValueOfIdentifiersAreConvertedInTheDatabase - */ public function testThatEntitiesAreFetchedFromTheDatabase() { - $auxiliary = $this->_em->find( - Models\ValueConversionType\AuxiliaryEntity::class, - 'abc' - ); + $auxiliary = $this->em->find(Entity\AuxiliaryEntity::class, 'abc'); - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity::class, + $inversed = $this->em->find( + Entity\InversedManyToManyCompositeIdForeignKeyEntity::class, ['id1' => 'def', 'foreignEntity' => 'abc'] ); - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToManyCompositeIdForeignKeyEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningManyToManyCompositeIdForeignKeyEntity::class, 'ghi'); - $this->assertInstanceOf(Models\ValueConversionType\AuxiliaryEntity::class, $auxiliary); - $this->assertInstanceOf(Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity::class, $inversed); - $this->assertInstanceOf(Models\ValueConversionType\OwningManyToManyCompositeIdForeignKeyEntity::class, $owning); + self::assertInstanceOf(Entity\AuxiliaryEntity::class, $auxiliary); + self::assertInstanceOf(Entity\InversedManyToManyCompositeIdForeignKeyEntity::class, $inversed); + self::assertInstanceOf(Entity\OwningManyToManyCompositeIdForeignKeyEntity::class, $owning); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { - $auxiliary = $this->_em->find( - Models\ValueConversionType\AuxiliaryEntity::class, - 'abc' - ); + $auxiliary = $this->em->find(Entity\AuxiliaryEntity::class, 'abc'); - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity::class, + $inversed = $this->em->find( + Entity\InversedManyToManyCompositeIdForeignKeyEntity::class, ['id1' => 'def', 'foreignEntity' => 'abc'] ); - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToManyCompositeIdForeignKeyEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningManyToManyCompositeIdForeignKeyEntity::class, 'ghi'); - $this->assertEquals('abc', $auxiliary->id4); - $this->assertEquals('def', $inversed->id1); - $this->assertEquals('abc', $inversed->foreignEntity->id4); - $this->assertEquals('ghi', $owning->id2); + self::assertEquals('abc', $auxiliary->id4); + self::assertEquals('def', $inversed->id1); + self::assertEquals('abc', $inversed->foreignEntity->id4); + self::assertEquals('ghi', $owning->id2); } - /** - * @depends testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase - */ public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEntityAsId() { - $auxiliary = $this->_em->find( - Models\ValueConversionType\AuxiliaryEntity::class, - 'abc' - ); + $auxiliary = $this->em->find(Entity\AuxiliaryEntity::class, 'abc'); - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity::class, + $inversed = $this->em->find( + Entity\InversedManyToManyCompositeIdForeignKeyEntity::class, ['id1' => 'def', 'foreignEntity' => $auxiliary] ); - $this->assertInstanceOf(Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity::class, $inversed); + self::assertInstanceOf(Entity\InversedManyToManyCompositeIdForeignKeyEntity::class, $inversed); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheCollectionFromOwningToInversedIsLoaded() { - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToManyCompositeIdForeignKeyEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningManyToManyCompositeIdForeignKeyEntity::class, 'ghi'); - $this->assertCount(1, $owning->associatedEntities); + self::assertCount(1, $owning->associatedEntities); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheCollectionFromInversedToOwningIsLoaded() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity::class, + $inversed = $this->em->find( + Entity\InversedManyToManyCompositeIdForeignKeyEntity::class, ['id1' => 'def', 'foreignEntity' => 'abc'] ); - $this->assertCount(1, $inversed->associatedEntities); + self::assertCount(1, $inversed->associatedEntities); } - /** - * @depends testThatTheCollectionFromOwningToInversedIsLoaded - * @depends testThatTheCollectionFromInversedToOwningIsLoaded - */ public function testThatTheJoinTableRowsAreRemovedWhenRemovingTheAssociation() { - $conn = $this->_em->getConnection(); + $conn = $this->em->getConnection(); // remove association - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity::class, + $inversed = $this->em->find( + Entity\InversedManyToManyCompositeIdForeignKeyEntity::class, ['id1' => 'def', 'foreignEntity' => 'abc'] ); @@ -185,11 +140,11 @@ public function testThatTheJoinTableRowsAreRemovedWhenRemovingTheAssociation() $owning->associatedEntities->removeElement($inversed); } - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); // test association is removed - $this->assertEquals(0, $conn->fetchColumn('SELECT COUNT(*) FROM vct_xref_manytomany_compositeid_foreignkey')); + self::assertEquals(0, $conn->fetchColumn('SELECT COUNT(*) FROM vct_xref_manytomany_compositeid_foreignkey')); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdTest.php index 4403f2bf959..76841e98b5e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdTest.php @@ -1,5 +1,7 @@ associatedEntities->add($owning); $owning->associatedEntities->add($inversed); - $this->_em->persist($inversed); - $this->_em->persist($owning); - - $this->_em->flush(); - $this->_em->clear(); - } - - public static function tearDownAfterClass() - { - $conn = static::$_sharedConn; + $this->em->persist($inversed); + $this->em->persist($owning); - $conn->executeUpdate('DROP TABLE vct_xref_manytomany_compositeid'); - $conn->executeUpdate('DROP TABLE vct_owning_manytomany_compositeid'); - $conn->executeUpdate('DROP TABLE vct_inversed_manytomany_compositeid'); + $this->em->flush(); + $this->em->clear(); } public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() { - $conn = $this->_em->getConnection(); + $conn = $this->em->getConnection(); - $this->assertEquals('nop', $conn->fetchColumn('SELECT id1 FROM vct_inversed_manytomany_compositeid LIMIT 1')); - $this->assertEquals('qrs', $conn->fetchColumn('SELECT id2 FROM vct_inversed_manytomany_compositeid LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT id1 FROM vct_inversed_manytomany_compositeid LIMIT 1')); + self::assertEquals('qrs', $conn->fetchColumn('SELECT id2 FROM vct_inversed_manytomany_compositeid LIMIT 1')); - $this->assertEquals('tuv', $conn->fetchColumn('SELECT id3 FROM vct_owning_manytomany_compositeid LIMIT 1')); + self::assertEquals('tuv', $conn->fetchColumn('SELECT id3 FROM vct_owning_manytomany_compositeid LIMIT 1')); - $this->assertEquals('nop', $conn->fetchColumn('SELECT inversed_id1 FROM vct_xref_manytomany_compositeid LIMIT 1')); - $this->assertEquals('qrs', $conn->fetchColumn('SELECT inversed_id2 FROM vct_xref_manytomany_compositeid LIMIT 1')); - $this->assertEquals('tuv', $conn->fetchColumn('SELECT owning_id FROM vct_xref_manytomany_compositeid LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT inversed_id1 FROM vct_xref_manytomany_compositeid LIMIT 1')); + self::assertEquals('qrs', $conn->fetchColumn('SELECT inversed_id2 FROM vct_xref_manytomany_compositeid LIMIT 1')); + self::assertEquals('tuv', $conn->fetchColumn('SELECT owning_id FROM vct_xref_manytomany_compositeid LIMIT 1')); } - /** - * @depends testThatTheValueOfIdentifiersAreConvertedInTheDatabase - */ public function testThatEntitiesAreFetchedFromTheDatabase() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyCompositeIdEntity::class, + $inversed = $this->em->find( + Entity\InversedManyToManyCompositeIdEntity::class, ['id1' => 'abc', 'id2' => 'def'] ); - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToManyCompositeIdEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningManyToManyCompositeIdEntity::class, 'ghi'); - $this->assertInstanceOf(Models\ValueConversionType\InversedManyToManyCompositeIdEntity::class, $inversed); - $this->assertInstanceOf(Models\ValueConversionType\OwningManyToManyCompositeIdEntity::class, $owning); + self::assertInstanceOf(Entity\InversedManyToManyCompositeIdEntity::class, $inversed); + self::assertInstanceOf(Entity\OwningManyToManyCompositeIdEntity::class, $owning); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyCompositeIdEntity::class, + $inversed = $this->em->find( + Entity\InversedManyToManyCompositeIdEntity::class, ['id1' => 'abc', 'id2' => 'def'] ); - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToManyCompositeIdEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningManyToManyCompositeIdEntity::class, 'ghi'); - $this->assertEquals('abc', $inversed->id1); - $this->assertEquals('def', $inversed->id2); - $this->assertEquals('ghi', $owning->id3); + self::assertEquals('abc', $inversed->id1); + self::assertEquals('def', $inversed->id2); + self::assertEquals('ghi', $owning->id3); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheCollectionFromOwningToInversedIsLoaded() { - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToManyCompositeIdEntity::class, + $owning = $this->em->find( + Entity\OwningManyToManyCompositeIdEntity::class, 'ghi' ); - $this->assertCount(1, $owning->associatedEntities); + self::assertCount(1, $owning->associatedEntities); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheCollectionFromInversedToOwningIsLoaded() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyCompositeIdEntity::class, + $inversed = $this->em->find( + Entity\InversedManyToManyCompositeIdEntity::class, ['id1' => 'abc', 'id2' => 'def'] ); - $this->assertCount(1, $inversed->associatedEntities); + self::assertCount(1, $inversed->associatedEntities); } - /** - * @depends testThatTheCollectionFromOwningToInversedIsLoaded - * @depends testThatTheCollectionFromInversedToOwningIsLoaded - */ public function testThatTheJoinTableRowsAreRemovedWhenRemovingTheAssociation() { - $conn = $this->_em->getConnection(); + $conn = $this->em->getConnection(); // remove association - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyCompositeIdEntity::class, + $inversed = $this->em->find( + Entity\InversedManyToManyCompositeIdEntity::class, ['id1' => 'abc', 'id2' => 'def'] ); @@ -147,11 +118,11 @@ public function testThatTheJoinTableRowsAreRemovedWhenRemovingTheAssociation() $owning->associatedEntities->removeElement($inversed); } - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); // test association is removed - $this->assertEquals(0, $conn->fetchColumn('SELECT COUNT(*) FROM vct_xref_manytomany_compositeid')); + self::assertEquals(0, $conn->fetchColumn('SELECT COUNT(*) FROM vct_xref_manytomany_compositeid')); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyExtraLazyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyExtraLazyTest.php index af1d99de3f9..26c63ff653e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyExtraLazyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyExtraLazyTest.php @@ -1,5 +1,7 @@ useModelSet('vct_manytomany_extralazy'); + parent::setUp(); $inversed1 = new Entity\InversedManyToManyExtraLazyEntity(); @@ -44,111 +47,70 @@ public function setUp() $inversed2->associatedEntities->add($owning2); $owning2->associatedEntities->add($inversed2); - $this->_em->persist($inversed1); - $this->_em->persist($inversed2); - $this->_em->persist($owning1); - $this->_em->persist($owning2); - - $this->_em->flush(); - $this->_em->clear(); - } - - public static function tearDownAfterClass() - { - $conn = static::$_sharedConn; + $this->em->persist($inversed1); + $this->em->persist($inversed2); + $this->em->persist($owning1); + $this->em->persist($owning2); - $conn->executeUpdate('DROP TABLE vct_xref_manytomany_extralazy'); - $conn->executeUpdate('DROP TABLE vct_owning_manytomany_extralazy'); - $conn->executeUpdate('DROP TABLE vct_inversed_manytomany_extralazy'); + $this->em->flush(); + $this->em->clear(); } public function testThatTheExtraLazyCollectionFromOwningToInversedIsCounted() { - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToManyExtraLazyEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningManyToManyExtraLazyEntity::class, 'ghi'); - $this->assertEquals(2, $owning->associatedEntities->count()); + self::assertEquals(2, $owning->associatedEntities->count()); } public function testThatTheExtraLazyCollectionFromInversedToOwningIsCounted() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyExtraLazyEntity::class, - 'abc' - ); + $inversed = $this->em->find(Entity\InversedManyToManyExtraLazyEntity::class, 'abc'); - $this->assertEquals(2, $inversed->associatedEntities->count()); + self::assertEquals(2, $inversed->associatedEntities->count()); } public function testThatTheExtraLazyCollectionFromOwningToInversedContainsAnEntity() { - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToManyExtraLazyEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningManyToManyExtraLazyEntity::class, 'ghi'); + $inversed = $this->em->find(Entity\InversedManyToManyExtraLazyEntity::class, 'abc'); - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyExtraLazyEntity::class, - 'abc' - ); - - $this->assertTrue($owning->associatedEntities->contains($inversed)); + self::assertTrue($owning->associatedEntities->contains($inversed)); } public function testThatTheExtraLazyCollectionFromInversedToOwningContainsAnEntity() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyExtraLazyEntity::class, - 'abc' - ); - - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToManyExtraLazyEntity::class, - 'ghi' - ); + $inversed = $this->em->find(Entity\InversedManyToManyExtraLazyEntity::class, 'abc'); + $owning = $this->em->find(Entity\OwningManyToManyExtraLazyEntity::class, 'ghi'); - $this->assertTrue($inversed->associatedEntities->contains($owning)); + self::assertTrue($inversed->associatedEntities->contains($owning)); } public function testThatTheExtraLazyCollectionFromOwningToInversedContainsAnIndexByKey() { - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToManyExtraLazyEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningManyToManyExtraLazyEntity::class, 'ghi'); - $this->assertTrue($owning->associatedEntities->containsKey('abc')); + self::assertTrue($owning->associatedEntities->containsKey('abc')); } public function testThatTheExtraLazyCollectionFromInversedToOwningContainsAnIndexByKey() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyExtraLazyEntity::class, - 'abc' - ); + $inversed = $this->em->find(Entity\InversedManyToManyExtraLazyEntity::class, 'abc'); - $this->assertTrue($inversed->associatedEntities->containsKey('ghi')); + self::assertTrue($inversed->associatedEntities->containsKey('ghi')); } public function testThatASliceOfTheExtraLazyCollectionFromOwningToInversedIsLoaded() { - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToManyExtraLazyEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningManyToManyExtraLazyEntity::class, 'ghi'); - $this->assertCount(1, $owning->associatedEntities->slice(0, 1)); + self::assertCount(1, $owning->associatedEntities->slice(0, 1)); } public function testThatASliceOfTheExtraLazyCollectionFromInversedToOwningIsLoaded() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyExtraLazyEntity::class, - 'abc' - ); + $inversed = $this->em->find(Entity\InversedManyToManyExtraLazyEntity::class, 'abc'); - $this->assertCount(1, $inversed->associatedEntities->slice(1, 1)); + self::assertCount(1, $inversed->associatedEntities->slice(1, 1)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyTest.php index 4532ee9d5fc..ba341104273 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyTest.php @@ -1,5 +1,7 @@ associatedEntities->add($owning); $owning->associatedEntities->add($inversed); - $this->_em->persist($inversed); - $this->_em->persist($owning); + $this->em->persist($inversed); + $this->em->persist($owning); - $this->_em->flush(); - $this->_em->clear(); - } - - public static function tearDownAfterClass() - { - $conn = static::$_sharedConn; - - $conn->executeUpdate('DROP TABLE vct_xref_manytomany'); - $conn->executeUpdate('DROP TABLE vct_owning_manytomany'); - $conn->executeUpdate('DROP TABLE vct_inversed_manytomany'); + $this->em->flush(); + $this->em->clear(); } public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() { - $conn = $this->_em->getConnection(); + $conn = $this->em->getConnection(); - $this->assertEquals('nop', $conn->fetchColumn('SELECT id1 FROM vct_inversed_manytomany LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT id1 FROM vct_inversed_manytomany LIMIT 1')); - $this->assertEquals('qrs', $conn->fetchColumn('SELECT id2 FROM vct_owning_manytomany LIMIT 1')); + self::assertEquals('qrs', $conn->fetchColumn('SELECT id2 FROM vct_owning_manytomany LIMIT 1')); - $this->assertEquals('nop', $conn->fetchColumn('SELECT inversed_id FROM vct_xref_manytomany LIMIT 1')); - $this->assertEquals('qrs', $conn->fetchColumn('SELECT owning_id FROM vct_xref_manytomany LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT inversed_id FROM vct_xref_manytomany LIMIT 1')); + self::assertEquals('qrs', $conn->fetchColumn('SELECT owning_id FROM vct_xref_manytomany LIMIT 1')); } - /** - * @depends testThatTheValueOfIdentifiersAreConvertedInTheDatabase - */ public function testThatEntitiesAreFetchedFromTheDatabase() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyEntity::class, - 'abc' - ); - - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToManyEntity::class, - 'def' - ); - - $this->assertInstanceOf(Models\ValueConversionType\InversedManyToManyEntity::class, $inversed); - $this->assertInstanceOf(Models\ValueConversionType\OwningManyToManyEntity::class, $owning); + $inversed = $this->em->find(Entity\InversedManyToManyEntity::class, 'abc'); + $owning = $this->em->find(Entity\OwningManyToManyEntity::class, 'def'); + + self::assertInstanceOf(Entity\InversedManyToManyEntity::class, $inversed); + self::assertInstanceOf(Entity\OwningManyToManyEntity::class, $owning); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyEntity::class, - 'abc' - ); - - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToManyEntity::class, - 'def' - ); - - $this->assertEquals('abc', $inversed->id1); - $this->assertEquals('def', $owning->id2); + $inversed = $this->em->find(Entity\InversedManyToManyEntity::class, 'abc'); + $owning = $this->em->find(Entity\OwningManyToManyEntity::class, 'def'); + + self::assertEquals('abc', $inversed->id1); + self::assertEquals('def', $owning->id2); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheCollectionFromOwningToInversedIsLoaded() { - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToManyEntity::class, - 'def' - ); + $owning = $this->em->find(Entity\OwningManyToManyEntity::class, 'def'); - $this->assertCount(1, $owning->associatedEntities); + self::assertCount(1, $owning->associatedEntities); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheCollectionFromInversedToOwningIsLoaded() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyEntity::class, - 'abc' - ); + $inversed = $this->em->find(Entity\InversedManyToManyEntity::class, 'abc'); - $this->assertCount(1, $inversed->associatedEntities); + self::assertCount(1, $inversed->associatedEntities); } - /** - * @depends testThatTheCollectionFromOwningToInversedIsLoaded - * @depends testThatTheCollectionFromInversedToOwningIsLoaded - */ public function testThatTheJoinTableRowsAreRemovedWhenRemovingTheAssociation() { - $conn = $this->_em->getConnection(); + $conn = $this->em->getConnection(); // remove association - $inversed = $this->_em->find( - Models\ValueConversionType\InversedManyToManyEntity::class, - 'abc' - ); + $inversed = $this->em->find(Entity\InversedManyToManyEntity::class, 'abc'); foreach ($inversed->associatedEntities as $owning) { $inversed->associatedEntities->removeElement($owning); $owning->associatedEntities->removeElement($inversed); } - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); // test association is removed - $this->assertEquals(0, $conn->fetchColumn('SELECT COUNT(*) FROM vct_xref_manytomany')); + self::assertEquals(0, $conn->fetchColumn('SELECT COUNT(*) FROM vct_xref_manytomany')); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdForeignKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdForeignKeyTest.php index b76687bc4b3..83136923d71 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdForeignKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdForeignKeyTest.php @@ -1,5 +1,7 @@ associatedEntities->add($owning); $owning->associatedEntity = $inversed; - $this->_em->persist($auxiliary); - $this->_em->persist($inversed); - $this->_em->persist($owning); - - $this->_em->flush(); - $this->_em->clear(); - } - - public static function tearDownAfterClass() - { - $conn = static::$_sharedConn; + $this->em->persist($auxiliary); + $this->em->persist($inversed); + $this->em->persist($owning); - $conn->executeUpdate('DROP TABLE vct_owning_manytoone_compositeid_foreignkey'); - $conn->executeUpdate('DROP TABLE vct_inversed_onetomany_compositeid_foreignkey'); - $conn->executeUpdate('DROP TABLE vct_auxiliary'); + $this->em->flush(); + $this->em->clear(); } public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() { - $conn = $this->_em->getConnection(); + $conn = $this->em->getConnection(); - $this->assertEquals('nop', $conn->fetchColumn('SELECT id4 FROM vct_auxiliary LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT id4 FROM vct_auxiliary LIMIT 1')); - $this->assertEquals('qrs', $conn->fetchColumn('SELECT id1 FROM vct_inversed_onetomany_compositeid_foreignkey LIMIT 1')); - $this->assertEquals('nop', $conn->fetchColumn('SELECT foreign_id FROM vct_inversed_onetomany_compositeid_foreignkey LIMIT 1')); + self::assertEquals('qrs', $conn->fetchColumn('SELECT id1 FROM vct_inversed_onetomany_compositeid_foreignkey LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT foreign_id FROM vct_inversed_onetomany_compositeid_foreignkey LIMIT 1')); - $this->assertEquals('tuv', $conn->fetchColumn('SELECT id2 FROM vct_owning_manytoone_compositeid_foreignkey LIMIT 1')); - $this->assertEquals('qrs', $conn->fetchColumn('SELECT associated_id FROM vct_owning_manytoone_compositeid_foreignkey LIMIT 1')); - $this->assertEquals('nop', $conn->fetchColumn('SELECT associated_foreign_id FROM vct_owning_manytoone_compositeid_foreignkey LIMIT 1')); + self::assertEquals('tuv', $conn->fetchColumn('SELECT id2 FROM vct_owning_manytoone_compositeid_foreignkey LIMIT 1')); + self::assertEquals('qrs', $conn->fetchColumn('SELECT associated_id FROM vct_owning_manytoone_compositeid_foreignkey LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT associated_foreign_id FROM vct_owning_manytoone_compositeid_foreignkey LIMIT 1')); } - /** - * @depends testThatTheValueOfIdentifiersAreConvertedInTheDatabase - */ public function testThatEntitiesAreFetchedFromTheDatabase() { - $auxiliary = $this->_em->find( - Models\ValueConversionType\AuxiliaryEntity::class, - 'abc' - ); + $auxiliary = $this->em->find(Entity\AuxiliaryEntity::class, 'abc'); - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity::class, + $inversed = $this->em->find( + Entity\InversedOneToManyCompositeIdForeignKeyEntity::class, ['id1' => 'def', 'foreignEntity' => 'abc'] ); - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToOneCompositeIdForeignKeyEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningManyToOneCompositeIdForeignKeyEntity::class, 'ghi'); - $this->assertInstanceOf(Models\ValueConversionType\AuxiliaryEntity::class, $auxiliary); - $this->assertInstanceOf(Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity::class, $inversed); - $this->assertInstanceOf(Models\ValueConversionType\OwningManyToOneCompositeIdForeignKeyEntity::class, $owning); + self::assertInstanceOf(Entity\AuxiliaryEntity::class, $auxiliary); + self::assertInstanceOf(Entity\InversedOneToManyCompositeIdForeignKeyEntity::class, $inversed); + self::assertInstanceOf(Entity\OwningManyToOneCompositeIdForeignKeyEntity::class, $owning); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { - $auxiliary = $this->_em->find( - Models\ValueConversionType\AuxiliaryEntity::class, - 'abc' - ); + $auxiliary = $this->em->find(Entity\AuxiliaryEntity::class, 'abc'); - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity::class, + $inversed = $this->em->find( + Entity\InversedOneToManyCompositeIdForeignKeyEntity::class, ['id1' => 'def', 'foreignEntity' => 'abc'] ); - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToOneCompositeIdForeignKeyEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningManyToOneCompositeIdForeignKeyEntity::class, 'ghi'); - $this->assertEquals('abc', $auxiliary->id4); - $this->assertEquals('def', $inversed->id1); - $this->assertEquals('abc', $inversed->foreignEntity->id4); - $this->assertEquals('ghi', $owning->id2); + self::assertEquals('abc', $auxiliary->id4); + self::assertEquals('def', $inversed->id1); + self::assertEquals('abc', $inversed->foreignEntity->id4); + self::assertEquals('ghi', $owning->id2); } - /** - * @depends testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase - */ public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEntityAsId() { - $auxiliary = $this->_em->find( - Models\ValueConversionType\AuxiliaryEntity::class, - 'abc' - ); + $auxiliary = $this->em->find(Entity\AuxiliaryEntity::class, 'abc'); - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity::class, + $inversed = $this->em->find( + Entity\InversedOneToManyCompositeIdForeignKeyEntity::class, ['id1' => 'def', 'foreignEntity' => $auxiliary] ); - $this->assertInstanceOf(Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity::class, $inversed); + self::assertInstanceOf(Entity\InversedOneToManyCompositeIdForeignKeyEntity::class, $inversed); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheProxyFromOwningToInversedIsLoaded() { - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToOneCompositeIdForeignKeyEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningManyToOneCompositeIdForeignKeyEntity::class, 'ghi'); $inversedProxy = $owning->associatedEntity; - $this->assertSame('def', $inversedProxy->id1, 'Proxy identifier is converted'); + self::assertSame('def', $inversedProxy->id1, 'Proxy identifier is converted'); - $this->assertEquals('some value to be loaded', $inversedProxy->someProperty); + self::assertEquals('some value to be loaded', $inversedProxy->someProperty); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheCollectionFromInversedToOwningIsLoaded() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity::class, + $inversed = $this->em->find( + Entity\InversedOneToManyCompositeIdForeignKeyEntity::class, ['id1' => 'def', 'foreignEntity' => 'abc'] ); - $this->assertCount(1, $inversed->associatedEntities); + self::assertCount(1, $inversed->associatedEntities); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdTest.php index 266a382e760..0845da1dc6a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdTest.php @@ -1,5 +1,7 @@ associatedEntities->add($owning); $owning->associatedEntity = $inversed; - $this->_em->persist($inversed); - $this->_em->persist($owning); - - $this->_em->flush(); - $this->_em->clear(); - } - - public static function tearDownAfterClass() - { - $conn = static::$_sharedConn; + $this->em->persist($inversed); + $this->em->persist($owning); - $conn->executeUpdate('DROP TABLE vct_owning_manytoone_compositeid'); - $conn->executeUpdate('DROP TABLE vct_inversed_onetomany_compositeid'); + $this->em->flush(); + $this->em->clear(); } public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() { - $conn = $this->_em->getConnection(); + $conn = $this->em->getConnection(); - $this->assertEquals('nop', $conn->fetchColumn('SELECT id1 FROM vct_inversed_onetomany_compositeid LIMIT 1')); - $this->assertEquals('qrs', $conn->fetchColumn('SELECT id2 FROM vct_inversed_onetomany_compositeid LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT id1 FROM vct_inversed_onetomany_compositeid LIMIT 1')); + self::assertEquals('qrs', $conn->fetchColumn('SELECT id2 FROM vct_inversed_onetomany_compositeid LIMIT 1')); - $this->assertEquals('tuv', $conn->fetchColumn('SELECT id3 FROM vct_owning_manytoone_compositeid LIMIT 1')); - $this->assertEquals('nop', $conn->fetchColumn('SELECT associated_id1 FROM vct_owning_manytoone_compositeid LIMIT 1')); - $this->assertEquals('qrs', $conn->fetchColumn('SELECT associated_id2 FROM vct_owning_manytoone_compositeid LIMIT 1')); + self::assertEquals('tuv', $conn->fetchColumn('SELECT id3 FROM vct_owning_manytoone_compositeid LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT associated_id1 FROM vct_owning_manytoone_compositeid LIMIT 1')); + self::assertEquals('qrs', $conn->fetchColumn('SELECT associated_id2 FROM vct_owning_manytoone_compositeid LIMIT 1')); } - /** - * @depends testThatTheValueOfIdentifiersAreConvertedInTheDatabase - */ public function testThatEntitiesAreFetchedFromTheDatabase() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToManyCompositeIdEntity::class, + $inversed = $this->em->find( + Entity\InversedOneToManyCompositeIdEntity::class, ['id1' => 'abc', 'id2' => 'def'] ); - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToOneCompositeIdEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningManyToOneCompositeIdEntity::class, 'ghi'); - $this->assertInstanceOf(Models\ValueConversionType\InversedOneToManyCompositeIdEntity::class, $inversed); - $this->assertInstanceOf(Models\ValueConversionType\OwningManyToOneCompositeIdEntity::class, $owning); + self::assertInstanceOf(Entity\InversedOneToManyCompositeIdEntity::class, $inversed); + self::assertInstanceOf(Entity\OwningManyToOneCompositeIdEntity::class, $owning); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToManyCompositeIdEntity::class, + $inversed = $this->em->find( + Entity\InversedOneToManyCompositeIdEntity::class, ['id1' => 'abc', 'id2' => 'def'] ); - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToOneCompositeIdEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningManyToOneCompositeIdEntity::class, 'ghi'); - $this->assertEquals('abc', $inversed->id1); - $this->assertEquals('def', $inversed->id2); - $this->assertEquals('ghi', $owning->id3); + self::assertEquals('abc', $inversed->id1); + self::assertEquals('def', $inversed->id2); + self::assertEquals('ghi', $owning->id3); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheProxyFromOwningToInversedIsLoaded() { - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToOneCompositeIdEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningManyToOneCompositeIdEntity::class, 'ghi'); $inversedProxy = $owning->associatedEntity; - $this->assertEquals('some value to be loaded', $inversedProxy->someProperty); + self::assertEquals('some value to be loaded', $inversedProxy->someProperty); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheCollectionFromInversedToOwningIsLoaded() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToManyCompositeIdEntity::class, + $inversed = $this->em->find( + Entity\InversedOneToManyCompositeIdEntity::class, ['id1' => 'abc', 'id2' => 'def'] ); - $this->assertCount(1, $inversed->associatedEntities); + self::assertCount(1, $inversed->associatedEntities); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyExtraLazyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyExtraLazyTest.php index 9da341467a4..4657eeece3b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyExtraLazyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyExtraLazyTest.php @@ -1,5 +1,7 @@ associatedEntities->add($owning3); $owning3->associatedEntity = $inversed; - $this->_em->persist($inversed); - $this->_em->persist($owning1); - $this->_em->persist($owning2); - $this->_em->persist($owning3); - - $this->_em->flush(); - $this->_em->clear(); - } - - public static function tearDownAfterClass() - { - $conn = static::$_sharedConn; + $this->em->persist($inversed); + $this->em->persist($owning1); + $this->em->persist($owning2); + $this->em->persist($owning3); - $conn->executeUpdate('DROP TABLE vct_owning_manytoone_extralazy'); - $conn->executeUpdate('DROP TABLE vct_inversed_onetomany_extralazy'); + $this->em->flush(); + $this->em->clear(); } public function testThatExtraLazyCollectionIsCounted() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToManyExtraLazyEntity::class, - 'abc' - ); + $inversed = $this->em->find(Entity\InversedOneToManyExtraLazyEntity::class, 'abc'); - $this->assertEquals(3, $inversed->associatedEntities->count()); + self::assertEquals(3, $inversed->associatedEntities->count()); } public function testThatExtraLazyCollectionContainsAnEntity() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToManyExtraLazyEntity::class, - 'abc' - ); - - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToOneExtraLazyEntity::class, - 'def' - ); + $inversed = $this->em->find(Entity\InversedOneToManyExtraLazyEntity::class, 'abc'); + $owning = $this->em->find(Entity\OwningManyToOneExtraLazyEntity::class, 'def'); - $this->assertTrue($inversed->associatedEntities->contains($owning)); + self::assertTrue($inversed->associatedEntities->contains($owning)); } public function testThatExtraLazyCollectionContainsAnIndexbyKey() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToManyExtraLazyEntity::class, - 'abc' - ); + $inversed = $this->em->find(Entity\InversedOneToManyExtraLazyEntity::class, 'abc'); - $this->assertTrue($inversed->associatedEntities->containsKey('def')); + self::assertTrue($inversed->associatedEntities->containsKey('def')); } public function testThatASliceOfTheExtraLazyCollectionIsLoaded() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToManyExtraLazyEntity::class, - 'abc' - ); + $inversed = $this->em->find(Entity\InversedOneToManyExtraLazyEntity::class, 'abc'); - $this->assertCount(2, $inversed->associatedEntities->slice(0, 2)); + self::assertCount(2, $inversed->associatedEntities->slice(0, 2)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyTest.php index 6a10296a7f9..3565e26a670 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyTest.php @@ -1,5 +1,7 @@ associatedEntities->add($owning); $owning->associatedEntity = $inversed; - $this->_em->persist($inversed); - $this->_em->persist($owning); + $this->em->persist($inversed); + $this->em->persist($owning); - $this->_em->flush(); - $this->_em->clear(); - } - - public static function tearDownAfterClass() - { - $conn = static::$_sharedConn; - - $conn->executeUpdate('DROP TABLE vct_owning_manytoone'); - $conn->executeUpdate('DROP TABLE vct_inversed_onetomany'); + $this->em->flush(); + $this->em->clear(); } public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() { - $conn = $this->_em->getConnection(); + $conn = $this->em->getConnection(); - $this->assertEquals('nop', $conn->fetchColumn('SELECT id1 FROM vct_inversed_onetomany LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT id1 FROM vct_inversed_onetomany LIMIT 1')); - $this->assertEquals('qrs', $conn->fetchColumn('SELECT id2 FROM vct_owning_manytoone LIMIT 1')); - $this->assertEquals('nop', $conn->fetchColumn('SELECT associated_id FROM vct_owning_manytoone LIMIT 1')); + self::assertEquals('qrs', $conn->fetchColumn('SELECT id2 FROM vct_owning_manytoone LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT associated_id FROM vct_owning_manytoone LIMIT 1')); } - /** - * @depends testThatTheValueOfIdentifiersAreConvertedInTheDatabase - */ public function testThatEntitiesAreFetchedFromTheDatabase() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToManyEntity::class, - 'abc' - ); - - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToOneEntity::class, - 'def' - ); - - $this->assertInstanceOf(Models\ValueConversionType\InversedOneToManyEntity::class, $inversed); - $this->assertInstanceOf(Models\ValueConversionType\OwningManyToOneEntity::class, $owning); + $inversed = $this->em->find(Entity\InversedOneToManyEntity::class, 'abc'); + $owning = $this->em->find(Entity\OwningManyToOneEntity::class, 'def'); + + self::assertInstanceOf(Entity\InversedOneToManyEntity::class, $inversed); + self::assertInstanceOf(Entity\OwningManyToOneEntity::class, $owning); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToManyEntity::class, - 'abc' - ); - - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToOneEntity::class, - 'def' - ); - - $this->assertEquals('abc', $inversed->id1); - $this->assertEquals('def', $owning->id2); + $inversed = $this->em->find(Entity\InversedOneToManyEntity::class, 'abc'); + $owning = $this->em->find(Entity\OwningManyToOneEntity::class, 'def'); + + self::assertEquals('abc', $inversed->id1); + self::assertEquals('def', $owning->id2); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheProxyFromOwningToInversedIsLoaded() { - $owning = $this->_em->find( - Models\ValueConversionType\OwningManyToOneEntity::class, - 'def' - ); + $owning = $this->em->find(Entity\OwningManyToOneEntity::class, 'def'); $inversedProxy = $owning->associatedEntity; - $this->assertEquals('some value to be loaded', $inversedProxy->someProperty); + self::assertEquals('some value to be loaded', $inversedProxy->someProperty); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheCollectionFromInversedToOwningIsLoaded() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToManyEntity::class, - 'abc' - ); + $inversed = $this->em->find(Entity\InversedOneToManyEntity::class, 'abc'); - $this->assertCount(1, $inversed->associatedEntities); + self::assertCount(1, $inversed->associatedEntities); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdForeignKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdForeignKeyTest.php index 206ca7e3258..26ee6e98986 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdForeignKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdForeignKeyTest.php @@ -1,5 +1,7 @@ useModelSet('vct_onetoone_compositeid_foreignkey'); + parent::setUp(); $auxiliary = new Entity\AuxiliaryEntity(); @@ -36,131 +39,88 @@ public function setUp() $inversed->associatedEntity = $owning; $owning->associatedEntity = $inversed; - $this->_em->persist($auxiliary); - $this->_em->persist($inversed); - $this->_em->persist($owning); - - $this->_em->flush(); - $this->_em->clear(); - } - - public static function tearDownAfterClass() - { - $conn = static::$_sharedConn; + $this->em->persist($auxiliary); + $this->em->persist($inversed); + $this->em->persist($owning); - $conn->executeUpdate('DROP TABLE vct_owning_onetoone_compositeid_foreignkey'); - $conn->executeUpdate('DROP TABLE vct_inversed_onetoone_compositeid_foreignkey'); - $conn->executeUpdate('DROP TABLE vct_auxiliary'); + $this->em->flush(); + $this->em->clear(); } public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() { - $conn = $this->_em->getConnection(); + $conn = $this->em->getConnection(); - $this->assertEquals('nop', $conn->fetchColumn('SELECT id4 FROM vct_auxiliary LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT id4 FROM vct_auxiliary LIMIT 1')); - $this->assertEquals('qrs', $conn->fetchColumn('SELECT id1 FROM vct_inversed_onetoone_compositeid_foreignkey LIMIT 1')); - $this->assertEquals('nop', $conn->fetchColumn('SELECT foreign_id FROM vct_inversed_onetoone_compositeid_foreignkey LIMIT 1')); + self::assertEquals('qrs', $conn->fetchColumn('SELECT id1 FROM vct_inversed_onetoone_compositeid_foreignkey LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT foreign_id FROM vct_inversed_onetoone_compositeid_foreignkey LIMIT 1')); - $this->assertEquals('tuv', $conn->fetchColumn('SELECT id2 FROM vct_owning_onetoone_compositeid_foreignkey LIMIT 1')); - $this->assertEquals('qrs', $conn->fetchColumn('SELECT associated_id FROM vct_owning_onetoone_compositeid_foreignkey LIMIT 1')); - $this->assertEquals('nop', $conn->fetchColumn('SELECT associated_foreign_id FROM vct_owning_onetoone_compositeid_foreignkey LIMIT 1')); + self::assertEquals('tuv', $conn->fetchColumn('SELECT id2 FROM vct_owning_onetoone_compositeid_foreignkey LIMIT 1')); + self::assertEquals('qrs', $conn->fetchColumn('SELECT associated_id FROM vct_owning_onetoone_compositeid_foreignkey LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT associated_foreign_id FROM vct_owning_onetoone_compositeid_foreignkey LIMIT 1')); } - /** - * @depends testThatTheValueOfIdentifiersAreConvertedInTheDatabase - */ public function testThatEntitiesAreFetchedFromTheDatabase() { - $auxiliary = $this->_em->find( - Models\ValueConversionType\AuxiliaryEntity::class, - 'abc' - ); + $auxiliary = $this->em->find(Entity\AuxiliaryEntity::class, 'abc'); - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity::class, + $inversed = $this->em->find( + Entity\InversedOneToOneCompositeIdForeignKeyEntity::class, ['id1' => 'def', 'foreignEntity' => 'abc'] ); - $owning = $this->_em->find( - Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningOneToOneCompositeIdForeignKeyEntity::class, 'ghi'); - $this->assertInstanceOf(Models\ValueConversionType\AuxiliaryEntity::class, $auxiliary); - $this->assertInstanceOf(Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity::class, $inversed); - $this->assertInstanceOf(Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity::class, $owning); + self::assertInstanceOf(Entity\AuxiliaryEntity::class, $auxiliary); + self::assertInstanceOf(Entity\InversedOneToOneCompositeIdForeignKeyEntity::class, $inversed); + self::assertInstanceOf(Entity\OwningOneToOneCompositeIdForeignKeyEntity::class, $owning); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { - $auxiliary = $this->_em->find( - Models\ValueConversionType\AuxiliaryEntity::class, - 'abc' - ); + $auxiliary = $this->em->find(Entity\AuxiliaryEntity::class, 'abc'); - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity::class, + $inversed = $this->em->find( + Entity\InversedOneToOneCompositeIdForeignKeyEntity::class, ['id1' => 'def', 'foreignEntity' => 'abc'] ); - $owning = $this->_em->find( - Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningOneToOneCompositeIdForeignKeyEntity::class, 'ghi'); - $this->assertEquals('abc', $auxiliary->id4); - $this->assertEquals('def', $inversed->id1); - $this->assertEquals('abc', $inversed->foreignEntity->id4); - $this->assertEquals('ghi', $owning->id2); + self::assertEquals('abc', $auxiliary->id4); + self::assertEquals('def', $inversed->id1); + self::assertEquals('abc', $inversed->foreignEntity->id4); + self::assertEquals('ghi', $owning->id2); } - /** - * @depends testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase - */ public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEntityAsId() { - $auxiliary = $this->_em->find( - Models\ValueConversionType\AuxiliaryEntity::class, - 'abc' - ); + $auxiliary = $this->em->find(Entity\AuxiliaryEntity::class, 'abc'); - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity::class, + $inversed = $this->em->find( + Entity\InversedOneToOneCompositeIdForeignKeyEntity::class, ['id1' => 'def', 'foreignEntity' => $auxiliary] ); - $this->assertInstanceOf(Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity::class, $inversed); + self::assertInstanceOf(Entity\InversedOneToOneCompositeIdForeignKeyEntity::class, $inversed); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheProxyFromOwningToInversedIsLoaded() { - $owning = $this->_em->find( - Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningOneToOneCompositeIdForeignKeyEntity::class, 'ghi'); $inversedProxy = $owning->associatedEntity; - $this->assertEquals('some value to be loaded', $inversedProxy->someProperty); + self::assertEquals('some value to be loaded', $inversedProxy->someProperty); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheEntityFromInversedToOwningIsEagerLoaded() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity::class, + $inversed = $this->em->find(Entity\InversedOneToOneCompositeIdForeignKeyEntity::class, ['id1' => 'def', 'foreignEntity' => 'abc'] ); - $this->assertInstanceOf(Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity::class, $inversed->associatedEntity); + self::assertInstanceOf(Entity\OwningOneToOneCompositeIdForeignKeyEntity::class, $inversed->associatedEntity); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdTest.php index 428fe80c6c5..4d5662ab96c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdTest.php @@ -1,5 +1,7 @@ useModelSet('vct_onetoone_compositeid'); + parent::setUp(); $inversed = new Entity\InversedOneToOneCompositeIdEntity(); @@ -32,31 +35,23 @@ public function setUp() $inversed->associatedEntity = $owning; $owning->associatedEntity = $inversed; - $this->_em->persist($inversed); - $this->_em->persist($owning); - - $this->_em->flush(); - $this->_em->clear(); - } - - public static function tearDownAfterClass() - { - $conn = static::$_sharedConn; + $this->em->persist($inversed); + $this->em->persist($owning); - $conn->executeUpdate('DROP TABLE vct_owning_onetoone_compositeid'); - $conn->executeUpdate('DROP TABLE vct_inversed_onetoone_compositeid'); + $this->em->flush(); + $this->em->clear(); } public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() { - $conn = $this->_em->getConnection(); + $conn = $this->em->getConnection(); - $this->assertEquals('nop', $conn->fetchColumn('SELECT id1 FROM vct_inversed_onetoone_compositeid LIMIT 1')); - $this->assertEquals('qrs', $conn->fetchColumn('SELECT id2 FROM vct_inversed_onetoone_compositeid LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT id1 FROM vct_inversed_onetoone_compositeid LIMIT 1')); + self::assertEquals('qrs', $conn->fetchColumn('SELECT id2 FROM vct_inversed_onetoone_compositeid LIMIT 1')); - $this->assertEquals('tuv', $conn->fetchColumn('SELECT id3 FROM vct_owning_onetoone_compositeid LIMIT 1')); - $this->assertEquals('nop', $conn->fetchColumn('SELECT associated_id1 FROM vct_owning_onetoone_compositeid LIMIT 1')); - $this->assertEquals('qrs', $conn->fetchColumn('SELECT associated_id2 FROM vct_owning_onetoone_compositeid LIMIT 1')); + self::assertEquals('tuv', $conn->fetchColumn('SELECT id3 FROM vct_owning_onetoone_compositeid LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT associated_id1 FROM vct_owning_onetoone_compositeid LIMIT 1')); + self::assertEquals('qrs', $conn->fetchColumn('SELECT associated_id2 FROM vct_owning_onetoone_compositeid LIMIT 1')); } /** @@ -64,18 +59,15 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() */ public function testThatEntitiesAreFetchedFromTheDatabase() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToOneCompositeIdEntity::class, + $inversed = $this->em->find( + Entity\InversedOneToOneCompositeIdEntity::class, ['id1' => 'abc', 'id2' => 'def'] ); - $owning = $this->_em->find( - Models\ValueConversionType\OwningOneToOneCompositeIdEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningOneToOneCompositeIdEntity::class, 'ghi'); - $this->assertInstanceOf(Models\ValueConversionType\InversedOneToOneCompositeIdEntity::class, $inversed); - $this->assertInstanceOf(Models\ValueConversionType\OwningOneToOneCompositeIdEntity::class, $owning); + self::assertInstanceOf(Entity\InversedOneToOneCompositeIdEntity::class, $inversed); + self::assertInstanceOf(Entity\OwningOneToOneCompositeIdEntity::class, $owning); } /** @@ -83,46 +75,34 @@ public function testThatEntitiesAreFetchedFromTheDatabase() */ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToOneCompositeIdEntity::class, + $inversed = $this->em->find( + Entity\InversedOneToOneCompositeIdEntity::class, ['id1' => 'abc', 'id2' => 'def'] ); - $owning = $this->_em->find( - Models\ValueConversionType\OwningOneToOneCompositeIdEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningOneToOneCompositeIdEntity::class, 'ghi'); - $this->assertEquals('abc', $inversed->id1); - $this->assertEquals('def', $inversed->id2); - $this->assertEquals('ghi', $owning->id3); + self::assertEquals('abc', $inversed->id1); + self::assertEquals('def', $inversed->id2); + self::assertEquals('ghi', $owning->id3); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheProxyFromOwningToInversedIsLoaded() { - $owning = $this->_em->find( - Models\ValueConversionType\OwningOneToOneCompositeIdEntity::class, - 'ghi' - ); + $owning = $this->em->find(Entity\OwningOneToOneCompositeIdEntity::class, 'ghi'); $inversedProxy = $owning->associatedEntity; - $this->assertEquals('some value to be loaded', $inversedProxy->someProperty); + self::assertEquals('some value to be loaded', $inversedProxy->someProperty); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheEntityFromInversedToOwningIsEagerLoaded() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToOneCompositeIdEntity::class, + $inversed = $this->em->find( + Entity\InversedOneToOneCompositeIdEntity::class, ['id1' => 'abc', 'id2' => 'def'] ); - $this->assertInstanceOf(Models\ValueConversionType\OwningOneToOneCompositeIdEntity::class, $inversed->associatedEntity); + self::assertInstanceOf(Entity\OwningOneToOneCompositeIdEntity::class, $inversed->associatedEntity); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneTest.php index 8ca8eebe56d..edf2364e6d4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneTest.php @@ -1,5 +1,7 @@ associatedEntity = $owning; $owning->associatedEntity = $inversed; - $this->_em->persist($inversed); - $this->_em->persist($owning); + $this->em->persist($inversed); + $this->em->persist($owning); - $this->_em->flush(); - $this->_em->clear(); - } - - public static function tearDownAfterClass() - { - $conn = static::$_sharedConn; - - $conn->executeUpdate('DROP TABLE vct_owning_onetoone'); - $conn->executeUpdate('DROP TABLE vct_inversed_onetoone'); + $this->em->flush(); + $this->em->clear(); } public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() { - $conn = $this->_em->getConnection(); + $conn = $this->em->getConnection(); - $this->assertEquals('nop', $conn->fetchColumn('SELECT id1 FROM vct_inversed_onetoone LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT id1 FROM vct_inversed_onetoone LIMIT 1')); - $this->assertEquals('qrs', $conn->fetchColumn('SELECT id2 FROM vct_owning_onetoone LIMIT 1')); - $this->assertEquals('nop', $conn->fetchColumn('SELECT associated_id FROM vct_owning_onetoone LIMIT 1')); + self::assertEquals('qrs', $conn->fetchColumn('SELECT id2 FROM vct_owning_onetoone LIMIT 1')); + self::assertEquals('nop', $conn->fetchColumn('SELECT associated_id FROM vct_owning_onetoone LIMIT 1')); } - /** - * @depends testThatTheValueOfIdentifiersAreConvertedInTheDatabase - */ public function testThatEntitiesAreFetchedFromTheDatabase() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToOneEntity::class, - 'abc' - ); - - $owning = $this->_em->find( - Models\ValueConversionType\OwningOneToOneEntity::class, - 'def' - ); - - $this->assertInstanceOf(Models\ValueConversionType\InversedOneToOneEntity::class, $inversed); - $this->assertInstanceOf(Models\ValueConversionType\OwningOneToOneEntity::class, $owning); + $inversed = $this->em->find(Entity\InversedOneToOneEntity::class, 'abc'); + $owning = $this->em->find(Entity\OwningOneToOneEntity::class, 'def'); + + self::assertInstanceOf(Entity\InversedOneToOneEntity::class, $inversed); + self::assertInstanceOf(Entity\OwningOneToOneEntity::class, $owning); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToOneEntity::class, - 'abc' - ); - - $owning = $this->_em->find( - Models\ValueConversionType\OwningOneToOneEntity::class, - 'def' - ); - - $this->assertEquals('abc', $inversed->id1); - $this->assertEquals('def', $owning->id2); + $inversed = $this->em->find(Entity\InversedOneToOneEntity::class, 'abc'); + $owning = $this->em->find(Entity\OwningOneToOneEntity::class, 'def'); + + self::assertEquals('abc', $inversed->id1); + self::assertEquals('def', $owning->id2); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheProxyFromOwningToInversedIsLoaded() { - $owning = $this->_em->find( - Models\ValueConversionType\OwningOneToOneEntity::class, - 'def' - ); + $owning = $this->em->find(Entity\OwningOneToOneEntity::class, 'def'); $inversedProxy = $owning->associatedEntity; - $this->assertEquals('some value to be loaded', $inversedProxy->someProperty); + self::assertEquals('some value to be loaded', $inversedProxy->someProperty); } - /** - * @depends testThatEntitiesAreFetchedFromTheDatabase - */ public function testThatTheEntityFromInversedToOwningIsEagerLoaded() { - $inversed = $this->_em->find( - Models\ValueConversionType\InversedOneToOneEntity::class, - 'abc' - ); + $inversed = $this->em->find(Entity\InversedOneToOneEntity::class, 'abc'); - $this->assertInstanceOf(Models\ValueConversionType\OwningOneToOneEntity::class, $inversed->associatedEntity); + self::assertInstanceOf(Entity\OwningOneToOneEntity::class, $inversed->associatedEntity); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueGeneratorsTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueGeneratorsTest.php new file mode 100644 index 00000000000..4484fc07e71 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/ValueGeneratorsTest.php @@ -0,0 +1,105 @@ +useModelSet('valueGenerators'); + parent::setUp(); + } + + public function testCompositeIdentifierWithMultipleGenerators() : void + { + $entity = new CompositeGeneratedIdentifier(); + $this->em->persist($entity); + $this->em->flush(); + + self::assertSame(FooGenerator::VALUE, $entity->getA()); + self::assertSame(BarGenerator::VALUE, $entity->getB()); + + $this->em->clear(); + + $entity = $this->getEntityManager()->find( + CompositeGeneratedIdentifier::class, + ['a' => FooGenerator::VALUE, 'b' => BarGenerator::VALUE] + ); + self::assertNotNull($entity); + } + + public function testNonIdentifierGenerators() : void + { + $entity = new NonIdentifierGenerators(); + + $this->em->persist($entity); + $this->em->flush(); + + self::assertNotNull($entity->getId()); + self::assertSame(FooGenerator::VALUE, $entity->getFoo()); + self::assertSame(BarGenerator::VALUE, $entity->getBar()); + + $this->em->clear(); + + $entity = $this->getEntityManager()->find(NonIdentifierGenerators::class, $entity->getId()); + self::assertNotNull($entity); + } + + public function testValueGeneratorsInInheritance() : void + { + $rootEntity = new InheritanceGeneratorsRoot(); + + $this->em->persist($rootEntity); + $this->em->flush(); + + $this->assertNotNull($rootEntity->getId()); + + $childAEntity = new InheritanceGeneratorsChildA(); + + $this->em->persist($childAEntity); + $this->em->flush(); + + $this->assertNotNull($childAEntity); + $this->assertSame(FooGenerator::VALUE, $childAEntity->getA()); + + $childBEntity = new InheritanceGeneratorsChildB(); + + $this->em->persist($childBEntity); + $this->em->flush(); + + $this->assertNotNull($childBEntity); + $this->assertSame(FooGenerator::VALUE, $childBEntity->getA()); + $this->assertSame(BarGenerator::VALUE, $childBEntity->getB()); + } + + public function testGeneratorsWithAssociationInIdentifier() : void + { + $entity = new AssociationIdentifier(); + + $this->em->persist($entity); + $this->em->flush(); + + $this->assertSame(FooGenerator::VALUE, $entity->getId()); + $this->assertSame(BarGenerator::VALUE, $entity->getRegular()); + + $entity = $this->em->find( + AssociationIdentifier::class, + ['id' => FooGenerator::VALUE, 'target' => AssociationIdentifierTarget::ID] + ); + + $this->assertNotNull($entity); + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueObjectsTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueObjectsTest.php index ff5de971acd..8715527be64 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueObjectsTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueObjectsTest.php @@ -1,13 +1,18 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC93Person::class), - $this->_em->getClassMetadata(DDC93Address::class), - $this->_em->getClassMetadata(DDC93Vehicle::class), - $this->_em->getClassMetadata(DDC93Car::class), - $this->_em->getClassMetadata(DDC3027Animal::class), - $this->_em->getClassMetadata(DDC3027Dog::class), + $this->em->getClassMetadata(DDC93Person::class), + $this->em->getClassMetadata(DDC93Address::class), + $this->em->getClassMetadata(DDC93Vehicle::class), + $this->em->getClassMetadata(DDC93Car::class), + $this->em->getClassMetadata(DDC3027Animal::class), + $this->em->getClassMetadata(DDC3027Dog::class), ] ); } catch(\Exception $e) { @@ -33,10 +38,10 @@ public function setUp() public function testMetadataHasReflectionEmbeddablesAccessible() { - $classMetadata = $this->_em->getClassMetadata(DDC93Person::class); + $classMetadata = $this->em->getClassMetadata(DDC93Person::class); - $this->assertInstanceOf(RuntimePublicReflectionProperty::class, $classMetadata->getReflectionProperty('address')); - $this->assertInstanceOf(ReflectionEmbeddedProperty::class, $classMetadata->getReflectionProperty('address.street')); + self::assertInstanceOf(RuntimePublicReflectionProperty::class, $classMetadata->getReflectionProperty('address')); + self::assertInstanceOf(ReflectionEmbeddedProperty::class, $classMetadata->getReflectionProperty('address.street')); } public function testCRUD() @@ -50,43 +55,43 @@ public function testCRUD() $person->address->country = new DDC93Country('Germany'); // 1. check saving value objects works - $this->_em->persist($person); - $this->_em->flush(); + $this->em->persist($person); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); // 2. check loading value objects works - $person = $this->_em->find(DDC93Person::class, $person->id); + $person = $this->em->find(DDC93Person::class, $person->id); - $this->assertInstanceOf(DDC93Address::class, $person->address); - $this->assertEquals('United States of Tara Street', $person->address->street); - $this->assertEquals('12345', $person->address->zip); - $this->assertEquals('funkytown', $person->address->city); - $this->assertInstanceOf(DDC93Country::class, $person->address->country); - $this->assertEquals('Germany', $person->address->country->name); + self::assertInstanceOf(DDC93Address::class, $person->address); + self::assertEquals('United States of Tara Street', $person->address->street); + self::assertEquals('12345', $person->address->zip); + self::assertEquals('funkytown', $person->address->city); + self::assertInstanceOf(DDC93Country::class, $person->address->country); + self::assertEquals('Germany', $person->address->country->name); // 3. check changing value objects works $person->address->street = "Street"; $person->address->zip = "54321"; $person->address->city = "another town"; $person->address->country->name = "United States of America"; - $this->_em->flush(); + $this->em->flush(); - $this->_em->clear(); + $this->em->clear(); - $person = $this->_em->find(DDC93Person::class, $person->id); + $person = $this->em->find(DDC93Person::class, $person->id); - $this->assertEquals('Street', $person->address->street); - $this->assertEquals('54321', $person->address->zip); - $this->assertEquals('another town', $person->address->city); - $this->assertEquals('United States of America', $person->address->country->name); + self::assertEquals('Street', $person->address->street); + self::assertEquals('54321', $person->address->zip); + self::assertEquals('another town', $person->address->city); + self::assertEquals('United States of America', $person->address->country->name); // 4. check deleting works $personId = $person->id;; - $this->_em->remove($person); - $this->_em->flush(); + $this->em->remove($person); + $this->em->flush(); - $this->assertNull($this->_em->find(DDC93Person::class, $personId)); + self::assertNull($this->em->find(DDC93Person::class, $personId)); } public function testLoadDql() @@ -100,33 +105,33 @@ public function testLoadDql() $person->address->city = "funkytown"; $person->address->country = new DDC93Country('United States of America'); - $this->_em->persist($person); + $this->em->persist($person); } - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); $dql = "SELECT p FROM " . __NAMESPACE__ . "\DDC93Person p"; - $persons = $this->_em->createQuery($dql)->getResult(); + $persons = $this->em->createQuery($dql)->getResult(); - $this->assertCount(3, $persons); + self::assertCount(3, $persons); foreach ($persons as $person) { - $this->assertInstanceOf(DDC93Address::class, $person->address); - $this->assertEquals('Tree', $person->address->street); - $this->assertEquals('12345', $person->address->zip); - $this->assertEquals('funkytown', $person->address->city); - $this->assertInstanceOf(DDC93Country::class, $person->address->country); - $this->assertEquals('United States of America', $person->address->country->name); + self::assertInstanceOf(DDC93Address::class, $person->address); + self::assertEquals('Tree', $person->address->street); + self::assertEquals('12345', $person->address->zip); + self::assertEquals('funkytown', $person->address->city); + self::assertInstanceOf(DDC93Country::class, $person->address->country); + self::assertEquals('United States of America', $person->address->country->name); } $dql = "SELECT p FROM " . __NAMESPACE__ . "\DDC93Person p"; - $persons = $this->_em->createQuery($dql)->getArrayResult(); + $persons = $this->em->createQuery($dql)->getArrayResult(); foreach ($persons as $person) { - $this->assertEquals('Tree', $person['address.street']); - $this->assertEquals('12345', $person['address.zip']); - $this->assertEquals('funkytown', $person['address.city']); - $this->assertEquals('United States of America', $person['address.country.name']); + self::assertEquals('Tree', $person['address.street']); + self::assertEquals('12345', $person['address.zip']); + self::assertEquals('funkytown', $person['address.city']); + self::assertEquals('United States of America', $person['address.country.name']); } } @@ -140,19 +145,19 @@ public function testDqlOnEmbeddedObjectsField() } $person = new DDC93Person('Johannes', new DDC93Address('Moo', '12345', 'Karlsruhe', new DDC93Country('Germany'))); - $this->_em->persist($person); - $this->_em->flush($person); + $this->em->persist($person); + $this->em->flush(); // SELECT $selectDql = "SELECT p FROM " . __NAMESPACE__ ."\\DDC93Person p WHERE p.address.city = :city AND p.address.country.name = :country"; - $loadedPerson = $this->_em->createQuery($selectDql) + $loadedPerson = $this->em->createQuery($selectDql) ->setParameter('city', 'Karlsruhe') ->setParameter('country', 'Germany') ->getSingleResult(); - $this->assertEquals($person, $loadedPerson); + self::assertEquals($person, $loadedPerson); - $this->assertNull( - $this->_em->createQuery($selectDql) + self::assertNull( + $this->em->createQuery($selectDql) ->setParameter('city', 'asdf') ->setParameter('country', 'Germany') ->getOneOrNullResult() @@ -160,76 +165,76 @@ public function testDqlOnEmbeddedObjectsField() // UPDATE $updateDql = "UPDATE " . __NAMESPACE__ . "\\DDC93Person p SET p.address.street = :street, p.address.country.name = :country WHERE p.address.city = :city"; - $this->_em->createQuery($updateDql) + $this->em->createQuery($updateDql) ->setParameter('street', 'Boo') ->setParameter('country', 'DE') ->setParameter('city', 'Karlsruhe') ->execute(); - $this->_em->refresh($person); - $this->assertEquals('Boo', $person->address->street); - $this->assertEquals('DE', $person->address->country->name); + $this->em->refresh($person); + self::assertEquals('Boo', $person->address->street); + self::assertEquals('DE', $person->address->country->name); // DELETE - $this->_em->createQuery("DELETE " . __NAMESPACE__ . "\\DDC93Person p WHERE p.address.city = :city AND p.address.country.name = :country") + $this->em->createQuery("DELETE " . __NAMESPACE__ . "\\DDC93Person p WHERE p.address.city = :city AND p.address.country.name = :country") ->setParameter('city', 'Karlsruhe') ->setParameter('country', 'DE') ->execute(); - $this->_em->clear(); - $this->assertNull($this->_em->find(DDC93Person::class, $person->id)); + $this->em->clear(); + self::assertNull($this->em->find(DDC93Person::class, $person->id)); } public function testPartialDqlOnEmbeddedObjectsField() { $person = new DDC93Person('Karl', new DDC93Address('Foo', '12345', 'Gosport', new DDC93Country('England'))); - $this->_em->persist($person); - $this->_em->flush($person); - $this->_em->clear(); + $this->em->persist($person); + $this->em->flush(); + $this->em->clear(); // Prove that the entity was persisted correctly. $dql = "SELECT p FROM " . __NAMESPACE__ ."\\DDC93Person p WHERE p.name = :name"; - $person = $this->_em->createQuery($dql) + $person = $this->em->createQuery($dql) ->setParameter('name', 'Karl') ->getSingleResult(); - $this->assertEquals('Gosport', $person->address->city); - $this->assertEquals('Foo', $person->address->street); - $this->assertEquals('12345', $person->address->zip); - $this->assertEquals('England', $person->address->country->name); + self::assertEquals('Gosport', $person->address->city); + self::assertEquals('Foo', $person->address->street); + self::assertEquals('12345', $person->address->zip); + self::assertEquals('England', $person->address->country->name); // Clear the EM and prove that the embeddable can be the subject of a partial query. - $this->_em->clear(); + $this->em->clear(); $dql = "SELECT PARTIAL p.{id,address.city} FROM " . __NAMESPACE__ ."\\DDC93Person p WHERE p.name = :name"; - $person = $this->_em->createQuery($dql) + $person = $this->em->createQuery($dql) ->setParameter('name', 'Karl') ->getSingleResult(); // Selected field must be equal, all other fields must be null. - $this->assertEquals('Gosport', $person->address->city); - $this->assertNull($person->address->street); - $this->assertNull($person->address->zip); - $this->assertNull($person->address->country); - $this->assertNull($person->name); + self::assertEquals('Gosport', $person->address->city); + self::assertNull($person->address->street); + self::assertNull($person->address->zip); + self::assertNull($person->address->country); + self::assertNull($person->name); // Clear the EM and prove that the embeddable can be the subject of a partial query regardless of attributes positions. - $this->_em->clear(); + $this->em->clear(); $dql = "SELECT PARTIAL p.{address.city, id} FROM " . __NAMESPACE__ ."\\DDC93Person p WHERE p.name = :name"; - $person = $this->_em->createQuery($dql) + $person = $this->em->createQuery($dql) ->setParameter('name', 'Karl') ->getSingleResult(); // Selected field must be equal, all other fields must be null. - $this->assertEquals('Gosport', $person->address->city); - $this->assertNull($person->address->street); - $this->assertNull($person->address->zip); - $this->assertNull($person->address->country); - $this->assertNull($person->name); + self::assertEquals('Gosport', $person->address->city); + self::assertNull($person->address->street); + self::assertNull($person->address->zip); + self::assertNull($person->address->country); + self::assertNull($person->name); } public function testDqlWithNonExistentEmbeddableField() @@ -237,7 +242,7 @@ public function testDqlWithNonExistentEmbeddableField() $this->expectException(QueryException::class); $this->expectExceptionMessage('no field or association named address.asdfasdf'); - $this->_em->createQuery("SELECT p FROM " . __NAMESPACE__ . "\\DDC93Person p WHERE p.address.asdfasdf IS NULL") + $this->em->createQuery("SELECT p FROM " . __NAMESPACE__ . "\\DDC93Person p WHERE p.address.asdfasdf IS NULL") ->execute(); } @@ -246,58 +251,58 @@ public function testPartialDqlWithNonExistentEmbeddableField() $this->expectException(QueryException::class); $this->expectExceptionMessage("no mapped field named 'address.asdfasdf'"); - $this->_em->createQuery("SELECT PARTIAL p.{id,address.asdfasdf} FROM " . __NAMESPACE__ . "\\DDC93Person p") + $this->em->createQuery("SELECT PARTIAL p.{id,address.asdfasdf} FROM " . __NAMESPACE__ . "\\DDC93Person p") ->execute(); } public function testEmbeddableWithInheritance() { $car = new DDC93Car(new DDC93Address('Foo', '12345', 'Asdf')); - $this->_em->persist($car); - $this->_em->flush($car); + $this->em->persist($car); + $this->em->flush(); - $reloadedCar = $this->_em->find(DDC93Car::class, $car->id); - $this->assertEquals($car, $reloadedCar); + $reloadedCar = $this->em->find(DDC93Car::class, $car->id); + self::assertEquals($car, $reloadedCar); } public function testInlineEmbeddableWithPrefix() { - $metadata = $this->_em->getClassMetadata(DDC3028PersonWithPrefix::class); + $metadata = $this->em->getClassMetadata(DDC3028PersonWithPrefix::class); - $this->assertEquals('foobar_id', $metadata->getColumnName('id.id')); - $this->assertEquals('bloo_foo_id', $metadata->getColumnName('nested.nestedWithPrefix.id')); - $this->assertEquals('bloo_nestedWithEmptyPrefix_id', $metadata->getColumnName('nested.nestedWithEmptyPrefix.id')); - $this->assertEquals('bloo_id', $metadata->getColumnName('nested.nestedWithPrefixFalse.id')); + self::assertEquals('foobar_id', $metadata->getColumnName('id.id')); + self::assertEquals('bloo_foo_id', $metadata->getColumnName('nested.nestedWithPrefix.id')); + self::assertEquals('bloo_nestedWithEmptyPrefix_id', $metadata->getColumnName('nested.nestedWithEmptyPrefix.id')); + self::assertEquals('bloo_id', $metadata->getColumnName('nested.nestedWithPrefixFalse.id')); } public function testInlineEmbeddableEmptyPrefix() { - $metadata = $this->_em->getClassMetadata(DDC3028PersonEmptyPrefix::class); + $metadata = $this->em->getClassMetadata(DDC3028PersonEmptyPrefix::class); - $this->assertEquals('id_id', $metadata->getColumnName('id.id')); - $this->assertEquals('nested_foo_id', $metadata->getColumnName('nested.nestedWithPrefix.id')); - $this->assertEquals('nested_nestedWithEmptyPrefix_id', $metadata->getColumnName('nested.nestedWithEmptyPrefix.id')); - $this->assertEquals('nested_id', $metadata->getColumnName('nested.nestedWithPrefixFalse.id')); + self::assertEquals('id_id', $metadata->getColumnName('id.id')); + self::assertEquals('nested_foo_id', $metadata->getColumnName('nested.nestedWithPrefix.id')); + self::assertEquals('nested_nestedWithEmptyPrefix_id', $metadata->getColumnName('nested.nestedWithEmptyPrefix.id')); + self::assertEquals('nested_id', $metadata->getColumnName('nested.nestedWithPrefixFalse.id')); } public function testInlineEmbeddablePrefixFalse() { $expectedColumnName = 'id'; - $actualColumnName = $this->_em + $actualColumnName = $this->em ->getClassMetadata(DDC3028PersonPrefixFalse::class) ->getColumnName('id.id'); - $this->assertEquals($expectedColumnName, $actualColumnName); + self::assertEquals($expectedColumnName, $actualColumnName); } public function testInlineEmbeddableInMappedSuperClass() { - $isFieldMapped = $this->_em + $isFieldMapped = $this->em ->getClassMetadata(DDC3027Dog::class) ->hasField('address.street'); - $this->assertTrue($isFieldMapped); + self::assertTrue($isFieldMapped); } /** @@ -314,9 +319,9 @@ public function testThrowsExceptionOnInfiniteEmbeddableNesting($embeddableClassN ) ); - $this->_schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(__NAMESPACE__ . '\\' . $embeddableClassName), + $this->em->getClassMetadata(__NAMESPACE__ . '\\' . $embeddableClassName), ] ); } @@ -332,20 +337,20 @@ public function getInfiniteEmbeddableNestingData() /** - * @Entity + * @ORM\Entity */ class DDC93Person { - /** @Id @GeneratedValue @Column(type="integer") */ + /** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ public $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $name; - /** @Embedded(class="DDC93Address") */ + /** @ORM\Embedded(class="DDC93Address") */ public $address; - /** @Embedded(class = "DDC93Timestamps") */ + /** @ORM\Embedded(class = "DDC93Timestamps") */ public $timestamps; public function __construct($name = null, DDC93Address $address = null) @@ -357,11 +362,11 @@ public function __construct($name = null, DDC93Address $address = null) } /** - * @Embeddable + * @ORM\Embeddable */ class DDC93Timestamps { - /** @Column(type = "datetime") */ + /** @ORM\Column(type = "datetime") */ public $createdAt; public function __construct(\DateTime $createdAt) @@ -371,20 +376,20 @@ public function __construct(\DateTime $createdAt) } /** - * @Entity + * @ORM\Entity * - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorColumn(name = "t", type = "string", length = 10) - * @DiscriminatorMap({ + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorColumn(name = "t", type = "string", length = 10) + * @ORM\DiscriminatorMap({ * "v" = "Doctrine\Tests\ORM\Functional\DDC93Car", * }) */ abstract class DDC93Vehicle { - /** @Id @GeneratedValue(strategy = "AUTO") @Column(type = "integer") */ + /** @ORM\Id @ORM\GeneratedValue(strategy = "AUTO") @ORM\Column(type = "integer") */ public $id; - /** @Embedded(class = "DDC93Address") */ + /** @ORM\Embedded(class = "DDC93Address") */ public $address; public function __construct(DDC93Address $address) @@ -394,19 +399,19 @@ public function __construct(DDC93Address $address) } /** - * @Entity + * @ORM\Entity */ class DDC93Car extends DDC93Vehicle { } /** - * @Embeddable + * @ORM\Embeddable */ class DDC93Country { /** - * @Column(type="string", nullable=true) + * @ORM\Column(type="string", nullable=true) */ public $name; @@ -417,23 +422,23 @@ public function __construct($name = null) } /** - * @Embeddable + * @ORM\Embeddable */ class DDC93Address { /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $street; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $zip; /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $city; - /** @Embedded(class = "DDC93Country") */ + /** @ORM\Embedded(class = "DDC93Country") */ public $country; public function __construct($street = null, $zip = null, $city = null, DDC93Country $country = null) @@ -445,36 +450,36 @@ public function __construct($street = null, $zip = null, $city = null, DDC93Coun } } -/** @Entity */ +/** @ORM\Entity */ class DDC93Customer { - /** @Id @GeneratedValue @Column(type="integer") */ + /** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */ private $id; - /** @Embedded(class = "DDC93ContactInfo", columnPrefix = "contact_info_") */ + /** @ORM\Embedded(class = "DDC93ContactInfo", columnPrefix = "contact_info_") */ private $contactInfo; } -/** @Embeddable */ +/** @ORM\Embeddable */ class DDC93ContactInfo { /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $email; - /** @Embedded(class = "DDC93Address") */ + /** @ORM\Embedded(class = "DDC93Address") */ public $address; } /** - * @Entity + * @ORM\Entity */ class DDC3028PersonWithPrefix { - /** @Embedded(class="DDC3028Id", columnPrefix = "foobar_") */ + /** @ORM\Embedded(class="DDC3028Id", columnPrefix = "foobar_") */ public $id; - /** @Embedded(class="DDC3028NestedEmbeddable", columnPrefix = "bloo_") */ + /** @ORM\Embedded(class="DDC3028NestedEmbeddable", columnPrefix = "bloo_") */ public $nested; public function __construct(DDC3028Id $id = null, DDC3028NestedEmbeddable $nested = null) @@ -485,14 +490,14 @@ public function __construct(DDC3028Id $id = null, DDC3028NestedEmbeddable $neste } /** - * @Entity + * @ORM\Entity */ class DDC3028PersonEmptyPrefix { - /** @Embedded(class="DDC3028Id", columnPrefix = "") */ + /** @ORM\Embedded(class="DDC3028Id", columnPrefix = "") */ public $id; - /** @Embedded(class="DDC3028NestedEmbeddable", columnPrefix = "") */ + /** @ORM\Embedded(class="DDC3028NestedEmbeddable", columnPrefix = "") */ public $nested; public function __construct(DDC3028Id $id = null, DDC3028NestedEmbeddable $nested = null) @@ -503,11 +508,11 @@ public function __construct(DDC3028Id $id = null, DDC3028NestedEmbeddable $neste } /** - * @Entity + * @ORM\Entity */ class DDC3028PersonPrefixFalse { - /** @Embedded(class="DDC3028Id", columnPrefix = false) */ + /** @ORM\Embedded(class="DDC3028Id", columnPrefix = false) */ public $id; public function __construct(DDC3028Id $id = null) @@ -517,12 +522,12 @@ public function __construct(DDC3028Id $id = null) } /** - * @Embeddable + * @ORM\Embeddable */ class DDC3028Id { /** - * @Id @Column(type="string") + * @ORM\Id @ORM\Column(type="string") */ public $id; @@ -533,17 +538,17 @@ public function __construct($id = null) } /** - * @Embeddable + * @ORM\Embeddable */ class DDC3028NestedEmbeddable { - /** @Embedded(class="DDC3028Id", columnPrefix = "foo_") */ + /** @ORM\Embedded(class="DDC3028Id", columnPrefix = "foo_") */ public $nestedWithPrefix; - /** @Embedded(class="DDC3028Id", columnPrefix = "") */ + /** @ORM\Embedded(class="DDC3028Id", columnPrefix = "") */ public $nestedWithEmptyPrefix; - /** @Embedded(class="DDC3028Id", columnPrefix = false) */ + /** @ORM\Embedded(class="DDC3028Id", columnPrefix = false) */ public $nestedWithPrefixFalse; public function __construct( @@ -558,89 +563,89 @@ public function __construct( } /** - * @MappedSuperclass + * @ORM\MappedSuperclass */ abstract class DDC3027Animal { - /** @Id @GeneratedValue(strategy = "AUTO") @Column(type = "integer") */ + /** @ORM\Id @ORM\GeneratedValue(strategy = "AUTO") @ORM\Column(type = "integer") */ public $id; - /** @Embedded(class = "DDC93Address") */ + /** @ORM\Embedded(class = "DDC93Address") */ public $address; } /** - * @Entity + * @ORM\Entity */ class DDC3027Dog extends DDC3027Animal { } /** - * @Embeddable + * @ORM\Embeddable */ class DDCInfiniteNestingEmbeddable { - /** @Embedded(class="DDCInfiniteNestingEmbeddable") */ + /** @ORM\Embedded(class="DDCInfiniteNestingEmbeddable") */ public $nested; } /** - * @Embeddable + * @ORM\Embeddable */ class DDCNestingEmbeddable1 { - /** @Embedded(class="DDC3028Id") */ + /** @ORM\Embedded(class="DDC3028Id") */ public $id1; - /** @Embedded(class="DDC3028Id") */ + /** @ORM\Embedded(class="DDC3028Id") */ public $id2; - /** @Embedded(class="DDCNestingEmbeddable2") */ + /** @ORM\Embedded(class="DDCNestingEmbeddable2") */ public $nested; } /** - * @Embeddable + * @ORM\Embeddable */ class DDCNestingEmbeddable2 { - /** @Embedded(class="DDC3028Id") */ + /** @ORM\Embedded(class="DDC3028Id") */ public $id1; - /** @Embedded(class="DDC3028Id") */ + /** @ORM\Embedded(class="DDC3028Id") */ public $id2; - /** @Embedded(class="DDCNestingEmbeddable3") */ + /** @ORM\Embedded(class="DDCNestingEmbeddable3") */ public $nested; } /** - * @Embeddable + * @ORM\Embeddable */ class DDCNestingEmbeddable3 { - /** @Embedded(class="DDC3028Id") */ + /** @ORM\Embedded(class="DDC3028Id") */ public $id1; - /** @Embedded(class="DDC3028Id") */ + /** @ORM\Embedded(class="DDC3028Id") */ public $id2; - /** @Embedded(class="DDCNestingEmbeddable4") */ + /** @ORM\Embedded(class="DDCNestingEmbeddable4") */ public $nested; } /** - * @Embeddable + * @ORM\Embeddable */ class DDCNestingEmbeddable4 { - /** @Embedded(class="DDC3028Id") */ + /** @ORM\Embedded(class="DDC3028Id") */ public $id1; - /** @Embedded(class="DDC3028Id") */ + /** @ORM\Embedded(class="DDC3028Id") */ public $id2; - /** @Embedded(class="DDCNestingEmbeddable1") */ + /** @ORM\Embedded(class="DDCNestingEmbeddable1") */ public $nested; } diff --git a/tests/Doctrine/Tests/ORM/Functional/VersionedOneToOneTest.php b/tests/Doctrine/Tests/ORM/Functional/VersionedOneToOneTest.php index f8062f9954e..d537840f392 100644 --- a/tests/Doctrine/Tests/ORM/Functional/VersionedOneToOneTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/VersionedOneToOneTest.php @@ -1,5 +1,7 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(FirstRelatedEntity::class), - $this->_em->getClassMetadata(SecondRelatedEntity::class) + $this->em->getClassMetadata(FirstRelatedEntity::class), + $this->em->getClassMetadata(SecondRelatedEntity::class) ] ); } catch (ORMException $e) { @@ -40,24 +42,24 @@ public function testSetVersionOnCreate() $secondRelatedEntity = new SecondRelatedEntity(); $secondRelatedEntity->name = 'Bob'; - $this->_em->persist($secondRelatedEntity); - $this->_em->flush(); + $this->em->persist($secondRelatedEntity); + $this->em->flush(); $firstRelatedEntity = new FirstRelatedEntity(); $firstRelatedEntity->name = 'Fred'; $firstRelatedEntity->secondEntity = $secondRelatedEntity; - $this->_em->persist($firstRelatedEntity); - $this->_em->flush(); + $this->em->persist($firstRelatedEntity); + $this->em->flush(); - $firstEntity = $this->_em->getRepository(FirstRelatedEntity::class) + $firstEntity = $this->em->getRepository(FirstRelatedEntity::class) ->findOneBy(['name' => 'Fred']); - $secondEntity = $this->_em->getRepository(SecondRelatedEntity::class) + $secondEntity = $this->em->getRepository(SecondRelatedEntity::class) ->findOneBy(['name' => 'Bob']); - $this->assertSame($firstRelatedEntity, $firstEntity); - $this->assertSame($secondRelatedEntity, $secondEntity); - $this->assertSame($firstEntity->secondEntity, $secondEntity); + self::assertSame($firstRelatedEntity, $firstEntity); + self::assertSame($secondRelatedEntity, $secondEntity); + self::assertSame($firstEntity->secondEntity, $secondEntity); } } diff --git a/tests/Doctrine/Tests/ORM/Hydration/AbstractHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/AbstractHydratorTest.php index 1cd49d5ca7e..bf699d104c2 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/AbstractHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/AbstractHydratorTest.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\Common\Persistence\Mapping\ClassMetadataFactory; use Doctrine\DBAL\Connection; use Doctrine\ORM\EntityManagerInterface; use Doctrine\Common\EventManager; @@ -9,6 +10,7 @@ use Doctrine\ORM\Events; use Doctrine\ORM\Query\ResultSetMapping; use Doctrine\ORM\Internal\Hydration\AbstractHydrator; +use Doctrine\ORM\UnitOfWork; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -29,10 +31,14 @@ public function testOnClearEventListenerIsDetachedOnCleanup() $mockEntityManagerInterface = $this->createMock(EntityManagerInterface::class); $mockEventManager = $this->createMock(EventManager::class); $mockStatement = $this->createMock(Statement::class); + $mockUow = $this->createMock(UnitOfWork::class); + $mockMetadataFactory = $this->createMock(ClassMetadataFactory::class); $mockResultMapping = $this->getMockBuilder(ResultSetMapping::class); - $mockEntityManagerInterface->expects(self::any())->method('getEventManager')->willReturn($mockEventManager); - $mockEntityManagerInterface->expects(self::any())->method('getConnection')->willReturn($mockConnection); + $mockEntityManagerInterface->method('getEventManager')->willReturn($mockEventManager); + $mockEntityManagerInterface->method('getConnection')->willReturn($mockConnection); + $mockEntityManagerInterface->method('getUnitOfWork')->willReturn($mockUow); + $mockEntityManagerInterface->method('getMetadataFactory')->willReturn($mockMetadataFactory); $mockStatement->expects(self::once())->method('fetch')->willReturn(false); /* @var $mockAbstractHydrator AbstractHydrator */ diff --git a/tests/Doctrine/Tests/ORM/Hydration/ArrayHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/ArrayHydratorTest.php index 6c0b30ef655..e160da2099a 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/ArrayHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/ArrayHydratorTest.php @@ -1,7 +1,10 @@ _em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(2, count($result)); - $this->assertTrue(is_array($result)); + self::assertEquals(2, count($result)); + self::assertTrue(is_array($result)); - $this->assertEquals(1, $result[0]['id']); - $this->assertEquals('romanb', $result[0]['name']); + self::assertEquals(1, $result[0]['id']); + self::assertEquals('romanb', $result[0]['name']); - $this->assertEquals(2, $result[1]['id']); - $this->assertEquals('jwage', $result[1]['name']); + self::assertEquals(2, $result[1]['id']); + self::assertEquals('jwage', $result[1]['name']); } /** @@ -75,7 +78,7 @@ public function testSimpleEntityWithScalarQuery($userEntityKey) $rsm->addEntityResult(CmsUser::class, $alias); $rsm->addFieldResult($alias, 's__id', 'id'); $rsm->addFieldResult($alias, 's__name', 'name'); - $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); + $rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); // Faked result set $resultSet = [ @@ -92,27 +95,27 @@ public function testSimpleEntityWithScalarQuery($userEntityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(2, count($result)); - $this->assertTrue(is_array($result)); + self::assertEquals(2, count($result)); + self::assertTrue(is_array($result)); - $this->assertArrayHasKey('nameUpper', $result[0]); - $this->assertArrayNotHasKey('id', $result[0]); - $this->assertArrayNotHasKey('name', $result[0]); + self::assertArrayHasKey('nameUpper', $result[0]); + self::assertArrayNotHasKey('id', $result[0]); + self::assertArrayNotHasKey('name', $result[0]); - $this->assertArrayHasKey(0, $result[0]); - $this->assertArrayHasKey('id', $result[0][0]); - $this->assertArrayHasKey('name', $result[0][0]); + self::assertArrayHasKey(0, $result[0]); + self::assertArrayHasKey('id', $result[0][0]); + self::assertArrayHasKey('name', $result[0][0]); - $this->assertArrayHasKey('nameUpper', $result[1]); - $this->assertArrayNotHasKey('id', $result[1]); - $this->assertArrayNotHasKey('name', $result[1]); + self::assertArrayHasKey('nameUpper', $result[1]); + self::assertArrayNotHasKey('id', $result[1]); + self::assertArrayNotHasKey('name', $result[1]); - $this->assertArrayHasKey(0, $result[1]); - $this->assertArrayHasKey('id', $result[1][0]); - $this->assertArrayHasKey('name', $result[1][0]); + self::assertArrayHasKey(0, $result[1]); + self::assertArrayHasKey('id', $result[1][0]); + self::assertArrayHasKey('name', $result[1][0]); } /** @@ -140,19 +143,19 @@ public function testSimpleEntityQueryWithAliasedUserEntity() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(2, count($result)); - $this->assertTrue(is_array($result)); + self::assertEquals(2, count($result)); + self::assertTrue(is_array($result)); - $this->assertArrayHasKey('user', $result[0]); - $this->assertEquals(1, $result[0]['user']['id']); - $this->assertEquals('romanb', $result[0]['user']['name']); + self::assertArrayHasKey('user', $result[0]); + self::assertEquals(1, $result[0]['user']['id']); + self::assertEquals('romanb', $result[0]['user']['name']); - $this->assertArrayHasKey('user', $result[1]); - $this->assertEquals(2, $result[1]['user']['id']); - $this->assertEquals('jwage', $result[1]['user']['name']); + self::assertArrayHasKey('user', $result[1]); + self::assertEquals(2, $result[1]['user']['id']); + self::assertEquals('jwage', $result[1]['user']['name']); } /** @@ -187,22 +190,22 @@ public function testSimpleMultipleRootEntityQuery() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(4, count($result)); + self::assertEquals(4, count($result)); - $this->assertEquals(1, $result[0]['id']); - $this->assertEquals('romanb', $result[0]['name']); + self::assertEquals(1, $result[0]['id']); + self::assertEquals('romanb', $result[0]['name']); - $this->assertEquals(1, $result[1]['id']); - $this->assertEquals('Cool things.', $result[1]['topic']); + self::assertEquals(1, $result[1]['id']); + self::assertEquals('Cool things.', $result[1]['topic']); - $this->assertEquals(2, $result[2]['id']); - $this->assertEquals('jwage', $result[2]['name']); + self::assertEquals(2, $result[2]['id']); + self::assertEquals('jwage', $result[2]['name']); - $this->assertEquals(2, $result[3]['id']); - $this->assertEquals('Cool things II.', $result[3]['topic']); + self::assertEquals(2, $result[3]['id']); + self::assertEquals('Cool things II.', $result[3]['topic']); } /** @@ -237,26 +240,26 @@ public function testSimpleMultipleRootEntityQueryWithAliasedUserEntity() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(4, count($result)); + self::assertEquals(4, count($result)); - $this->assertArrayHasKey('user', $result[0]); - $this->assertEquals(1, $result[0]['user']['id']); - $this->assertEquals('romanb', $result[0]['user']['name']); + self::assertArrayHasKey('user', $result[0]); + self::assertEquals(1, $result[0]['user']['id']); + self::assertEquals('romanb', $result[0]['user']['name']); - $this->assertArrayHasKey(0, $result[1]); - $this->assertEquals(1, $result[1][0]['id']); - $this->assertEquals('Cool things.', $result[1][0]['topic']); + self::assertArrayHasKey(0, $result[1]); + self::assertEquals(1, $result[1][0]['id']); + self::assertEquals('Cool things.', $result[1][0]['topic']); - $this->assertArrayHasKey('user', $result[2]); - $this->assertEquals(2, $result[2]['user']['id']); - $this->assertEquals('jwage', $result[2]['user']['name']); + self::assertArrayHasKey('user', $result[2]); + self::assertEquals(2, $result[2]['user']['id']); + self::assertEquals('jwage', $result[2]['user']['name']); - $this->assertArrayHasKey(0, $result[3]); - $this->assertEquals(2, $result[3][0]['id']); - $this->assertEquals('Cool things II.', $result[3][0]['topic']); + self::assertArrayHasKey(0, $result[3]); + self::assertEquals(2, $result[3][0]['id']); + self::assertEquals('Cool things II.', $result[3][0]['topic']); } /** @@ -291,26 +294,26 @@ public function testSimpleMultipleRootEntityQueryWithAliasedArticleEntity() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(4, count($result)); + self::assertEquals(4, count($result)); - $this->assertArrayHasKey(0, $result[0]); - $this->assertEquals(1, $result[0][0]['id']); - $this->assertEquals('romanb', $result[0][0]['name']); + self::assertArrayHasKey(0, $result[0]); + self::assertEquals(1, $result[0][0]['id']); + self::assertEquals('romanb', $result[0][0]['name']); - $this->assertArrayHasKey('article', $result[1]); - $this->assertEquals(1, $result[1]['article']['id']); - $this->assertEquals('Cool things.', $result[1]['article']['topic']); + self::assertArrayHasKey('article', $result[1]); + self::assertEquals(1, $result[1]['article']['id']); + self::assertEquals('Cool things.', $result[1]['article']['topic']); - $this->assertArrayHasKey(0, $result[2]); - $this->assertEquals(2, $result[2][0]['id']); - $this->assertEquals('jwage', $result[2][0]['name']); + self::assertArrayHasKey(0, $result[2]); + self::assertEquals(2, $result[2][0]['id']); + self::assertEquals('jwage', $result[2][0]['name']); - $this->assertArrayHasKey('article', $result[3]); - $this->assertEquals(2, $result[3]['article']['id']); - $this->assertEquals('Cool things II.', $result[3]['article']['topic']); + self::assertArrayHasKey('article', $result[3]); + self::assertEquals(2, $result[3]['article']['id']); + self::assertEquals('Cool things II.', $result[3]['article']['topic']); } /** @@ -345,26 +348,26 @@ public function testSimpleMultipleRootEntityQueryWithAliasedEntities() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(4, count($result)); + self::assertEquals(4, count($result)); - $this->assertArrayHasKey('user', $result[0]); - $this->assertEquals(1, $result[0]['user']['id']); - $this->assertEquals('romanb', $result[0]['user']['name']); + self::assertArrayHasKey('user', $result[0]); + self::assertEquals(1, $result[0]['user']['id']); + self::assertEquals('romanb', $result[0]['user']['name']); - $this->assertArrayHasKey('article', $result[1]); - $this->assertEquals(1, $result[1]['article']['id']); - $this->assertEquals('Cool things.', $result[1]['article']['topic']); + self::assertArrayHasKey('article', $result[1]); + self::assertEquals(1, $result[1]['article']['id']); + self::assertEquals('Cool things.', $result[1]['article']['topic']); - $this->assertArrayHasKey('user', $result[2]); - $this->assertEquals(2, $result[2]['user']['id']); - $this->assertEquals('jwage', $result[2]['user']['name']); + self::assertArrayHasKey('user', $result[2]); + self::assertEquals(2, $result[2]['user']['id']); + self::assertEquals('jwage', $result[2]['user']['name']); - $this->assertArrayHasKey('article', $result[3]); - $this->assertEquals(2, $result[3]['article']['id']); - $this->assertEquals('Cool things II.', $result[3]['article']['topic']); + self::assertArrayHasKey('article', $result[3]); + self::assertEquals(2, $result[3]['article']['id']); + self::assertEquals('Cool things II.', $result[3]['article']['topic']); } /** @@ -382,7 +385,7 @@ public function testMixedQueryNormalJoin($userEntityKey) $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addScalarResult('sclr0', 'numPhones', 'integer'); + $rsm->addScalarResult('sclr0', 'numPhones', Type::getType('integer')); // Faked result set $resultSet = [ @@ -400,21 +403,21 @@ public function testMixedQueryNormalJoin($userEntityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(2, count($result)); - $this->assertTrue(is_array($result)); - $this->assertTrue(is_array($result[0])); - $this->assertTrue(is_array($result[1])); + self::assertEquals(2, count($result)); + self::assertTrue(is_array($result)); + self::assertTrue(is_array($result[0])); + self::assertTrue(is_array($result[1])); // first user => 2 phonenumbers - $this->assertArrayHasKey($userEntityKey, $result[0]); - $this->assertEquals(2, $result[0]['numPhones']); + self::assertArrayHasKey($userEntityKey, $result[0]); + self::assertEquals(2, $result[0]['numPhones']); // second user => 1 phonenumber - $this->assertArrayHasKey($userEntityKey, $result[1]); - $this->assertEquals(1, $result[1]['numPhones']); + self::assertArrayHasKey($userEntityKey, $result[1]); + self::assertEquals(1, $result[1]['numPhones']); } /** @@ -437,7 +440,7 @@ public function testMixedQueryFetchJoin($userEntityKey) ); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); + $rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); $rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); // Faked result set @@ -464,26 +467,26 @@ public function testMixedQueryFetchJoin($userEntityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertTrue(is_array($result)); - $this->assertTrue(is_array($result[0])); - $this->assertTrue(is_array($result[1])); + self::assertTrue(is_array($result)); + self::assertTrue(is_array($result[0])); + self::assertTrue(is_array($result[1])); // first user => 2 phonenumbers - $this->assertEquals(2, count($result[0][$userEntityKey]['phonenumbers'])); - $this->assertEquals('ROMANB', $result[0]['nameUpper']); + self::assertEquals(2, count($result[0][$userEntityKey]['phonenumbers'])); + self::assertEquals('ROMANB', $result[0]['nameUpper']); // second user => 1 phonenumber - $this->assertEquals(1, count($result[1][$userEntityKey]['phonenumbers'])); - $this->assertEquals('JWAGE', $result[1]['nameUpper']); + self::assertEquals(1, count($result[1][$userEntityKey]['phonenumbers'])); + self::assertEquals('JWAGE', $result[1]['nameUpper']); - $this->assertEquals(42, $result[0][$userEntityKey]['phonenumbers'][0]['phonenumber']); - $this->assertEquals(43, $result[0][$userEntityKey]['phonenumbers'][1]['phonenumber']); - $this->assertEquals(91, $result[1][$userEntityKey]['phonenumbers'][0]['phonenumber']); + self::assertEquals(42, $result[0][$userEntityKey]['phonenumbers'][0]['phonenumber']); + self::assertEquals(43, $result[0][$userEntityKey]['phonenumbers'][1]['phonenumber']); + self::assertEquals(91, $result[1][$userEntityKey]['phonenumbers'][0]['phonenumber']); } /** @@ -508,7 +511,7 @@ public function testMixedQueryFetchJoinCustomIndex($userEntityKey) ); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); + $rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); $rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); $rsm->addIndexBy('u', 'id'); $rsm->addIndexBy('p', 'phonenumber'); @@ -538,29 +541,29 @@ public function testMixedQueryFetchJoinCustomIndex($userEntityKey) $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertTrue(is_array($result)); - $this->assertTrue(is_array($result[1])); - $this->assertTrue(is_array($result[2])); + self::assertTrue(is_array($result)); + self::assertTrue(is_array($result[1])); + self::assertTrue(is_array($result[2])); // test the scalar values - $this->assertEquals('ROMANB', $result[1]['nameUpper']); - $this->assertEquals('JWAGE', $result[2]['nameUpper']); + self::assertEquals('ROMANB', $result[1]['nameUpper']); + self::assertEquals('JWAGE', $result[2]['nameUpper']); // first user => 2 phonenumbers. notice the custom indexing by user id - $this->assertEquals(2, count($result[1][$userEntityKey]['phonenumbers'])); + self::assertEquals(2, count($result[1][$userEntityKey]['phonenumbers'])); // second user => 1 phonenumber. notice the custom indexing by user id - $this->assertEquals(1, count($result[2][$userEntityKey]['phonenumbers'])); + self::assertEquals(1, count($result[2][$userEntityKey]['phonenumbers'])); // test the custom indexing of the phonenumbers - $this->assertTrue(isset($result[1][$userEntityKey]['phonenumbers']['42'])); - $this->assertTrue(isset($result[1][$userEntityKey]['phonenumbers']['43'])); - $this->assertTrue(isset($result[2][$userEntityKey]['phonenumbers']['91'])); + self::assertTrue(isset($result[1][$userEntityKey]['phonenumbers']['42'])); + self::assertTrue(isset($result[1][$userEntityKey]['phonenumbers']['43'])); + self::assertTrue(isset($result[2][$userEntityKey]['phonenumbers']['91'])); } /** @@ -593,7 +596,7 @@ public function testMixedQueryMultipleFetchJoin() ); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); + $rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); $rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); $rsm->addFieldResult('a', 'a__id', 'id'); $rsm->addFieldResult('a', 'a__topic', 'topic'); @@ -652,30 +655,30 @@ public function testMixedQueryMultipleFetchJoin() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(2, count($result)); - $this->assertTrue(is_array($result)); - $this->assertTrue(is_array($result[0])); - $this->assertTrue(is_array($result[1])); + self::assertEquals(2, count($result)); + self::assertTrue(is_array($result)); + self::assertTrue(is_array($result[0])); + self::assertTrue(is_array($result[1])); // first user => 2 phonenumbers, 2 articles - $this->assertEquals(2, count($result[0][0]['phonenumbers'])); - $this->assertEquals(2, count($result[0][0]['articles'])); - $this->assertEquals('ROMANB', $result[0]['nameUpper']); + self::assertEquals(2, count($result[0][0]['phonenumbers'])); + self::assertEquals(2, count($result[0][0]['articles'])); + self::assertEquals('ROMANB', $result[0]['nameUpper']); // second user => 1 phonenumber, 2 articles - $this->assertEquals(1, count($result[1][0]['phonenumbers'])); - $this->assertEquals(2, count($result[1][0]['articles'])); - $this->assertEquals('JWAGE', $result[1]['nameUpper']); - - $this->assertEquals(42, $result[0][0]['phonenumbers'][0]['phonenumber']); - $this->assertEquals(43, $result[0][0]['phonenumbers'][1]['phonenumber']); - $this->assertEquals(91, $result[1][0]['phonenumbers'][0]['phonenumber']); - - $this->assertEquals('Getting things done!', $result[0][0]['articles'][0]['topic']); - $this->assertEquals('ZendCon', $result[0][0]['articles'][1]['topic']); - $this->assertEquals('LINQ', $result[1][0]['articles'][0]['topic']); - $this->assertEquals('PHP7', $result[1][0]['articles'][1]['topic']); + self::assertEquals(1, count($result[1][0]['phonenumbers'])); + self::assertEquals(2, count($result[1][0]['articles'])); + self::assertEquals('JWAGE', $result[1]['nameUpper']); + + self::assertEquals(42, $result[0][0]['phonenumbers'][0]['phonenumber']); + self::assertEquals(43, $result[0][0]['phonenumbers'][1]['phonenumber']); + self::assertEquals(91, $result[1][0]['phonenumbers'][0]['phonenumber']); + + self::assertEquals('Getting things done!', $result[0][0]['articles'][0]['topic']); + self::assertEquals('ZendCon', $result[0][0]['articles'][1]['topic']); + self::assertEquals('LINQ', $result[1][0]['articles'][0]['topic']); + self::assertEquals('PHP7', $result[1][0]['articles'][1]['topic']); } /** @@ -718,7 +721,7 @@ public function testMixedQueryMultipleDeepMixedFetchJoin() ); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); + $rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); $rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); $rsm->addFieldResult('a', 'a__id', 'id'); $rsm->addFieldResult('a', 'a__topic', 'topic'); @@ -791,44 +794,44 @@ public function testMixedQueryMultipleDeepMixedFetchJoin() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(2, count($result)); - $this->assertTrue(is_array($result)); - $this->assertTrue(is_array($result[0])); - $this->assertTrue(is_array($result[1])); + self::assertEquals(2, count($result)); + self::assertTrue(is_array($result)); + self::assertTrue(is_array($result[0])); + self::assertTrue(is_array($result[1])); // first user => 2 phonenumbers, 2 articles, 1 comment on first article - $this->assertEquals(2, count($result[0][0]['phonenumbers'])); - $this->assertEquals(2, count($result[0][0]['articles'])); - $this->assertEquals(1, count($result[0][0]['articles'][0]['comments'])); - $this->assertEquals('ROMANB', $result[0]['nameUpper']); + self::assertEquals(2, count($result[0][0]['phonenumbers'])); + self::assertEquals(2, count($result[0][0]['articles'])); + self::assertEquals(1, count($result[0][0]['articles'][0]['comments'])); + self::assertEquals('ROMANB', $result[0]['nameUpper']); // second user => 1 phonenumber, 2 articles, no comments - $this->assertEquals(1, count($result[1][0]['phonenumbers'])); - $this->assertEquals(2, count($result[1][0]['articles'])); - $this->assertEquals('JWAGE', $result[1]['nameUpper']); + self::assertEquals(1, count($result[1][0]['phonenumbers'])); + self::assertEquals(2, count($result[1][0]['articles'])); + self::assertEquals('JWAGE', $result[1]['nameUpper']); - $this->assertEquals(42, $result[0][0]['phonenumbers'][0]['phonenumber']); - $this->assertEquals(43, $result[0][0]['phonenumbers'][1]['phonenumber']); - $this->assertEquals(91, $result[1][0]['phonenumbers'][0]['phonenumber']); + self::assertEquals(42, $result[0][0]['phonenumbers'][0]['phonenumber']); + self::assertEquals(43, $result[0][0]['phonenumbers'][1]['phonenumber']); + self::assertEquals(91, $result[1][0]['phonenumbers'][0]['phonenumber']); - $this->assertEquals('Getting things done!', $result[0][0]['articles'][0]['topic']); - $this->assertEquals('ZendCon', $result[0][0]['articles'][1]['topic']); - $this->assertEquals('LINQ', $result[1][0]['articles'][0]['topic']); - $this->assertEquals('PHP7', $result[1][0]['articles'][1]['topic']); + self::assertEquals('Getting things done!', $result[0][0]['articles'][0]['topic']); + self::assertEquals('ZendCon', $result[0][0]['articles'][1]['topic']); + self::assertEquals('LINQ', $result[1][0]['articles'][0]['topic']); + self::assertEquals('PHP7', $result[1][0]['articles'][1]['topic']); - $this->assertEquals('First!', $result[0][0]['articles'][0]['comments'][0]['topic']); + self::assertEquals('First!', $result[0][0]['articles'][0]['comments'][0]['topic']); - $this->assertTrue(isset($result[0][0]['articles'][0]['comments'])); + self::assertTrue(isset($result[0][0]['articles'][0]['comments'])); // empty comment collections - $this->assertTrue(is_array($result[0][0]['articles'][1]['comments'])); - $this->assertEquals(0, count($result[0][0]['articles'][1]['comments'])); - $this->assertTrue(is_array($result[1][0]['articles'][0]['comments'])); - $this->assertEquals(0, count($result[1][0]['articles'][0]['comments'])); - $this->assertTrue(is_array($result[1][0]['articles'][1]['comments'])); - $this->assertEquals(0, count($result[1][0]['articles'][1]['comments'])); + self::assertTrue(is_array($result[0][0]['articles'][1]['comments'])); + self::assertEquals(0, count($result[0][0]['articles'][1]['comments'])); + self::assertTrue(is_array($result[1][0]['articles'][0]['comments'])); + self::assertEquals(0, count($result[1][0]['articles'][0]['comments'])); + self::assertTrue(is_array($result[1][0]['articles'][1]['comments'])); + self::assertEquals(0, count($result[1][0]['articles'][1]['comments'])); } /** @@ -905,17 +908,17 @@ public function testEntityQueryCustomResultSetOrder() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(2, count($result)); - $this->assertTrue(is_array($result)); - $this->assertTrue(is_array($result[0])); - $this->assertTrue(is_array($result[1])); - $this->assertTrue(isset($result[0]['boards'])); - $this->assertEquals(3, count($result[0]['boards'])); - $this->assertTrue(isset($result[1]['boards'])); - $this->assertEquals(1, count($result[1]['boards'])); + self::assertEquals(2, count($result)); + self::assertTrue(is_array($result)); + self::assertTrue(is_array($result[0])); + self::assertTrue(is_array($result[1])); + self::assertTrue(isset($result[0]['boards'])); + self::assertEquals(3, count($result[0]['boards'])); + self::assertTrue(isset($result[1]['boards'])); + self::assertEquals(1, count($result[1]['boards'])); } /** @@ -933,10 +936,10 @@ public function testChainedJoinWithScalars($entityKey) $rsm->addEntityResult(CmsUser::class, 'u', $entityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addScalarResult('a__id', 'id', 'integer'); - $rsm->addScalarResult('a__topic', 'topic', 'string'); - $rsm->addScalarResult('c__id', 'cid', 'integer'); - $rsm->addScalarResult('c__topic', 'ctopic', 'string'); + $rsm->addScalarResult('a__id', 'id', Type::getType('integer')); + $rsm->addScalarResult('a__topic', 'topic', Type::getType('string')); + $rsm->addScalarResult('c__id', 'cid', Type::getType('integer')); + $rsm->addScalarResult('c__topic', 'ctopic', Type::getType('string')); // Faked result set $resultSet = [ @@ -968,28 +971,28 @@ public function testChainedJoinWithScalars($entityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(3, count($result)); - - $this->assertEquals(2, count($result[0][$entityKey])); // User array - $this->assertEquals(1, $result[0]['id']); - $this->assertEquals('The First', $result[0]['topic']); - $this->assertEquals(1, $result[0]['cid']); - $this->assertEquals('First Comment', $result[0]['ctopic']); - - $this->assertEquals(2, count($result[1][$entityKey])); // User array, duplicated - $this->assertEquals(1, $result[1]['id']); // duplicated - $this->assertEquals('The First', $result[1]['topic']); // duplicated - $this->assertEquals(2, $result[1]['cid']); - $this->assertEquals('Second Comment', $result[1]['ctopic']); - - $this->assertEquals(2, count($result[2][$entityKey])); // User array, duplicated - $this->assertEquals(42, $result[2]['id']); - $this->assertEquals('The Answer', $result[2]['topic']); - $this->assertNull($result[2]['cid']); - $this->assertNull($result[2]['ctopic']); + self::assertEquals(3, count($result)); + + self::assertEquals(2, count($result[0][$entityKey])); // User array + self::assertEquals(1, $result[0]['id']); + self::assertEquals('The First', $result[0]['topic']); + self::assertEquals(1, $result[0]['cid']); + self::assertEquals('First Comment', $result[0]['ctopic']); + + self::assertEquals(2, count($result[1][$entityKey])); // User array, duplicated + self::assertEquals(1, $result[1]['id']); // duplicated + self::assertEquals('The First', $result[1]['topic']); // duplicated + self::assertEquals(2, $result[1]['cid']); + self::assertEquals('Second Comment', $result[1]['ctopic']); + + self::assertEquals(2, count($result[2][$entityKey])); // User array, duplicated + self::assertEquals(42, $result[2]['id']); + self::assertEquals('The Answer', $result[2]['topic']); + self::assertNull($result[2]['cid']); + self::assertNull($result[2]['ctopic']); } /** @@ -1017,20 +1020,20 @@ public function testResultIteration() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $iterator = $hydrator->iterate($stmt, $rsm); $rowNum = 0; while (($row = $iterator->next()) !== false) { - $this->assertEquals(1, count($row)); - $this->assertTrue(is_array($row[0])); + self::assertEquals(1, count($row)); + self::assertTrue(is_array($row[0])); if ($rowNum == 0) { - $this->assertEquals(1, $row[0]['id']); - $this->assertEquals('romanb', $row[0]['name']); + self::assertEquals(1, $row[0]['id']); + self::assertEquals('romanb', $row[0]['name']); } else if ($rowNum == 1) { - $this->assertEquals(2, $row[0]['id']); - $this->assertEquals('jwage', $row[0]['name']); + self::assertEquals(2, $row[0]['id']); + self::assertEquals('jwage', $row[0]['name']); } ++$rowNum; @@ -1062,21 +1065,21 @@ public function testResultIterationWithAliasedUserEntity() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $iterator = $hydrator->iterate($stmt, $rsm); $rowNum = 0; while (($row = $iterator->next()) !== false) { - $this->assertEquals(1, count($row)); - $this->assertArrayHasKey(0, $row); - $this->assertArrayHasKey('user', $row[0]); + self::assertEquals(1, count($row)); + self::assertArrayHasKey(0, $row); + self::assertArrayHasKey('user', $row[0]); if ($rowNum == 0) { - $this->assertEquals(1, $row[0]['user']['id']); - $this->assertEquals('romanb', $row[0]['user']['name']); + self::assertEquals(1, $row[0]['user']['id']); + self::assertEquals('romanb', $row[0]['user']['name']); } else if ($rowNum == 1) { - $this->assertEquals(2, $row[0]['user']['id']); - $this->assertEquals('jwage', $row[0]['user']['name']); + self::assertEquals(2, $row[0]['user']['id']); + self::assertEquals('jwage', $row[0]['user']['name']); } ++$rowNum; @@ -1107,13 +1110,13 @@ public function testSkipUnknownColumns() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(1, count($result)); - $this->assertArrayHasKey('id', $result[0]); - $this->assertArrayHasKey('name', $result[0]); - $this->assertArrayNotHasKey('foo', $result[0]); + self::assertEquals(1, count($result)); + self::assertArrayHasKey('id', $result[0]); + self::assertArrayHasKey('name', $result[0]); + self::assertArrayNotHasKey('foo', $result[0]); } /** @@ -1130,7 +1133,7 @@ public function testMissingIdForRootEntity($userEntityKey) $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); + $rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); // Faked result set $resultSet = [ @@ -1158,20 +1161,20 @@ public function testMissingIdForRootEntity($userEntityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(4, count($result), "Should hydrate four results."); + self::assertEquals(4, count($result), "Should hydrate four results."); - $this->assertEquals('ROMANB', $result[0]['nameUpper']); - $this->assertEquals('ROMANB', $result[1]['nameUpper']); - $this->assertEquals('JWAGE', $result[2]['nameUpper']); - $this->assertEquals('JWAGE', $result[3]['nameUpper']); + self::assertEquals('ROMANB', $result[0]['nameUpper']); + self::assertEquals('ROMANB', $result[1]['nameUpper']); + self::assertEquals('JWAGE', $result[2]['nameUpper']); + self::assertEquals('JWAGE', $result[3]['nameUpper']); - $this->assertEquals(['id' => 1, 'status' => 'developer'], $result[0][$userEntityKey]); - $this->assertNull($result[1][$userEntityKey]); - $this->assertEquals(['id' => 2, 'status' => 'developer'], $result[2][$userEntityKey]); - $this->assertNull($result[3][$userEntityKey]); + self::assertEquals(['id' => 1, 'status' => 'developer'], $result[0][$userEntityKey]); + self::assertNull($result[1][$userEntityKey]); + self::assertEquals(['id' => 2, 'status' => 'developer'], $result[2][$userEntityKey]); + self::assertNull($result[3][$userEntityKey]); } /** @@ -1189,7 +1192,7 @@ public function testIndexByAndMixedResult($userEntityKey) $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); + $rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); $rsm->addIndexBy('u', 'id'); // Faked result set @@ -1208,15 +1211,15 @@ public function testIndexByAndMixedResult($userEntityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertTrue(isset($result[1])); - $this->assertEquals(1, $result[1][$userEntityKey]['id']); + self::assertTrue(isset($result[1])); + self::assertEquals(1, $result[1][$userEntityKey]['id']); - $this->assertTrue(isset($result[2])); - $this->assertEquals(2, $result[2][$userEntityKey]['id']); + self::assertTrue(isset($result[2])); + self::assertEquals(2, $result[2][$userEntityKey]['id']); } } diff --git a/tests/Doctrine/Tests/ORM/Hydration/CustomHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/CustomHydratorTest.php index 7342b942f4f..24b127cbae6 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/CustomHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/CustomHydratorTest.php @@ -1,5 +1,7 @@ _getTestEntityManager(); + $em = $this->getTestEntityManager(); $config = $em->getConfiguration(); $config->addCustomHydrationMode('CustomHydrator', CustomHydrator::class); $hydrator = $em->newHydrator('CustomHydrator'); - $this->assertInstanceOf(CustomHydrator::class, $hydrator); - $this->assertNull($config->getCustomHydrationMode('does not exist')); + self::assertInstanceOf(CustomHydrator::class, $hydrator); + self::assertNull($config->getCustomHydrationMode('does not exist')); } } @@ -23,6 +25,6 @@ class CustomHydrator extends AbstractHydrator { protected function hydrateAllData() { - return $this->_stmt->fetchAll(PDO::FETCH_ASSOC); + return $this->stmt->fetchAll(PDO::FETCH_ASSOC); } } diff --git a/tests/Doctrine/Tests/ORM/Hydration/HydrationTestCase.php b/tests/Doctrine/Tests/ORM/Hydration/HydrationTestCase.php index a2b099162be..36f644444f1 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/HydrationTestCase.php +++ b/tests/Doctrine/Tests/ORM/Hydration/HydrationTestCase.php @@ -1,21 +1,23 @@ _em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); } /** Helper method */ - protected function _createParserResult($resultSetMapping, $isMixedQuery = false) + protected function createParserResult($resultSetMapping, $isMixedQuery = false) { $parserResult = new ParserResult; $parserResult->setResultSetMapping($resultSetMapping); diff --git a/tests/Doctrine/Tests/ORM/Hydration/ObjectHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/ObjectHydratorTest.php index c7d82a0dc7a..67faa0f4dba 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/ObjectHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/ObjectHydratorTest.php @@ -1,8 +1,12 @@ _em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertInstanceOf(CmsUser::class, $result[0]); - $this->assertInstanceOf(CmsUser::class, $result[1]); + self::assertInstanceOf(CmsUser::class, $result[0]); + self::assertInstanceOf(CmsUser::class, $result[1]); - $this->assertEquals(1, $result[0]->id); - $this->assertEquals('romanb', $result[0]->name); + self::assertEquals(1, $result[0]->id); + self::assertEquals('romanb', $result[0]->name); - $this->assertEquals(2, $result[1]->id); - $this->assertEquals('jwage', $result[1]->name); + self::assertEquals(2, $result[1]->id); + self::assertEquals('jwage', $result[1]->name); } /** @@ -115,22 +119,22 @@ public function testSimpleEntityQueryWithAliasedUserEntity() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertArrayHasKey('user', $result[0]); - $this->assertInstanceOf(CmsUser::class, $result[0]['user']); + self::assertArrayHasKey('user', $result[0]); + self::assertInstanceOf(CmsUser::class, $result[0]['user']); - $this->assertArrayHasKey('user', $result[1]); - $this->assertInstanceOf(CmsUser::class, $result[1]['user']); + self::assertArrayHasKey('user', $result[1]); + self::assertInstanceOf(CmsUser::class, $result[1]['user']); - $this->assertEquals(1, $result[0]['user']->id); - $this->assertEquals('romanb', $result[0]['user']->name); + self::assertEquals(1, $result[0]['user']->id); + self::assertEquals('romanb', $result[0]['user']->name); - $this->assertEquals(2, $result[1]['user']->id); - $this->assertEquals('jwage', $result[1]['user']->name); + self::assertEquals(2, $result[1]['user']->id); + self::assertEquals('jwage', $result[1]['user']->name); } /** @@ -164,27 +168,27 @@ public function testSimpleMultipleRootEntityQuery() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(4, count($result)); + self::assertEquals(4, count($result)); - $this->assertInstanceOf(CmsUser::class, $result[0]); - $this->assertInstanceOf(CmsArticle::class, $result[1]); - $this->assertInstanceOf(CmsUser::class, $result[2]); - $this->assertInstanceOf(CmsArticle::class, $result[3]); + self::assertInstanceOf(CmsUser::class, $result[0]); + self::assertInstanceOf(CmsArticle::class, $result[1]); + self::assertInstanceOf(CmsUser::class, $result[2]); + self::assertInstanceOf(CmsArticle::class, $result[3]); - $this->assertEquals(1, $result[0]->id); - $this->assertEquals('romanb', $result[0]->name); + self::assertEquals(1, $result[0]->id); + self::assertEquals('romanb', $result[0]->name); - $this->assertEquals(1, $result[1]->id); - $this->assertEquals('Cool things.', $result[1]->topic); + self::assertEquals(1, $result[1]->id); + self::assertEquals('Cool things.', $result[1]->topic); - $this->assertEquals(2, $result[2]->id); - $this->assertEquals('jwage', $result[2]->name); + self::assertEquals(2, $result[2]->id); + self::assertEquals('jwage', $result[2]->name); - $this->assertEquals(2, $result[3]->id); - $this->assertEquals('Cool things II.', $result[3]->topic); + self::assertEquals(2, $result[3]->id); + self::assertEquals('Cool things II.', $result[3]->topic); } /** @@ -218,34 +222,34 @@ public function testSimpleMultipleRootEntityQueryWithAliasedUserEntity() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(4, count($result)); - - $this->assertArrayHasKey('user', $result[0]); - $this->assertArrayNotHasKey(0, $result[0]); - $this->assertInstanceOf(CmsUser::class, $result[0]['user']); - $this->assertEquals(1, $result[0]['user']->id); - $this->assertEquals('romanb', $result[0]['user']->name); - - $this->assertArrayHasKey(0, $result[1]); - $this->assertArrayNotHasKey('user', $result[1]); - $this->assertInstanceOf(CmsArticle::class, $result[1][0]); - $this->assertEquals(1, $result[1][0]->id); - $this->assertEquals('Cool things.', $result[1][0]->topic); - - $this->assertArrayHasKey('user', $result[2]); - $this->assertArrayNotHasKey(0, $result[2]); - $this->assertInstanceOf(CmsUser::class, $result[2]['user']); - $this->assertEquals(2, $result[2]['user']->id); - $this->assertEquals('jwage', $result[2]['user']->name); - - $this->assertArrayHasKey(0, $result[3]); - $this->assertArrayNotHasKey('user', $result[3]); - $this->assertInstanceOf(CmsArticle::class, $result[3][0]); - $this->assertEquals(2, $result[3][0]->id); - $this->assertEquals('Cool things II.', $result[3][0]->topic); + self::assertEquals(4, count($result)); + + self::assertArrayHasKey('user', $result[0]); + self::assertArrayNotHasKey(0, $result[0]); + self::assertInstanceOf(CmsUser::class, $result[0]['user']); + self::assertEquals(1, $result[0]['user']->id); + self::assertEquals('romanb', $result[0]['user']->name); + + self::assertArrayHasKey(0, $result[1]); + self::assertArrayNotHasKey('user', $result[1]); + self::assertInstanceOf(CmsArticle::class, $result[1][0]); + self::assertEquals(1, $result[1][0]->id); + self::assertEquals('Cool things.', $result[1][0]->topic); + + self::assertArrayHasKey('user', $result[2]); + self::assertArrayNotHasKey(0, $result[2]); + self::assertInstanceOf(CmsUser::class, $result[2]['user']); + self::assertEquals(2, $result[2]['user']->id); + self::assertEquals('jwage', $result[2]['user']->name); + + self::assertArrayHasKey(0, $result[3]); + self::assertArrayNotHasKey('user', $result[3]); + self::assertInstanceOf(CmsArticle::class, $result[3][0]); + self::assertEquals(2, $result[3][0]->id); + self::assertEquals('Cool things II.', $result[3][0]->topic); } /** @@ -279,34 +283,34 @@ public function testSimpleMultipleRootEntityQueryWithAliasedArticleEntity() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(4, count($result)); - - $this->assertArrayHasKey(0, $result[0]); - $this->assertArrayNotHasKey('article', $result[0]); - $this->assertInstanceOf(CmsUser::class, $result[0][0]); - $this->assertEquals(1, $result[0][0]->id); - $this->assertEquals('romanb', $result[0][0]->name); - - $this->assertArrayHasKey('article', $result[1]); - $this->assertArrayNotHasKey(0, $result[1]); - $this->assertInstanceOf(CmsArticle::class, $result[1]['article']); - $this->assertEquals(1, $result[1]['article']->id); - $this->assertEquals('Cool things.', $result[1]['article']->topic); - - $this->assertArrayHasKey(0, $result[2]); - $this->assertArrayNotHasKey('article', $result[2]); - $this->assertInstanceOf(CmsUser::class, $result[2][0]); - $this->assertEquals(2, $result[2][0]->id); - $this->assertEquals('jwage', $result[2][0]->name); - - $this->assertArrayHasKey('article', $result[3]); - $this->assertArrayNotHasKey(0, $result[3]); - $this->assertInstanceOf(CmsArticle::class, $result[3]['article']); - $this->assertEquals(2, $result[3]['article']->id); - $this->assertEquals('Cool things II.', $result[3]['article']->topic); + self::assertEquals(4, count($result)); + + self::assertArrayHasKey(0, $result[0]); + self::assertArrayNotHasKey('article', $result[0]); + self::assertInstanceOf(CmsUser::class, $result[0][0]); + self::assertEquals(1, $result[0][0]->id); + self::assertEquals('romanb', $result[0][0]->name); + + self::assertArrayHasKey('article', $result[1]); + self::assertArrayNotHasKey(0, $result[1]); + self::assertInstanceOf(CmsArticle::class, $result[1]['article']); + self::assertEquals(1, $result[1]['article']->id); + self::assertEquals('Cool things.', $result[1]['article']->topic); + + self::assertArrayHasKey(0, $result[2]); + self::assertArrayNotHasKey('article', $result[2]); + self::assertInstanceOf(CmsUser::class, $result[2][0]); + self::assertEquals(2, $result[2][0]->id); + self::assertEquals('jwage', $result[2][0]->name); + + self::assertArrayHasKey('article', $result[3]); + self::assertArrayNotHasKey(0, $result[3]); + self::assertInstanceOf(CmsArticle::class, $result[3]['article']); + self::assertEquals(2, $result[3]['article']->id); + self::assertEquals('Cool things II.', $result[3]['article']->topic); } /** @@ -340,34 +344,34 @@ public function testSimpleMultipleRootEntityQueryWithAliasedEntities() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(4, count($result)); - - $this->assertArrayHasKey('user', $result[0]); - $this->assertArrayNotHasKey('article', $result[0]); - $this->assertInstanceOf(CmsUser::class, $result[0]['user']); - $this->assertEquals(1, $result[0]['user']->id); - $this->assertEquals('romanb', $result[0]['user']->name); - - $this->assertArrayHasKey('article', $result[1]); - $this->assertArrayNotHasKey('user', $result[1]); - $this->assertInstanceOf(CmsArticle::class, $result[1]['article']); - $this->assertEquals(1, $result[1]['article']->id); - $this->assertEquals('Cool things.', $result[1]['article']->topic); - - $this->assertArrayHasKey('user', $result[2]); - $this->assertArrayNotHasKey('article', $result[2]); - $this->assertInstanceOf(CmsUser::class, $result[2]['user']); - $this->assertEquals(2, $result[2]['user']->id); - $this->assertEquals('jwage', $result[2]['user']->name); - - $this->assertArrayHasKey('article', $result[3]); - $this->assertArrayNotHasKey('user', $result[3]); - $this->assertInstanceOf(CmsArticle::class, $result[3]['article']); - $this->assertEquals(2, $result[3]['article']->id); - $this->assertEquals('Cool things II.', $result[3]['article']->topic); + self::assertEquals(4, count($result)); + + self::assertArrayHasKey('user', $result[0]); + self::assertArrayNotHasKey('article', $result[0]); + self::assertInstanceOf(CmsUser::class, $result[0]['user']); + self::assertEquals(1, $result[0]['user']->id); + self::assertEquals('romanb', $result[0]['user']->name); + + self::assertArrayHasKey('article', $result[1]); + self::assertArrayNotHasKey('user', $result[1]); + self::assertInstanceOf(CmsArticle::class, $result[1]['article']); + self::assertEquals(1, $result[1]['article']->id); + self::assertEquals('Cool things.', $result[1]['article']->topic); + + self::assertArrayHasKey('user', $result[2]); + self::assertArrayNotHasKey('article', $result[2]); + self::assertInstanceOf(CmsUser::class, $result[2]['user']); + self::assertEquals(2, $result[2]['user']->id); + self::assertEquals('jwage', $result[2]['user']->name); + + self::assertArrayHasKey('article', $result[3]); + self::assertArrayNotHasKey('user', $result[3]); + self::assertInstanceOf(CmsArticle::class, $result[3]['article']); + self::assertEquals(2, $result[3]['article']->id); + self::assertEquals('Cool things II.', $result[3]['article']->topic); } /** @@ -384,7 +388,7 @@ public function testMixedQueryNormalJoin($userEntityKey) $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addScalarResult('sclr0', 'numPhones', 'integer'); + $rsm->addScalarResult('sclr0', 'numPhones', Type::getType('integer')); // Faked result set $resultSet = [ @@ -402,22 +406,22 @@ public function testMixedQueryNormalJoin($userEntityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertInternalType('array', $result); - $this->assertInternalType('array', $result[0]); - $this->assertInternalType('array', $result[1]); + self::assertInternalType('array', $result); + self::assertInternalType('array', $result[0]); + self::assertInternalType('array', $result[1]); // first user => 2 phonenumbers - $this->assertEquals(2, $result[0]['numPhones']); - $this->assertInstanceOf(CmsUser::class, $result[0][$userEntityKey]); + self::assertEquals(2, $result[0]['numPhones']); + self::assertInstanceOf(CmsUser::class, $result[0][$userEntityKey]); // second user => 1 phonenumber - $this->assertEquals(1, $result[1]['numPhones']); - $this->assertInstanceOf(CmsUser::class, $result[1][$userEntityKey]); + self::assertEquals(1, $result[1]['numPhones']); + self::assertInstanceOf(CmsUser::class, $result[1][$userEntityKey]); } /** @@ -440,7 +444,7 @@ public function testMixedQueryFetchJoin($userEntityKey) $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); $rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); - $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); + $rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); // Faked result set $resultSet = [ @@ -466,34 +470,34 @@ public function testMixedQueryFetchJoin($userEntityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertInternalType('array', $result); - $this->assertInternalType('array', $result[0]); - $this->assertInternalType('array', $result[1]); + self::assertInternalType('array', $result); + self::assertInternalType('array', $result[0]); + self::assertInternalType('array', $result[1]); - $this->assertInstanceOf(CmsUser::class, $result[0][$userEntityKey]); - $this->assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->phonenumbers); - $this->assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[0]); + self::assertInstanceOf(CmsUser::class, $result[0][$userEntityKey]); + self::assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->phonenumbers); + self::assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[0]); - $this->assertInstanceOf(CmsUser::class, $result[1][$userEntityKey]); - $this->assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->phonenumbers); - $this->assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[1]); + self::assertInstanceOf(CmsUser::class, $result[1][$userEntityKey]); + self::assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->phonenumbers); + self::assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[1]); // first user => 2 phonenumbers - $this->assertEquals(2, count($result[0][$userEntityKey]->phonenumbers)); - $this->assertEquals('ROMANB', $result[0]['nameUpper']); + self::assertEquals(2, count($result[0][$userEntityKey]->phonenumbers)); + self::assertEquals('ROMANB', $result[0]['nameUpper']); // second user => 1 phonenumber - $this->assertEquals(1, count($result[1][$userEntityKey]->phonenumbers)); - $this->assertEquals('JWAGE', $result[1]['nameUpper']); + self::assertEquals(1, count($result[1][$userEntityKey]->phonenumbers)); + self::assertEquals('JWAGE', $result[1]['nameUpper']); - $this->assertEquals(42, $result[0][$userEntityKey]->phonenumbers[0]->phonenumber); - $this->assertEquals(43, $result[0][$userEntityKey]->phonenumbers[1]->phonenumber); - $this->assertEquals(91, $result[1][$userEntityKey]->phonenumbers[0]->phonenumber); + self::assertEquals(42, $result[0][$userEntityKey]->phonenumbers[0]->phonenumber); + self::assertEquals(43, $result[0][$userEntityKey]->phonenumbers[1]->phonenumber); + self::assertEquals(91, $result[1][$userEntityKey]->phonenumbers[0]->phonenumber); } /** @@ -517,7 +521,7 @@ public function testMixedQueryFetchJoinCustomIndex($userEntityKey) ); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); + $rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); $rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); $rsm->addIndexBy('u', 'id'); $rsm->addIndexBy('p', 'phonenumber'); @@ -547,33 +551,33 @@ public function testMixedQueryFetchJoinCustomIndex($userEntityKey) $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertInternalType('array', $result); - $this->assertInternalType('array', $result[1]); - $this->assertInternalType('array', $result[2]); + self::assertInternalType('array', $result); + self::assertInternalType('array', $result[1]); + self::assertInternalType('array', $result[2]); // test the scalar values - $this->assertEquals('ROMANB', $result[1]['nameUpper']); - $this->assertEquals('JWAGE', $result[2]['nameUpper']); + self::assertEquals('ROMANB', $result[1]['nameUpper']); + self::assertEquals('JWAGE', $result[2]['nameUpper']); - $this->assertInstanceOf(CmsUser::class, $result[1][$userEntityKey]); - $this->assertInstanceOf(CmsUser::class, $result[2][$userEntityKey]); - $this->assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->phonenumbers); + self::assertInstanceOf(CmsUser::class, $result[1][$userEntityKey]); + self::assertInstanceOf(CmsUser::class, $result[2][$userEntityKey]); + self::assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->phonenumbers); // first user => 2 phonenumbers. notice the custom indexing by user id - $this->assertEquals(2, count($result[1][$userEntityKey]->phonenumbers)); + self::assertEquals(2, count($result[1][$userEntityKey]->phonenumbers)); // second user => 1 phonenumber. notice the custom indexing by user id - $this->assertEquals(1, count($result[2][$userEntityKey]->phonenumbers)); + self::assertEquals(1, count($result[2][$userEntityKey]->phonenumbers)); // test the custom indexing of the phonenumbers - $this->assertTrue(isset($result[1][$userEntityKey]->phonenumbers['42'])); - $this->assertTrue(isset($result[1][$userEntityKey]->phonenumbers['43'])); - $this->assertTrue(isset($result[2][$userEntityKey]->phonenumbers['91'])); + self::assertTrue(isset($result[1][$userEntityKey]->phonenumbers['42'])); + self::assertTrue(isset($result[1][$userEntityKey]->phonenumbers['43'])); + self::assertTrue(isset($result[2][$userEntityKey]->phonenumbers['91'])); } /** @@ -602,7 +606,7 @@ public function testMixedQueryMultipleFetchJoin($userEntityKey) ); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); + $rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); $rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); $rsm->addFieldResult('a', 'a__id', 'id'); $rsm->addFieldResult('a', 'a__topic', 'topic'); @@ -661,28 +665,28 @@ public function testMixedQueryMultipleFetchJoin($userEntityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(2, count($result)); - - $this->assertTrue(is_array($result)); - $this->assertTrue(is_array($result[0])); - $this->assertTrue(is_array($result[1])); - - $this->assertInstanceOf(CmsUser::class, $result[0][$userEntityKey]); - $this->assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->phonenumbers); - $this->assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[0]); - $this->assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[1]); - $this->assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->articles); - $this->assertInstanceOf(CmsArticle::class, $result[0][$userEntityKey]->articles[0]); - $this->assertInstanceOf(CmsArticle::class, $result[0][$userEntityKey]->articles[1]); - - $this->assertInstanceOf(CmsUser::class, $result[1][$userEntityKey]); - $this->assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->phonenumbers); - $this->assertInstanceOf(CmsPhonenumber::class, $result[1][$userEntityKey]->phonenumbers[0]); - $this->assertInstanceOf(CmsArticle::class, $result[1][$userEntityKey]->articles[0]); - $this->assertInstanceOf(CmsArticle::class, $result[1][$userEntityKey]->articles[1]); + self::assertEquals(2, count($result)); + + self::assertTrue(is_array($result)); + self::assertTrue(is_array($result[0])); + self::assertTrue(is_array($result[1])); + + self::assertInstanceOf(CmsUser::class, $result[0][$userEntityKey]); + self::assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->phonenumbers); + self::assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[0]); + self::assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[1]); + self::assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->articles); + self::assertInstanceOf(CmsArticle::class, $result[0][$userEntityKey]->articles[0]); + self::assertInstanceOf(CmsArticle::class, $result[0][$userEntityKey]->articles[1]); + + self::assertInstanceOf(CmsUser::class, $result[1][$userEntityKey]); + self::assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->phonenumbers); + self::assertInstanceOf(CmsPhonenumber::class, $result[1][$userEntityKey]->phonenumbers[0]); + self::assertInstanceOf(CmsArticle::class, $result[1][$userEntityKey]->articles[0]); + self::assertInstanceOf(CmsArticle::class, $result[1][$userEntityKey]->articles[1]); } /** @@ -718,7 +722,7 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) ); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); + $rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); $rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); $rsm->addFieldResult('a', 'a__id', 'id'); $rsm->addFieldResult('a', 'a__topic', 'topic'); @@ -791,46 +795,46 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertTrue(is_array($result)); - $this->assertTrue(is_array($result[0])); - $this->assertTrue(is_array($result[1])); + self::assertTrue(is_array($result)); + self::assertTrue(is_array($result[0])); + self::assertTrue(is_array($result[1])); - $this->assertInstanceOf(CmsUser::class, $result[0][$userEntityKey]); - $this->assertInstanceOf(CmsUser::class, $result[1][$userEntityKey]); + self::assertInstanceOf(CmsUser::class, $result[0][$userEntityKey]); + self::assertInstanceOf(CmsUser::class, $result[1][$userEntityKey]); // phonenumbers - $this->assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->phonenumbers); - $this->assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[0]); - $this->assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[1]); + self::assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->phonenumbers); + self::assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[0]); + self::assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[1]); - $this->assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->phonenumbers); - $this->assertInstanceOf(CmsPhonenumber::class, $result[1][$userEntityKey]->phonenumbers[0]); + self::assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->phonenumbers); + self::assertInstanceOf(CmsPhonenumber::class, $result[1][$userEntityKey]->phonenumbers[0]); // articles - $this->assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->articles); - $this->assertInstanceOf(CmsArticle::class, $result[0][$userEntityKey]->articles[0]); - $this->assertInstanceOf(CmsArticle::class, $result[0][$userEntityKey]->articles[1]); + self::assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->articles); + self::assertInstanceOf(CmsArticle::class, $result[0][$userEntityKey]->articles[0]); + self::assertInstanceOf(CmsArticle::class, $result[0][$userEntityKey]->articles[1]); - $this->assertInstanceOf(CmsArticle::class, $result[1][$userEntityKey]->articles[0]); - $this->assertInstanceOf(CmsArticle::class, $result[1][$userEntityKey]->articles[1]); + self::assertInstanceOf(CmsArticle::class, $result[1][$userEntityKey]->articles[0]); + self::assertInstanceOf(CmsArticle::class, $result[1][$userEntityKey]->articles[1]); // article comments - $this->assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->articles[0]->comments); - $this->assertInstanceOf(CmsComment::class, $result[0][$userEntityKey]->articles[0]->comments[0]); + self::assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->articles[0]->comments); + self::assertInstanceOf(CmsComment::class, $result[0][$userEntityKey]->articles[0]->comments[0]); // empty comment collections - $this->assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->articles[1]->comments); - $this->assertEquals(0, count($result[0][$userEntityKey]->articles[1]->comments)); + self::assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->articles[1]->comments); + self::assertEquals(0, count($result[0][$userEntityKey]->articles[1]->comments)); - $this->assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->articles[0]->comments); - $this->assertEquals(0, count($result[1][$userEntityKey]->articles[0]->comments)); - $this->assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->articles[1]->comments); - $this->assertEquals(0, count($result[1][$userEntityKey]->articles[1]->comments)); + self::assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->articles[0]->comments); + self::assertEquals(0, count($result[1][$userEntityKey]->articles[0]->comments)); + self::assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->articles[1]->comments); + self::assertEquals(0, count($result[1][$userEntityKey]->articles[1]->comments)); } /** @@ -904,24 +908,24 @@ public function testEntityQueryCustomResultSetOrder() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertInstanceOf(ForumCategory::class, $result[0]); - $this->assertInstanceOf(ForumCategory::class, $result[1]); + self::assertInstanceOf(ForumCategory::class, $result[0]); + self::assertInstanceOf(ForumCategory::class, $result[1]); - $this->assertTrue($result[0] !== $result[1]); + self::assertTrue($result[0] !== $result[1]); - $this->assertEquals(1, $result[0]->getId()); - $this->assertEquals(2, $result[1]->getId()); + self::assertEquals(1, $result[0]->getId()); + self::assertEquals(2, $result[1]->getId()); - $this->assertTrue(isset($result[0]->boards)); - $this->assertEquals(3, count($result[0]->boards)); + self::assertTrue(isset($result[0]->boards)); + self::assertEquals(3, count($result[0]->boards)); - $this->assertTrue(isset($result[1]->boards)); - $this->assertEquals(1, count($result[1]->boards)); + self::assertTrue(isset($result[1]->boards)); + self::assertEquals(1, count($result[1]->boards)); } /** @@ -947,11 +951,11 @@ public function testSkipUnknownColumns() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(1, count($result)); - $this->assertInstanceOf(CmsUser::class, $result[0]); + self::assertEquals(1, count($result)); + self::assertInstanceOf(CmsUser::class, $result[0]); } /** @@ -964,8 +968,8 @@ public function testScalarQueryWithoutResultVariables($userEntityKey) { $rsm = new ResultSetMapping; $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); - $rsm->addScalarResult('sclr0', 'id', 'integer'); - $rsm->addScalarResult('sclr1', 'name', 'string'); + $rsm->addScalarResult('sclr0', 'id', Type::getType('integer')); + $rsm->addScalarResult('sclr1', 'name', Type::getType('string')); // Faked result set $resultSet = [ @@ -980,19 +984,19 @@ public function testScalarQueryWithoutResultVariables($userEntityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertInternalType('array', $result[0]); - $this->assertInternalType('array', $result[1]); + self::assertInternalType('array', $result[0]); + self::assertInternalType('array', $result[1]); - $this->assertEquals(1, $result[0]['id']); - $this->assertEquals('romanb', $result[0]['name']); + self::assertEquals(1, $result[0]['id']); + self::assertEquals('romanb', $result[0]['name']); - $this->assertEquals(2, $result[1]['id']); - $this->assertEquals('jwage', $result[1]['name']); + self::assertEquals(2, $result[1]['id']); + self::assertEquals('jwage', $result[1]['name']); } /** @@ -1005,7 +1009,7 @@ public function testCreatesProxyForLazyLoadingWithForeignKeys() $rsm->addEntityResult(ECommerceProduct::class, 'p'); $rsm->addFieldResult('p', 'p__id', 'id'); $rsm->addFieldResult('p', 'p__name', 'name'); - $rsm->addMetaResult('p', 'p__shipping_id', 'shipping_id', false, 'integer'); + $rsm->addMetaResult('p', 'p__shipping_id', 'shipping_id', false, Type::getType('integer')); // Faked result set $resultSet = [ @@ -1029,19 +1033,20 @@ public function testCreatesProxyForLazyLoadingWithForeignKeys() ->with($this->equalTo(ECommerceShipping::class), ['id' => 42]) ->will($this->returnValue($proxyInstance)); - $this->_em->setProxyFactory($proxyFactory); + // @todo guilhermeblanco This should never have happened... replace this Reflection injection with proper API. + $this->swapPrivateProperty($this->em, 'proxyFactory', $proxyFactory); // configuring lazy loading - $metadata = $this->_em->getClassMetadata(ECommerceProduct::class); - $metadata->associationMappings['shipping']['fetch'] = ClassMetadata::FETCH_LAZY; + $metadata = $this->em->getClassMetadata(ECommerceProduct::class); + $metadata->getProperty('shipping')->setFetchMode(FetchMode::LAZY); $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(1, count($result)); + self::assertEquals(1, count($result)); - $this->assertInstanceOf(ECommerceProduct::class, $result[0]); + self::assertInstanceOf(ECommerceProduct::class, $result[0]); } /** @@ -1054,7 +1059,7 @@ public function testCreatesProxyForLazyLoadingWithForeignKeysWithAliasedProductE $rsm->addEntityResult(ECommerceProduct::class, 'p', 'product'); $rsm->addFieldResult('p', 'p__id', 'id'); $rsm->addFieldResult('p', 'p__name', 'name'); - $rsm->addMetaResult('p', 'p__shipping_id', 'shipping_id', false, 'integer'); + $rsm->addMetaResult('p', 'p__shipping_id', 'shipping_id', false, Type::getType('integer')); // Faked result set $resultSet = [ @@ -1078,20 +1083,21 @@ public function testCreatesProxyForLazyLoadingWithForeignKeysWithAliasedProductE ->with($this->equalTo(ECommerceShipping::class), ['id' => 42]) ->will($this->returnValue($proxyInstance)); - $this->_em->setProxyFactory($proxyFactory); + // @todo guilhermeblanco This should never have happened... replace this Reflection injection with proper API. + $this->swapPrivateProperty($this->em, 'proxyFactory', $proxyFactory); // configuring lazy loading - $metadata = $this->_em->getClassMetadata(ECommerceProduct::class); - $metadata->associationMappings['shipping']['fetch'] = ClassMetadata::FETCH_LAZY; + $metadata = $this->em->getClassMetadata(ECommerceProduct::class); + $metadata->getProperty('shipping')->setFetchMode(FetchMode::LAZY); $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(1, count($result)); + self::assertEquals(1, count($result)); - $this->assertInternalType('array', $result[0]); - $this->assertInstanceOf(ECommerceProduct::class, $result[0]['product']); + self::assertInternalType('array', $result[0]); + self::assertInstanceOf(ECommerceProduct::class, $result[0]['product']); } /** @@ -1145,16 +1151,16 @@ public function testChainedJoinWithEmptyCollections() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertInstanceOf(CmsUser::class, $result[0]); - $this->assertInstanceOf(CmsUser::class, $result[1]); + self::assertInstanceOf(CmsUser::class, $result[0]); + self::assertInstanceOf(CmsUser::class, $result[1]); - $this->assertEquals(0, $result[0]->articles->count()); - $this->assertEquals(0, $result[1]->articles->count()); + self::assertEquals(0, $result[0]->articles->count()); + self::assertEquals(0, $result[1]->articles->count()); } /** @@ -1208,21 +1214,87 @@ public function testChainedJoinWithEmptyCollectionsWithAliasedUserEntity() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertInternalType('array', $result[0]); - $this->assertInstanceOf(CmsUser::class, $result[0]['user']); + self::assertInternalType('array', $result[0]); + self::assertInstanceOf(CmsUser::class, $result[0]['user']); - $this->assertInternalType('array', $result[1]); - $this->assertInstanceOf(CmsUser::class, $result[1]['user']); + self::assertInternalType('array', $result[1]); + self::assertInstanceOf(CmsUser::class, $result[1]['user']); - $this->assertEquals(0, $result[0]['user']->articles->count()); - $this->assertEquals(0, $result[1]['user']->articles->count()); + self::assertEquals(0, $result[0]['user']->articles->count()); + self::assertEquals(0, $result[1]['user']->articles->count()); } + /** + * SELECT PARTIAL u.{id,status}, a.id, a.topic, c.id as cid, c.topic as ctopic + * FROM CmsUser u + * LEFT JOIN u.articles a + * LEFT JOIN a.comments c + * + * @todo Figure it out why this test is commented out and provide a better description in docblock + * + * @group bubu + * @dataProvider provideDataForUserEntityResult + */ + /*public function testChainedJoinWithScalars($userEntityKey) + { + $rsm = new ResultSetMapping; + $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); + $rsm->addFieldResult('u', 'u__id', 'id'); + $rsm->addFieldResult('u', 'u__status', 'status'); + $rsm->addScalarResult('a__id', 'id', Type::getType('integer')); + $rsm->addScalarResult('a__topic', 'topic', Type::getType('string')); + $rsm->addScalarResult('c__id', 'cid', Type::getType('integer')); + $rsm->addScalarResult('c__topic', 'ctopic', Type::getType('string')); + + // Faked result set + $resultSet = array( + //row1 + array( + 'u__id' => '1', + 'u__status' => 'developer', + 'a__id' => '1', + 'a__topic' => 'The First', + 'c__id' => '1', + 'c__topic' => 'First Comment' + ), + array( + 'u__id' => '1', + 'u__status' => 'developer', + 'a__id' => '1', + 'a__topic' => 'The First', + 'c__id' => '2', + 'c__topic' => 'Second Comment' + ), + array( + 'u__id' => '1', + 'u__status' => 'developer', + 'a__id' => '42', + 'a__topic' => 'The Answer', + 'c__id' => null, + 'c__topic' => null + ), + ); + + $stmt = new HydratorMockStatement($resultSet); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); + $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + + \Doctrine\Common\Util\Debug::dump($result, 3); + + self::assertEquals(1, count($result)); + + self::assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0][$userEntityKey]); // User object + self::assertEquals(42, $result[0]['id']); + self::assertEquals('The First', $result[0]['topic']); + self::assertEquals(1, $result[0]['cid']); + self::assertEquals('First Comment', $result[0]['ctopic']); + }*/ + /** * SELECT PARTIAL u.{id, name} * FROM Doctrine\Tests\Models\CMS\CmsUser u @@ -1247,20 +1319,20 @@ public function testResultIteration() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $iterableResult = $hydrator->iterate($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $rowNum = 0; while (($row = $iterableResult->next()) !== false) { - $this->assertEquals(1, count($row)); - $this->assertInstanceOf(CmsUser::class, $row[0]); + self::assertEquals(1, count($row)); + self::assertInstanceOf(CmsUser::class, $row[0]); if ($rowNum == 0) { - $this->assertEquals(1, $row[0]->id); - $this->assertEquals('romanb', $row[0]->name); + self::assertEquals(1, $row[0]->id); + self::assertEquals('romanb', $row[0]->name); } else if ($rowNum == 1) { - $this->assertEquals(2, $row[0]->id); - $this->assertEquals('jwage', $row[0]->name); + self::assertEquals(2, $row[0]->id); + self::assertEquals('jwage', $row[0]->name); } ++$rowNum; @@ -1291,22 +1363,22 @@ public function testResultIterationWithAliasedUserEntity() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $iterableResult = $hydrator->iterate($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $rowNum = 0; while (($row = $iterableResult->next()) !== false) { - $this->assertEquals(1, count($row)); - $this->assertArrayHasKey(0, $row); - $this->assertArrayHasKey('user', $row[0]); - $this->assertInstanceOf(CmsUser::class, $row[0]['user']); + self::assertEquals(1, count($row)); + self::assertArrayHasKey(0, $row); + self::assertArrayHasKey('user', $row[0]); + self::assertInstanceOf(CmsUser::class, $row[0]['user']); if ($rowNum == 0) { - $this->assertEquals(1, $row[0]['user']->id); - $this->assertEquals('romanb', $row[0]['user']->name); + self::assertEquals(1, $row[0]['user']->id); + self::assertEquals('romanb', $row[0]['user']->name); } else if ($rowNum == 1) { - $this->assertEquals(2, $row[0]['user']->id); - $this->assertEquals('jwage', $row[0]['user']->name); + self::assertEquals(2, $row[0]['user']->id); + self::assertEquals('jwage', $row[0]['user']->name); } ++$rowNum; @@ -1422,18 +1494,18 @@ public function testManyToManyHydration() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertContainsOnly(CmsUser::class, $result); + self::assertContainsOnly(CmsUser::class, $result); - $this->assertEquals(2, count($result[0]->groups)); - $this->assertEquals(2, count($result[0]->phonenumbers)); + self::assertEquals(2, count($result[0]->groups)); + self::assertEquals(2, count($result[0]->phonenumbers)); - $this->assertEquals(4, count($result[1]->groups)); - $this->assertEquals(2, count($result[1]->phonenumbers)); + self::assertEquals(4, count($result[1]->groups)); + self::assertEquals(2, count($result[1]->phonenumbers)); } /** @@ -1545,21 +1617,21 @@ public function testManyToManyHydrationWithAliasedUserEntity() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertInternalType('array', $result[0]); - $this->assertInstanceOf(CmsUser::class, $result[0]['user']); - $this->assertInternalType('array', $result[1]); - $this->assertInstanceOf(CmsUser::class, $result[1]['user']); + self::assertInternalType('array', $result[0]); + self::assertInstanceOf(CmsUser::class, $result[0]['user']); + self::assertInternalType('array', $result[1]); + self::assertInstanceOf(CmsUser::class, $result[1]['user']); - $this->assertEquals(2, count($result[0]['user']->groups)); - $this->assertEquals(2, count($result[0]['user']->phonenumbers)); + self::assertEquals(2, count($result[0]['user']->groups)); + self::assertEquals(2, count($result[0]['user']->phonenumbers)); - $this->assertEquals(4, count($result[1]['user']->groups)); - $this->assertEquals(2, count($result[1]['user']->phonenumbers)); + self::assertEquals(4, count($result[1]['user']->groups)); + self::assertEquals(2, count($result[1]['user']->phonenumbers)); } /** @@ -1575,7 +1647,7 @@ public function testMissingIdForRootEntity($userEntityKey) $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); + $rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); // Faked result set $resultSet = [ @@ -1603,21 +1675,21 @@ public function testMissingIdForRootEntity($userEntityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(4, count($result), "Should hydrate four results."); + self::assertEquals(4, count($result), "Should hydrate four results."); - $this->assertEquals('ROMANB', $result[0]['nameUpper']); - $this->assertEquals('ROMANB', $result[1]['nameUpper']); - $this->assertEquals('JWAGE', $result[2]['nameUpper']); - $this->assertEquals('JWAGE', $result[3]['nameUpper']); + self::assertEquals('ROMANB', $result[0]['nameUpper']); + self::assertEquals('ROMANB', $result[1]['nameUpper']); + self::assertEquals('JWAGE', $result[2]['nameUpper']); + self::assertEquals('JWAGE', $result[3]['nameUpper']); - $this->assertInstanceOf(CmsUser::class, $result[0][$userEntityKey]); - $this->assertNull($result[1][$userEntityKey]); + self::assertInstanceOf(CmsUser::class, $result[0][$userEntityKey]); + self::assertNull($result[1][$userEntityKey]); - $this->assertInstanceOf(CmsUser::class, $result[2][$userEntityKey]); - $this->assertNull($result[3][$userEntityKey]); + self::assertInstanceOf(CmsUser::class, $result[2][$userEntityKey]); + self::assertNull($result[3][$userEntityKey]); } /** @@ -1640,7 +1712,7 @@ public function testMissingIdForCollectionValuedChildEntity($userEntityKey) ); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); + $rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); $rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); // Faked result set @@ -1673,13 +1745,13 @@ public function testMissingIdForCollectionValuedChildEntity($userEntityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertEquals(1, $result[0][$userEntityKey]->phonenumbers->count()); - $this->assertEquals(1, $result[1][$userEntityKey]->phonenumbers->count()); + self::assertEquals(1, $result[0][$userEntityKey]->phonenumbers->count()); + self::assertEquals(1, $result[1][$userEntityKey]->phonenumbers->count()); } /** @@ -1702,10 +1774,10 @@ public function testMissingIdForSingleValuedChildEntity($userEntityKey) ); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); + $rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); $rsm->addFieldResult('a', 'a__id', 'id'); $rsm->addFieldResult('a', 'a__city', 'city'); - $rsm->addMetaResult('a', 'user_id', 'user_id', false, 'string'); + $rsm->addMetaResult('a', 'user_id', 'user_id', false, Type::getType('string')); // Faked result set $resultSet = [ @@ -1727,13 +1799,13 @@ public function testMissingIdForSingleValuedChildEntity($userEntityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertInstanceOf(CmsAddress::class, $result[0][$userEntityKey]->address); - $this->assertNull($result[1][$userEntityKey]->address); + self::assertInstanceOf(CmsAddress::class, $result[0][$userEntityKey]->address); + self::assertNull($result[1][$userEntityKey]->address); } /** @@ -1750,7 +1822,7 @@ public function testIndexByAndMixedResult($userEntityKey) $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); + $rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); $rsm->addIndexBy('u', 'id'); // Faked result set @@ -1769,16 +1841,16 @@ public function testIndexByAndMixedResult($userEntityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals(2, count($result)); + self::assertEquals(2, count($result)); - $this->assertTrue(isset($result[1])); - $this->assertEquals(1, $result[1][$userEntityKey]->id); + self::assertTrue(isset($result[1])); + self::assertEquals(1, $result[1][$userEntityKey]->id); - $this->assertTrue(isset($result[2])); - $this->assertEquals(2, $result[2][$userEntityKey]->id); + self::assertTrue(isset($result[2])); + self::assertEquals(2, $result[2][$userEntityKey]->id); } /** @@ -1792,7 +1864,7 @@ public function testIndexByScalarsOnly($userEntityKey) { $rsm = new ResultSetMapping; $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); - $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); + $rsm->addScalarResult('sclr0', 'nameUpper', Type::getType('string')); $rsm->addIndexByScalar('sclr0'); // Faked result set @@ -1807,10 +1879,10 @@ public function testIndexByScalarsOnly($userEntityKey) ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); - $this->assertEquals( + self::assertEquals( [ 'ROMANB' => ['nameUpper' => 'ROMANB'], 'JWAGE' => ['nameUpper' => 'JWAGE'] @@ -1843,7 +1915,7 @@ public function testMissingMetaMappingException() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $hydrator->hydrateAll($stmt, $rsm); } @@ -1860,11 +1932,11 @@ public function testMissingDiscriminatorColumnException() $rsm->addEntityResult(CompanyFixContract::class, 'c'); $rsm->addJoinedEntityResult(CompanyEmployee::class, 'e', 'c', 'salesPerson'); $rsm->addFieldResult('c', 'c__id', 'id'); - $rsm->addMetaResult('c', 'c_discr', 'discr', false, 'string'); + $rsm->addMetaResult('c', 'c_discr', 'discr', false, Type::getType('string')); $rsm->setDiscriminatorColumn('c', 'c_discr'); $rsm->addFieldResult('e', 'e__id', 'id'); $rsm->addFieldResult('e', 'e__name', 'name'); - $rsm->addMetaResult('e ', 'e_discr', 'discr', false, 'string'); + $rsm->addMetaResult('e ', 'e_discr', 'discr', false, Type::getType('string')); $rsm->setDiscriminatorColumn('e', 'e_discr'); $resultSet = [ @@ -1877,7 +1949,7 @@ public function testMissingDiscriminatorColumnException() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $hydrator->hydrateAll($stmt, $rsm); } @@ -1894,7 +1966,7 @@ public function testInvalidDiscriminatorValueException() $rsm->addEntityResult(CompanyPerson::class, 'p'); $rsm->addFieldResult('p', 'p__id', 'id'); $rsm->addFieldResult('p', 'p__name', 'name'); - $rsm->addMetaResult('p', 'discr', 'discr', false, 'string'); + $rsm->addMetaResult('p', 'discr', 'discr', false, Type::getType('string')); $rsm->setDiscriminatorColumn('p', 'discr'); $resultSet = [ @@ -1906,7 +1978,7 @@ public function testInvalidDiscriminatorValueException() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $hydrator->hydrateAll($stmt, $rsm); } @@ -1927,13 +1999,28 @@ public function testFetchJoinCollectionValuedAssociationWithDefaultArrayValue() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertCount(1, $result); - $this->assertInstanceOf(EntityWithArrayDefaultArrayValueM2M::class, $result[0]); - $this->assertInstanceOf(PersistentCollection::class, $result[0]->collection); - $this->assertCount(1, $result[0]->collection); - $this->assertInstanceOf(SimpleEntity::class, $result[0]->collection[0]); + self::assertCount(1, $result); + self::assertInstanceOf(EntityWithArrayDefaultArrayValueM2M::class, $result[0]); + self::assertInstanceOf(PersistentCollection::class, $result[0]->collection); + self::assertCount(1, $result[0]->collection); + self::assertInstanceOf(SimpleEntity::class, $result[0]->collection[0]); + } + + /** + * @param object $object + * @param string $propertyName + * @param mixed $newValue + */ + private function swapPrivateProperty($object, string $propertyName, $newValue) + { + $reflectionClass = new \ReflectionClass($object); + $reflectionProperty = $reflectionClass->getProperty($propertyName); + + $reflectionProperty->setAccessible(true); + + $reflectionProperty->setValue($object, $newValue); } } diff --git a/tests/Doctrine/Tests/ORM/Hydration/ResultSetMappingTest.php b/tests/Doctrine/Tests/ORM/Hydration/ResultSetMappingTest.php index 30352b365a3..4fdff963d71 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/ResultSetMappingTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/ResultSetMappingTest.php @@ -1,9 +1,18 @@ _rsm = new ResultSetMapping; - $this->_em = $this->_getTestEntityManager(); + + $this->metadataBuildingContext = new ClassMetadataBuildingContext( + $this->createMock(ClassMetadataFactory::class), + new RuntimeReflectionService() + ); + + $this->em = $this->getTestEntityManager(); + $this->rsm = new ResultSetMapping; } /** @@ -38,33 +59,33 @@ protected function setUp() { */ public function testBasicResultSetMapping() { - $this->_rsm->addEntityResult( + $this->rsm->addEntityResult( CmsUser::class, 'u' ); - $this->_rsm->addFieldResult('u', 'id', 'id'); - $this->_rsm->addFieldResult('u', 'status', 'status'); - $this->_rsm->addFieldResult('u', 'username', 'username'); - $this->_rsm->addFieldResult('u', 'name', 'name'); - - $this->assertFalse($this->_rsm->isScalarResult('id')); - $this->assertFalse($this->_rsm->isScalarResult('status')); - $this->assertFalse($this->_rsm->isScalarResult('username')); - $this->assertFalse($this->_rsm->isScalarResult('name')); - - $this->assertTrue($this->_rsm->getClassName('u') == CmsUser::class); - $class = $this->_rsm->getDeclaringClass('id'); - $this->assertTrue($class == CmsUser::class); - - $this->assertEquals('u', $this->_rsm->getEntityAlias('id')); - $this->assertEquals('u', $this->_rsm->getEntityAlias('status')); - $this->assertEquals('u', $this->_rsm->getEntityAlias('username')); - $this->assertEquals('u', $this->_rsm->getEntityAlias('name')); - - $this->assertEquals('id', $this->_rsm->getFieldName('id')); - $this->assertEquals('status', $this->_rsm->getFieldName('status')); - $this->assertEquals('username', $this->_rsm->getFieldName('username')); - $this->assertEquals('name', $this->_rsm->getFieldName('name')); + $this->rsm->addFieldResult('u', 'id', 'id'); + $this->rsm->addFieldResult('u', 'status', 'status'); + $this->rsm->addFieldResult('u', 'username', 'username'); + $this->rsm->addFieldResult('u', 'name', 'name'); + + self::assertFalse($this->rsm->isScalarResult('id')); + self::assertFalse($this->rsm->isScalarResult('status')); + self::assertFalse($this->rsm->isScalarResult('username')); + self::assertFalse($this->rsm->isScalarResult('name')); + + self::assertTrue($this->rsm->getClassName('u') == CmsUser::class); + $class = $this->rsm->getDeclaringClass('id'); + self::assertTrue($class == CmsUser::class); + + self::assertEquals('u', $this->rsm->getEntityAlias('id')); + self::assertEquals('u', $this->rsm->getEntityAlias('status')); + self::assertEquals('u', $this->rsm->getEntityAlias('username')); + self::assertEquals('u', $this->rsm->getEntityAlias('name')); + + self::assertEquals('id', $this->rsm->getFieldName('id')); + self::assertEquals('status', $this->rsm->getFieldName('status')); + self::assertEquals('username', $this->rsm->getFieldName('username')); + self::assertEquals('name', $this->rsm->getFieldName('name')); } /** @@ -74,26 +95,26 @@ public function testBasicResultSetMapping() */ public function testFluentInterface() { - $rms = $this->_rsm; - - $this->_rsm->addEntityResult(CmsUser::class,'u'); - $this->_rsm->addJoinedEntityResult(CmsPhonenumber::class,'p','u','phonenumbers'); - $this->_rsm->addFieldResult('u', 'id', 'id'); - $this->_rsm->addFieldResult('u', 'name', 'name'); - $this->_rsm->setDiscriminatorColumn('name', 'name'); - $this->_rsm->addIndexByColumn('id', 'id'); - $this->_rsm->addIndexBy('username', 'username'); - $this->_rsm->addIndexByScalar('sclr0'); - $this->_rsm->addScalarResult('sclr0', 'numPhones'); - $this->_rsm->addMetaResult('a', 'user_id', 'user_id'); - - $this->assertTrue($rms->hasIndexBy('id')); - $this->assertTrue($rms->isFieldResult('id')); - $this->assertTrue($rms->isFieldResult('name')); - $this->assertTrue($rms->isScalarResult('sclr0')); - $this->assertTrue($rms->isRelation('p')); - $this->assertTrue($rms->hasParentAlias('p')); - $this->assertTrue($rms->isMixedResult()); + $rms = $this->rsm; + + $this->rsm->addEntityResult(CmsUser::class,'u'); + $this->rsm->addJoinedEntityResult(CmsPhonenumber::class,'p','u','phonenumbers'); + $this->rsm->addFieldResult('u', 'id', 'id'); + $this->rsm->addFieldResult('u', 'name', 'name'); + $this->rsm->setDiscriminatorColumn('name', 'name'); + $this->rsm->addIndexByColumn('id', 'id'); + $this->rsm->addIndexBy('username', 'username'); + $this->rsm->addIndexByScalar('sclr0'); + $this->rsm->addScalarResult('sclr0', 'numPhones', Type::getType('integer')); + $this->rsm->addMetaResult('a', 'user_id', 'user_id', false, Type::getType('integer')); + + self::assertTrue($rms->hasIndexBy('id')); + self::assertTrue($rms->isFieldResult('id')); + self::assertTrue($rms->isFieldResult('name')); + self::assertTrue($rms->isScalarResult('sclr0')); + self::assertTrue($rms->isRelation('p')); + self::assertTrue($rms->hasParentAlias('p')); + self::assertTrue($rms->isMixedResult()); } /** @@ -101,91 +122,87 @@ public function testFluentInterface() */ public function testAddNamedNativeQueryResultSetMapping() { - $cm = new ClassMetadata(CmsUser::class); - $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService); + $cm = new ClassMetadata(CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new TableMetadata("cms_users")); - $cm->mapOneToOne( - [ - 'fieldName' => 'email', - 'targetEntity' => CmsEmail::class, - 'cascade' => ['persist'], - 'inversedBy' => 'user', - 'orphanRemoval' => false, - 'joinColumns' => [ - [ - 'nullable' => true, - 'referencedColumnName' => 'id', - ] - ] - ] - ); + $joinColumn = new JoinColumnMetadata(); + $joinColumn->setReferencedColumnName('id'); + $joinColumn->setNullable(true); + + $association = new OneToOneAssociationMetadata('email'); + $association->setTargetEntity(CmsEmail::class); + $association->setInversedBy('user'); + $association->setCascade(['persist']); + $association->addJoinColumn($joinColumn); + + $cm->addProperty($association); $cm->addNamedNativeQuery( + 'find-all', + 'SELECT u.id AS user_id, e.id AS email_id, u.name, e.email, u.id + e.id AS scalarColumn FROM cms_users u INNER JOIN cms_emails e ON e.id = u.email_id', [ - 'name' => 'find-all', - 'query' => 'SELECT u.id AS user_id, e.id AS email_id, u.name, e.email, u.id + e.id AS scalarColumn FROM cms_users u INNER JOIN cms_emails e ON e.id = u.email_id', - 'resultSetMapping' => 'find-all', + 'resultSetMapping' => 'find-all', ] ); $cm->addSqlResultSetMapping( [ - 'name' => 'find-all', - 'entities' => [ - [ - 'entityClass' => '__CLASS__', - 'fields' => [ - [ - 'name' => 'id', - 'column'=> 'user_id' - ], - [ - 'name' => 'name', - 'column'=> 'name' + 'name' => 'find-all', + 'entities' => [ + [ + 'entityClass' => '__CLASS__', + 'fields' => [ + [ + 'name' => 'id', + 'column'=> 'user_id' + ], + [ + 'name' => 'name', + 'column'=> 'name' + ] + ] + ], + [ + 'entityClass' => 'CmsEmail', + 'fields' => [ + [ + 'name' => 'id', + 'column'=> 'email_id' + ], + [ + 'name' => 'email', + 'column'=> 'email' + ] ] ] ], - [ - 'entityClass' => 'CmsEmail', - 'fields' => [ - [ - 'name' => 'id', - 'column'=> 'email_id' - ], - [ - 'name' => 'email', - 'column'=> 'email' - ] + 'columns' => [ + [ + 'name' => 'scalarColumn' ] ] - ], - 'columns' => [ - [ - 'name' => 'scalarColumn' - ] - ] ] ); $queryMapping = $cm->getNamedNativeQuery('find-all'); - $rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($this->_em); + $rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($this->em); $rsm->addNamedNativeQueryMapping($cm, $queryMapping); - $this->assertEquals('scalarColumn', $rsm->getScalarAlias('scalarColumn')); + self::assertEquals('scalarColumn', $rsm->getScalarAlias('scalarColumn')); - $this->assertEquals('c0', $rsm->getEntityAlias('user_id')); - $this->assertEquals('c0', $rsm->getEntityAlias('name')); - $this->assertEquals(CmsUser::class, $rsm->getClassName('c0')); - $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('name')); - $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('user_id')); + self::assertEquals('e0', $rsm->getEntityAlias('user_id')); + self::assertEquals('e0', $rsm->getEntityAlias('name')); + self::assertEquals(CmsUser::class, $rsm->getClassName('e0')); + self::assertEquals(CmsUser::class, $rsm->getDeclaringClass('name')); + self::assertEquals(CmsUser::class, $rsm->getDeclaringClass('user_id')); - $this->assertEquals('c1', $rsm->getEntityAlias('email_id')); - $this->assertEquals('c1', $rsm->getEntityAlias('email')); - $this->assertEquals(CmsEmail::class, $rsm->getClassName('c1')); - $this->assertEquals(CmsEmail::class, $rsm->getDeclaringClass('email')); - $this->assertEquals(CmsEmail::class, $rsm->getDeclaringClass('email_id')); + self::assertEquals('e1', $rsm->getEntityAlias('email_id')); + self::assertEquals('e1', $rsm->getEntityAlias('email')); + self::assertEquals(CmsEmail::class, $rsm->getClassName('e1')); + self::assertEquals(CmsEmail::class, $rsm->getDeclaringClass('email')); + self::assertEquals(CmsEmail::class, $rsm->getDeclaringClass('email_id')); } /** @@ -193,14 +210,14 @@ public function testAddNamedNativeQueryResultSetMapping() */ public function testAddNamedNativeQueryResultSetMappingWithoutFields() { - $cm = new ClassMetadata(CmsUser::class); - $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService); + $cm = new ClassMetadata(CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new TableMetadata("cms_users")); $cm->addNamedNativeQuery( + 'find-all', + 'SELECT u.id AS user_id, e.id AS email_id, u.name, e.email, u.id + e.id AS scalarColumn FROM cms_users u INNER JOIN cms_emails e ON e.id = u.email_id', [ - 'name' => 'find-all', - 'query' => 'SELECT u.id AS user_id, e.id AS email_id, u.name, e.email, u.id + e.id AS scalarColumn FROM cms_users u INNER JOIN cms_emails e ON e.id = u.email_id', - 'resultSetMapping' => 'find-all', + 'resultSetMapping' => 'find-all', ] ); @@ -221,20 +238,20 @@ public function testAddNamedNativeQueryResultSetMappingWithoutFields() ); $queryMapping = $cm->getNamedNativeQuery('find-all'); - $rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($this->_em); + $rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($this->em); $rsm->addNamedNativeQueryMapping($cm, $queryMapping); - $this->assertEquals('scalarColumn', $rsm->getScalarAlias('scalarColumn')); - $this->assertEquals('c0', $rsm->getEntityAlias('id')); - $this->assertEquals('c0', $rsm->getEntityAlias('name')); - $this->assertEquals('c0', $rsm->getEntityAlias('status')); - $this->assertEquals('c0', $rsm->getEntityAlias('username')); - $this->assertEquals(CmsUser::class, $rsm->getClassName('c0')); - $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('id')); - $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('name')); - $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('status')); - $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('username')); + self::assertEquals('scalarColumn', $rsm->getScalarAlias('scalarColumn')); + self::assertEquals('e0', $rsm->getEntityAlias('id')); + self::assertEquals('e0', $rsm->getEntityAlias('name')); + self::assertEquals('e0', $rsm->getEntityAlias('status')); + self::assertEquals('e0', $rsm->getEntityAlias('username')); + self::assertEquals(CmsUser::class, $rsm->getClassName('e0')); + self::assertEquals(CmsUser::class, $rsm->getDeclaringClass('id')); + self::assertEquals(CmsUser::class, $rsm->getDeclaringClass('name')); + self::assertEquals(CmsUser::class, $rsm->getDeclaringClass('status')); + self::assertEquals(CmsUser::class, $rsm->getDeclaringClass('username')); } /** @@ -242,45 +259,43 @@ public function testAddNamedNativeQueryResultSetMappingWithoutFields() */ public function testAddNamedNativeQueryResultClass() { - $cm = new ClassMetadata(CmsUser::class); - - $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService); + $cm = $this->em->getClassMetadata(CmsUser::class); $cm->addNamedNativeQuery( + 'find-all', + 'SELECT * FROM cms_users', [ - 'name' => 'find-all', - 'resultClass' => '__CLASS__', - 'query' => 'SELECT * FROM cms_users', + 'resultClass' => '__CLASS__', ] ); $queryMapping = $cm->getNamedNativeQuery('find-all'); - $rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($this->_em); + $rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($this->em); $rsm->addNamedNativeQueryMapping($cm, $queryMapping); - $this->assertEquals('c0', $rsm->getEntityAlias('id')); - $this->assertEquals('c0', $rsm->getEntityAlias('name')); - $this->assertEquals('c0', $rsm->getEntityAlias('status')); - $this->assertEquals('c0', $rsm->getEntityAlias('username')); - $this->assertEquals(CmsUser::class, $rsm->getClassName('c0')); - $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('id')); - $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('name')); - $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('status')); - $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('username')); + self::assertEquals('e0', $rsm->getEntityAlias('id')); + self::assertEquals('e0', $rsm->getEntityAlias('name')); + self::assertEquals('e0', $rsm->getEntityAlias('status')); + self::assertEquals('e0', $rsm->getEntityAlias('username')); + self::assertEquals(CmsUser::class, $rsm->getClassName('e0')); + self::assertEquals(CmsUser::class, $rsm->getDeclaringClass('id')); + self::assertEquals(CmsUser::class, $rsm->getDeclaringClass('name')); + self::assertEquals(CmsUser::class, $rsm->getDeclaringClass('status')); + self::assertEquals(CmsUser::class, $rsm->getDeclaringClass('username')); } /** * @group DDC-117 */ public function testIndexByMetadataColumn() { - $this->_rsm->addEntityResult(LegacyUser::class, 'u'); - $this->_rsm->addJoinedEntityResult(LegacyUserReference::class, 'lu', 'u', '_references'); - $this->_rsm->addMetaResult('lu', '_source', '_source', true, 'integer'); - $this->_rsm->addMetaResult('lu', '_target', '_target', true, 'integer'); - $this->_rsm->addIndexBy('lu', '_source'); + $this->rsm->addEntityResult(LegacyUser::class, 'u'); + $this->rsm->addJoinedEntityResult(LegacyUserReference::class, 'lu', 'u', '_references'); + $this->rsm->addMetaResult('lu', '_source', '_source', true, Type::getType('integer')); + $this->rsm->addMetaResult('lu', '_target', '_target', true, Type::getType('integer')); + $this->rsm->addIndexBy('lu', '_source'); - $this->assertTrue($this->_rsm->hasIndexBy('lu')); + self::assertTrue($this->rsm->hasIndexBy('lu')); } } diff --git a/tests/Doctrine/Tests/ORM/Hydration/ScalarHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/ScalarHydratorTest.php index 919486cc8ec..d80cd5a0f6a 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/ScalarHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/ScalarHydratorTest.php @@ -1,8 +1,11 @@ _em); + $hydrator = new ScalarHydrator($this->em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertInternalType('array', $result); - $this->assertCount(2, $result); - $this->assertEquals('romanb', $result[0]['u_name']); - $this->assertEquals(1, $result[0]['u_id']); - $this->assertEquals('jwage', $result[1]['u_name']); - $this->assertEquals(2, $result[1]['u_id']); + self::assertInternalType('array', $result); + self::assertCount(2, $result); + self::assertEquals('romanb', $result[0]['u_name']); + self::assertEquals(1, $result[0]['u_id']); + self::assertEquals('jwage', $result[1]['u_name']); + self::assertEquals(2, $result[1]['u_id']); } /** @@ -51,9 +54,9 @@ public function testNewHydrationSimpleEntityQuery() public function testHydrateScalarResults() { $rsm = new ResultSetMapping(); - $rsm->addScalarResult('foo1', 'foo', 'string'); - $rsm->addScalarResult('bar2', 'bar', 'string'); - $rsm->addScalarResult('baz3', 'baz', 'string'); + $rsm->addScalarResult('foo1', 'foo', Type::getType('string')); + $rsm->addScalarResult('bar2', 'bar', Type::getType('string')); + $rsm->addScalarResult('baz3', 'baz', Type::getType('string')); $resultSet = [ [ @@ -64,7 +67,7 @@ public function testHydrateScalarResults() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new ScalarHydrator($this->_em); + $hydrator = new ScalarHydrator($this->em); self::assertCount(1, $hydrator->hydrateAll($stmt, $rsm)); } @@ -78,9 +81,9 @@ public function testSkipUnknownColumns() $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); - $rsm->addScalarResult('foo1', 'foo', 'string'); - $rsm->addScalarResult('bar2', 'bar', 'string'); - $rsm->addScalarResult('baz3', 'baz', 'string'); + $rsm->addScalarResult('foo1', 'foo', Type::getType('string')); + $rsm->addScalarResult('bar2', 'bar', Type::getType('string')); + $rsm->addScalarResult('baz3', 'baz', Type::getType('string')); $resultSet = [ [ @@ -94,7 +97,7 @@ public function testSkipUnknownColumns() ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new ScalarHydrator($this->_em); + $hydrator = new ScalarHydrator($this->em); self::assertCount(1, $hydrator->hydrateAll($stmt, $rsm)); } diff --git a/tests/Doctrine/Tests/ORM/Hydration/SimpleObjectHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/SimpleObjectHydratorTest.php index ffcd81e3571..041cf0381e5 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/SimpleObjectHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/SimpleObjectHydratorTest.php @@ -1,7 +1,11 @@ addEntityResult(CompanyPerson::class, 'p'); $rsm->addFieldResult('p', 'p__id', 'id'); $rsm->addFieldResult('p', 'p__name', 'name'); - $rsm->addMetaResult('p ', 'discr', 'discr', false, 'string'); + $rsm->addMetaResult('p ', 'discr', 'discr', false, Type::getType('string')); $rsm->setDiscriminatorColumn('p', 'discr'); + $resultSet = [ [ 'u__id' => '1', @@ -33,14 +39,16 @@ public function testMissingDiscriminatorColumnException() ], ]; - $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\SimpleObjectHydrator($this->_em); + $stmt = new HydratorMockStatement($resultSet); + $hydrator = new SimpleObjectHydrator($this->em); + $hydrator->hydrateAll($stmt, $rsm); } public function testExtraFieldInResultSetShouldBeIgnore() { $rsm = new ResultSetMapping; + $rsm->addEntityResult(CmsAddress::class, 'a'); $rsm->addFieldResult('a', 'a__id', 'id'); $rsm->addFieldResult('a', 'a__city', 'city'); @@ -53,13 +61,15 @@ public function testExtraFieldInResultSetShouldBeIgnore() ]; $expectedEntity = new \Doctrine\Tests\Models\CMS\CmsAddress(); + $expectedEntity->id = 1; $expectedEntity->city = 'Cracow'; - $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\SimpleObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals($result[0], $expectedEntity); + $stmt = new HydratorMockStatement($resultSet); + $hydrator = new SimpleObjectHydrator($this->em); + $result = $hydrator->hydrateAll($stmt, $rsm); + + self::assertEquals($result[0], $expectedEntity); } /** @@ -73,10 +83,9 @@ public function testInvalidDiscriminatorValueException() $rsm = new ResultSetMapping; $rsm->addEntityResult(CompanyPerson::class, 'p'); - $rsm->addFieldResult('p', 'p__id', 'id'); $rsm->addFieldResult('p', 'p__name', 'name'); - $rsm->addMetaResult('p', 'discr', 'discr', false, 'string'); + $rsm->addMetaResult('p', 'discr', 'discr', false, Type::getType('string')); $rsm->setDiscriminatorColumn('p', 'discr'); $resultSet = [ @@ -87,8 +96,9 @@ public function testInvalidDiscriminatorValueException() ], ]; - $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\SimpleObjectHydrator($this->_em); + $stmt = new HydratorMockStatement($resultSet); + $hydrator = new SimpleObjectHydrator($this->em); + $hydrator->hydrateAll($stmt, $rsm); } @@ -102,7 +112,7 @@ public function testNullValueShouldNotOverwriteFieldWithSameNameInJoinedInherita $rsm->addFieldResult('p', 'p__id', 'id'); $rsm->addFieldResult('p', 'm__tags', 'tags', Issue5989Manager::class); $rsm->addFieldResult('p', 'e__tags', 'tags', Issue5989Employee::class); - $rsm->addMetaResult('p', 'discr', 'discr', false, 'string'); + $rsm->addMetaResult('p', 'discr', 'discr', false, Type::getType('string')); $resultSet = [ [ 'p__id' => '1', @@ -116,9 +126,10 @@ public function testNullValueShouldNotOverwriteFieldWithSameNameInJoinedInherita $expectedEntity->id = 1; $expectedEntity->tags = ['tag1', 'tag2']; - $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\SimpleObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals($result[0], $expectedEntity); + $stmt = new HydratorMockStatement($resultSet); + $hydrator = new \Doctrine\ORM\Internal\Hydration\SimpleObjectHydrator($this->em); + $result = $hydrator->hydrateAll($stmt, $rsm); + + self::assertEquals($result[0], $expectedEntity); } } diff --git a/tests/Doctrine/Tests/ORM/Hydration/SingleScalarHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/SingleScalarHydratorTest.php index f9d91be638d..981105bf06c 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/SingleScalarHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/SingleScalarHydratorTest.php @@ -1,5 +1,7 @@ addFieldResult('u', 'u__name', 'name'); $stmt = new HydratorMockStatement($resultSet); - $hydrator = new SingleScalarHydrator($this->_em); + $hydrator = new SingleScalarHydrator($this->em); if ($name === 'result1') { $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals('romanb', $result); + + self::assertEquals('romanb', $result); + return; } if ($name === 'result2') { $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertEquals(1, $result); + + self::assertEquals(1, $result); return; } if (in_array($name, ['result3', 'result4'], true)) { $this->expectException(NonUniqueResultException::class); + $hydrator->hydrateAll($stmt, $rsm); } } diff --git a/tests/Doctrine/Tests/ORM/Id/AssignedGeneratorTest.php b/tests/Doctrine/Tests/ORM/Id/AssignedGeneratorTest.php deleted file mode 100644 index aa0240ebcd5..00000000000 --- a/tests/Doctrine/Tests/ORM/Id/AssignedGeneratorTest.php +++ /dev/null @@ -1,70 +0,0 @@ -_em = $this->_getTestEntityManager(); - $this->_assignedGen = new AssignedGenerator; - } - - /** - * @dataProvider entitiesWithoutId - */ - public function testThrowsExceptionIfIdNotAssigned($entity) - { - $this->expectException(ORMException::class); - - $this->_assignedGen->generate($this->_em, $entity); - } - - public function entitiesWithoutId(): array - { - return [ - 'single' => [new AssignedSingleIdEntity()], - 'composite' => [new AssignedCompositeIdEntity()], - ]; - } - - public function testCorrectIdGeneration() - { - $entity = new AssignedSingleIdEntity; - $entity->myId = 1; - $id = $this->_assignedGen->generate($this->_em, $entity); - $this->assertEquals(['myId' => 1], $id); - - $entity = new AssignedCompositeIdEntity; - $entity->myId2 = 2; - $entity->myId1 = 4; - $id = $this->_assignedGen->generate($this->_em, $entity); - $this->assertEquals(['myId1' => 4, 'myId2' => 2], $id); - } -} - -/** @Entity */ -class AssignedSingleIdEntity { - /** @Id @Column(type="integer") */ - public $myId; -} - -/** @Entity */ -class AssignedCompositeIdEntity { - /** @Id @Column(type="integer") */ - public $myId1; - /** @Id @Column(type="integer") */ - public $myId2; -} diff --git a/tests/Doctrine/Tests/ORM/Internal/HydrationCompleteHandlerTest.php b/tests/Doctrine/Tests/ORM/Internal/HydrationCompleteHandlerTest.php index e4e9bcdf7df..783a3d88f76 100644 --- a/tests/Doctrine/Tests/ORM/Internal/HydrationCompleteHandlerTest.php +++ b/tests/Doctrine/Tests/ORM/Internal/HydrationCompleteHandlerTest.php @@ -1,21 +1,6 @@ . - */ + +declare(strict_types=1); namespace Doctrine\Tests\ORM\Internal; @@ -25,7 +10,7 @@ use Doctrine\ORM\Events; use Doctrine\ORM\Internal\HydrationCompleteHandler; use Doctrine\ORM\Mapping\ClassMetadata; -use PHPUnit\Framework\TestCase; +use Doctrine\Tests\DoctrineTestCase; use stdClass; /** @@ -33,7 +18,7 @@ * * @covers \Doctrine\ORM\Internal\HydrationCompleteHandler */ -class HydrationCompleteHandlerTest extends TestCase +class HydrationCompleteHandlerTest extends DoctrineTestCase { /** * @var \Doctrine\ORM\Event\ListenersInvoker|\PHPUnit_Framework_MockObject_MockObject diff --git a/tests/Doctrine/Tests/ORM/LazyCriteriaCollectionTest.php b/tests/Doctrine/Tests/ORM/LazyCriteriaCollectionTest.php index 9286da614f8..d2b4b2764b9 100644 --- a/tests/Doctrine/Tests/ORM/LazyCriteriaCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/LazyCriteriaCollectionTest.php @@ -1,12 +1,14 @@ persister->expects($this->once())->method('count')->with($this->criteria)->will($this->returnValue(10)); + $this->persister->expects(self::once())->method('count')->with($this->criteria)->will($this->returnValue(10)); - $this->assertSame(10, $this->lazyCriteriaCollection->count()); - $this->assertSame(10, $this->lazyCriteriaCollection->count()); - $this->assertSame(10, $this->lazyCriteriaCollection->count()); + self::assertSame(10, $this->lazyCriteriaCollection->count()); + self::assertSame(10, $this->lazyCriteriaCollection->count()); + self::assertSame(10, $this->lazyCriteriaCollection->count()); } public function testCountIsCachedEvenWithZeroResult() { - $this->persister->expects($this->once())->method('count')->with($this->criteria)->will($this->returnValue(0)); + $this->persister->expects(self::once())->method('count')->with($this->criteria)->will($this->returnValue(0)); - $this->assertSame(0, $this->lazyCriteriaCollection->count()); - $this->assertSame(0, $this->lazyCriteriaCollection->count()); - $this->assertSame(0, $this->lazyCriteriaCollection->count()); + self::assertSame(0, $this->lazyCriteriaCollection->count()); + self::assertSame(0, $this->lazyCriteriaCollection->count()); + self::assertSame(0, $this->lazyCriteriaCollection->count()); } public function testCountUsesWrappedCollectionWhenInitialized() { $this ->persister - ->expects($this->once()) + ->expects(self::once()) ->method('loadCriteria') ->with($this->criteria) ->will($this->returnValue(['foo', 'bar', 'baz'])); // should never call the persister's count - $this->persister->expects($this->never())->method('count'); + $this->persister->expects(self::never())->method('count'); - $this->assertSame(['foo', 'bar', 'baz'], $this->lazyCriteriaCollection->toArray()); + self::assertSame(['foo', 'bar', 'baz'], $this->lazyCriteriaCollection->toArray()); - $this->assertSame(3, $this->lazyCriteriaCollection->count()); + self::assertSame(3, $this->lazyCriteriaCollection->count()); } public function testMatchingUsesThePersisterOnlyOnce() @@ -88,7 +90,7 @@ public function testMatchingUsesThePersisterOnlyOnce() $this ->persister - ->expects($this->once()) + ->expects(self::once()) ->method('loadCriteria') ->with($this->criteria) ->will($this->returnValue([$foo, $bar, $baz])); @@ -99,40 +101,40 @@ public function testMatchingUsesThePersisterOnlyOnce() $filtered = $this->lazyCriteriaCollection->matching($criteria); - $this->assertInstanceOf(Collection::class, $filtered); - $this->assertEquals([$foo], $filtered->toArray()); + self::assertInstanceOf(Collection::class, $filtered); + self::assertEquals([$foo], $filtered->toArray()); - $this->assertEquals([$foo], $this->lazyCriteriaCollection->matching($criteria)->toArray()); + self::assertEquals([$foo], $this->lazyCriteriaCollection->matching($criteria)->toArray()); } public function testIsEmptyUsesCountWhenNotInitialized() { - $this->persister->expects($this->once())->method('count')->with($this->criteria)->will($this->returnValue(0)); + $this->persister->expects(self::once())->method('count')->with($this->criteria)->will($this->returnValue(0)); - $this->assertTrue($this->lazyCriteriaCollection->isEmpty()); + self::assertTrue($this->lazyCriteriaCollection->isEmpty()); } public function testIsEmptyIsFalseIfCountIsNotZero() { - $this->persister->expects($this->once())->method('count')->with($this->criteria)->will($this->returnValue(1)); + $this->persister->expects(self::once())->method('count')->with($this->criteria)->will($this->returnValue(1)); - $this->assertFalse($this->lazyCriteriaCollection->isEmpty()); + self::assertFalse($this->lazyCriteriaCollection->isEmpty()); } public function testIsEmptyUsesWrappedCollectionWhenInitialized() { $this ->persister - ->expects($this->once()) + ->expects(self::once()) ->method('loadCriteria') ->with($this->criteria) ->will($this->returnValue(['foo', 'bar', 'baz'])); // should never call the persister's count - $this->persister->expects($this->never())->method('count'); + $this->persister->expects(self::never())->method('count'); - $this->assertSame(['foo', 'bar', 'baz'], $this->lazyCriteriaCollection->toArray()); + self::assertSame(['foo', 'bar', 'baz'], $this->lazyCriteriaCollection->toArray()); - $this->assertFalse($this->lazyCriteriaCollection->isEmpty()); + self::assertFalse($this->lazyCriteriaCollection->isEmpty()); } } diff --git a/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php index e13d7aa7e5b..498f0545a62 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php @@ -1,18 +1,20 @@ metadataBuildingContext = new Mapping\ClassMetadataBuildingContext( + $this->createMock(ClassMetadataFactory::class), + new RuntimeReflectionService() + ); + } + + abstract protected function loadDriver(); public function createClassMetadata($entityClassName) { - $mappingDriver = $this->_loadDriver(); + $mappingDriver = $this->loadDriver(); + + $class = new ClassMetadata($entityClassName, $this->metadataBuildingContext); - $class = new ClassMetadata($entityClassName); - $class->initializeReflection(new RuntimeReflectionService()); - $mappingDriver->loadMetadataForClass($entityClassName, $class); + $mappingDriver->loadMetadataForClass($entityClassName, $class, $this->metadataBuildingContext); return $class; } - /** - * @param \Doctrine\ORM\EntityManager $entityClassName - * @return \Doctrine\ORM\Mapping\ClassMetadataFactory - */ - protected function createClassMetadataFactory(EntityManager $em = null) + protected function createClassMetadataFactory(EntityManagerInterface $em = null) : ClassMetadataFactory { - $driver = $this->_loadDriver(); - $em = $em ?: $this->_getTestEntityManager(); + $driver = $this->loadDriver(); + $em = $em ?: $this->getTestEntityManager(); $factory = new ClassMetadataFactory(); + $em->getConfiguration()->setMetadataDriverImpl($driver); $factory->setEntityManager($em); return $factory; } + /** + * @param ClassMetadata $class + */ public function testEntityTableNameAndInheritance() { $class = $this->createClassMetadata(User::class); - $this->assertEquals('cms_users', $class->getTableName()); - $this->assertEquals(ClassMetadata::INHERITANCE_TYPE_NONE, $class->inheritanceType); + self::assertEquals('cms_users', $class->getTableName()); + self::assertEquals(Mapping\InheritanceType::NONE, $class->inheritanceType); return $class; } /** - * @depends testEntityTableNameAndInheritance + * * @param ClassMetadata $class */ - public function testEntityIndexes($class) + public function testEntityIndexes() { - $this->assertArrayHasKey('indexes', $class->table, 'ClassMetadata should have indexes key in table property.'); - $this->assertEquals( + $class = $this->createClassMetadata('Doctrine\Tests\ORM\Mapping\User'); + + self::assertCount(2, $class->table->getIndexes()); + self::assertEquals( [ - 'name_idx' => ['columns' => ['name']], - 0 => ['columns' => ['user_email']] - ], $class->table['indexes']); + 'name_idx' => [ + 'name' => 'name_idx', + 'columns' => ['name'], + 'unique' => false, + 'options' => [], + 'flags' => [], + ], + 0 => [ + 'name' => null, + 'columns' => ['user_email'], + 'unique' => false, + 'options' => [], + 'flags' => [], + ] + ], + $class->table->getIndexes() + ); return $class; } @@ -98,14 +131,18 @@ public function testEntityIndexFlagsAndPartialIndexes() { $class = $this->createClassMetadata(Comment::class); - $this->assertEquals( + self::assertEquals( [ - 0 => [ - 'columns' => ['content'], - 'flags' => ['fulltext'], - 'options' => ['where' => 'content IS NOT NULL'], - ] - ], $class->table['indexes']); + 0 => [ + 'name' => null, + 'columns' => ['content'], + 'unique' => false, + 'flags' => ['fulltext'], + 'options' => ['where' => 'content IS NOT NULL'], + ] + ], + $class->table->getIndexes() + ); } /** @@ -114,13 +151,18 @@ public function testEntityIndexFlagsAndPartialIndexes() */ public function testEntityUniqueConstraints($class) { - $this->assertArrayHasKey('uniqueConstraints', $class->table, - 'ClassMetadata should have uniqueConstraints key in table property when Unique Constraints are set.'); - - $this->assertEquals( + self::assertCount(1, $class->table->getUniqueConstraints()); + self::assertEquals( [ - "search_idx" => ["columns" => ["name", "user_email"], 'options' => ['where' => 'name IS NOT NULL']] - ], $class->table['uniqueConstraints']); + 'search_idx' => [ + 'name' => 'search_idx', + 'columns' => ['name', 'user_email'], + 'options' => [], + 'flags' => [], + ] + ], + $class->table->getUniqueConstraints() + ); return $class; } @@ -131,12 +173,14 @@ public function testEntityUniqueConstraints($class) */ public function testEntityOptions($class) { - $this->assertArrayHasKey('options', $class->table, 'ClassMetadata should have options key in table property.'); - - $this->assertEquals( + self::assertCount(2, $class->table->getOptions()); + self::assertEquals( [ - 'foo' => 'bar', 'baz' => ['key' => 'val'] - ], $class->table['options']); + 'foo' => 'bar', + 'baz' => ['key' => 'val'] + ], + $class->table->getOptions() + ); return $class; } @@ -147,14 +191,17 @@ public function testEntityOptions($class) */ public function testEntitySequence($class) { - $this->assertInternalType('array', $class->sequenceGeneratorDefinition, 'No Sequence Definition set on this driver.'); - $this->assertEquals( + self::assertInternalType( + 'array', + $class->getProperty('id')->getValueGenerator()->getDefinition(), + 'No Sequence Definition set on this driver.' + ); + self::assertEquals( [ - 'sequenceName' => 'tablename_seq', + 'sequenceName' => 'tablename_seq', 'allocationSize' => 100, - 'initialValue' => 1, ], - $class->sequenceGeneratorDefinition + $class->getProperty('id')->getValueGenerator()->getDefinition() ); } @@ -162,12 +209,15 @@ public function testEntityCustomGenerator() { $class = $this->createClassMetadata(Animal::class); - $this->assertEquals(ClassMetadata::GENERATOR_TYPE_CUSTOM, - $class->generatorType, "Generator Type"); - $this->assertEquals( - ["class" => "stdClass"], - $class->customGeneratorDefinition, - "Custom Generator Definition"); + self::assertEquals(Mapping\GeneratorType::CUSTOM, $class->getProperty('id')->getValueGenerator()->getType(), "Generator Type"); + self::assertEquals( + [ + 'class' => 'stdClass', + 'arguments' => [], + ], + $class->getProperty('id')->getValueGenerator()->getDefinition(), + "Generator Definition" + ); } @@ -175,27 +225,32 @@ public function testEntityCustomGenerator() * @depends testEntityTableNameAndInheritance * @param ClassMetadata $class */ - public function testFieldMappings($class) + public function testProperties($class) { - $this->assertEquals(4, count($class->fieldMappings)); - $this->assertTrue(isset($class->fieldMappings['id'])); - $this->assertTrue(isset($class->fieldMappings['name'])); - $this->assertTrue(isset($class->fieldMappings['email'])); - $this->assertTrue(isset($class->fieldMappings['version'])); + self::assertCount(7, $class->getDeclaredPropertiesIterator()); + + self::assertNotNull($class->getProperty('id')); + self::assertNotNull($class->getProperty('name')); + self::assertNotNull($class->getProperty('email')); + self::assertNotNull($class->getProperty('version')); + self::assertNotNull($class->getProperty('version')); return $class; } /** - * @depends testFieldMappings + * @depends testProperties * @param ClassMetadata $class */ - public function testVersionedField($class) + public function testVersionProperty($class) { - $this->assertTrue($class->isVersioned); - $this->assertEquals("version", $class->versionField); + self::assertTrue($class->isVersioned()); + self::assertNotNull($class->versionProperty); - $this->assertFalse(isset($class->fieldMappings['version']['version'])); + $versionPropertyName = $class->versionProperty->getName(); + + self::assertEquals("version", $versionPropertyName); + self::assertNotNull($class->getProperty($versionPropertyName)); } /** @@ -204,9 +259,13 @@ public function testVersionedField($class) */ public function testFieldMappingsColumnNames($class) { - $this->assertEquals("id", $class->fieldMappings['id']['columnName']); - $this->assertEquals("name", $class->fieldMappings['name']['columnName']); - $this->assertEquals("user_email", $class->fieldMappings['email']['columnName']); + self::assertNotNull($class->getProperty('id')); + self::assertNotNull($class->getProperty('name')); + self::assertNotNull($class->getProperty('email')); + + self::assertEquals("id", $class->getProperty('id')->getColumnName()); + self::assertEquals("name", $class->getProperty('name')->getColumnName()); + self::assertEquals("user_email", $class->getProperty('email')->getColumnName()); return $class; } @@ -217,10 +276,14 @@ public function testFieldMappingsColumnNames($class) */ public function testStringFieldMappings($class) { - $this->assertEquals('string', $class->fieldMappings['name']['type']); - $this->assertEquals(50, $class->fieldMappings['name']['length']); - $this->assertTrue($class->fieldMappings['name']['nullable']); - $this->assertTrue($class->fieldMappings['name']['unique']); + self::assertNotNull($class->getProperty('name')); + + $property = $class->getProperty('name'); + + self::assertEquals('string', $property->getTypeName()); + self::assertEquals(50, $property->getLength()); + self::assertTrue($property->isNullable()); + self::assertTrue($property->isUnique()); return $class; } @@ -234,8 +297,12 @@ public function testStringFieldMappings($class) */ public function testFieldOptions(ClassMetadata $class) { + self::assertNotNull($class->getProperty('name')); + + $property = $class->getProperty('name'); $expected = ['foo' => 'bar', 'baz' => ['key' => 'val'], 'fixed' => false]; - $this->assertEquals($expected, $class->fieldMappings['name']['options']); + + self::assertEquals($expected, $property->getOptions()); return $class; } @@ -246,20 +313,29 @@ public function testFieldOptions(ClassMetadata $class) */ public function testIdFieldOptions($class) { - $this->assertEquals(['foo' => 'bar', 'unsigned' => false], $class->fieldMappings['id']['options']); + self::assertNotNull($class->getProperty('id')); + + $property = $class->getProperty('id'); + $expected = ['foo' => 'bar', 'unsigned' => false]; + + self::assertEquals($expected, $property->getOptions()); return $class; } /** - * @depends testFieldMappings + * @depends testProperties * @param ClassMetadata $class */ public function testIdentifier($class) { - $this->assertEquals(['id'], $class->identifier); - $this->assertEquals('integer', $class->fieldMappings['id']['type']); - $this->assertEquals(ClassMetadata::GENERATOR_TYPE_AUTO, $class->generatorType, "ID-Generator is not ClassMetadata::GENERATOR_TYPE_AUTO"); + self::assertNotNull($class->getProperty('id')); + + $property = $class->getProperty('id'); + + self::assertEquals('integer', $property->getTypeName()); + self::assertEquals(['id'], $class->identifier); + self::assertEquals(Mapping\GeneratorType::AUTO, $property->getValueGenerator()->getType(), "ID-Generator is not GeneratorType::AUTO"); return $class; } @@ -273,41 +349,31 @@ public function testBooleanValuesForOptionIsSetCorrectly() { $class = $this->createClassMetadata(User::class); - $this->assertInternalType('bool', $class->fieldMappings['id']['options']['unsigned']); - $this->assertFalse($class->fieldMappings['id']['options']['unsigned']); + $idOptions = $class->getProperty('id')->getOptions(); + $nameOptions = $class->getProperty('name')->getOptions(); - $this->assertInternalType('bool', $class->fieldMappings['name']['options']['fixed']); - $this->assertFalse($class->fieldMappings['name']['options']['fixed']); + self::assertInternalType('bool', $idOptions['unsigned']); + self::assertFalse($idOptions['unsigned']); + self::assertInternalType('bool', $nameOptions['fixed']); + self::assertFalse($nameOptions['fixed']); return $class; } /** - * @depends testIdentifier + * @depends testProperties * @param ClassMetadata $class */ - public function testAssociations($class) + public function testOwningOneToOneAssociation($class) { - $this->assertEquals(3, count($class->associationMappings)); + self::assertArrayHasKey('address', iterator_to_array($class->getDeclaredPropertiesIterator())); - return $class; - } + $association = $class->getProperty('address'); - /** - * @depends testAssociations - * @param ClassMetadata $class - */ - public function testOwningOneToOneAssociation($class) - { - $this->assertTrue(isset($class->associationMappings['address'])); - $this->assertTrue($class->associationMappings['address']['isOwningSide']); - $this->assertEquals('user', $class->associationMappings['address']['inversedBy']); + self::assertTrue($association->isOwningSide()); + self::assertEquals('user', $association->getInversedBy()); // Check cascading - $this->assertTrue($class->associationMappings['address']['isCascadeRemove']); - $this->assertFalse($class->associationMappings['address']['isCascadePersist']); - $this->assertFalse($class->associationMappings['address']['isCascadeRefresh']); - $this->assertFalse($class->associationMappings['address']['isCascadeDetach']); - $this->assertFalse($class->associationMappings['address']['isCascadeMerge']); + self::assertEquals(['remove'], $association->getCascade()); return $class; } @@ -318,17 +384,18 @@ public function testOwningOneToOneAssociation($class) */ public function testInverseOneToManyAssociation($class) { - $this->assertTrue(isset($class->associationMappings['phonenumbers'])); - $this->assertFalse($class->associationMappings['phonenumbers']['isOwningSide']); - $this->assertTrue($class->associationMappings['phonenumbers']['isCascadePersist']); - $this->assertTrue($class->associationMappings['phonenumbers']['isCascadeRemove']); - $this->assertFalse($class->associationMappings['phonenumbers']['isCascadeRefresh']); - $this->assertFalse($class->associationMappings['phonenumbers']['isCascadeDetach']); - $this->assertFalse($class->associationMappings['phonenumbers']['isCascadeMerge']); - $this->assertTrue($class->associationMappings['phonenumbers']['orphanRemoval']); + self::assertArrayHasKey('phonenumbers', iterator_to_array($class->getDeclaredPropertiesIterator())); + + $association = $class->getProperty('phonenumbers'); + + self::assertFalse($association->isOwningSide()); + self::assertTrue($association->isOrphanRemoval()); + + // Check cascading + self::assertEquals(['persist', 'remove'], $association->getCascade()); // Test Order By - $this->assertEquals(['number' => 'ASC'], $class->associationMappings['phonenumbers']['orderBy']); + self::assertEquals(['number' => 'ASC'], $association->getOrderBy()); return $class; } @@ -339,16 +406,17 @@ public function testInverseOneToManyAssociation($class) */ public function testManyToManyAssociationWithCascadeAll($class) { - $this->assertTrue(isset($class->associationMappings['groups'])); - $this->assertTrue($class->associationMappings['groups']['isOwningSide']); + self::assertArrayHasKey('groups', iterator_to_array($class->getDeclaredPropertiesIterator())); + + $association = $class->getProperty('groups'); + + self::assertTrue($association->isOwningSide()); + // Make sure that cascade-all works as expected - $this->assertTrue($class->associationMappings['groups']['isCascadeRemove']); - $this->assertTrue($class->associationMappings['groups']['isCascadePersist']); - $this->assertTrue($class->associationMappings['groups']['isCascadeRefresh']); - $this->assertTrue($class->associationMappings['groups']['isCascadeDetach']); - $this->assertTrue($class->associationMappings['groups']['isCascadeMerge']); + self::assertEquals(['remove', 'persist', 'refresh'], $association->getCascade()); - $this->assertFalse(isset($class->associationMappings['groups']['orderBy'])); + // Test Order By + self::assertEquals([], $association->getOrderBy()); return $class; } @@ -359,9 +427,9 @@ public function testManyToManyAssociationWithCascadeAll($class) */ public function testLifecycleCallbacks($class) { - $this->assertEquals(count($class->lifecycleCallbacks), 2); - $this->assertEquals($class->lifecycleCallbacks['prePersist'][0], 'doStuffOnPrePersist'); - $this->assertEquals($class->lifecycleCallbacks['postPersist'][0], 'doStuffOnPostPersist'); + self::assertEquals(count($class->lifecycleCallbacks), 2); + self::assertEquals($class->lifecycleCallbacks['prePersist'][0], 'doStuffOnPrePersist'); + self::assertEquals($class->lifecycleCallbacks['postPersist'][0], 'doStuffOnPostPersist'); return $class; } @@ -372,8 +440,8 @@ public function testLifecycleCallbacks($class) */ public function testLifecycleCallbacksSupportMultipleMethodNames($class) { - $this->assertEquals(count($class->lifecycleCallbacks['prePersist']), 2); - $this->assertEquals($class->lifecycleCallbacks['prePersist'][1], 'doOtherStuffOnPrePersistToo'); + self::assertEquals(count($class->lifecycleCallbacks['prePersist']), 2); + self::assertEquals($class->lifecycleCallbacks['prePersist'][1], 'doOtherStuffOnPrePersistToo'); return $class; } @@ -385,8 +453,13 @@ public function testLifecycleCallbacksSupportMultipleMethodNames($class) public function testJoinColumnUniqueAndNullable($class) { // Non-Nullability of Join Column - $this->assertFalse($class->associationMappings['groups']['joinTable']['joinColumns'][0]['nullable']); - $this->assertFalse($class->associationMappings['groups']['joinTable']['joinColumns'][0]['unique']); + $association = $class->getProperty('groups'); + $joinTable = $association->getJoinTable(); + $joinColumns = $joinTable->getJoinColumns(); + $joinColumn = reset($joinColumns); + + self::assertFalse($joinColumn->isNullable()); + self::assertFalse($joinColumn->isUnique()); return $class; } @@ -397,8 +470,16 @@ public function testJoinColumnUniqueAndNullable($class) */ public function testColumnDefinition($class) { - $this->assertEquals("CHAR(32) NOT NULL", $class->fieldMappings['email']['columnDefinition']); - $this->assertEquals("INT NULL", $class->associationMappings['groups']['joinTable']['inverseJoinColumns'][0]['columnDefinition']); + self::assertNotNull($class->getProperty('email')); + + $property = $class->getProperty('email'); + $association = $class->getProperty('groups'); + $joinTable = $association->getJoinTable(); + $inverseJoinColumns = $joinTable->getInverseJoinColumns(); + $inverseJoinColumn = reset($inverseJoinColumns); + + self::assertEquals("CHAR(32) NOT NULL", $property->getColumnDefinition()); + self::assertEquals("INT NULL", $inverseJoinColumn->getColumnDefinition()); return $class; } @@ -409,7 +490,11 @@ public function testColumnDefinition($class) */ public function testJoinColumnOnDelete($class) { - $this->assertEquals('CASCADE', $class->associationMappings['address']['joinColumns'][0]['onDelete']); + $association = $class->getProperty('address'); + $joinColumns = $association->getJoinColumns(); + $joinColumn = reset($joinColumns); + + self::assertEquals('CASCADE', $joinColumn->getOnDelete()); return $class; } @@ -425,10 +510,15 @@ public function testDiscriminatorColumnDefaults() $class = $this->createClassMetadata(Animal::class); - $this->assertEquals( - ['name' => 'discr', 'type' => 'string', 'length' => '32', 'fieldName' => 'discr', 'columnDefinition' => null], - $class->discriminatorColumn - ); + self::assertNotNull($class->discriminatorColumn); + + $discrColumn = $class->discriminatorColumn; + + self::assertEquals('Animal', $discrColumn->getTableName()); + self::assertEquals('discr', $discrColumn->getColumnName()); + self::assertEquals('string', $discrColumn->getTypeName()); + self::assertEquals(32, $discrColumn->getLength()); + self::assertNull($discrColumn->getColumnDefinition()); } /** @@ -436,29 +526,25 @@ public function testDiscriminatorColumnDefaults() */ public function testMappedSuperclassWithRepository() { - $em = $this->_getTestEntityManager(); - $factory = $this->createClassMetadataFactory($em); - - - $class = $factory->getMetadataFor(DDC869CreditCardPayment::class); - - $this->assertTrue(isset($class->fieldMappings['id'])); - $this->assertTrue(isset($class->fieldMappings['value'])); - $this->assertTrue(isset($class->fieldMappings['creditCardNumber'])); - $this->assertEquals($class->customRepositoryClassName, DDC869PaymentRepository::class); - $this->assertInstanceOf(DDC869PaymentRepository::class, $em->getRepository(DDC869CreditCardPayment::class)); - $this->assertTrue($em->getRepository(DDC869ChequePayment::class)->isTrue()); - + $em = $this->getTestEntityManager(); + $factory = $this->createClassMetadataFactory($em); + $class = $factory->getMetadataFor(DDC869CreditCardPayment::class); + self::assertNotNull($class->getProperty('id')); + self::assertNotNull($class->getProperty('value')); + self::assertNotNull($class->getProperty('creditCardNumber')); + self::assertEquals($class->getCustomRepositoryClassName(), DDC869PaymentRepository::class); + self::assertInstanceOf(DDC869PaymentRepository::class, $em->getRepository(DDC869CreditCardPayment::class)); + self::assertTrue($em->getRepository(DDC869ChequePayment::class)->isTrue()); $class = $factory->getMetadataFor(DDC869ChequePayment::class); - $this->assertTrue(isset($class->fieldMappings['id'])); - $this->assertTrue(isset($class->fieldMappings['value'])); - $this->assertTrue(isset($class->fieldMappings['serialNumber'])); - $this->assertEquals($class->customRepositoryClassName, DDC869PaymentRepository::class); - $this->assertInstanceOf(DDC869PaymentRepository::class, $em->getRepository(DDC869ChequePayment::class)); - $this->assertTrue($em->getRepository(DDC869ChequePayment::class)->isTrue()); + self::assertNotNull($class->getProperty('id')); + self::assertNotNull($class->getProperty('value')); + self::assertNotNull($class->getProperty('serialNumber')); + self::assertEquals($class->getCustomRepositoryClassName(), DDC869PaymentRepository::class); + self::assertInstanceOf(DDC869PaymentRepository::class, $em->getRepository(DDC869ChequePayment::class)); + self::assertTrue($em->getRepository(DDC869ChequePayment::class)->isTrue()); } /** @@ -466,37 +552,28 @@ public function testMappedSuperclassWithRepository() */ public function testDefaultFieldType() { - $factory = $this->createClassMetadataFactory(); - $class = $factory->getMetadataFor(DDC1476EntityWithDefaultFieldType::class); - - - $this->assertArrayHasKey('id', $class->fieldMappings); - $this->assertArrayHasKey('name', $class->fieldMappings); - - - $this->assertArrayHasKey('type', $class->fieldMappings['id']); - $this->assertArrayHasKey('type', $class->fieldMappings['name']); - - $this->assertEquals('string', $class->fieldMappings['id']['type']); - $this->assertEquals('string', $class->fieldMappings['name']['type']); - - + $factory = $this->createClassMetadataFactory(); + $class = $factory->getMetadataFor(DDC1476EntityWithDefaultFieldType::class); - $this->assertArrayHasKey('fieldName', $class->fieldMappings['id']); - $this->assertArrayHasKey('fieldName', $class->fieldMappings['name']); + self::assertNotNull($class->getProperty('id')); + self::assertNotNull($class->getProperty('name')); - $this->assertEquals('id', $class->fieldMappings['id']['fieldName']); - $this->assertEquals('name', $class->fieldMappings['name']['fieldName']); + $idProperty = $class->getProperty('id'); + $nameProperty = $class->getProperty('name'); + self::assertInstanceOf(Mapping\FieldMetadata::class, $idProperty); + self::assertInstanceOf(Mapping\FieldMetadata::class, $nameProperty); + self::assertEquals('string', $idProperty->getTypeName()); + self::assertEquals('string', $nameProperty->getTypeName()); - $this->assertArrayHasKey('columnName', $class->fieldMappings['id']); - $this->assertArrayHasKey('columnName', $class->fieldMappings['name']); + self::assertEquals('id', $idProperty->getName()); + self::assertEquals('name', $nameProperty->getName()); - $this->assertEquals('id', $class->fieldMappings['id']['columnName']); - $this->assertEquals('name', $class->fieldMappings['name']['columnName']); + self::assertEquals('id', $idProperty->getColumnName()); + self::assertEquals('name', $nameProperty->getColumnName()); - $this->assertEquals(ClassMetadataInfo::GENERATOR_TYPE_NONE, $class->generatorType); + self::assertFalse($idProperty->hasValueGenerator()); } /** @@ -506,15 +583,11 @@ public function testIdentifierColumnDefinition() { $class = $this->createClassMetadata(DDC1170Entity::class); + self::assertNotNull($class->getProperty('id')); + self::assertNotNull($class->getProperty('value')); - $this->assertArrayHasKey('id', $class->fieldMappings); - $this->assertArrayHasKey('value', $class->fieldMappings); - - $this->assertArrayHasKey('columnDefinition', $class->fieldMappings['id']); - $this->assertArrayHasKey('columnDefinition', $class->fieldMappings['value']); - - $this->assertEquals("INT unsigned NOT NULL", $class->fieldMappings['id']['columnDefinition']); - $this->assertEquals("VARCHAR(255) NOT NULL", $class->fieldMappings['value']['columnDefinition']); + self::assertEquals("INT unsigned NOT NULL", $class->getProperty('id')->getColumnDefinition()); + self::assertEquals("VARCHAR(255) NOT NULL", $class->getProperty('value')->getColumnDefinition()); } /** @@ -522,19 +595,20 @@ public function testIdentifierColumnDefinition() */ public function testNamingStrategy() { - $em = $this->_getTestEntityManager(); - $factory = $this->createClassMetadataFactory($em); - + $em = $this->getTestEntityManager(); + $factory = $this->createClassMetadataFactory($em); - $this->assertInstanceOf(DefaultNamingStrategy::class, $em->getConfiguration()->getNamingStrategy()); + self::assertInstanceOf(DefaultNamingStrategy::class, $em->getConfiguration()->getNamingStrategy()); $em->getConfiguration()->setNamingStrategy(new UnderscoreNamingStrategy(CASE_UPPER)); - $this->assertInstanceOf(UnderscoreNamingStrategy::class, $em->getConfiguration()->getNamingStrategy()); + self::assertInstanceOf(UnderscoreNamingStrategy::class, $em->getConfiguration()->getNamingStrategy()); - $class = $factory->getMetadataFor(DDC1476EntityWithDefaultFieldType::class); + $class = $factory->getMetadataFor(DDC1476EntityWithDefaultFieldType::class); + $idProperty = $class->getProperty('id'); + $nameProperty = $class->getProperty('name'); - $this->assertEquals('ID', $class->getColumnName('id')); - $this->assertEquals('NAME', $class->getColumnName('name')); - $this->assertEquals('DDC1476ENTITY_WITH_DEFAULT_FIELD_TYPE', $class->table['name']); + self::assertEquals('ID', $idProperty->getColumnName()); + self::assertEquals('NAME', $nameProperty->getColumnName()); + self::assertEquals('DDC1476ENTITY_WITH_DEFAULT_FIELD_TYPE', $class->table->getName()); } /** @@ -545,11 +619,12 @@ public function testDiscriminatorColumnDefinition() { $class = $this->createClassMetadata(DDC807Entity::class); - $this->assertArrayHasKey('columnDefinition', $class->discriminatorColumn); - $this->assertArrayHasKey('name', $class->discriminatorColumn); + self::assertNotNull($class->discriminatorColumn); + + $discrColumn = $class->discriminatorColumn; - $this->assertEquals("ENUM('ONE','TWO')", $class->discriminatorColumn['columnDefinition']); - $this->assertEquals("dtype", $class->discriminatorColumn['name']); + self::assertEquals('dtype', $discrColumn->getColumnName()); + self::assertEquals("ENUM('ONE','TWO')", $discrColumn->getColumnDefinition()); } /** @@ -578,10 +653,10 @@ public function testIdentifierRequiredShouldMentionParentClasses() public function testNamedQuery() { - $driver = $this->_loadDriver(); + $driver = $this->loadDriver(); $class = $this->createClassMetadata(User::class); - $this->assertCount(1, $class->getNamedQueries(), sprintf("Named queries not processed correctly by driver %s", get_class($driver))); + self::assertCount(1, $class->getNamedQueries(), sprintf("Named queries not processed correctly by driver %s", get_class($driver))); } /** @@ -589,51 +664,49 @@ public function testNamedQuery() */ public function testNamedNativeQuery() { - $class = $this->createClassMetadata(CmsAddress::class); - //named native query - $this->assertCount(3, $class->namedNativeQueries); - $this->assertArrayHasKey('find-all', $class->namedNativeQueries); - $this->assertArrayHasKey('find-by-id', $class->namedNativeQueries); - + // named native query + self::assertCount(3, $class->namedNativeQueries); + self::assertArrayHasKey('find-all', $class->namedNativeQueries); + self::assertArrayHasKey('find-by-id', $class->namedNativeQueries); $findAllQuery = $class->getNamedNativeQuery('find-all'); - $this->assertEquals('find-all', $findAllQuery['name']); - $this->assertEquals('mapping-find-all', $findAllQuery['resultSetMapping']); - $this->assertEquals('SELECT id, country, city FROM cms_addresses', $findAllQuery['query']); + + self::assertEquals('mapping-find-all', $findAllQuery['resultSetMapping']); + self::assertEquals('SELECT id, country, city FROM cms_addresses', $findAllQuery['query']); $findByIdQuery = $class->getNamedNativeQuery('find-by-id'); - $this->assertEquals('find-by-id', $findByIdQuery['name']); - $this->assertEquals(CmsAddress::class,$findByIdQuery['resultClass']); - $this->assertEquals('SELECT * FROM cms_addresses WHERE id = ?', $findByIdQuery['query']); + + self::assertEquals(CmsAddress::class,$findByIdQuery['resultClass']); + self::assertEquals('SELECT * FROM cms_addresses WHERE id = ?', $findByIdQuery['query']); $countQuery = $class->getNamedNativeQuery('count'); - $this->assertEquals('count', $countQuery['name']); - $this->assertEquals('mapping-count', $countQuery['resultSetMapping']); - $this->assertEquals('SELECT COUNT(*) AS count FROM cms_addresses', $countQuery['query']); + + self::assertEquals('mapping-count', $countQuery['resultSetMapping']); + self::assertEquals('SELECT COUNT(*) AS count FROM cms_addresses', $countQuery['query']); // result set mapping - $this->assertCount(3, $class->sqlResultSetMappings); - $this->assertArrayHasKey('mapping-count', $class->sqlResultSetMappings); - $this->assertArrayHasKey('mapping-find-all', $class->sqlResultSetMappings); - $this->assertArrayHasKey('mapping-without-fields', $class->sqlResultSetMappings); + self::assertCount(3, $class->sqlResultSetMappings); + self::assertArrayHasKey('mapping-count', $class->sqlResultSetMappings); + self::assertArrayHasKey('mapping-find-all', $class->sqlResultSetMappings); + self::assertArrayHasKey('mapping-without-fields', $class->sqlResultSetMappings); $findAllMapping = $class->getSqlResultSetMapping('mapping-find-all'); - $this->assertEquals('mapping-find-all', $findAllMapping['name']); - $this->assertEquals(CmsAddress::class, $findAllMapping['entities'][0]['entityClass']); - $this->assertEquals(['name'=>'id','column'=>'id'], $findAllMapping['entities'][0]['fields'][0]); - $this->assertEquals(['name'=>'city','column'=>'city'], $findAllMapping['entities'][0]['fields'][1]); - $this->assertEquals(['name'=>'country','column'=>'country'], $findAllMapping['entities'][0]['fields'][2]); + + self::assertEquals(CmsAddress::class, $findAllMapping['entities'][0]['entityClass']); + self::assertEquals(['name'=>'id','column'=>'id'], $findAllMapping['entities'][0]['fields'][0]); + self::assertEquals(['name'=>'city','column'=>'city'], $findAllMapping['entities'][0]['fields'][1]); + self::assertEquals(['name'=>'country','column'=>'country'], $findAllMapping['entities'][0]['fields'][2]); $withoutFieldsMapping = $class->getSqlResultSetMapping('mapping-without-fields'); - $this->assertEquals('mapping-without-fields', $withoutFieldsMapping['name']); - $this->assertEquals(CmsAddress::class, $withoutFieldsMapping['entities'][0]['entityClass']); - $this->assertEquals([], $withoutFieldsMapping['entities'][0]['fields']); + + self::assertEquals('__CLASS__', $withoutFieldsMapping['entities'][0]['entityClass']); + self::assertEquals([], $withoutFieldsMapping['entities'][0]['fields']); $countMapping = $class->getSqlResultSetMapping('mapping-count'); - $this->assertEquals('mapping-count', $countMapping['name']); - $this->assertEquals(['name'=>'count'], $countMapping['columns'][0]); + + self::assertEquals(['name'=>'count'], $countMapping['columns'][0]); } @@ -642,70 +715,85 @@ public function testNamedNativeQuery() */ public function testSqlResultSetMapping() { - $userMetadata = $this->createClassMetadata(CmsUser::class); $personMetadata = $this->createClassMetadata(CompanyPerson::class); // user asserts - $this->assertCount(4, $userMetadata->getSqlResultSetMappings()); + self::assertCount(4, $userMetadata->getSqlResultSetMappings()); $mapping = $userMetadata->getSqlResultSetMapping('mappingJoinedAddress'); - $this->assertEquals([],$mapping['columns']); - $this->assertEquals('mappingJoinedAddress', $mapping['name']); - $this->assertNull($mapping['entities'][0]['discriminatorColumn']); - $this->assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][0]['fields'][0]); - $this->assertEquals(['name'=>'name','column'=>'name'], $mapping['entities'][0]['fields'][1]); - $this->assertEquals(['name'=>'status','column'=>'status'], $mapping['entities'][0]['fields'][2]); - $this->assertEquals(['name'=>'address.zip','column'=>'zip'], $mapping['entities'][0]['fields'][3]); - $this->assertEquals(['name'=>'address.city','column'=>'city'], $mapping['entities'][0]['fields'][4]); - $this->assertEquals(['name'=>'address.country','column'=>'country'], $mapping['entities'][0]['fields'][5]); - $this->assertEquals(['name'=>'address.id','column'=>'a_id'], $mapping['entities'][0]['fields'][6]); - $this->assertEquals($userMetadata->name, $mapping['entities'][0]['entityClass']); + self::assertEquals([],$mapping['columns']); + self::assertEquals('mappingJoinedAddress', $mapping['name']); + + self::assertNull($mapping['entities'][0]['discriminatorColumn']); + + self::assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][0]['fields'][0]); + self::assertEquals(['name'=>'name','column'=>'name'], $mapping['entities'][0]['fields'][1]); + self::assertEquals(['name'=>'status','column'=>'status'], $mapping['entities'][0]['fields'][2]); + self::assertEquals(['name'=>'address.zip','column'=>'zip'], $mapping['entities'][0]['fields'][3]); + self::assertEquals(['name'=>'address.city','column'=>'city'], $mapping['entities'][0]['fields'][4]); + self::assertEquals(['name'=>'address.country','column'=>'country'], $mapping['entities'][0]['fields'][5]); + self::assertEquals(['name'=>'address.id','column'=>'a_id'], $mapping['entities'][0]['fields'][6]); + self::assertEquals('__CLASS__', $mapping['entities'][0]['entityClass']); $mapping = $userMetadata->getSqlResultSetMapping('mappingJoinedPhonenumber'); - $this->assertEquals([],$mapping['columns']); - $this->assertEquals('mappingJoinedPhonenumber', $mapping['name']); - $this->assertNull($mapping['entities'][0]['discriminatorColumn']); - $this->assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][0]['fields'][0]); - $this->assertEquals(['name'=>'name','column'=>'name'], $mapping['entities'][0]['fields'][1]); - $this->assertEquals(['name'=>'status','column'=>'status'], $mapping['entities'][0]['fields'][2]); - $this->assertEquals(['name'=>'phonenumbers.phonenumber','column'=>'number'], $mapping['entities'][0]['fields'][3]); - $this->assertEquals($userMetadata->name, $mapping['entities'][0]['entityClass']); + + self::assertEquals([],$mapping['columns']); + self::assertEquals('mappingJoinedPhonenumber', $mapping['name']); + + self::assertNull($mapping['entities'][0]['discriminatorColumn']); + + self::assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][0]['fields'][0]); + self::assertEquals(['name'=>'name','column'=>'name'], $mapping['entities'][0]['fields'][1]); + self::assertEquals(['name'=>'status','column'=>'status'], $mapping['entities'][0]['fields'][2]); + self::assertEquals(['name'=>'phonenumbers.phonenumber','column'=>'number'], $mapping['entities'][0]['fields'][3]); + self::assertEquals($userMetadata->getClassName(), $mapping['entities'][0]['entityClass']); $mapping = $userMetadata->getSqlResultSetMapping('mappingUserPhonenumberCount'); - $this->assertEquals(['name'=>'numphones'],$mapping['columns'][0]); - $this->assertEquals('mappingUserPhonenumberCount', $mapping['name']); - $this->assertNull($mapping['entities'][0]['discriminatorColumn']); - $this->assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][0]['fields'][0]); - $this->assertEquals(['name'=>'name','column'=>'name'], $mapping['entities'][0]['fields'][1]); - $this->assertEquals(['name'=>'status','column'=>'status'], $mapping['entities'][0]['fields'][2]); - $this->assertEquals($userMetadata->name, $mapping['entities'][0]['entityClass']); + + self::assertEquals(['name'=>'numphones'],$mapping['columns'][0]); + self::assertEquals('mappingUserPhonenumberCount', $mapping['name']); + + self::assertNull($mapping['entities'][0]['discriminatorColumn']); + + self::assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][0]['fields'][0]); + self::assertEquals(['name'=>'name','column'=>'name'], $mapping['entities'][0]['fields'][1]); + self::assertEquals(['name'=>'status','column'=>'status'], $mapping['entities'][0]['fields'][2]); + self::assertEquals($userMetadata->getClassName(), $mapping['entities'][0]['entityClass']); $mapping = $userMetadata->getSqlResultSetMapping('mappingMultipleJoinsEntityResults'); - $this->assertEquals(['name'=>'numphones'],$mapping['columns'][0]); - $this->assertEquals('mappingMultipleJoinsEntityResults', $mapping['name']); - $this->assertNull($mapping['entities'][0]['discriminatorColumn']); - $this->assertEquals(['name'=>'id','column'=>'u_id'], $mapping['entities'][0]['fields'][0]); - $this->assertEquals(['name'=>'name','column'=>'u_name'], $mapping['entities'][0]['fields'][1]); - $this->assertEquals(['name'=>'status','column'=>'u_status'], $mapping['entities'][0]['fields'][2]); - $this->assertEquals($userMetadata->name, $mapping['entities'][0]['entityClass']); - $this->assertNull($mapping['entities'][1]['discriminatorColumn']); - $this->assertEquals(['name'=>'id','column'=>'a_id'], $mapping['entities'][1]['fields'][0]); - $this->assertEquals(['name'=>'zip','column'=>'a_zip'], $mapping['entities'][1]['fields'][1]); - $this->assertEquals(['name'=>'country','column'=>'a_country'], $mapping['entities'][1]['fields'][2]); - $this->assertEquals(CmsAddress::class, $mapping['entities'][1]['entityClass']); + + self::assertEquals(['name'=>'numphones'],$mapping['columns'][0]); + self::assertEquals('mappingMultipleJoinsEntityResults', $mapping['name']); + + self::assertNull($mapping['entities'][0]['discriminatorColumn']); + + self::assertEquals(['name'=>'id','column'=>'u_id'], $mapping['entities'][0]['fields'][0]); + self::assertEquals(['name'=>'name','column'=>'u_name'], $mapping['entities'][0]['fields'][1]); + self::assertEquals(['name'=>'status','column'=>'u_status'], $mapping['entities'][0]['fields'][2]); + self::assertEquals('__CLASS__', $mapping['entities'][0]['entityClass']); + + self::assertNull($mapping['entities'][1]['discriminatorColumn']); + + self::assertEquals(['name'=>'id','column'=>'a_id'], $mapping['entities'][1]['fields'][0]); + self::assertEquals(['name'=>'zip','column'=>'a_zip'], $mapping['entities'][1]['fields'][1]); + self::assertEquals(['name'=>'country','column'=>'a_country'], $mapping['entities'][1]['fields'][2]); + self::assertEquals(CmsAddress::class, $mapping['entities'][1]['entityClass']); //person asserts - $this->assertCount(1, $personMetadata->getSqlResultSetMappings()); + self::assertCount(1, $personMetadata->getSqlResultSetMappings()); $mapping = $personMetadata->getSqlResultSetMapping('mappingFetchAll'); - $this->assertEquals([],$mapping['columns']); - $this->assertEquals('mappingFetchAll', $mapping['name']); - $this->assertEquals('discriminator', $mapping['entities'][0]['discriminatorColumn']); - $this->assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][0]['fields'][0]); - $this->assertEquals(['name'=>'name','column'=>'name'], $mapping['entities'][0]['fields'][1]); - $this->assertEquals($personMetadata->name, $mapping['entities'][0]['entityClass']); + + self::assertEquals([], $mapping['columns']); + self::assertEquals('mappingFetchAll', $mapping['name']); + + self::assertEquals('discriminator', $mapping['entities'][0]['discriminatorColumn']); + + self::assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][0]['fields'][0]); + self::assertEquals(['name'=>'name','column'=>'name'], $mapping['entities'][0]['fields'][1]); + self::assertEquals('__CLASS__', $mapping['entities'][0]['entityClass']); } /* @@ -713,82 +801,73 @@ public function testSqlResultSetMapping() */ public function testAssociationOverridesMapping() { - $factory = $this->createClassMetadataFactory(); $adminMetadata = $factory->getMetadataFor(DDC964Admin::class); $guestMetadata = $factory->getMetadataFor(DDC964Guest::class); - // assert groups association mappings - $this->assertArrayHasKey('groups', $guestMetadata->associationMappings); - $this->assertArrayHasKey('groups', $adminMetadata->associationMappings); + self::assertArrayHasKey('groups', iterator_to_array($guestMetadata->getDeclaredPropertiesIterator())); + self::assertArrayHasKey('groups', iterator_to_array($adminMetadata->getDeclaredPropertiesIterator())); - $guestGroups = $guestMetadata->associationMappings['groups']; - $adminGroups = $adminMetadata->associationMappings['groups']; + $guestGroups = $guestMetadata->getProperty('groups'); + $adminGroups = $adminMetadata->getProperty('groups'); // assert not override attributes - $this->assertEquals($guestGroups['fieldName'], $adminGroups['fieldName']); - $this->assertEquals($guestGroups['type'], $adminGroups['type']); - $this->assertEquals($guestGroups['mappedBy'], $adminGroups['mappedBy']); - $this->assertEquals($guestGroups['inversedBy'], $adminGroups['inversedBy']); - $this->assertEquals($guestGroups['isOwningSide'], $adminGroups['isOwningSide']); - $this->assertEquals($guestGroups['fetch'], $adminGroups['fetch']); - $this->assertEquals($guestGroups['isCascadeRemove'], $adminGroups['isCascadeRemove']); - $this->assertEquals($guestGroups['isCascadePersist'], $adminGroups['isCascadePersist']); - $this->assertEquals($guestGroups['isCascadeRefresh'], $adminGroups['isCascadeRefresh']); - $this->assertEquals($guestGroups['isCascadeMerge'], $adminGroups['isCascadeMerge']); - $this->assertEquals($guestGroups['isCascadeDetach'], $adminGroups['isCascadeDetach']); + self::assertEquals($guestGroups->getName(), $adminGroups->getName()); + self::assertEquals(get_class($guestGroups), get_class($adminGroups)); + self::assertEquals($guestGroups->getMappedBy(), $adminGroups->getMappedBy()); + self::assertEquals($guestGroups->getInversedBy(), $adminGroups->getInversedBy()); + self::assertEquals($guestGroups->isOwningSide(), $adminGroups->isOwningSide()); + self::assertEquals($guestGroups->getFetchMode(), $adminGroups->getFetchMode()); + self::assertEquals($guestGroups->getCascade(), $adminGroups->getCascade()); // assert not override attributes - $this->assertEquals('ddc964_users_groups', $guestGroups['joinTable']['name']); - $this->assertEquals('user_id', $guestGroups['joinTable']['joinColumns'][0]['name']); - $this->assertEquals('group_id', $guestGroups['joinTable']['inverseJoinColumns'][0]['name']); - - $this->assertEquals(['user_id'=>'id'], $guestGroups['relationToSourceKeyColumns']); - $this->assertEquals(['group_id'=>'id'], $guestGroups['relationToTargetKeyColumns']); - $this->assertEquals(['user_id','group_id'], $guestGroups['joinTableColumns']); - - - $this->assertEquals('ddc964_users_admingroups', $adminGroups['joinTable']['name']); - $this->assertEquals('adminuser_id', $adminGroups['joinTable']['joinColumns'][0]['name']); - $this->assertEquals('admingroup_id', $adminGroups['joinTable']['inverseJoinColumns'][0]['name']); - - $this->assertEquals(['adminuser_id'=>'id'], $adminGroups['relationToSourceKeyColumns']); - $this->assertEquals(['admingroup_id'=>'id'], $adminGroups['relationToTargetKeyColumns']); - $this->assertEquals(['adminuser_id','admingroup_id'], $adminGroups['joinTableColumns']); - + $guestGroupsJoinTable = $guestGroups->getJoinTable(); + $guestGroupsJoinColumns = $guestGroupsJoinTable->getJoinColumns(); + $guestGroupsJoinColumn = reset($guestGroupsJoinColumns); + $guestGroupsInverseJoinColumns = $guestGroupsJoinTable->getInverseJoinColumns(); + $guestGroupsInverseJoinColumn = reset($guestGroupsInverseJoinColumns); + + self::assertEquals('ddc964_users_groups', $guestGroupsJoinTable->getName()); + self::assertEquals('user_id', $guestGroupsJoinColumn->getColumnName()); + self::assertEquals('group_id', $guestGroupsInverseJoinColumn->getColumnName()); + + $adminGroupsJoinTable = $adminGroups->getJoinTable(); + $adminGroupsJoinColumns = $adminGroupsJoinTable->getJoinColumns(); + $adminGroupsJoinColumn = reset($adminGroupsJoinColumns); + $adminGroupsInverseJoinColumns = $adminGroupsJoinTable->getInverseJoinColumns(); + $adminGroupsInverseJoinColumn = reset($adminGroupsInverseJoinColumns); + + self::assertEquals('ddc964_users_admingroups', $adminGroupsJoinTable->getName()); + self::assertEquals('adminuser_id', $adminGroupsJoinColumn->getColumnName()); + self::assertEquals('admingroup_id', $adminGroupsInverseJoinColumn->getColumnName()); // assert address association mappings - $this->assertArrayHasKey('address', $guestMetadata->associationMappings); - $this->assertArrayHasKey('address', $adminMetadata->associationMappings); + self::assertArrayHasKey('address', iterator_to_array($guestMetadata->getDeclaredPropertiesIterator())); + self::assertArrayHasKey('address', iterator_to_array($adminMetadata->getDeclaredPropertiesIterator())); - $guestAddress = $guestMetadata->associationMappings['address']; - $adminAddress = $adminMetadata->associationMappings['address']; + $guestAddress = $guestMetadata->getProperty('address'); + $adminAddress = $adminMetadata->getProperty('address'); // assert not override attributes - $this->assertEquals($guestAddress['fieldName'], $adminAddress['fieldName']); - $this->assertEquals($guestAddress['type'], $adminAddress['type']); - $this->assertEquals($guestAddress['mappedBy'], $adminAddress['mappedBy']); - $this->assertEquals($guestAddress['inversedBy'], $adminAddress['inversedBy']); - $this->assertEquals($guestAddress['isOwningSide'], $adminAddress['isOwningSide']); - $this->assertEquals($guestAddress['fetch'], $adminAddress['fetch']); - $this->assertEquals($guestAddress['isCascadeRemove'], $adminAddress['isCascadeRemove']); - $this->assertEquals($guestAddress['isCascadePersist'], $adminAddress['isCascadePersist']); - $this->assertEquals($guestAddress['isCascadeRefresh'], $adminAddress['isCascadeRefresh']); - $this->assertEquals($guestAddress['isCascadeMerge'], $adminAddress['isCascadeMerge']); - $this->assertEquals($guestAddress['isCascadeDetach'], $adminAddress['isCascadeDetach']); + self::assertEquals($guestAddress->getName(), $adminAddress->getName()); + self::assertEquals(get_class($guestAddress), get_class($adminAddress)); + self::assertEquals($guestAddress->getMappedBy(), $adminAddress->getMappedBy()); + self::assertEquals($guestAddress->getInversedBy(), $adminAddress->getInversedBy()); + self::assertEquals($guestAddress->isOwningSide(), $adminAddress->isOwningSide()); + self::assertEquals($guestAddress->getFetchMode(), $adminAddress->getFetchMode()); + self::assertEquals($guestAddress->getCascade(), $adminAddress->getCascade()); // assert override - $this->assertEquals('address_id', $guestAddress['joinColumns'][0]['name']); - $this->assertEquals(['address_id'=>'id'], $guestAddress['sourceToTargetKeyColumns']); - $this->assertEquals(['address_id'=>'address_id'], $guestAddress['joinColumnFieldNames']); - $this->assertEquals(['id'=>'address_id'], $guestAddress['targetToSourceKeyColumns']); + $guestAddressJoinColumns = $guestAddress->getJoinColumns(); + $guestAddressJoinColumn = reset($guestAddressJoinColumns); + self::assertEquals('address_id', $guestAddressJoinColumn->getColumnName()); - $this->assertEquals('adminaddress_id', $adminAddress['joinColumns'][0]['name']); - $this->assertEquals(['adminaddress_id'=>'id'], $adminAddress['sourceToTargetKeyColumns']); - $this->assertEquals(['adminaddress_id'=>'adminaddress_id'], $adminAddress['joinColumnFieldNames']); - $this->assertEquals(['id'=>'adminaddress_id'], $adminAddress['targetToSourceKeyColumns']); + $adminAddressJoinColumns = $adminAddress->getJoinColumns(); + $adminAddressJoinColumn = reset($adminAddressJoinColumns); + + self::assertEquals('adminaddress_id', $adminAddressJoinColumn->getColumnName()); } /* @@ -796,16 +875,16 @@ public function testAssociationOverridesMapping() */ public function testInversedByOverrideMapping() { - $factory = $this->createClassMetadataFactory(); $adminMetadata = $factory->getMetadataFor(DDC3579Admin::class); // assert groups association mappings - $this->assertArrayHasKey('groups', $adminMetadata->associationMappings); - $adminGroups = $adminMetadata->associationMappings['groups']; + self::assertArrayHasKey('groups', iterator_to_array($adminMetadata->getDeclaredPropertiesIterator())); + + $adminGroups = $adminMetadata->getProperty('groups'); // assert override - $this->assertEquals('admins', $adminGroups['inversedBy']); + self::assertEquals('admins', $adminGroups->getInversedBy()); } /** @@ -816,8 +895,11 @@ public function testFetchOverrideMapping() // check override metadata $contractMetadata = $this->createClassMetadataFactory()->getMetadataFor(DDC5934Contract::class); - $this->assertArrayHasKey('members', $contractMetadata->associationMappings); - $this->assertSame(ClassMetadata::FETCH_EXTRA_LAZY, $contractMetadata->associationMappings['members']['fetch']); + self::assertArrayHasKey('members', iterator_to_array($contractMetadata->getDeclaredPropertiesIterator())); + + $contractMembers = $contractMetadata->getProperty('members'); + + self::assertSame(Mapping\FetchMode::EXTRA_LAZY, $contractMembers->getFetchMode()); } /** @@ -825,38 +907,64 @@ public function testFetchOverrideMapping() */ public function testAttributeOverridesMapping() { - $factory = $this->createClassMetadataFactory(); - $guestMetadata = $factory->getMetadataFor(DDC964Guest::class); $adminMetadata = $factory->getMetadataFor(DDC964Admin::class); - $this->assertTrue($adminMetadata->fieldMappings['id']['id']); - $this->assertEquals('id', $adminMetadata->fieldMappings['id']['fieldName']); - $this->assertEquals('user_id', $adminMetadata->fieldMappings['id']['columnName']); - $this->assertEquals(['user_id'=>'id','user_name'=>'name'], $adminMetadata->fieldNames); - $this->assertEquals(['id'=>'user_id','name'=>'user_name'], $adminMetadata->columnNames); - $this->assertEquals(150, $adminMetadata->fieldMappings['id']['length']); - - - $this->assertEquals('name', $adminMetadata->fieldMappings['name']['fieldName']); - $this->assertEquals('user_name', $adminMetadata->fieldMappings['name']['columnName']); - $this->assertEquals(250, $adminMetadata->fieldMappings['name']['length']); - $this->assertTrue($adminMetadata->fieldMappings['name']['nullable']); - $this->assertFalse($adminMetadata->fieldMappings['name']['unique']); - - - $this->assertTrue($guestMetadata->fieldMappings['id']['id']); - $this->assertEquals('guest_id', $guestMetadata->fieldMappings['id']['columnName']); - $this->assertEquals('id', $guestMetadata->fieldMappings['id']['fieldName']); - $this->assertEquals(['guest_id'=>'id','guest_name'=>'name'], $guestMetadata->fieldNames); - $this->assertEquals(['id'=>'guest_id','name'=>'guest_name'], $guestMetadata->columnNames); - $this->assertEquals(140, $guestMetadata->fieldMappings['id']['length']); - - $this->assertEquals('name', $guestMetadata->fieldMappings['name']['fieldName']); - $this->assertEquals('guest_name', $guestMetadata->fieldMappings['name']['columnName']); - $this->assertEquals(240, $guestMetadata->fieldMappings['name']['length']); - $this->assertFalse($guestMetadata->fieldMappings['name']['nullable']); - $this->assertTrue($guestMetadata->fieldMappings['name']['unique']); + self::assertEquals( + [ + 'user_id' => 'id', + 'user_name' => 'name', + 'adminaddress_id' => 'address', + ], + $adminMetadata->fieldNames + ); + + self::assertNotNull($adminMetadata->getProperty('id')); + + $idProperty = $adminMetadata->getProperty('id'); + + self::assertTrue($idProperty->isPrimaryKey()); + self::assertEquals('id', $idProperty->getName()); + self::assertEquals('user_id', $idProperty->getColumnName()); + + self::assertNotNull($adminMetadata->getProperty('name')); + + $nameProperty = $adminMetadata->getProperty('name'); + + self::assertEquals('name', $nameProperty->getName()); + self::assertEquals('user_name', $nameProperty->getColumnName()); + self::assertEquals(250, $nameProperty->getLength()); + self::assertTrue($nameProperty->isNullable()); + self::assertFalse($nameProperty->isUnique()); + + $guestMetadata = $factory->getMetadataFor(DDC964Guest::class); + + self::assertEquals( + [ + 'guest_id' => 'id', + 'guest_name' => 'name', + 'address_id' => 'address', + ], + $guestMetadata->fieldNames + ); + + self::assertNotNull($guestMetadata->getProperty('id')); + + $idProperty = $guestMetadata->getProperty('id'); + + self::assertTrue($idProperty->isPrimaryKey()); + self::assertEquals('id', $idProperty->getName()); + self::assertEquals('guest_id', $idProperty->getColumnName()); + + self::assertNotNull($guestMetadata->getProperty('name')); + + $nameProperty = $guestMetadata->getProperty('name'); + + self::assertEquals('name', $nameProperty->getName()); + self::assertEquals('guest_name', $nameProperty->getColumnName()); + self::assertEquals(240, $nameProperty->getLength()); + self::assertFalse($nameProperty->isNullable()); + self::assertTrue($nameProperty->isUnique()); } /** @@ -864,30 +972,28 @@ public function testAttributeOverridesMapping() */ public function testEntityListeners() { - $em = $this->_getTestEntityManager(); - $factory = $this->createClassMetadataFactory($em); + $factory = $this->createClassMetadataFactory(); $superClass = $factory->getMetadataFor(CompanyContract::class); $flexClass = $factory->getMetadataFor(CompanyFixContract::class); $fixClass = $factory->getMetadataFor(CompanyFlexContract::class); - $ultraClass = $factory->getMetadataFor(CompanyFlexUltraContract::class); - $this->assertArrayHasKey(Events::prePersist, $superClass->entityListeners); - $this->assertArrayHasKey(Events::postPersist, $superClass->entityListeners); + self::assertArrayHasKey(Events::prePersist, $superClass->entityListeners); + self::assertArrayHasKey(Events::postPersist, $superClass->entityListeners); - $this->assertCount(1, $superClass->entityListeners[Events::prePersist]); - $this->assertCount(1, $superClass->entityListeners[Events::postPersist]); + self::assertCount(1, $superClass->entityListeners[Events::prePersist]); + self::assertCount(1, $superClass->entityListeners[Events::postPersist]); $postPersist = $superClass->entityListeners[Events::postPersist][0]; $prePersist = $superClass->entityListeners[Events::prePersist][0]; - $this->assertEquals(CompanyContractListener::class, $postPersist['class']); - $this->assertEquals(CompanyContractListener::class, $prePersist['class']); - $this->assertEquals('postPersistHandler', $postPersist['method']); - $this->assertEquals('prePersistHandler', $prePersist['method']); + self::assertEquals(CompanyContractListener::class, $postPersist['class']); + self::assertEquals(CompanyContractListener::class, $prePersist['class']); + self::assertEquals('postPersistHandler', $postPersist['method']); + self::assertEquals('prePersistHandler', $prePersist['method']); //Inherited listeners - $this->assertEquals($fixClass->entityListeners, $superClass->entityListeners); - $this->assertEquals($flexClass->entityListeners, $superClass->entityListeners); + self::assertEquals($fixClass->entityListeners, $superClass->entityListeners); + self::assertEquals($flexClass->entityListeners, $superClass->entityListeners); } /** @@ -895,32 +1001,31 @@ public function testEntityListeners() */ public function testEntityListenersOverride() { - $em = $this->_getTestEntityManager(); - $factory = $this->createClassMetadataFactory($em); + $factory = $this->createClassMetadataFactory(); $ultraClass = $factory->getMetadataFor(CompanyFlexUltraContract::class); //overridden listeners - $this->assertArrayHasKey(Events::postPersist, $ultraClass->entityListeners); - $this->assertArrayHasKey(Events::prePersist, $ultraClass->entityListeners); + self::assertArrayHasKey(Events::postPersist, $ultraClass->entityListeners); + self::assertArrayHasKey(Events::prePersist, $ultraClass->entityListeners); - $this->assertCount(1, $ultraClass->entityListeners[Events::postPersist]); - $this->assertCount(3, $ultraClass->entityListeners[Events::prePersist]); + self::assertCount(1, $ultraClass->entityListeners[Events::postPersist]); + self::assertCount(3, $ultraClass->entityListeners[Events::prePersist]); $postPersist = $ultraClass->entityListeners[Events::postPersist][0]; $prePersist = $ultraClass->entityListeners[Events::prePersist][0]; - $this->assertEquals(CompanyContractListener::class, $postPersist['class']); - $this->assertEquals(CompanyContractListener::class, $prePersist['class']); - $this->assertEquals('postPersistHandler', $postPersist['method']); - $this->assertEquals('prePersistHandler', $prePersist['method']); + self::assertEquals(CompanyContractListener::class, $postPersist['class']); + self::assertEquals(CompanyContractListener::class, $prePersist['class']); + self::assertEquals('postPersistHandler', $postPersist['method']); + self::assertEquals('prePersistHandler', $prePersist['method']); $prePersist = $ultraClass->entityListeners[Events::prePersist][1]; - $this->assertEquals(CompanyFlexUltraContractListener::class, $prePersist['class']); - $this->assertEquals('prePersistHandler1', $prePersist['method']); + self::assertEquals(CompanyFlexUltraContractListener::class, $prePersist['class']); + self::assertEquals('prePersistHandler1', $prePersist['method']); $prePersist = $ultraClass->entityListeners[Events::prePersist][2]; - $this->assertEquals(CompanyFlexUltraContractListener::class, $prePersist['class']); - $this->assertEquals('prePersistHandler2', $prePersist['method']); + self::assertEquals(CompanyFlexUltraContractListener::class, $prePersist['class']); + self::assertEquals('prePersistHandler2', $prePersist['method']); } @@ -929,27 +1034,26 @@ public function testEntityListenersOverride() */ public function testEntityListenersNamingConvention() { - $em = $this->_getTestEntityManager(); - $factory = $this->createClassMetadataFactory($em); - $metadata = $factory->getMetadataFor(CmsAddress::class); - - $this->assertArrayHasKey(Events::postPersist, $metadata->entityListeners); - $this->assertArrayHasKey(Events::prePersist, $metadata->entityListeners); - $this->assertArrayHasKey(Events::postUpdate, $metadata->entityListeners); - $this->assertArrayHasKey(Events::preUpdate, $metadata->entityListeners); - $this->assertArrayHasKey(Events::postRemove, $metadata->entityListeners); - $this->assertArrayHasKey(Events::preRemove, $metadata->entityListeners); - $this->assertArrayHasKey(Events::postLoad, $metadata->entityListeners); - $this->assertArrayHasKey(Events::preFlush, $metadata->entityListeners); - - $this->assertCount(1, $metadata->entityListeners[Events::postPersist]); - $this->assertCount(1, $metadata->entityListeners[Events::prePersist]); - $this->assertCount(1, $metadata->entityListeners[Events::postUpdate]); - $this->assertCount(1, $metadata->entityListeners[Events::preUpdate]); - $this->assertCount(1, $metadata->entityListeners[Events::postRemove]); - $this->assertCount(1, $metadata->entityListeners[Events::preRemove]); - $this->assertCount(1, $metadata->entityListeners[Events::postLoad]); - $this->assertCount(1, $metadata->entityListeners[Events::preFlush]); + $factory = $this->createClassMetadataFactory(); + $metadata = $factory->getMetadataFor(CmsAddress::class); + + self::assertArrayHasKey(Events::postPersist, $metadata->entityListeners); + self::assertArrayHasKey(Events::prePersist, $metadata->entityListeners); + self::assertArrayHasKey(Events::postUpdate, $metadata->entityListeners); + self::assertArrayHasKey(Events::preUpdate, $metadata->entityListeners); + self::assertArrayHasKey(Events::postRemove, $metadata->entityListeners); + self::assertArrayHasKey(Events::preRemove, $metadata->entityListeners); + self::assertArrayHasKey(Events::postLoad, $metadata->entityListeners); + self::assertArrayHasKey(Events::preFlush, $metadata->entityListeners); + + self::assertCount(1, $metadata->entityListeners[Events::postPersist]); + self::assertCount(1, $metadata->entityListeners[Events::prePersist]); + self::assertCount(1, $metadata->entityListeners[Events::postUpdate]); + self::assertCount(1, $metadata->entityListeners[Events::preUpdate]); + self::assertCount(1, $metadata->entityListeners[Events::postRemove]); + self::assertCount(1, $metadata->entityListeners[Events::preRemove]); + self::assertCount(1, $metadata->entityListeners[Events::postLoad]); + self::assertCount(1, $metadata->entityListeners[Events::preFlush]); $postPersist = $metadata->entityListeners[Events::postPersist][0]; $prePersist = $metadata->entityListeners[Events::prePersist][0]; @@ -960,24 +1064,23 @@ public function testEntityListenersNamingConvention() $postLoad = $metadata->entityListeners[Events::postLoad][0]; $preFlush = $metadata->entityListeners[Events::preFlush][0]; - - $this->assertEquals(CmsAddressListener::class, $postPersist['class']); - $this->assertEquals(CmsAddressListener::class, $prePersist['class']); - $this->assertEquals(CmsAddressListener::class, $postUpdate['class']); - $this->assertEquals(CmsAddressListener::class, $preUpdate['class']); - $this->assertEquals(CmsAddressListener::class, $postRemove['class']); - $this->assertEquals(CmsAddressListener::class, $preRemove['class']); - $this->assertEquals(CmsAddressListener::class, $postLoad['class']); - $this->assertEquals(CmsAddressListener::class, $preFlush['class']); - - $this->assertEquals(Events::postPersist, $postPersist['method']); - $this->assertEquals(Events::prePersist, $prePersist['method']); - $this->assertEquals(Events::postUpdate, $postUpdate['method']); - $this->assertEquals(Events::preUpdate, $preUpdate['method']); - $this->assertEquals(Events::postRemove, $postRemove['method']); - $this->assertEquals(Events::preRemove, $preRemove['method']); - $this->assertEquals(Events::postLoad, $postLoad['method']); - $this->assertEquals(Events::preFlush, $preFlush['method']); + self::assertEquals(CmsAddressListener::class, $postPersist['class']); + self::assertEquals(CmsAddressListener::class, $prePersist['class']); + self::assertEquals(CmsAddressListener::class, $postUpdate['class']); + self::assertEquals(CmsAddressListener::class, $preUpdate['class']); + self::assertEquals(CmsAddressListener::class, $postRemove['class']); + self::assertEquals(CmsAddressListener::class, $preRemove['class']); + self::assertEquals(CmsAddressListener::class, $postLoad['class']); + self::assertEquals(CmsAddressListener::class, $preFlush['class']); + + self::assertEquals(Events::postPersist, $postPersist['method']); + self::assertEquals(Events::prePersist, $prePersist['method']); + self::assertEquals(Events::postUpdate, $postUpdate['method']); + self::assertEquals(Events::preUpdate, $preUpdate['method']); + self::assertEquals(Events::postRemove, $postRemove['method']); + self::assertEquals(Events::preRemove, $preRemove['method']); + self::assertEquals(Events::postLoad, $postLoad['method']); + self::assertEquals(Events::preFlush, $preFlush['method']); } /** @@ -985,27 +1088,28 @@ public function testEntityListenersNamingConvention() */ public function testSecondLevelCacheMapping() { - $em = $this->_getTestEntityManager(); - $factory = $this->createClassMetadataFactory($em); + $factory = $this->createClassMetadataFactory(); $class = $factory->getMetadataFor(City::class); - $this->assertArrayHasKey('usage', $class->cache); - $this->assertArrayHasKey('region', $class->cache); - $this->assertEquals(ClassMetadata::CACHE_USAGE_READ_ONLY, $class->cache['usage']); - $this->assertEquals('doctrine_tests_models_cache_city', $class->cache['region']); - - $this->assertArrayHasKey('state', $class->associationMappings); - $this->assertArrayHasKey('cache', $class->associationMappings['state']); - $this->assertArrayHasKey('usage', $class->associationMappings['state']['cache']); - $this->assertArrayHasKey('region', $class->associationMappings['state']['cache']); - $this->assertEquals(ClassMetadata::CACHE_USAGE_READ_ONLY, $class->associationMappings['state']['cache']['usage']); - $this->assertEquals('doctrine_tests_models_cache_city__state', $class->associationMappings['state']['cache']['region']); - - $this->assertArrayHasKey('attractions', $class->associationMappings); - $this->assertArrayHasKey('cache', $class->associationMappings['attractions']); - $this->assertArrayHasKey('usage', $class->associationMappings['attractions']['cache']); - $this->assertArrayHasKey('region', $class->associationMappings['attractions']['cache']); - $this->assertEquals(ClassMetadata::CACHE_USAGE_READ_ONLY, $class->associationMappings['attractions']['cache']['usage']); - $this->assertEquals('doctrine_tests_models_cache_city__attractions', $class->associationMappings['attractions']['cache']['region']); + + self::assertNotNull($class->getCache()); + self::assertEquals(Mapping\CacheUsage::READ_ONLY, $class->getCache()->getUsage()); + self::assertEquals('doctrine_tests_models_cache_city', $class->getCache()->getRegion()); + + self::assertArrayHasKey('state', iterator_to_array($class->getDeclaredPropertiesIterator())); + + $stateAssociation = $class->getProperty('state'); + + self::assertNotNull($stateAssociation->getCache()); + self::assertEquals(Mapping\CacheUsage::READ_ONLY, $stateAssociation->getCache()->getUsage()); + self::assertEquals('doctrine_tests_models_cache_city__state', $stateAssociation->getCache()->getRegion()); + + self::assertArrayHasKey('attractions', iterator_to_array($class->getDeclaredPropertiesIterator())); + + $attractionsAssociation = $class->getProperty('attractions'); + + self::assertNotNull($attractionsAssociation->getCache()); + self::assertEquals(Mapping\CacheUsage::READ_ONLY, $attractionsAssociation->getCache()->getUsage()); + self::assertEquals('doctrine_tests_models_cache_city__attractions', $attractionsAssociation->getCache()->getRegion()); } /** @@ -1014,11 +1118,11 @@ public function testSecondLevelCacheMapping() */ public function testSchemaDefinitionViaExplicitTableSchemaAnnotationProperty() { - /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */ - $metadata = $this->createClassMetadataFactory()->getMetadataFor(ExplicitSchemaAndTable::class); + $factory = $this->createClassMetadataFactory(); + $metadata = $factory->getMetadataFor(ExplicitSchemaAndTable::class); - $this->assertSame('explicit_schema', $metadata->getSchemaName()); - $this->assertSame('explicit_table', $metadata->getTableName()); + self::assertSame('explicit_schema', $metadata->getSchemaName()); + self::assertSame('explicit_table', $metadata->getTableName()); } /** @@ -1027,11 +1131,11 @@ public function testSchemaDefinitionViaExplicitTableSchemaAnnotationProperty() */ public function testSchemaDefinitionViaSchemaDefinedInTableNameInTableAnnotationProperty() { - /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */ - $metadata = $this->createClassMetadataFactory()->getMetadataFor(SchemaAndTableInTableName::class); + $factory = $this->createClassMetadataFactory(); + $metadata = $factory->getMetadataFor(SchemaAndTableInTableName::class); - $this->assertSame('implicit_schema', $metadata->getSchemaName()); - $this->assertSame('implicit_table', $metadata->getTableName()); + self::assertSame('implicit_schema', $metadata->getSchemaName()); + self::assertSame('implicit_table', $metadata->getTableName()); } /** @@ -1043,10 +1147,14 @@ public function testDiscriminatorColumnDefaultLength() if (strpos(get_class($this), 'PHPMappingDriver') !== false) { $this->markTestSkipped('PHP Mapping Drivers have no defaults.'); } + $class = $this->createClassMetadata(SingleTableEntityNoDiscriminatorColumnMapping::class); - $this->assertEquals(255, $class->discriminatorColumn['length']); + + self::assertEquals(255, $class->discriminatorColumn->getLength()); + $class = $this->createClassMetadata(SingleTableEntityIncompleteDiscriminatorColumnMapping::class); - $this->assertEquals(255, $class->discriminatorColumn['length']); + + self::assertEquals(255, $class->discriminatorColumn->getLength()); } /** @@ -1058,10 +1166,14 @@ public function testDiscriminatorColumnDefaultType() if (strpos(get_class($this), 'PHPMappingDriver') !== false) { $this->markTestSkipped('PHP Mapping Drivers have no defaults.'); } + $class = $this->createClassMetadata(SingleTableEntityNoDiscriminatorColumnMapping::class); - $this->assertEquals('string', $class->discriminatorColumn['type']); + + self::assertEquals('string', $class->discriminatorColumn->getTypeName()); + $class = $this->createClassMetadata(SingleTableEntityIncompleteDiscriminatorColumnMapping::class); - $this->assertEquals('string', $class->discriminatorColumn['type']); + + self::assertEquals('string', $class->discriminatorColumn->getTypeName()); } /** @@ -1073,301 +1185,301 @@ public function testDiscriminatorColumnDefaultName() if (strpos(get_class($this), 'PHPMappingDriver') !== false) { $this->markTestSkipped('PHP Mapping Drivers have no defaults.'); } + $class = $this->createClassMetadata(SingleTableEntityNoDiscriminatorColumnMapping::class); - $this->assertEquals('dtype', $class->discriminatorColumn['name']); + + self::assertEquals('dtype', $class->discriminatorColumn->getColumnName()); + $class = $this->createClassMetadata(SingleTableEntityIncompleteDiscriminatorColumnMapping::class); - $this->assertEquals('dtype', $class->discriminatorColumn['name']); - } + self::assertEquals('dtype', $class->discriminatorColumn->getColumnName()); + } } /** - * @Entity - * @HasLifecycleCallbacks - * @Table( + * @ORM\Entity + * @ORM\HasLifecycleCallbacks + * @ORM\Table( * name="cms_users", - * uniqueConstraints={@UniqueConstraint(name="search_idx", columns={"name", "user_email"}, options={"where": "name IS NOT NULL"})}, - * indexes={@Index(name="name_idx", columns={"name"}), @Index(name="0", columns={"user_email"})}, + * uniqueConstraints={@ORM\UniqueConstraint(name="search_idx", columns={"name", "user_email"})}, + * indexes={@ORM\Index(name="name_idx", columns={"name"}), @ORM\Index(columns={"user_email"})}, * options={"foo": "bar", "baz": {"key": "val"}} * ) - * @NamedQueries({@NamedQuery(name="all", query="SELECT u FROM __CLASS__ u")}) + * @ORM\NamedQueries({@ORM\NamedQuery(name="all", query="SELECT u FROM __CLASS__ u")}) */ class User { /** - * @Id - * @Column(type="integer", options={"foo": "bar", "unsigned": false}) - * @generatedValue(strategy="AUTO") - * @SequenceGenerator(sequenceName="tablename_seq", initialValue=1, allocationSize=100) + * @ORM\Id + * @ORM\Column(type="integer", options={"foo": "bar", "unsigned": false}) + * @ORM\GeneratedValue(strategy="AUTO") + * @ORM\SequenceGenerator(sequenceName="tablename_seq", allocationSize=100) **/ public $id; /** - * @Column(length=50, nullable=true, unique=true, options={"foo": "bar", "baz": {"key": "val"}, "fixed": false}) + * @ORM\Column(length=50, nullable=true, unique=true, options={"foo": "bar", "baz": {"key": "val"}, "fixed": false}) */ public $name; /** - * @Column(name="user_email", columnDefinition="CHAR(32) NOT NULL") + * @ORM\Column(name="user_email", columnDefinition="CHAR(32) NOT NULL") */ public $email; /** - * @OneToOne(targetEntity="Address", cascade={"remove"}, inversedBy="user") - * @JoinColumn(onDelete="CASCADE") + * @ORM\OneToOne(targetEntity="Address", cascade={"remove"}, inversedBy="user") + * @ORM\JoinColumn(onDelete="CASCADE") */ public $address; /** - * @OneToMany(targetEntity="Phonenumber", mappedBy="user", cascade={"persist"}, orphanRemoval=true) - * @OrderBy({"number"="ASC"}) + * @ORM\OneToMany(targetEntity="Phonenumber", mappedBy="user", cascade={"persist"}, orphanRemoval=true) + * @ORM\OrderBy({"number"="ASC"}) */ public $phonenumbers; /** - * @ManyToMany(targetEntity="Group", cascade={"all"}) - * @JoinTable(name="cms_user_groups", - * joinColumns={@JoinColumn(name="user_id", referencedColumnName="id", nullable=false, unique=false)}, - * inverseJoinColumns={@JoinColumn(name="group_id", referencedColumnName="id", columnDefinition="INT NULL")} + * @ORM\ManyToMany(targetEntity="Group", cascade={"all"}) + * @ORM\JoinTable(name="cms_user_groups", + * joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false, unique=false)}, + * inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id", columnDefinition="INT NULL")} * ) */ public $groups; /** - * @Column(type="integer") - * @Version + * @ORM\Column(type="integer") + * @ORM\Version */ public $version; /** - * @PrePersist + * @ORM\PrePersist */ public function doStuffOnPrePersist() { } /** - * @PrePersist + * @ORM\PrePersist */ public function doOtherStuffOnPrePersistToo() { } /** - * @PostPersist + * @ORM\PostPersist */ public function doStuffOnPostPersist() { } - public static function loadMetadata(ClassMetadataInfo $metadata) + public static function loadMetadata(ClassMetadata $metadata) { - $metadata->setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); - $metadata->setPrimaryTable( - [ - 'name' => 'cms_users', - 'options' => ['foo' => 'bar', 'baz' => ['key' => 'val']], - ] - ); - $metadata->setChangeTrackingPolicy(ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT); - $metadata->addLifecycleCallback('doStuffOnPrePersist', 'prePersist'); - $metadata->addLifecycleCallback('doOtherStuffOnPrePersistToo', 'prePersist'); - $metadata->addLifecycleCallback('doStuffOnPostPersist', 'postPersist'); - $metadata->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'id', - 'options' => ['foo' => 'bar', 'unsigned' => false], - ] - ); - $metadata->mapField( - [ - 'fieldName' => 'name', - 'type' => 'string', - 'length' => 50, - 'unique' => true, - 'nullable' => true, - 'columnName' => 'name', - 'options' => ['foo' => 'bar', 'baz' => ['key' => 'val'], 'fixed' => false], - ] - ); - $metadata->mapField( - [ - 'fieldName' => 'email', - 'type' => 'string', - 'columnName' => 'user_email', - 'columnDefinition' => 'CHAR(32) NOT NULL', - ] - ); - $mapping = ['fieldName' => 'version', 'type' => 'integer']; - $metadata->setVersionMapping($mapping); - $metadata->mapField($mapping); - $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); - $metadata->mapOneToOne( + $tableMetadata = new Mapping\TableMetadata(); + + $tableMetadata->setName('cms_users'); + $tableMetadata->addIndex( [ - 'fieldName' => 'address', - 'targetEntity' => Address::class, - 'cascade' => - [ - 0 => 'remove', - ], - 'mappedBy' => NULL, - 'inversedBy' => 'user', - 'joinColumns' => - [ - 0 => - [ - 'name' => 'address_id', - 'referencedColumnName' => 'id', - 'onDelete' => 'CASCADE', - ], - ], - 'orphanRemoval' => false, + 'name' => 'name_idx', + 'columns' => ['name'], + 'unique' => false, + 'options' => [], + 'flags' => [], ] ); - $metadata->mapOneToMany( + + $tableMetadata->addIndex( [ - 'fieldName' => 'phonenumbers', - 'targetEntity' => Phonenumber::class, - 'cascade' => - [ - 1 => 'persist', - ], - 'mappedBy' => 'user', - 'orphanRemoval' => true, - 'orderBy' => - [ - 'number' => 'ASC', - ], + 'name' => null, + 'columns' => ['user_email'], + 'unique' => false, + 'options' => [], + 'flags' => [], ] ); - $metadata->mapManyToMany( - [ - 'fieldName' => 'groups', - 'targetEntity' => Group::class, - 'cascade' => - [ - 0 => 'remove', - 1 => 'persist', - 2 => 'refresh', - 3 => 'merge', - 4 => 'detach', - ], - 'mappedBy' => NULL, - 'joinTable' => - [ - 'name' => 'cms_users_groups', - 'joinColumns' => - [ - 0 => - [ - 'name' => 'user_id', - 'referencedColumnName' => 'id', - 'unique' => false, - 'nullable' => false, - ], - ], - 'inverseJoinColumns' => - [ - 0 => + + $tableMetadata->addUniqueConstraint( [ - 'name' => 'group_id', - 'referencedColumnName' => 'id', - 'columnDefinition' => 'INT NULL', - ], - ], - ], - 'orderBy' => NULL, + 'name' => 'search_idx', + 'columns' => ['name', 'user_email'], + 'options' => [], + 'flags' => [], ] ); - $metadata->table['uniqueConstraints'] = [ - 'search_idx' => ['columns' => ['name', 'user_email'], 'options'=> ['where' => 'name IS NOT NULL']], - ]; - $metadata->table['indexes'] = [ - 'name_idx' => ['columns' => ['name']], 0 => ['columns' => ['user_email']] - ]; - $metadata->setSequenceGeneratorDefinition( + $tableMetadata->addOption('foo', 'bar'); + $tableMetadata->addOption('baz', ['key' => 'val']); + + $metadata->setTable($tableMetadata); + $metadata->setInheritanceType(Mapping\InheritanceType::NONE); + $metadata->setChangeTrackingPolicy(Mapping\ChangeTrackingPolicy::DEFERRED_IMPLICIT); + + $metadata->addLifecycleCallback('doStuffOnPrePersist', 'prePersist'); + $metadata->addLifecycleCallback('doOtherStuffOnPrePersistToo', 'prePersist'); + $metadata->addLifecycleCallback('doStuffOnPostPersist', 'postPersist'); + + $metadata->setGeneratorDefinition( [ - 'sequenceName' => 'tablename_seq', + 'sequenceName' => 'tablename_seq', 'allocationSize' => 100, - 'initialValue' => 1, ] ); + $metadata->addNamedQuery( [ 'name' => 'all', 'query' => 'SELECT u FROM __CLASS__ u' ] ); + + $fieldMetadata = new Mapping\FieldMetadata('id'); + $fieldMetadata->setType(Type::getType('integer')); + $fieldMetadata->setPrimaryKey(true); + $fieldMetadata->setOptions(['foo' => 'bar', 'unsigned' => false]); + + $metadata->addProperty($fieldMetadata); + + $fieldMetadata = new Mapping\FieldMetadata('name'); + $fieldMetadata->setType(Type::getType('string')); + $fieldMetadata->setLength(50); + $fieldMetadata->setNullable(true); + $fieldMetadata->setUnique(true); + $fieldMetadata->setOptions( + [ + 'foo' => 'bar', + 'baz' => [ + 'key' => 'val', + ], + 'fixed' => false, + ] + ); + + $metadata->addProperty($fieldMetadata); + + $fieldMetadata = new Mapping\FieldMetadata('email'); + + $fieldMetadata->setType(Type::getType('string')); + $fieldMetadata->setColumnName('user_email'); + $fieldMetadata->setColumnDefinition('CHAR(32) NOT NULL'); + + $metadata->addProperty($fieldMetadata); + + $fieldMetadata = new Mapping\VersionFieldMetadata('version'); + + $fieldMetadata->setType(Type::getType('integer')); + + $metadata->addProperty($fieldMetadata); + $metadata->setIdGeneratorType(Mapping\GeneratorType::AUTO); + + $joinColumns = []; + + $joinColumn = new Mapping\JoinColumnMetadata(); + + $joinColumn->setColumnName('address_id'); + $joinColumn->setReferencedColumnName('id'); + $joinColumn->setOnDelete('CASCADE'); + + $joinColumns[] = $joinColumn; + + $association = new Mapping\OneToOneAssociationMetadata('address'); + + $association->setJoinColumns($joinColumns); + $association->setTargetEntity(Address::class); + $association->setInversedBy('user'); + $association->setCascade(['remove']); + $association->setOrphanRemoval(false); + + $metadata->addProperty($association); + + $association = new Mapping\OneToManyAssociationMetadata('phonenumbers'); + + $association->setTargetEntity(Phonenumber::class); + $association->setMappedBy('user'); + $association->setCascade(['persist']); + $association->setOrderBy(['number' => 'ASC']); + $association->setOrphanRemoval(true); + + $metadata->addProperty($association); + + $joinTable = new Mapping\JoinTableMetadata(); + $joinTable->setName('cms_users_groups'); + + $joinColumn = new Mapping\JoinColumnMetadata(); + + $joinColumn->setColumnName('user_id'); + $joinColumn->setReferencedColumnName('id'); + $joinColumn->setNullable(false); + $joinColumn->setUnique(false); + + $joinTable->addJoinColumn($joinColumn); + + $joinColumn = new Mapping\JoinColumnMetadata(); + + $joinColumn->setColumnName('group_id'); + $joinColumn->setReferencedColumnName('id'); + $joinColumn->setColumnDefinition('INT NULL'); + + $joinTable->addInverseJoinColumn($joinColumn); + + $association = new Mapping\ManyToManyAssociationMetadata('groups'); + + $association->setJoinTable($joinTable); + $association->setTargetEntity(Group::class); + $association->setCascade(['remove', 'persist', 'refresh']); + + $metadata->addProperty($association); } } /** - * @Entity - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorMap({"cat" = "Cat", "dog" = "Dog"}) - * @DiscriminatorColumn(name="discr", length=32, type="string") + * @ORM\Entity + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorMap({"cat" = "Cat", "dog" = "Dog"}) + * @ORM\DiscriminatorColumn(name="discr", length=32, type="string") */ abstract class Animal { /** - * @Id @Column(type="string") @GeneratedValue(strategy="CUSTOM") - * @CustomIdGenerator(class="stdClass") + * @ORM\Id @ORM\Column(type="string") @ORM\GeneratedValue(strategy="CUSTOM") + * @ORM\CustomIdGenerator(class="stdClass") */ public $id; - - public static function loadMetadata(ClassMetadataInfo $metadata) - { - $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_CUSTOM); - $metadata->setCustomGeneratorDefinition(["class" => "stdClass"]); - } } -/** @Entity */ +/** @ORM\Entity */ class Cat extends Animal { - public static function loadMetadata(ClassMetadataInfo $metadata) - { - - } } -/** @Entity */ +/** @ORM\Entity */ class Dog extends Animal { - public static function loadMetadata(ClassMetadataInfo $metadata) - { - - } } - /** - * @Entity + * @ORM\Entity */ class DDC1170Entity { - /** * @param string $value */ - function __construct($value = null) + public function __construct($value = null) { $this->value = $value; } /** - * @Id - * @GeneratedValue(strategy="NONE") - * @Column(type="integer", columnDefinition = "INT unsigned NOT NULL") + * @ORM\Id + * @ORM\GeneratedValue(strategy="NONE") + * @ORM\Column(type="integer", columnDefinition = "INT unsigned NOT NULL") **/ private $id; /** - * @Column(columnDefinition = "VARCHAR(255) NOT NULL") + * @ORM\Column(columnDefinition = "VARCHAR(255) NOT NULL") */ private $value; @@ -1387,62 +1499,22 @@ public function getValue() return $this->value; } - public static function loadMetadata(ClassMetadataInfo $metadata) - { - $metadata->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'columnDefinition' => 'INT unsigned NOT NULL', - ] - ); - - $metadata->mapField( - [ - 'fieldName' => 'value', - 'columnDefinition' => 'VARCHAR(255) NOT NULL' - ] - ); - - $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); - } - } /** - * @Entity - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorMap({"ONE" = "DDC807SubClasse1", "TWO" = "DDC807SubClasse2"}) - * @DiscriminatorColumn(name = "dtype", columnDefinition="ENUM('ONE','TWO')") + * @ORM\Entity + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorMap({"ONE" = "DDC807SubClasse1", "TWO" = "DDC807SubClasse2"}) + * @ORM\DiscriminatorColumn(name = "dtype", columnDefinition="ENUM('ONE','TWO')") */ class DDC807Entity { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="NONE") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="NONE") **/ - public $id; - - public static function loadMetadata(ClassMetadataInfo $metadata) - { - $metadata->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - ] - ); - - $metadata->setDiscriminatorColumn( - [ - 'name' => "dtype", - 'type' => "string", - 'columnDefinition' => "ENUM('ONE','TWO')" - ] - ); - - $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); - } + public $id; } class DDC807SubClasse1 {} @@ -1453,46 +1525,21 @@ class Phonenumber {} class Group {} /** - * @Entity - * @Table(indexes={@Index(columns={"content"}, flags={"fulltext"}, options={"where": "content IS NOT NULL"})}) + * @ORM\Entity + * @ORM\Table(indexes={@ORM\Index(columns={"content"}, flags={"fulltext"}, options={"where": "content IS NOT NULL"})}) */ class Comment { /** - * @Column(type="text") + * @ORM\Column(type="text") */ private $content; - - public static function loadMetadata(ClassMetadataInfo $metadata) - { - $metadata->setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); - $metadata->setPrimaryTable( - [ - 'indexes' => [ - ['columns' => ['content'], 'flags' => ['fulltext'], 'options' => ['where' => 'content IS NOT NULL']] - ] - ] - ); - - $metadata->mapField( - [ - 'fieldName' => 'content', - 'type' => 'text', - 'scale' => 0, - 'length' => NULL, - 'unique' => false, - 'nullable' => false, - 'precision' => 0, - 'columnName' => 'content', - ] - ); - } } /** - * @Entity - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorMap({ + * @ORM\Entity + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorMap({ * "ONE" = "SingleTableEntityNoDiscriminatorColumnMappingSub1", * "TWO" = "SingleTableEntityNoDiscriminatorColumnMappingSub2" * }) @@ -1500,60 +1547,44 @@ public static function loadMetadata(ClassMetadataInfo $metadata) class SingleTableEntityNoDiscriminatorColumnMapping { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="NONE") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="NONE") */ public $id; - - public static function loadMetadata(ClassMetadataInfo $metadata) - { - $metadata->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - ] - ); - - $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); - } } +/** + * @ORM\Entity + */ class SingleTableEntityNoDiscriminatorColumnMappingSub1 extends SingleTableEntityNoDiscriminatorColumnMapping {} + +/** + * @ORM\Entity + */ class SingleTableEntityNoDiscriminatorColumnMappingSub2 extends SingleTableEntityNoDiscriminatorColumnMapping {} /** - * @Entity - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorMap({ + * @ORM\Entity + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorMap({ * "ONE" = "SingleTableEntityIncompleteDiscriminatorColumnMappingSub1", * "TWO" = "SingleTableEntityIncompleteDiscriminatorColumnMappingSub2" * }) - * @DiscriminatorColumn(name="dtype") + * @ORM\DiscriminatorColumn(name="dtype") */ class SingleTableEntityIncompleteDiscriminatorColumnMapping { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="NONE") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="NONE") */ public $id; - - public static function loadMetadata(ClassMetadataInfo $metadata) - { - $metadata->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - ] - ); - - $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); - } } class SingleTableEntityIncompleteDiscriminatorColumnMappingSub1 extends SingleTableEntityIncompleteDiscriminatorColumnMapping {} + class SingleTableEntityIncompleteDiscriminatorColumnMappingSub2 extends SingleTableEntityIncompleteDiscriminatorColumnMapping {} diff --git a/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php index b30ed703bc4..86bed2b9754 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php @@ -1,14 +1,13 @@ initializeReflection(new RuntimeReflectionService()); - $reader = new AnnotationReader(); - $annotationDriver = new AnnotationDriver($reader); + $cm = new ClassMetadata('stdClass', $this->metadataBuildingContext); + + $mappingDriver = $this->loadDriver(); - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $annotationDriver->loadMetadataForClass('stdClass', $cm); + $this->expectException(MappingException::class); + + $mappingDriver->loadMetadataForClass('stdClass', $cm, $this->metadataBuildingContext); } /** - * @expectedException Doctrine\ORM\Cache\CacheException + * @expectedException \Doctrine\ORM\Cache\CacheException * @expectedExceptionMessage Entity association field "Doctrine\Tests\ORM\Mapping\AnnotationSLC#foo" not configured as part of the second-level cache. */ public function testFailingSecondLevelCacheAssociation() { - $mappingDriver = $this->_loadDriver(); + $mappingDriver = $this->loadDriver(); - $class = new ClassMetadata(AnnotationSLC::class); - $mappingDriver->loadMetadataForClass(AnnotationSLC::class, $class); + $class = new ClassMetadata(AnnotationSLC::class, $this->metadataBuildingContext); + $mappingDriver->loadMetadataForClass(AnnotationSLC::class, $class, $this->metadataBuildingContext); } /** @@ -50,12 +49,17 @@ public function testFailingSecondLevelCacheAssociation() */ public function testColumnWithMissingTypeDefaultsToString() { - $cm = new ClassMetadata(ColumnWithoutType::class); - $cm->initializeReflection(new RuntimeReflectionService()); - $annotationDriver = $this->_loadDriver(); + $cm = new ClassMetadata(ColumnWithoutType::class, $this->metadataBuildingContext); + + $mappingDriver = $this->loadDriver(); - $annotationDriver->loadMetadataForClass(Mapping\InvalidColumn::class, $cm); - $this->assertEquals('string', $cm->fieldMappings['id']['type']); + $mappingDriver->loadMetadataForClass(ColumnWithoutType::class, $cm, $this->metadataBuildingContext); + + self::assertNotNull($cm->getProperty('id')); + + $idProperty = $cm->getProperty('id'); + + self::assertEquals('string', $idProperty->getTypeName()); } /** @@ -63,13 +67,13 @@ public function testColumnWithMissingTypeDefaultsToString() */ public function testGetAllClassNamesIsIdempotent() { - $annotationDriver = $this->_loadDriverForCMSModels(); + $annotationDriver = $this->loadDriverForCMSModels(); $original = $annotationDriver->getAllClassNames(); - $annotationDriver = $this->_loadDriverForCMSModels(); + $annotationDriver = $this->loadDriverForCMSModels(); $afterTestReset = $annotationDriver->getAllClassNames(); - $this->assertEquals($original, $afterTestReset); + self::assertEquals($original, $afterTestReset); } /** @@ -77,13 +81,13 @@ public function testGetAllClassNamesIsIdempotent() */ public function testGetAllClassNamesIsIdempotentEvenWithDifferentDriverInstances() { - $annotationDriver = $this->_loadDriverForCMSModels(); + $annotationDriver = $this->loadDriverForCMSModels(); $original = $annotationDriver->getAllClassNames(); - $annotationDriver = $this->_loadDriverForCMSModels(); + $annotationDriver = $this->loadDriverForCMSModels(); $afterTestReset = $annotationDriver->getAllClassNames(); - $this->assertEquals($original, $afterTestReset); + self::assertEquals($original, $afterTestReset); } /** @@ -91,12 +95,12 @@ public function testGetAllClassNamesIsIdempotentEvenWithDifferentDriverInstances */ public function testGetAllClassNamesReturnsAlreadyLoadedClassesIfAppropriate() { - $this->_ensureIsLoaded(CmsUser::class); + $this->ensureIsLoaded(CmsUser::class); - $annotationDriver = $this->_loadDriverForCMSModels(); + $annotationDriver = $this->loadDriverForCMSModels(); $classes = $annotationDriver->getAllClassNames(); - $this->assertContains(CmsUser::class, $classes); + self::assertContains(CmsUser::class, $classes); } /** @@ -104,27 +108,27 @@ public function testGetAllClassNamesReturnsAlreadyLoadedClassesIfAppropriate() */ public function testGetClassNamesReturnsOnlyTheAppropriateClasses() { - $this->_ensureIsLoaded(ECommerceCart::class); + $this->ensureIsLoaded(ECommerceCart::class); - $annotationDriver = $this->_loadDriverForCMSModels(); + $annotationDriver = $this->loadDriverForCMSModels(); $classes = $annotationDriver->getAllClassNames(); - $this->assertNotContains(ECommerceCart::class, $classes); + self::assertNotContains(ECommerceCart::class, $classes); } - protected function _loadDriverForCMSModels() + protected function loadDriverForCMSModels() { - $annotationDriver = $this->_loadDriver(); + $annotationDriver = $this->loadDriver(); $annotationDriver->addPaths([__DIR__ . '/../../Models/CMS/']); return $annotationDriver; } - protected function _loadDriver() + protected function loadDriver() { return $this->createAnnotationDriver(); } - protected function _ensureIsLoaded($entityClassName) + protected function ensureIsLoaded($entityClassName) { new $entityClassName; } @@ -136,19 +140,21 @@ protected function _ensureIsLoaded($entityClassName) */ public function testJoinTablesWithMappedSuperclassForAnnotationDriver() { - $annotationDriver = $this->_loadDriver(); + $annotationDriver = $this->loadDriver(); $annotationDriver->addPaths([__DIR__ . '/../../Models/DirectoryTree/']); - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); $em->getConfiguration()->setMetadataDriverImpl($annotationDriver); $factory = new ClassMetadataFactory(); $factory->setEntityManager($em); $classPage = $factory->getMetadataFor(File::class); - $this->assertEquals(File::class, $classPage->associationMappings['parentDirectory']['sourceEntity']); + self::assertArrayHasKey('parentDirectory', iterator_to_array($classPage->getDeclaredPropertiesIterator())); + self::assertEquals(File::class, $classPage->getProperty('parentDirectory')->getSourceEntity()); $classDirectory = $factory->getMetadataFor(Directory::class); - $this->assertEquals(Directory::class, $classDirectory->associationMappings['parentDirectory']['sourceEntity']); + self::assertArrayHasKey('parentDirectory', iterator_to_array($classDirectory->getDeclaredPropertiesIterator())); + self::assertEquals(Directory::class, $classDirectory->getProperty('parentDirectory')->getSourceEntity()); } /** @@ -156,9 +162,9 @@ public function testJoinTablesWithMappedSuperclassForAnnotationDriver() */ public function testInvalidMappedSuperClassWithManyToManyAssociation() { - $annotationDriver = $this->_loadDriver(); + $annotationDriver = $this->loadDriver(); - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); $em->getConfiguration()->setMetadataDriverImpl($annotationDriver); $factory = new ClassMetadataFactory(); $factory->setEntityManager($em); @@ -172,44 +178,23 @@ public function testInvalidMappedSuperClassWithManyToManyAssociation() $usingInvalidMsc = $factory->getMetadataFor(UsingInvalidMappedSuperClass::class); } - /** - * @group DDC-1050 - */ - public function testInvalidMappedSuperClassWithInheritanceInformation() - { - $annotationDriver = $this->_loadDriver(); - - $em = $this->_getTestEntityManager(); - $em->getConfiguration()->setMetadataDriverImpl($annotationDriver); - $factory = new ClassMetadataFactory(); - $factory->setEntityManager($em); - - $this->expectException(MappingException::class); - $this->expectExceptionMessage( - "It is not supported to define inheritance information on a mapped " . - "superclass '" . MappedSuperClassInheritence::class . "'." - ); - - $usingInvalidMsc = $factory->getMetadataFor(MappedSuperClassInheritence::class); - } - /** * @group DDC-1034 */ public function testInheritanceSkipsParentLifecycleCallbacks() { - $annotationDriver = $this->_loadDriver(); + $annotationDriver = $this->loadDriver(); - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); $em->getConfiguration()->setMetadataDriverImpl($annotationDriver); $factory = new ClassMetadataFactory(); $factory->setEntityManager($em); $cm = $factory->getMetadataFor(AnnotationChild::class); - $this->assertEquals(["postLoad" => ["postLoad"], "preUpdate" => ["preUpdate"]], $cm->lifecycleCallbacks); + self::assertEquals(["postLoad" => ["postLoad"], "preUpdate" => ["preUpdate"]], $cm->lifecycleCallbacks); $cm = $factory->getMetadataFor(AnnotationParent::class); - $this->assertEquals(["postLoad" => ["postLoad"], "preUpdate" => ["preUpdate"]], $cm->lifecycleCallbacks); + self::assertEquals(["postLoad" => ["postLoad"], "preUpdate" => ["preUpdate"]], $cm->lifecycleCallbacks); } /** @@ -217,9 +202,9 @@ public function testInheritanceSkipsParentLifecycleCallbacks() */ public function testMappedSuperclassInMiddleOfInheritanceHierarchy() { - $annotationDriver = $this->_loadDriver(); + $annotationDriver = $this->loadDriver(); - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); $em->getConfiguration()->setMetadataDriverImpl($annotationDriver); $factory = new ClassMetadataFactory(); @@ -230,89 +215,92 @@ public function testMappedSuperclassInMiddleOfInheritanceHierarchy() public function testInvalidFetchOptionThrowsException() { - $annotationDriver = $this->_loadDriver(); + $annotationDriver = $this->loadDriver(); - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); $em->getConfiguration()->setMetadataDriverImpl($annotationDriver); $factory = new ClassMetadataFactory(); $factory->setEntityManager($em); $this->expectException(AnnotationException::class); - $this->expectExceptionMessage('[Enum Error] Attribute "fetch" of @Doctrine\ORM\Mapping\OneToMany declared on property Doctrine\Tests\ORM\Mapping\InvalidFetchOption::$collection accept only [LAZY, EAGER, EXTRA_LAZY], but got eager.'); + $this->expectExceptionMessage('[Enum Error] Attribute "fetch" of @Doctrine\ORM\Annotation\OneToMany declared on property Doctrine\Tests\ORM\Mapping\InvalidFetchOption::$collection accept only [LAZY, EAGER, EXTRA_LAZY], but got eager.'); $factory->getMetadataFor(InvalidFetchOption::class); } public function testAttributeOverridesMappingWithTrait() { - $factory = $this->createClassMetadataFactory(); + $factory = $this->createClassMetadataFactory(); $metadataWithoutOverride = $factory->getMetadataFor(DDC1872ExampleEntityWithoutOverride::class); $metadataWithOverride = $factory->getMetadataFor(DDC1872ExampleEntityWithOverride::class); - $this->assertEquals('trait_foo', $metadataWithoutOverride->fieldMappings['foo']['columnName']); - $this->assertEquals('foo_overridden', $metadataWithOverride->fieldMappings['foo']['columnName']); - $this->assertArrayHasKey('example_trait_bar_id', $metadataWithoutOverride->associationMappings['bar']['joinColumnFieldNames']); - $this->assertArrayHasKey('example_entity_overridden_bar_id', $metadataWithOverride->associationMappings['bar']['joinColumnFieldNames']); - } -} + self::assertNotNull($metadataWithoutOverride->getProperty('foo')); + self::assertNotNull($metadataWithOverride->getProperty('foo')); -/** - * @Entity - */ -class ColumnWithoutType -{ - /** @Id @Column */ - public $id; + $fooPropertyWithoutOverride = $metadataWithoutOverride->getProperty('foo'); + $fooPropertyWithOverride = $metadataWithOverride->getProperty('foo'); + + self::assertEquals('trait_foo', $fooPropertyWithoutOverride->getColumnName()); + self::assertEquals('foo_overridden', $fooPropertyWithOverride->getColumnName()); + + $barPropertyWithoutOverride = $metadataWithoutOverride->getProperty('bar'); + $barPropertyWithOverride = $metadataWithOverride->getProperty('bar'); + + $barPropertyWithoutOverrideFirstJoinColumn = $barPropertyWithoutOverride->getJoinColumns()[0]; + $barPropertyWithOverrideFirstJoinColumn = $barPropertyWithOverride->getJoinColumns()[0]; + + self::assertEquals('example_trait_bar_id', $barPropertyWithoutOverrideFirstJoinColumn->getColumnName()); + self::assertEquals('example_entity_overridden_bar_id', $barPropertyWithOverrideFirstJoinColumn->getColumnName()); + } } /** - * @MappedSuperclass + * @ORM\MappedSuperclass */ class InvalidMappedSuperClass { /** - * @ManyToMany(targetEntity="Doctrine\Tests\Models\CMS\CmsUser", mappedBy="invalid") + * @ORM\ManyToMany(targetEntity="Doctrine\Tests\Models\CMS\CmsUser", mappedBy="invalid") */ private $users; } /** - * @Entity + * @ORM\Entity */ class UsingInvalidMappedSuperClass extends InvalidMappedSuperClass { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ private $id; } /** - * @MappedSuperclass - * @InheritanceType("JOINED") - * @DiscriminatorMap({"test" = "ColumnWithoutType"}) + * @ORM\Entity */ -class MappedSuperClassInheritence +class ColumnWithoutType { - + /** @ORM\Id @ORM\Column */ + public $id; } /** - * @Entity - * @InheritanceType("JOINED") - * @DiscriminatorMap({"parent" = "AnnotationParent", "child" = "AnnotationChild"}) - * @HasLifecycleCallbacks + * @ORM\Entity + * @ORM\InheritanceType("JOINED") + * @ORM\DiscriminatorMap({"parent" = "AnnotationParent", "child" = "AnnotationChild"}) + * @ORM\HasLifecycleCallbacks */ class AnnotationParent { /** - * @Id @Column(type="integer") @GeneratedValue + * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ private $id; /** - * @PostLoad + * @ORM\PostLoad */ public function postLoad() { @@ -320,7 +308,7 @@ public function postLoad() } /** - * @PreUpdate + * @ORM\PreUpdate */ public function preUpdate() { @@ -329,8 +317,8 @@ public function preUpdate() } /** - * @Entity - * @HasLifecycleCallbacks + * @ORM\Entity + * @ORM\HasLifecycleCallbacks */ class AnnotationChild extends AnnotationParent { @@ -338,66 +326,66 @@ class AnnotationChild extends AnnotationParent } /** - * @Entity - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorMap({"s"="SuperEntity", "c"="ChildEntity"}) + * @ORM\Entity + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorMap({"s"="SuperEntity", "c"="ChildEntity"}) */ class SuperEntity { - /** @Id @Column(type="string") */ + /** @ORM\Id @ORM\Column(type="string") */ private $id; } /** - * @MappedSuperclass + * @ORM\MappedSuperclass */ class MiddleMappedSuperclass extends SuperEntity { - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ private $name; } /** - * @Entity + * @ORM\Entity */ class ChildEntity extends MiddleMappedSuperclass { /** - * @Column(type="string") + * @ORM\Column(type="string") */ private $text; } /** - * @Entity + * @ORM\Entity */ class InvalidFetchOption { /** - * @OneToMany(targetEntity="Doctrine\Tests\Models\CMS\CmsUser", fetch="eager") + * @ORM\OneToMany(targetEntity="Doctrine\Tests\Models\CMS\CmsUser", fetch="eager") */ private $collection; } /** - * @Entity - * @Cache + * @ORM\Entity + * @ORM\Cache */ class AnnotationSLC { /** - * @Id - * @ManyToOne(targetEntity="AnnotationSLCFoo") + * @ORM\Id + * @ORM\ManyToOne(targetEntity="AnnotationSLCFoo") */ public $foo; } /** - * @Entity + * @ORM\Entity */ class AnnotationSLCFoo { /** - * @Column(type="string") + * @ORM\Column(type="string") */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Mapping/AnsiQuoteStrategyTest.php b/tests/Doctrine/Tests/ORM/Mapping/AnsiQuoteStrategyTest.php deleted file mode 100644 index a0b422c0f76..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/AnsiQuoteStrategyTest.php +++ /dev/null @@ -1,165 +0,0 @@ -_getTestEntityManager(); - $this->platform = $em->getConnection()->getDatabasePlatform(); - $this->strategy = new AnsiQuoteStrategy(); - } - - /** - * @param string $className - * @return \Doctrine\ORM\Mapping\ClassMetadata - */ - private function createClassMetadata($className) - { - $class = new ClassMetadata($className); - $class->initializeReflection(new RuntimeReflectionService()); - - return $class; - } - - public function testGetColumnName() - { - $class = $this->createClassMetadata(CmsUser::class); - $class->mapField(['fieldName' => 'name', 'columnName' => 'name']); - $class->mapField(['fieldName' => 'id', 'columnName' => 'id', 'id' => true]); - - $this->assertEquals('id' ,$this->strategy->getColumnName('id', $class, $this->platform)); - $this->assertEquals('name' ,$this->strategy->getColumnName('name', $class, $this->platform)); - } - - public function testGetTableName() - { - $class = $this->createClassMetadata(CmsUser::class); - - $class->setPrimaryTable(['name'=>'cms_user']); - $this->assertEquals('cms_user' ,$this->strategy->getTableName($class, $this->platform)); - } - - public function testJoinTableName() - { - $class = $this->createClassMetadata(CmsAddress::class); - - $class->mapManyToMany( - [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser', - 'inversedBy' => 'users', - 'joinTable' => [ - 'name' => 'cmsaddress_cmsuser' - ] - ] - ); - - $this->assertEquals('cmsaddress_cmsuser', $this->strategy->getJoinTableName($class->associationMappings['user'], $class, $this->platform)); - - } - - public function testIdentifierColumnNames() - { - $class = $this->createClassMetadata(CmsAddress::class); - - $class->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'columnName' => 'id', - ] - ); - - $this->assertEquals(['id'], $this->strategy->getIdentifierColumnNames($class, $this->platform)); - } - - - public function testColumnAlias() - { - $this->assertEquals('columnName_1', $this->strategy->getColumnAlias('columnName', 1, $this->platform)); - } - - public function testJoinColumnName() - { - $class = $this->createClassMetadata(DDC117ArticleDetails::class); - - $class->mapOneToOne( - [ - 'id' => true, - 'fieldName' => 'article', - 'targetEntity' => DDC117Article::class, - 'joinColumns' => [ - [ - 'name' => 'article' - ] - ], - ] - ); - - $joinColumn = $class->associationMappings['article']['joinColumns'][0]; - $this->assertEquals('article',$this->strategy->getJoinColumnName($joinColumn, $class, $this->platform)); - } - - public function testReferencedJoinColumnName() - { - $cm = $this->createClassMetadata(DDC117ArticleDetails::class); - - $cm->mapOneToOne( - [ - 'id' => true, - 'fieldName' => 'article', - 'targetEntity' => DDC117Article::class, - 'joinColumns' => [ - [ - 'name' => 'article' - ] - ], - ] - ); - - $joinColumn = $cm->associationMappings['article']['joinColumns'][0]; - $this->assertEquals('id',$this->strategy->getReferencedJoinColumnName($joinColumn, $cm, $this->platform)); - } - - public function testGetSequenceName() - { - $class = $this->createClassMetadata(CmsUser::class); - $definition = [ - 'sequenceName' => 'user_id_seq', - 'allocationSize' => 1, - 'initialValue' => 2 - ]; - - $class->setSequenceGeneratorDefinition($definition); - - $this->assertEquals('user_id_seq',$this->strategy->getSequenceName($definition, $class, $this->platform)); - } -} diff --git a/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php b/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php index 292954506a4..da6a2f55aae 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php @@ -1,13 +1,17 @@ cmf = new ClassMetadataFactory(); - $this->cmf->setEntityManager($this->_getTestEntityManager()); + $this->cmf->setEntityManager($this->getTestEntityManager()); } public function testGetMetadataForTransientClassThrowsException() @@ -41,29 +45,32 @@ public function testGetMetadataForSubclassWithTransientBaseClass() { $class = $this->cmf->getMetadataFor(EntitySubClass::class); - $this->assertEmpty($class->subClasses); - $this->assertEmpty($class->parentClasses); - $this->assertArrayHasKey('id', $class->fieldMappings); - $this->assertArrayHasKey('name', $class->fieldMappings); + self::assertEmpty($class->getSubClasses()); + self::assertCount(0, $class->getAncestorsIterator()); + + self::assertNotNull($class->getProperty('id')); + self::assertNotNull($class->getProperty('name')); } public function testGetMetadataForSubclassWithMappedSuperclass() { $class = $this->cmf->getMetadataFor(EntitySubClass2::class); - $this->assertEmpty($class->subClasses); - $this->assertEmpty($class->parentClasses); + self::assertEmpty($class->getSubClasses()); + self::assertCount(0, $class->getAncestorsIterator()); + + self::assertNotNull($class->getProperty('id')); + self::assertNotNull($class->getProperty('name')); + self::assertNotNull($class->getProperty('mapped1')); + self::assertNotNull($class->getProperty('mapped2')); - $this->assertArrayHasKey('mapped1', $class->fieldMappings); - $this->assertArrayHasKey('mapped2', $class->fieldMappings); - $this->assertArrayHasKey('id', $class->fieldMappings); - $this->assertArrayHasKey('name', $class->fieldMappings); + self::assertTrue($class->isInheritedProperty('mapped1')); + self::assertTrue($class->isInheritedProperty('mapped2')); - $this->assertArrayNotHasKey('inherited', $class->fieldMappings['mapped1']); - $this->assertArrayNotHasKey('inherited', $class->fieldMappings['mapped2']); - $this->assertArrayNotHasKey('transient', $class->fieldMappings); + self::assertNotNull($class->getProperty('transient')); + self::assertInstanceOf(TransientMetadata::class, $class->getProperty('transient')); - $this->assertArrayHasKey('mappedRelated1', $class->associationMappings); + self::assertArrayHasKey('mappedRelated1', iterator_to_array($class->getDeclaredPropertiesIterator())); } /** @@ -73,42 +80,28 @@ public function testGetMetadataForSubclassWithMappedSuperclassWithRepository() { $class = $this->cmf->getMetadataFor(DDC869CreditCardPayment::class); - $this->assertArrayHasKey('id', $class->fieldMappings); - $this->assertArrayHasKey('value', $class->fieldMappings); - $this->assertArrayHasKey('creditCardNumber', $class->fieldMappings); - $this->assertEquals($class->customRepositoryClassName, DDC869PaymentRepository::class); + self::assertEquals($class->getCustomRepositoryClassName(), DDC869PaymentRepository::class); + + self::assertNotNull($class->getProperty('id')); + self::assertNotNull($class->getProperty('value')); + self::assertNotNull($class->getProperty('creditCardNumber')); $class = $this->cmf->getMetadataFor(DDC869ChequePayment::class); - $this->assertArrayHasKey('id', $class->fieldMappings); - $this->assertArrayHasKey('value', $class->fieldMappings); - $this->assertArrayHasKey('serialNumber', $class->fieldMappings); - $this->assertEquals($class->customRepositoryClassName, DDC869PaymentRepository::class); + self::assertEquals($class->getCustomRepositoryClassName(), DDC869PaymentRepository::class); + self::assertNotNull($class->getProperty('id')); + self::assertNotNull($class->getProperty('value')); + self::assertNotNull($class->getProperty('serialNumber')); // override repositoryClass $class = $this->cmf->getMetadataFor(SubclassWithRepository::class); - $this->assertArrayHasKey('id', $class->fieldMappings); - $this->assertArrayHasKey('value', $class->fieldMappings); - $this->assertEquals($class->customRepositoryClassName, EntityRepository::class); - } - - /** - * @group DDC-388 - */ - public function testSerializationWithPrivateFieldsFromMappedSuperclass() - { - - $class = $this->cmf->getMetadataFor(EntitySubClass2::class); - - $class2 = unserialize(serialize($class)); - $class2->wakeupReflection(new RuntimeReflectionService); + self::assertEquals($class->getCustomRepositoryClassName(), EntityRepository::class); - $this->assertArrayHasKey('mapped1', $class2->reflFields); - $this->assertArrayHasKey('mapped2', $class2->reflFields); - $this->assertArrayHasKey('mappedRelated1', $class2->reflFields); + self::assertNotNull($class->getProperty('id')); + self::assertNotNull($class->getProperty('value')); } /** @@ -118,9 +111,9 @@ public function testUnmappedSuperclassInHierarchy() { $class = $this->cmf->getMetadataFor(HierarchyD::class); - $this->assertArrayHasKey('id', $class->fieldMappings); - $this->assertArrayHasKey('a', $class->fieldMappings); - $this->assertArrayHasKey('d', $class->fieldMappings); + self::assertNotNull($class->getProperty('id')); + self::assertNotNull($class->getProperty('a')); + self::assertNotNull($class->getProperty('d')); } /** @@ -147,7 +140,7 @@ public function testMappedSuperclassWithId() { $class = $this->cmf->getMetadataFor(SuperclassEntity::class); - $this->assertArrayHasKey('id', $class->fieldMappings); + self::assertNotNull($class->getProperty('id')); } /** @@ -156,13 +149,13 @@ public function testMappedSuperclassWithId() */ public function testGeneratedValueFromMappedSuperclass() { + /* @var ClassMetadata $class */ $class = $this->cmf->getMetadataFor(SuperclassEntity::class); - /* @var $class ClassMetadataInfo */ - $this->assertInstanceOf(SequenceGenerator::class, $class->idGenerator); - $this->assertEquals( - ['allocationSize' => 1, 'initialValue' => 10, 'sequenceName' => 'foo'], - $class->sequenceGeneratorDefinition + self::assertSame(GeneratorType::SEQUENCE, $class->getProperty('id')->getValueGenerator()->getType()); + self::assertEquals( + ['allocationSize' => 1, 'sequenceName' => 'foo'], + $class->getProperty('id')->getValueGenerator()->getDefinition() ); } @@ -172,13 +165,13 @@ public function testGeneratedValueFromMappedSuperclass() */ public function testSequenceDefinitionInHierarchyWithSandwichMappedSuperclass() { + /* @var ClassMetadata $class */ $class = $this->cmf->getMetadataFor(HierarchyD::class); - /* @var $class ClassMetadataInfo */ - $this->assertInstanceOf(SequenceGenerator::class, $class->idGenerator); - $this->assertEquals( - ['allocationSize' => 1, 'initialValue' => 10, 'sequenceName' => 'foo'], - $class->sequenceGeneratorDefinition + self::assertSame(GeneratorType::SEQUENCE, $class->getProperty('id')->getValueGenerator()->getType()); + self::assertEquals( + ['allocationSize' => 1, 'sequenceName' => 'foo'], + $class->getProperty('id')->getValueGenerator()->getDefinition() ); } @@ -188,31 +181,15 @@ public function testSequenceDefinitionInHierarchyWithSandwichMappedSuperclass() */ public function testMultipleMappedSuperclasses() { + /* @var ClassMetadata $class */ $class = $this->cmf->getMetadataFor(MediumSuperclassEntity::class); - /* @var $class ClassMetadataInfo */ - $this->assertInstanceOf(SequenceGenerator::class, $class->idGenerator); - $this->assertEquals( - ['allocationSize' => 1, 'initialValue' => 10, 'sequenceName' => 'foo'], - $class->sequenceGeneratorDefinition + self::assertSame(GeneratorType::SEQUENCE, $class->getProperty('id')->getValueGenerator()->getType()); + self::assertEquals( + ['allocationSize' => 1, 'sequenceName' => 'foo'], + $class->getProperty('id')->getValueGenerator()->getDefinition() ); } - - /** - * Ensure indexes are inherited from the mapped superclass. - * - * @group DDC-3418 - */ - public function testMappedSuperclassIndex() - { - $class = $this->cmf->getMetadataFor(EntityIndexSubClass::class); - /* @var $class ClassMetadataInfo */ - - $this->assertArrayHasKey('mapped1', $class->fieldMappings); - $this->assertArrayHasKey('IDX_NAME_INDEX', $class->table['uniqueConstraints']); - $this->assertArrayHasKey('IDX_MAPPED1_INDEX', $class->table['uniqueConstraints']); - $this->assertArrayHasKey('IDX_MAPPED2_INDEX', $class->table['indexes']); - } } class TransientBaseClass { @@ -220,66 +197,62 @@ class TransientBaseClass { private $transient2; } -/** @Entity */ +/** @ORM\Entity */ class EntitySubClass extends TransientBaseClass { - /** @Id @Column(type="integer") */ + /** @ORM\Id @ORM\Column(type="integer") */ private $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ private $name; } -/** @MappedSuperclass */ +/** @ORM\MappedSuperclass */ class MappedSuperclassBase { - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ private $mapped1; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ private $mapped2; /** - * @OneToOne(targetEntity="MappedSuperclassRelated1") - * @JoinColumn(name="related1_id", referencedColumnName="id") + * @ORM\OneToOne(targetEntity="MappedSuperclassRelated1") + * @ORM\JoinColumn(name="related1_id", referencedColumnName="id") */ private $mappedRelated1; private $transient; } class MappedSuperclassRelated1 {} -/** @Entity */ +/** @ORM\Entity */ class EntitySubClass2 extends MappedSuperclassBase { - /** @Id @Column(type="integer") */ + /** @ORM\Id @ORM\Column(type="integer") */ private $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ private $name; } /** - * @MappedSuperclass - * @Table( - * uniqueConstraints={@UniqueConstraint(name="IDX_MAPPED1_INDEX",columns={"mapped1"})}, - * indexes={@Index(name="IDX_MAPPED2_INDEX", columns={"mapped2"})} - * ) + * @ORM\MappedSuperclass */ class MappedSuperclassBaseIndex { - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ private $mapped1; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ private $mapped2; } -/** @Entity @Table(uniqueConstraints={@UniqueConstraint(name="IDX_NAME_INDEX",columns={"name"})}) */ +/** @ORM\Entity @ORM\Table(uniqueConstraints={@ORM\UniqueConstraint(name="IDX_NAME_INDEX",columns={"name"})}) */ class EntityIndexSubClass extends MappedSuperclassBaseIndex { - /** @Id @Column(type="integer") */ + /** @ORM\Id @ORM\Column(type="integer") */ private $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ private $name; } /** - * @Entity - * @InheritanceType("SINGLE_TABLE") - * @DiscriminatorColumn(name="type", type="string", length=20) - * @DiscriminatorMap({ + * @ORM\Entity + * @ORM\InheritanceType("SINGLE_TABLE") + * @ORM\DiscriminatorColumn(name="type", type="string", length=20) + * @ORM\DiscriminatorMap({ * "c" = "HierarchyC", * "d" = "HierarchyD", * "e" = "HierarchyE" @@ -288,74 +261,74 @@ class EntityIndexSubClass extends MappedSuperclassBaseIndex abstract class HierarchyBase { /** - * @Column(type="integer") @Id @GeneratedValue(strategy="SEQUENCE") - * @SequenceGenerator(sequenceName="foo", initialValue=10) + * @ORM\Column(type="integer") @ORM\Id @ORM\GeneratedValue(strategy="SEQUENCE") + * @ORM\SequenceGenerator(sequenceName="foo") * @var int */ public $id; } -/** @MappedSuperclass */ +/** @ORM\MappedSuperclass */ abstract class HierarchyASuperclass extends HierarchyBase { - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $a; } -/** @Entity */ +/** @ORM\Entity */ class HierarchyBEntity extends HierarchyBase { - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $b; } -/** @Entity */ +/** @ORM\Entity */ class HierarchyC extends HierarchyBase { - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $c; } -/** @Entity */ +/** @ORM\Entity */ class HierarchyD extends HierarchyASuperclass { - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $d; } -/** @Entity */ +/** @ORM\Entity */ class HierarchyE extends HierarchyBEntity { - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $e; } -/** @Entity */ +/** @ORM\Entity */ class SuperclassEntity extends SuperclassBase { } -/** @MappedSuperclass */ +/** @ORM\MappedSuperclass */ abstract class SuperclassBase { /** - * @Column(type="integer") @Id @GeneratedValue(strategy="SEQUENCE") - * @SequenceGenerator(sequenceName="foo", initialValue=10) + * @ORM\Column(type="integer") @ORM\Id @ORM\GeneratedValue(strategy="SEQUENCE") + * @ORM\SequenceGenerator(sequenceName="foo") */ public $id; } -/** @MappedSuperclass */ +/** @ORM\MappedSuperclass */ abstract class MediumSuperclassBase extends SuperclassBase { } -/** @Entity */ +/** @ORM\Entity */ class MediumSuperclassEntity extends MediumSuperclassBase { } -/** @Entity(repositoryClass = "Doctrine\ORM\EntityRepository") */ +/** @ORM\Entity(repositoryClass = "Doctrine\ORM\EntityRepository") */ class SubclassWithRepository extends DDC869Payment { } diff --git a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataBuilderTest.php b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataBuilderTest.php deleted file mode 100644 index 657ad65b474..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataBuilderTest.php +++ /dev/null @@ -1,848 +0,0 @@ -cm = new ClassMetadata(CmsUser::class); - $this->cm->initializeReflection(new RuntimeReflectionService()); - $this->builder = new ClassMetadataBuilder($this->cm); - } - - public function testSetMappedSuperClass() - { - $this->assertIsFluent($this->builder->setMappedSuperClass()); - $this->assertTrue($this->cm->isMappedSuperclass); - $this->assertFalse($this->cm->isEmbeddedClass); - } - - public function testSetEmbedable() - { - $this->assertIsFluent($this->builder->setEmbeddable()); - $this->assertTrue($this->cm->isEmbeddedClass); - $this->assertFalse($this->cm->isMappedSuperclass); - } - - public function testAddEmbeddedWithOnlyRequiredParams() - { - $this->assertIsFluent($this->builder->addEmbedded('name', Name::class)); - - $this->assertEquals( - [ - 'name' => [ - 'class' => Name::class, - 'columnPrefix' => null, - 'declaredField' => null, - 'originalField' => null, - ] - ], $this->cm->embeddedClasses); - } - - public function testAddEmbeddedWithPrefix() - { - $this->assertIsFluent( - $this->builder->addEmbedded( - 'name', - Name::class, - 'nm_' - ) - ); - - $this->assertEquals( - [ - 'name' => [ - 'class' => Name::class, - 'columnPrefix' => 'nm_', - 'declaredField' => null, - 'originalField' => null, - ] - ], $this->cm->embeddedClasses); - } - - public function testCreateEmbeddedWithoutExtraParams() - { - $embeddedBuilder = ($this->builder->createEmbedded('name', Name::class)); - $this->assertInstanceOf(EmbeddedBuilder::class, $embeddedBuilder); - - $this->assertFalse(isset($this->cm->embeddedClasses['name'])); - - $this->assertIsFluent($embeddedBuilder->build()); - $this->assertEquals( - [ - 'class' => Name::class, - 'columnPrefix' => null, - 'declaredField' => null, - 'originalField' => null - ], - $this->cm->embeddedClasses['name'] - ); - } - - public function testCreateEmbeddedWithColumnPrefix() - { - $embeddedBuilder = ($this->builder->createEmbedded('name', Name::class)); - - $this->assertEquals($embeddedBuilder, $embeddedBuilder->setColumnPrefix('nm_')); - - $this->assertIsFluent($embeddedBuilder->build()); - - $this->assertEquals( - [ - 'class' => Name::class, - 'columnPrefix' => 'nm_', - 'declaredField' => null, - 'originalField' => null - ], - $this->cm->embeddedClasses['name'] - ); - } - - public function testSetCustomRepositoryClass() - { - $this->assertIsFluent($this->builder->setCustomRepositoryClass(CmsGroup::class)); - $this->assertEquals(CmsGroup::class, $this->cm->customRepositoryClassName); - } - - public function testSetReadOnly() - { - $this->assertIsFluent($this->builder->setReadOnly()); - $this->assertTrue($this->cm->isReadOnly); - } - - public function testSetTable() - { - $this->assertIsFluent($this->builder->setTable('users')); - $this->assertEquals('users', $this->cm->table['name']); - } - - public function testAddIndex() - { - $this->assertIsFluent($this->builder->addIndex(['username', 'name'], 'users_idx')); - $this->assertEquals(['users_idx' => ['columns' => ['username', 'name']]], $this->cm->table['indexes']); - } - - public function testAddUniqueConstraint() - { - $this->assertIsFluent($this->builder->addUniqueConstraint(['username', 'name'], 'users_idx')); - $this->assertEquals(['users_idx' => ['columns' => ['username', 'name']]], $this->cm->table['uniqueConstraints']); - } - - public function testSetPrimaryTableRelated() - { - $this->builder->addUniqueConstraint(['username', 'name'], 'users_idx'); - $this->builder->addIndex(['username', 'name'], 'users_idx'); - $this->builder->setTable('users'); - - $this->assertEquals( - [ - 'name' => 'users', - 'indexes' => ['users_idx' => ['columns' => ['username', 'name']]], - 'uniqueConstraints' => ['users_idx' => ['columns' => ['username', 'name']]], - ], - $this->cm->table - ); - } - - public function testSetInheritanceJoined() - { - $this->assertIsFluent($this->builder->setJoinedTableInheritance()); - $this->assertEquals(ClassMetadata::INHERITANCE_TYPE_JOINED, $this->cm->inheritanceType); - } - - public function testSetInheritanceSingleTable() - { - $this->assertIsFluent($this->builder->setSingleTableInheritance()); - $this->assertEquals(ClassMetadata::INHERITANCE_TYPE_SINGLE_TABLE, $this->cm->inheritanceType); - } - - public function testSetDiscriminatorColumn() - { - $this->assertIsFluent($this->builder->setDiscriminatorColumn('discr', 'string', '124')); - $this->assertEquals(['fieldName' => 'discr', 'name' => 'discr', 'type' => 'string', 'length' => '124'], $this->cm->discriminatorColumn); - } - - public function testAddDiscriminatorMapClass() - { - $this->assertIsFluent($this->builder->addDiscriminatorMapClass('test', CmsUser::class)); - $this->assertIsFluent($this->builder->addDiscriminatorMapClass('test2', CmsGroup::class)); - - $this->assertEquals( - ['test' => CmsUser::class, 'test2' => CmsGroup::class], $this->cm->discriminatorMap); - $this->assertEquals('test', $this->cm->discriminatorValue); - } - - public function testChangeTrackingPolicyExplicit() - { - $this->assertIsFluent($this->builder->setChangeTrackingPolicyDeferredExplicit()); - $this->assertEquals(ClassMetadata::CHANGETRACKING_DEFERRED_EXPLICIT, $this->cm->changeTrackingPolicy); - } - - public function testChangeTrackingPolicyNotify() - { - $this->assertIsFluent($this->builder->setChangeTrackingPolicyNotify()); - $this->assertEquals(ClassMetadata::CHANGETRACKING_NOTIFY, $this->cm->changeTrackingPolicy); - } - - public function testAddField() - { - $this->assertIsFluent($this->builder->addField('name', 'string')); - $this->assertEquals(['columnName' => 'name', 'fieldName' => 'name', 'type' => 'string'], $this->cm->fieldMappings['name']); - } - - public function testCreateField() - { - $fieldBuilder = ($this->builder->createField('name', 'string')); - $this->assertInstanceOf(FieldBuilder::class, $fieldBuilder); - - $this->assertFalse(isset($this->cm->fieldMappings['name'])); - $this->assertIsFluent($fieldBuilder->build()); - $this->assertEquals(['columnName' => 'name', 'fieldName' => 'name', 'type' => 'string'], $this->cm->fieldMappings['name']); - } - - public function testCreateVersionedField() - { - $this->builder->createField('name', 'integer')->columnName('username')->length(124)->nullable()->columnDefinition('foobar')->unique()->isVersionField()->build(); - $this->assertEquals( - [ - 'columnDefinition' => 'foobar', - 'columnName' => 'username', - 'default' => 1, - 'fieldName' => 'name', - 'length' => 124, - 'type' => 'integer', - 'nullable' => true, - 'unique' => true, - ], $this->cm->fieldMappings['name']); - } - - public function testCreatePrimaryField() - { - $this->builder->createField('id', 'integer')->makePrimaryKey()->generatedValue()->build(); - - $this->assertEquals(['id'], $this->cm->identifier); - $this->assertEquals(['columnName' => 'id', 'fieldName' => 'id', 'id' => true, 'type' => 'integer'], $this->cm->fieldMappings['id']); - } - - public function testCreateUnsignedOptionField() - { - $this->builder->createField('state', 'integer')->option('unsigned', true)->build(); - - $this->assertEquals( - ['fieldName' => 'state', 'type' => 'integer', 'options' => ['unsigned' => true], 'columnName' => 'state'], $this->cm->fieldMappings['state']); - } - - public function testAddLifecycleEvent() - { - $this->builder->addLifecycleEvent('getStatus', 'postLoad'); - - $this->assertEquals(['postLoad' => ['getStatus']], $this->cm->lifecycleCallbacks); - } - - public function testCreateManyToOne() - { - $this->assertIsFluent( - $this->builder->createManyToOne('groups', CmsGroup::class) - ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') - ->cascadeAll() - ->fetchExtraLazy() - ->build() - ); - - $this->assertEquals( - [ - 'groups' => [ - 'fieldName' => 'groups', - 'targetEntity' => CmsGroup::class, - 'cascade' => [ - 0 => 'remove', - 1 => 'persist', - 2 => 'refresh', - 3 => 'merge', - 4 => 'detach', - ], - 'fetch' => 4, - 'joinColumns' => [ - 0 => - [ - 'name' => 'group_id', - 'referencedColumnName' => 'id', - 'nullable' => true, - 'unique' => false, - 'onDelete' => 'CASCADE', - 'columnDefinition' => NULL, - ], - ], - 'type' => 2, - 'mappedBy' => NULL, - 'inversedBy' => NULL, - 'isOwningSide' => true, - 'sourceEntity' => CmsUser::class, - 'isCascadeRemove' => true, - 'isCascadePersist' => true, - 'isCascadeRefresh' => true, - 'isCascadeMerge' => true, - 'isCascadeDetach' => true, - 'sourceToTargetKeyColumns' => - [ - 'group_id' => 'id', - ], - 'joinColumnFieldNames' => - [ - 'group_id' => 'group_id', - ], - 'targetToSourceKeyColumns' => - [ - 'id' => 'group_id', - ], - 'orphanRemoval' => false, - ], - ], $this->cm->associationMappings); - } - - public function testCreateManyToOneWithIdentity() - { - $this->assertIsFluent( - $this - ->builder - ->createManyToOne('groups', CmsGroup::class) - ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') - ->cascadeAll() - ->fetchExtraLazy() - ->makePrimaryKey() - ->build() - ); - - $this->assertEquals( - [ - 'groups' => [ - 'fieldName' => 'groups', - 'targetEntity' => CmsGroup::class, - 'cascade' => [ - 0 => 'remove', - 1 => 'persist', - 2 => 'refresh', - 3 => 'merge', - 4 => 'detach', - ], - 'fetch' => 4, - 'joinColumns' => [ - 0 => - [ - 'name' => 'group_id', - 'referencedColumnName' => 'id', - 'nullable' => true, - 'unique' => false, - 'onDelete' => 'CASCADE', - 'columnDefinition' => NULL, - ], - ], - 'type' => 2, - 'mappedBy' => NULL, - 'inversedBy' => NULL, - 'isOwningSide' => true, - 'sourceEntity' => CmsUser::class, - 'isCascadeRemove' => true, - 'isCascadePersist' => true, - 'isCascadeRefresh' => true, - 'isCascadeMerge' => true, - 'isCascadeDetach' => true, - 'sourceToTargetKeyColumns' => - [ - 'group_id' => 'id', - ], - 'joinColumnFieldNames' => - [ - 'group_id' => 'group_id', - ], - 'targetToSourceKeyColumns' => - [ - 'id' => 'group_id', - ], - 'orphanRemoval' => false, - 'id' => true - ], - ], - $this->cm->associationMappings - ); - } - - public function testCreateOneToOne() - { - $this->assertIsFluent( - $this->builder->createOneToOne('groups', CmsGroup::class) - ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') - ->cascadeAll() - ->fetchExtraLazy() - ->build() - ); - - $this->assertEquals( - [ - 'groups' => [ - 'fieldName' => 'groups', - 'targetEntity' => CmsGroup::class, - 'cascade' => [ - 0 => 'remove', - 1 => 'persist', - 2 => 'refresh', - 3 => 'merge', - 4 => 'detach', - ], - 'fetch' => 4, - 'joinColumns' => [ - 0 => - [ - 'name' => 'group_id', - 'referencedColumnName' => 'id', - 'nullable' => true, - 'unique' => true, - 'onDelete' => 'CASCADE', - 'columnDefinition' => NULL, - ], - ], - 'type' => 1, - 'mappedBy' => NULL, - 'inversedBy' => NULL, - 'isOwningSide' => true, - 'sourceEntity' => CmsUser::class, - 'isCascadeRemove' => true, - 'isCascadePersist' => true, - 'isCascadeRefresh' => true, - 'isCascadeMerge' => true, - 'isCascadeDetach' => true, - 'sourceToTargetKeyColumns' => - [ - 'group_id' => 'id', - ], - 'joinColumnFieldNames' => - [ - 'group_id' => 'group_id', - ], - 'targetToSourceKeyColumns' => - [ - 'id' => 'group_id', - ], - 'orphanRemoval' => false - ], - ], $this->cm->associationMappings); - } - - public function testCreateOneToOneWithIdentity() - { - $this->assertIsFluent( - $this - ->builder - ->createOneToOne('groups', CmsGroup::class) - ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') - ->cascadeAll() - ->fetchExtraLazy() - ->makePrimaryKey() - ->build() - ); - - $this->assertEquals( - [ - 'groups' => [ - 'fieldName' => 'groups', - 'targetEntity' => CmsGroup::class, - 'cascade' => [ - 0 => 'remove', - 1 => 'persist', - 2 => 'refresh', - 3 => 'merge', - 4 => 'detach', - ], - 'fetch' => 4, - 'id' => true, - 'joinColumns' => [ - 0 => - [ - 'name' => 'group_id', - 'referencedColumnName' => 'id', - 'nullable' => true, - 'unique' => false, - 'onDelete' => 'CASCADE', - 'columnDefinition' => NULL, - ], - ], - 'type' => 1, - 'mappedBy' => NULL, - 'inversedBy' => NULL, - 'isOwningSide' => true, - 'sourceEntity' => CmsUser::class, - 'isCascadeRemove' => true, - 'isCascadePersist' => true, - 'isCascadeRefresh' => true, - 'isCascadeMerge' => true, - 'isCascadeDetach' => true, - 'sourceToTargetKeyColumns' => - [ - 'group_id' => 'id', - ], - 'joinColumnFieldNames' => - [ - 'group_id' => 'group_id', - ], - 'targetToSourceKeyColumns' => - [ - 'id' => 'group_id', - ], - 'orphanRemoval' => false - ], - ], - $this->cm->associationMappings - ); - } - - public function testThrowsExceptionOnCreateOneToOneWithIdentityOnInverseSide() - { - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - - $this - ->builder - ->createOneToOne('groups', CmsGroup::class) - ->mappedBy('test') - ->fetchExtraLazy() - ->makePrimaryKey() - ->build(); - } - - public function testCreateManyToMany() - { - $this->assertIsFluent( - $this->builder->createManyToMany('groups', CmsGroup::class) - ->setJoinTable('groups_users') - ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') - ->addInverseJoinColumn('user_id', 'id') - ->cascadeAll() - ->fetchExtraLazy() - ->build() - ); - - $this->assertEquals( - [ - 'groups' => - [ - 'fieldName' => 'groups', - 'targetEntity' => CmsGroup::class, - 'cascade' => - [ - 0 => 'remove', - 1 => 'persist', - 2 => 'refresh', - 3 => 'merge', - 4 => 'detach', - ], - 'fetch' => 4, - 'joinTable' => - [ - 'joinColumns' => - [ - 0 => - [ - 'name' => 'group_id', - 'referencedColumnName' => 'id', - 'nullable' => true, - 'unique' => false, - 'onDelete' => 'CASCADE', - 'columnDefinition' => NULL, - ], - ], - 'inverseJoinColumns' => - [ - 0 => - [ - 'name' => 'user_id', - 'referencedColumnName' => 'id', - 'nullable' => true, - 'unique' => false, - 'onDelete' => NULL, - 'columnDefinition' => NULL, - ], - ], - 'name' => 'groups_users', - ], - 'type' => 8, - 'mappedBy' => NULL, - 'inversedBy' => NULL, - 'isOwningSide' => true, - 'sourceEntity' => CmsUser::class, - 'isCascadeRemove' => true, - 'isCascadePersist' => true, - 'isCascadeRefresh' => true, - 'isCascadeMerge' => true, - 'isCascadeDetach' => true, - 'isOnDeleteCascade' => true, - 'relationToSourceKeyColumns' => - [ - 'group_id' => 'id', - ], - 'joinTableColumns' => - [ - 0 => 'group_id', - 1 => 'user_id', - ], - 'relationToTargetKeyColumns' => - [ - 'user_id' => 'id', - ], - 'orphanRemoval' => false, - ], - ], $this->cm->associationMappings); - } - - public function testThrowsExceptionOnCreateManyToManyWithIdentity() - { - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - - $this->builder->createManyToMany('groups', CmsGroup::class) - ->makePrimaryKey() - ->setJoinTable('groups_users') - ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') - ->addInverseJoinColumn('user_id', 'id') - ->cascadeAll() - ->fetchExtraLazy() - ->build(); - } - - public function testCreateOneToMany() - { - $this->assertIsFluent( - $this->builder->createOneToMany('groups', CmsGroup::class) - ->mappedBy('test') - ->setOrderBy(['test']) - ->setIndexBy('test') - ->build() - ); - - $this->assertEquals( - [ - 'groups' => - [ - 'fieldName' => 'groups', - 'targetEntity' => CmsGroup::class, - 'mappedBy' => 'test', - 'orderBy' => - [ - 0 => 'test', - ], - 'indexBy' => 'test', - 'type' => 4, - 'inversedBy' => NULL, - 'isOwningSide' => false, - 'sourceEntity' => CmsUser::class, - 'fetch' => 2, - 'cascade' => - [ - ], - 'isCascadeRemove' => false, - 'isCascadePersist' => false, - 'isCascadeRefresh' => false, - 'isCascadeMerge' => false, - 'isCascadeDetach' => false, - 'orphanRemoval' => false, - ], - ], $this->cm->associationMappings); - } - - public function testThrowsExceptionOnCreateOneToManyWithIdentity() - { - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - - $this->builder->createOneToMany('groups', CmsGroup::class) - ->makePrimaryKey() - ->mappedBy('test') - ->setOrderBy(['test']) - ->setIndexBy('test') - ->build(); - } - - public function testOrphanRemovalOnCreateOneToOne() - { - $this->assertIsFluent( - $this->builder - ->createOneToOne('groups', CmsGroup::class) - ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') - ->orphanRemoval() - ->build() - ); - - $this->assertEquals( - [ - 'groups' => [ - 'fieldName' => 'groups', - 'targetEntity' => CmsGroup::class, - 'cascade' => [], - 'fetch' => 2, - 'joinColumns' => [ - 0 => - [ - 'name' => 'group_id', - 'referencedColumnName' => 'id', - 'nullable' => true, - 'unique' => true, - 'onDelete' => 'CASCADE', - 'columnDefinition' => NULL, - ], - ], - 'type' => 1, - 'mappedBy' => NULL, - 'inversedBy' => NULL, - 'isOwningSide' => true, - 'sourceEntity' => CmsUser::class, - 'isCascadeRemove' => true, - 'isCascadePersist' => false, - 'isCascadeRefresh' => false, - 'isCascadeMerge' => false, - 'isCascadeDetach' => false, - 'sourceToTargetKeyColumns' => - [ - 'group_id' => 'id', - ], - 'joinColumnFieldNames' => - [ - 'group_id' => 'group_id', - ], - 'targetToSourceKeyColumns' => - [ - 'id' => 'group_id', - ], - 'orphanRemoval' => true - ], - ], $this->cm->associationMappings); - } - - public function testOrphanRemovalOnCreateOneToMany() - { - $this->assertIsFluent( - $this->builder - ->createOneToMany('groups', CmsGroup::class) - ->mappedBy('test') - ->orphanRemoval() - ->build() - ); - - $this->assertEquals( - [ - 'groups' => - [ - 'fieldName' => 'groups', - 'targetEntity' => CmsGroup::class, - 'mappedBy' => 'test', - 'type' => 4, - 'inversedBy' => NULL, - 'isOwningSide' => false, - 'sourceEntity' => CmsUser::class, - 'fetch' => 2, - 'cascade' => [], - 'isCascadeRemove' => true, - 'isCascadePersist' => false, - 'isCascadeRefresh' => false, - 'isCascadeMerge' => false, - 'isCascadeDetach' => false, - 'orphanRemoval' => true, - ], - ], $this->cm->associationMappings); - } - - public function testExceptionOnOrphanRemovalOnManyToOne() - { - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - - $this->builder - ->createManyToOne('groups', CmsGroup::class) - ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') - ->orphanRemoval() - ->build(); - } - - public function testOrphanRemovalOnManyToMany() - { - $this->builder - ->createManyToMany('groups', CmsGroup::class) - ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') - ->orphanRemoval() - ->build(); - - $this->assertEquals( - [ - 'groups' => [ - 'fieldName' => 'groups', - 'targetEntity' => CmsGroup::class, - 'cascade' => [], - 'fetch' => 2, - 'joinTable' => [ - 'joinColumns' => [ - 0 => [ - 'name' => 'group_id', - 'referencedColumnName' => 'id', - 'nullable' => true, - 'unique' => false, - 'onDelete' => 'CASCADE', - 'columnDefinition' => NULL, - ], - ], - 'inverseJoinColumns' => [ - 0 => [ - 'name' => 'cmsgroup_id', - 'referencedColumnName' => 'id', - 'onDelete' => 'CASCADE' - ] - ], - 'name' => 'cmsuser_cmsgroup', - ], - 'type' => 8, - 'mappedBy' => NULL, - 'inversedBy' => NULL, - 'isOwningSide' => true, - 'sourceEntity' => CmsUser::class, - 'isCascadeRemove' => false, - 'isCascadePersist' => false, - 'isCascadeRefresh' => false, - 'isCascadeMerge' => false, - 'isCascadeDetach' => false, - 'isOnDeleteCascade' => true, - 'relationToSourceKeyColumns' => [ - 'group_id' => 'id', - ], - 'joinTableColumns' => [ - 0 => 'group_id', - 1 => 'cmsgroup_id', - ], - 'relationToTargetKeyColumns' => [ - 'cmsgroup_id' => 'id', - ], - 'orphanRemoval' => true, - ], - ], $this->cm->associationMappings); - } - - public function assertIsFluent($ret) - { - $this->assertSame($this->builder, $ret, "Return Value has to be same instance as used builder"); - } -} diff --git a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php index d1cf1b48f88..4cfaf4925c3 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php @@ -1,21 +1,24 @@ _createEntityManager($mockDriver); + $entityManager = $this->createEntityManager($mockDriver); $conn = $entityManager->getConnection(); $mockPlatform = $conn->getDatabasePlatform(); $mockPlatform->setPrefersSequences(true); $mockPlatform->setPrefersIdentityColumns(false); - $cm1 = $this->_createValidClassMetadata(); + $cm1 = $this->createValidClassMetadata(); // SUT $cmf = new ClassMetadataFactory(); $cmf->setEntityManager($entityManager); - $cmf->setMetadataFor($cm1->name, $cm1); + $cmf->setMetadataFor($cm1->getClassName(), $cm1); // Prechecks - $this->assertEquals([], $cm1->parentClasses); - $this->assertEquals(ClassMetadata::INHERITANCE_TYPE_NONE, $cm1->inheritanceType); - $this->assertTrue($cm1->hasField('name')); - $this->assertEquals(2, count($cm1->associationMappings)); - $this->assertEquals(ClassMetadata::GENERATOR_TYPE_AUTO, $cm1->generatorType); - $this->assertEquals('group', $cm1->table['name']); + self::assertCount(0, $cm1->getAncestorsIterator()); + self::assertEquals(Mapping\InheritanceType::NONE, $cm1->inheritanceType); + self::assertEquals(Mapping\GeneratorType::AUTO, $cm1->getProperty('id')->getValueGenerator()->getType()); + self::assertTrue($cm1->hasField('name')); + self::assertCount(4, $cm1->getDeclaredPropertiesIterator()); // 2 fields + 2 associations + self::assertEquals('group', $cm1->table->getName()); // Go - $cmMap1 = $cmf->getMetadataFor($cm1->name); + $cmMap1 = $cmf->getMetadataFor($cm1->getClassName()); - $this->assertSame($cm1, $cmMap1); - $this->assertEquals('group', $cmMap1->table['name']); - $this->assertTrue($cmMap1->table['quoted']); - $this->assertEquals([], $cmMap1->parentClasses); - $this->assertTrue($cmMap1->hasField('name')); + self::assertSame($cm1, $cmMap1); + self::assertEquals('group', $cmMap1->table->getName()); + self::assertCount(0, $cmMap1->getAncestorsIterator()); + self::assertTrue($cmMap1->hasField('name')); } - public function testGetMetadataFor_ReturnsLoadedCustomIdGenerator() + public function testGetMetadataFor_ThrowsExceptionOnUnknownCustomGeneratorClass() { - $cm1 = $this->_createValidClassMetadata(); - $cm1->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_CUSTOM); - $cm1->customGeneratorDefinition = ['class' => CustomIdGenerator::class]; - $cmf = $this->_createTestFactory(); - $cmf->setMetadataForClass($cm1->name, $cm1); + $cm1 = $this->createValidClassMetadata(); + + $cm1->getProperty('id')->setValueGenerator( + new Mapping\ValueGeneratorMetadata( + Mapping\GeneratorType::CUSTOM, + [ + 'class' => 'NotExistingGenerator', + 'arguments' => [], + ] + ) + ); - $actual = $cmf->getMetadataFor($cm1->name); + $cmf = $this->createTestFactory(); - $this->assertEquals(ClassMetadata::GENERATOR_TYPE_CUSTOM, $actual->generatorType); - $this->assertInstanceOf(CustomIdGenerator::class, $actual->idGenerator); - } + $cmf->setMetadataForClass($cm1->getClassName(), $cm1); - public function testGetMetadataFor_ThrowsExceptionOnUnknownCustomGeneratorClass() - { - $cm1 = $this->_createValidClassMetadata(); - $cm1->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_CUSTOM); - $cm1->customGeneratorDefinition = ["class" => "NotExistingGenerator"]; - $cmf = $this->_createTestFactory(); - $cmf->setMetadataForClass($cm1->name, $cm1); $this->expectException(ORMException::class); - $actual = $cmf->getMetadataFor($cm1->name); + $actual = $cmf->getMetadataFor($cm1->getClassName()); } public function testGetMetadataFor_ThrowsExceptionOnMissingCustomGeneratorDefinition() { - $cm1 = $this->_createValidClassMetadata(); - $cm1->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_CUSTOM); - $cmf = $this->_createTestFactory(); - $cmf->setMetadataForClass($cm1->name, $cm1); + $cm1 = $this->createValidClassMetadata(); + + $cm1->getProperty('id')->setValueGenerator( + new Mapping\ValueGeneratorMetadata(Mapping\GeneratorType::CUSTOM) + ); + + $cmf = $this->createTestFactory(); + + $cmf->setMetadataForClass($cm1->getClassName(), $cm1); + $this->expectException(ORMException::class); - $actual = $cmf->getMetadataFor($cm1->name); + $actual = $cmf->getMetadataFor($cm1->getClassName()); } public function testHasGetMetadata_NamespaceSeparatorIsNotNormalized() @@ -110,7 +115,7 @@ public function testHasGetMetadata_NamespaceSeparatorIsNotNormalized() $metadataDriver = $this->createAnnotationDriver([__DIR__ . '/../../Models/Global/']); - $entityManager = $this->_createEntityManager($metadataDriver); + $entityManager = $this->createEntityManager($metadataDriver); $mf = $entityManager->getMetadataFactory(); $m1 = $mf->getMetadataFor(DoctrineGlobal_Article::class); @@ -118,9 +123,9 @@ public function testHasGetMetadata_NamespaceSeparatorIsNotNormalized() $h2 = $mf->hasMetadataFor('\\' . DoctrineGlobal_Article::class); $m2 = $mf->getMetadataFor('\\' . DoctrineGlobal_Article::class); - $this->assertNotSame($m1, $m2); - $this->assertFalse($h2); - $this->assertTrue($h1); + self::assertNotSame($m1, $m2); + self::assertFalse($h2); + self::assertTrue($h1); } /** @@ -139,10 +144,10 @@ public function testIsTransient() ->with($this->equalTo(CmsArticle::class)) ->will($this->returnValue(false)); - $em = $this->_createEntityManager($driver); + $em = $this->createEntityManager($driver); - $this->assertTrue($em->getMetadataFactory()->isTransient(CmsUser::class)); - $this->assertFalse($em->getMetadataFactory()->isTransient(CmsArticle::class)); + self::assertTrue($em->getMetadataFactory()->isTransient(CmsUser::class)); + self::assertFalse($em->getMetadataFactory()->isTransient(CmsArticle::class)); } /** @@ -161,18 +166,18 @@ public function testIsTransientEntityNamespace() ->with($this->equalTo(CmsArticle::class)) ->will($this->returnValue(false)); - $em = $this->_createEntityManager($driver); + $em = $this->createEntityManager($driver); $em->getConfiguration()->addEntityNamespace('CMS', 'Doctrine\Tests\Models\CMS'); - $this->assertTrue($em->getMetadataFactory()->isTransient('CMS:CmsUser')); - $this->assertFalse($em->getMetadataFactory()->isTransient('CMS:CmsArticle')); + self::assertTrue($em->getMetadataFactory()->isTransient('CMS:CmsUser')); + self::assertFalse($em->getMetadataFactory()->isTransient('CMS:CmsArticle')); } public function testAddDefaultDiscriminatorMap() { $cmf = new ClassMetadataFactory(); $driver = $this->createAnnotationDriver([__DIR__ . '/../../Models/JoinedInheritanceType/']); - $em = $this->_createEntityManager($driver); + $em = $this->createEntityManager($driver); $cmf->setEntityManager($em); $rootMetadata = $cmf->getMetadataFor(RootClass::class); @@ -190,12 +195,12 @@ public function testAddDefaultDiscriminatorMap() $childClassKey = array_search($childClass, $rootDiscriminatorMap); $anotherChildClassKey = array_search($anotherChildClass, $rootDiscriminatorMap); - $this->assertEquals('rootclass', $rootClassKey); - $this->assertEquals('childclass', $childClassKey); - $this->assertEquals('anotherchildclass', $anotherChildClassKey); + self::assertEquals('rootclass', $rootClassKey); + self::assertEquals('childclass', $childClassKey); + self::assertEquals('anotherchildclass', $anotherChildClassKey); - $this->assertEquals($childDiscriminatorMap, $rootDiscriminatorMap); - $this->assertEquals($anotherChildDiscriminatorMap, $rootDiscriminatorMap); + self::assertEquals($childDiscriminatorMap, $rootDiscriminatorMap); + self::assertEquals($anotherChildDiscriminatorMap, $rootDiscriminatorMap); // ClassMetadataFactory::addDefaultDiscriminatorMap shouldn't be called again, because the // discriminator map is already cached @@ -212,7 +217,10 @@ public function testGetAllMetadataWorksWithBadConnection() // DDC-3551 $conn = $this->createMock(Connection::class); $mockDriver = new MetadataDriverMock(); - $em = $this->_createEntityManager($mockDriver, $conn); + $conn->expects($this->any()) + ->method('getEventManager') + ->willReturn(new EventManager()); + $em = $this->createEntityManager($mockDriver, $conn); $conn->expects($this->any()) ->method('getDatabasePlatform') @@ -224,19 +232,22 @@ public function testGetAllMetadataWorksWithBadConnection() // getting all the metadata should work, even if get DatabasePlatform blows up $metadata = $cmf->getAllMetadata(); // this will just be an empty array - there was no error - $this->assertEquals([], $metadata); + self::assertEquals([], $metadata); } - protected function _createEntityManager($metadataDriver, $conn = null) + protected function createEntityManager($metadataDriver, $conn = null) { $driverMock = new DriverMock(); $config = new Configuration(); + $config->setProxyDir(__DIR__ . '/../../Proxies'); $config->setProxyNamespace('Doctrine\Tests\Proxies'); - $eventManager = new EventManager(); + if (!$conn) { - $conn = new ConnectionMock([], $driverMock, $config, $eventManager); + $conn = new ConnectionMock([], $driverMock, $config, new EventManager()); } + $eventManager = $conn->getEventManager(); + $config->setMetadataDriverImpl($metadataDriver); return EntityManagerMock::create($conn, $config, $eventManager); @@ -245,10 +256,10 @@ protected function _createEntityManager($metadataDriver, $conn = null) /** * @return ClassMetadataFactoryTestSubject */ - protected function _createTestFactory() + protected function createTestFactory() { $mockDriver = new MetadataDriverMock(); - $entityManager = $this->_createEntityManager($mockDriver); + $entityManager = $this->createEntityManager($mockDriver); $cmf = new ClassMetadataFactoryTestSubject(); $cmf->setEntityManager($entityManager); return $cmf; @@ -258,27 +269,62 @@ protected function _createTestFactory() * @param string $class * @return ClassMetadata */ - protected function _createValidClassMetadata() + protected function createValidClassMetadata() { // Self-made metadata - $cm1 = new ClassMetadata(TestEntity1::class); - $cm1->initializeReflection(new RuntimeReflectionService()); - $cm1->setPrimaryTable(['name' => '`group`']); + $metadataBuildingContext = new Mapping\ClassMetadataBuildingContext( + $this->createMock(ClassMetadataFactory::class), + new RuntimeReflectionService() + ); + + $cm1 = new ClassMetadata(TestEntity1::class, $metadataBuildingContext); + + $tableMetadata = new Mapping\TableMetadata(); + $tableMetadata->setName('group'); + + $cm1->setTable($tableMetadata); + // Add a mapped field - $cm1->mapField(['fieldName' => 'name', 'type' => 'string']); + $fieldMetadata = new Mapping\FieldMetadata('id'); + + $fieldMetadata->setType(Type::getType('integer')); + $fieldMetadata->setPrimaryKey(true); + $fieldMetadata->setValueGenerator(new Mapping\ValueGeneratorMetadata(Mapping\GeneratorType::AUTO)); + + $cm1->addProperty($fieldMetadata); + // Add a mapped field - $cm1->mapField(['fieldName' => 'id', 'type' => 'integer', 'id' => true]); + $fieldMetadata = new Mapping\FieldMetadata('name'); + + $fieldMetadata->setType(Type::getType('string')); + + $cm1->addProperty($fieldMetadata); + // and a mapped association - $cm1->mapOneToOne(['fieldName' => 'other', 'targetEntity' => 'TestEntity1', 'mappedBy' => 'this']); + $association = new Mapping\OneToOneAssociationMetadata('other'); + + $association->setTargetEntity(TestEntity1::class); + $association->setMappedBy('this'); + + $cm1->addProperty($association); + // and an association on the owning side - $joinColumns = [ - ['name' => 'other_id', 'referencedColumnName' => 'id'] - ]; - $cm1->mapOneToOne( - ['fieldName' => 'association', 'targetEntity' => 'TestEntity1', 'joinColumns' => $joinColumns] - ); - // and an id generator type - $cm1->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_AUTO); + $joinColumns = []; + + $joinColumn = new Mapping\JoinColumnMetadata(); + + $joinColumn->setColumnName("other_id"); + $joinColumn->setReferencedColumnName("id"); + + $joinColumns[] = $joinColumn; + + $association = new Mapping\OneToOneAssociationMetadata('association'); + + $association->setJoinColumns($joinColumns); + $association->setTargetEntity(TestEntity1::class); + + $cm1->addProperty($association); + return $cm1; } @@ -289,77 +335,70 @@ public function testQuoteMetadata() { $cmf = new ClassMetadataFactory(); $driver = $this->createAnnotationDriver([__DIR__ . '/../../Models/Quote/']); - $em = $this->_createEntityManager($driver); + $em = $this->createEntityManager($driver); $cmf->setEntityManager($em); - $userMetadata = $cmf->getMetadataFor(Quote\User::class); $phoneMetadata = $cmf->getMetadataFor(Quote\Phone::class); $groupMetadata = $cmf->getMetadataFor(Quote\Group::class); $addressMetadata = $cmf->getMetadataFor(Quote\Address::class); - // Phone Class Metadata - $this->assertTrue($phoneMetadata->fieldMappings['number']['quoted']); - $this->assertEquals('phone-number', $phoneMetadata->fieldMappings['number']['columnName']); - - $user = $phoneMetadata->associationMappings['user']; - $this->assertTrue($user['joinColumns'][0]['quoted']); - $this->assertEquals('user-id', $user['joinColumns'][0]['name']); - $this->assertEquals('user-id', $user['joinColumns'][0]['referencedColumnName']); + self::assertNotNull($phoneMetadata->getProperty('number')); + self::assertEquals('phone-number', $phoneMetadata->getProperty('number')->getColumnName()); + $user = $phoneMetadata->getProperty('user'); + $userJoinColumns = $user->getJoinColumns(); + $phoneUserJoinColumn = reset($userJoinColumns); - - // User Group Metadata - $this->assertTrue($groupMetadata->fieldMappings['id']['quoted']); - $this->assertTrue($groupMetadata->fieldMappings['name']['quoted']); - - $this->assertEquals('user-id', $userMetadata->fieldMappings['id']['columnName']); - $this->assertEquals('user-name', $userMetadata->fieldMappings['name']['columnName']); - - $user = $groupMetadata->associationMappings['parent']; - $this->assertTrue($user['joinColumns'][0]['quoted']); - $this->assertEquals('parent-id', $user['joinColumns'][0]['name']); - $this->assertEquals('group-id', $user['joinColumns'][0]['referencedColumnName']); - + self::assertEquals('user-id', $phoneUserJoinColumn->getColumnName()); + self::assertEquals('user-id', $phoneUserJoinColumn->getReferencedColumnName()); // Address Class Metadata - $this->assertTrue($addressMetadata->fieldMappings['id']['quoted']); - $this->assertTrue($addressMetadata->fieldMappings['zip']['quoted']); - - $this->assertEquals('address-id', $addressMetadata->fieldMappings['id']['columnName']); - $this->assertEquals('address-zip', $addressMetadata->fieldMappings['zip']['columnName']); - - $user = $addressMetadata->associationMappings['user']; - $this->assertTrue($user['joinColumns'][0]['quoted']); - $this->assertEquals('user-id', $user['joinColumns'][0]['name']); - $this->assertEquals('user-id', $user['joinColumns'][0]['referencedColumnName']); - - + self::assertNotNull($addressMetadata->getProperty('id')); + self::assertNotNull($addressMetadata->getProperty('zip')); + self::assertEquals('address-id', $addressMetadata->getProperty('id')->getColumnName()); + self::assertEquals('address-zip', $addressMetadata->getProperty('zip')->getColumnName()); // User Class Metadata - $this->assertTrue($userMetadata->fieldMappings['id']['quoted']); - $this->assertTrue($userMetadata->fieldMappings['name']['quoted']); - - $this->assertEquals('user-id', $userMetadata->fieldMappings['id']['columnName']); - $this->assertEquals('user-name', $userMetadata->fieldMappings['name']['columnName']); - - - $address = $userMetadata->associationMappings['address']; - $this->assertTrue($address['joinColumns'][0]['quoted']); - $this->assertEquals('address-id', $address['joinColumns'][0]['name']); - $this->assertEquals('address-id', $address['joinColumns'][0]['referencedColumnName']); - - $groups = $userMetadata->associationMappings['groups']; - $this->assertTrue($groups['joinTable']['quoted']); - $this->assertTrue($groups['joinTable']['joinColumns'][0]['quoted']); - $this->assertEquals('quote-users-groups', $groups['joinTable']['name']); - $this->assertEquals('user-id', $groups['joinTable']['joinColumns'][0]['name']); - $this->assertEquals('user-id', $groups['joinTable']['joinColumns'][0]['referencedColumnName']); - - $this->assertTrue($groups['joinTable']['inverseJoinColumns'][0]['quoted']); - $this->assertEquals('group-id', $groups['joinTable']['inverseJoinColumns'][0]['name']); - $this->assertEquals('group-id', $groups['joinTable']['inverseJoinColumns'][0]['referencedColumnName']); + self::assertNotNull($userMetadata->getProperty('id')); + self::assertNotNull($userMetadata->getProperty('name')); + self::assertEquals('user-id', $userMetadata->getProperty('id')->getColumnName()); + self::assertEquals('user-name', $userMetadata->getProperty('name')->getColumnName()); + + $group = $groupMetadata->getProperty('parent'); + $groupJoinColumns = $group->getJoinColumns(); + $groupUserJoinColumn = reset($groupJoinColumns); + + self::assertEquals('parent-id', $groupUserJoinColumn->getColumnName()); + self::assertEquals('group-id', $groupUserJoinColumn->getReferencedColumnName()); + + $user = $addressMetadata->getProperty('user'); + $userJoinColumns = $user->getJoinColumns(); + $addressUserJoinColumn = reset($userJoinColumns); + + self::assertEquals('user-id', $addressUserJoinColumn->getColumnName()); + self::assertEquals('user-id', $addressUserJoinColumn->getReferencedColumnName()); + + $address = $userMetadata->getProperty('address'); + $addressJoinColumns = $address->getJoinColumns(); + $userAddressJoinColumn = reset($addressJoinColumns); + + self::assertEquals('address-id', $userAddressJoinColumn->getColumnName()); + self::assertEquals('address-id', $userAddressJoinColumn->getReferencedColumnName()); + + $groups = $userMetadata->getProperty('groups'); + $groupsJoinTable = $groups->getJoinTable(); + $userGroupsJoinColumns = $groupsJoinTable->getJoinColumns(); + $userGroupsJoinColumn = reset($userGroupsJoinColumns); + $userGroupsInverseJoinColumns = $groupsJoinTable->getInverseJoinColumns(); + $userGroupsInverseJoinColumn = reset($userGroupsInverseJoinColumns); + + self::assertEquals('quote-users-groups', $groupsJoinTable->getName()); + self::assertEquals('user-id', $userGroupsJoinColumn->getColumnName()); + self::assertEquals('user-id', $userGroupsJoinColumn->getReferencedColumnName()); + self::assertEquals('group-id', $userGroupsInverseJoinColumn->getColumnName()); + self::assertEquals('group-id', $userGroupsInverseJoinColumn->getReferencedColumnName()); } /** @@ -370,11 +409,12 @@ public function testQuoteMetadata() public function testFallbackLoadingCausesEventTriggeringThatCanModifyFetchedMetadata() { $test = $this; - /* @var $metadata \Doctrine\Common\Persistence\Mapping\ClassMetadata */ + + /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */ $metadata = $this->createMock(ClassMetadata::class); $cmf = new ClassMetadataFactory(); $mockDriver = new MetadataDriverMock(); - $em = $this->_createEntityManager($mockDriver); + $em = $this->createEntityManager($mockDriver); $listener = $this->getMockBuilder(\stdClass::class)->setMethods(['onClassMetadataNotFound'])->getMock(); $eventManager = $em->getEventManager(); @@ -393,7 +433,7 @@ public function testFallbackLoadingCausesEventTriggeringThatCanModifyFetchedMeta $eventManager->addEventListener([Events::onClassMetadataNotFound], $listener); - $this->assertSame($metadata, $cmf->getMetadataFor('Foo')); + self::assertSame($metadata, $cmf->getMetadataFor('Foo')); } /** @@ -403,21 +443,22 @@ public function testAcceptsEntityManagerInterfaceInstances() { $classMetadataFactory = new ClassMetadataFactory(); - /* @var $entityManager EntityManager */ + /* @var EntityManagerInterface EntityManager */ $entityManager = $this->createMock(EntityManagerInterface::class); $classMetadataFactory->setEntityManager($entityManager); // not really the cleanest way to check it, but we won't add a getter to the CMF just for the sake of testing. - $this->assertAttributeSame($entityManager, 'em', $classMetadataFactory); + self::assertAttributeSame($entityManager, 'em', $classMetadataFactory); } /** + * @group embedded * @group DDC-3305 */ public function testRejectsEmbeddableWithoutValidClassName() { - $metadata = $this->_createValidClassMetadata(); + $metadata = $this->createValidClassMetadata(); $metadata->mapEmbedded( [ @@ -427,29 +468,30 @@ public function testRejectsEmbeddableWithoutValidClassName() ] ); - $cmf = $this->_createTestFactory(); + $cmf = $this->createTestFactory(); - $cmf->setMetadataForClass($metadata->name, $metadata); + $cmf->setMetadataForClass($metadata->getClassName(), $metadata); $this->expectException(MappingException::class); $this->expectExceptionMessage('The embed mapping \'embedded\' misses the \'class\' attribute.'); - $cmf->getMetadataFor($metadata->name); + $cmf->getMetadataFor($metadata->getClassName()); } /** + * @group embedded * @group DDC-4006 */ public function testInheritsIdGeneratorMappingFromEmbeddable() { $cmf = new ClassMetadataFactory(); $driver = $this->createAnnotationDriver([__DIR__ . '/../../Models/DDC4006/']); - $em = $this->_createEntityManager($driver); + $em = $this->createEntityManager($driver); $cmf->setEntityManager($em); $userMetadata = $cmf->getMetadataFor(DDC4006User::class); - $this->assertTrue($userMetadata->isIdGeneratorIdentity()); + self::assertTrue($userMetadata->isIdGeneratorIdentity()); } } @@ -459,13 +501,18 @@ class ClassMetadataFactoryTestSubject extends ClassMetadataFactory private $mockMetadata = []; private $requestedClasses = []; - /** @override */ - protected function newClassMetadataInstance($className) + protected function newClassMetadataInstance( + string $className, + ?Mapping\ClassMetadata $parent, + Mapping\ClassMetadataBuildingContext $metadataBuildingContext + ) : ClassMetadata { $this->requestedClasses[] = $className; + if ( ! isset($this->mockMetadata[$className])) { throw new \InvalidArgumentException("No mock metadata found for class $className."); } + return $this->mockMetadata[$className]; } @@ -489,9 +536,20 @@ class TestEntity1 private $embedded; } -class CustomIdGenerator extends AbstractIdGenerator +class CustomIdGenerator implements Generator { - public function generate(EntityManager $em, $entity) + /** + * {@inheritdoc} + */ + public function generate(EntityManagerInterface $em, $entity): \Generator + { + } + + /** + * {@inheritdoc} + */ + public function isPostInsertGenerator() { + return false; } } diff --git a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataLoadEventTest.php b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataLoadEventTest.php index bf268cf829a..9c73478434e 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataLoadEventTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataLoadEventTest.php @@ -1,9 +1,14 @@ _getTestEntityManager(); - $metadataFactory = $em->getMetadataFactory(); - $evm = $em->getEventManager(); - $evm->addEventListener(Events::loadClassMetadata, $this); - $classMetadata = $metadataFactory->getMetadataFor(LoadEventTestEntity::class); - $this->assertTrue($classMetadata->hasField('about')); - $this->assertArrayHasKey('about', $classMetadata->reflFields); - $this->assertInstanceOf('ReflectionProperty', $classMetadata->reflFields['about']); + $entityManager = $this->getTestEntityManager(); + $metadataFactory = $entityManager->getMetadataFactory(); + $eventManager = $entityManager->getEventManager(); + + $eventManager->addEventListener(Events::loadClassMetadata, $this); + + $metadata = $metadataFactory->getMetadataFor(LoadEventTestEntity::class); + $property = $metadata->getProperty('about'); + + self::assertInstanceOf(Mapping\FieldMetadata::class, $property); + + $test = new LoadEventTestEntity(); + + $property->setValue($test, 'About who?'); + + self::assertEquals('About who?', $test->about); } public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs) { - $classMetadata = $eventArgs->getClassMetadata(); - $field = [ - 'fieldName' => 'about', - 'type' => 'string', - 'length' => 255 - ]; - $classMetadata->mapField($field); + $metadata = $eventArgs->getClassMetadata(); + $fieldMetadata = new Mapping\FieldMetadata('about'); + + $fieldMetadata->setType(Type::getType('string')); + $fieldMetadata->setLength(255); + + $metadata->setPropertyOverride($fieldMetadata); } } /** - * @Entity - * @Table(name="load_event_test_entity") + * @ORM\Entity + * @ORM\Table(name="load_event_test_entity") */ class LoadEventTestEntity { /** - * @Id @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** - * @Column(type="string", length=255) + * @ORM\Column(type="string", length=255) */ private $name; - private $about; + public $about; } diff --git a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php index 24d9559f78a..8dd92dcaa09 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php @@ -1,95 +1,177 @@ metadataBuildingContext = new Mapping\ClassMetadataBuildingContext( + $this->createMock(Mapping\ClassMetadataFactory::class), + new RuntimeReflectionService() + ); + } + + public function testClassMetadataInstanceSimpleState() + { + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); + + self::assertInstanceOf(\ReflectionClass::class, $cm->getReflectionClass()); + self::assertEquals(CMS\CmsUser::class, $cm->getClassName()); + self::assertEquals(CMS\CmsUser::class, $cm->getRootClassName()); + self::assertEquals([], $cm->getSubClasses()); + self::assertCount(0, $cm->getAncestorsIterator()); + self::assertEquals(Mapping\InheritanceType::NONE, $cm->inheritanceType); + } + public function testClassMetadataInstanceSerialization() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); - - // Test initial state - $this->assertTrue(count($cm->getReflectionProperties()) == 0); - $this->assertInstanceOf('ReflectionClass', $cm->reflClass); - $this->assertEquals(CMS\CmsUser::class, $cm->name); - $this->assertEquals(CMS\CmsUser::class, $cm->rootEntityName); - $this->assertEquals([], $cm->subClasses); - $this->assertEquals([], $cm->parentClasses); - $this->assertEquals(ClassMetadata::INHERITANCE_TYPE_NONE, $cm->inheritanceType); - - // Customize state - $cm->setInheritanceType(ClassMetadata::INHERITANCE_TYPE_SINGLE_TABLE); - $cm->setSubclasses(["One", "Two", "Three"]); - $cm->setParentClasses(["UserParent"]); - $cm->setCustomRepositoryClass("UserRepository"); - $cm->setDiscriminatorColumn(['name' => 'disc', 'type' => 'integer']); - $cm->mapOneToOne(['fieldName' => 'phonenumbers', 'targetEntity' => 'CmsAddress', 'mappedBy' => 'foo']); - $cm->markReadOnly(); - $cm->addNamedQuery(['name' => 'dql', 'query' => 'foo']); - $this->assertEquals(1, count($cm->associationMappings)); + $parent = new ClassMetadata(CMS\CmsEmployee::class, $this->metadataBuildingContext); + $parent->setTable(new Mapping\TableMetadata('cms_employee')); + + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable($parent->table); + $cm->setParent($parent); + + $discrColumn = new DiscriminatorColumnMetadata(); + + $discrColumn->setColumnName('disc'); + $discrColumn->setType(Type::getType('integer')); + + $cm->setInheritanceType(Mapping\InheritanceType::SINGLE_TABLE); + $cm->setSubclasses([ + 'Doctrine\Tests\Models\CMS\One', + 'Doctrine\Tests\Models\CMS\Two', + 'Doctrine\Tests\Models\CMS\Three' + ]); + $cm->setCustomRepositoryClassName('Doctrine\Tests\Models\CMS\UserRepository'); + $cm->setDiscriminatorColumn($discrColumn); + $cm->asReadOnly(); + $cm->addNamedQuery('dql', 'foo'); + + $association = new Mapping\OneToOneAssociationMetadata('phonenumbers'); + + $association->setTargetEntity(CMS\CmsAddress::class); + $association->setMappedBy('foo'); + + $cm->addProperty($association); + + self::assertCount(1, $cm->getDeclaredPropertiesIterator()); $serialized = serialize($cm); $cm = unserialize($serialized); + $cm->wakeupReflection(new RuntimeReflectionService()); // Check state - $this->assertTrue(count($cm->getReflectionProperties()) > 0); - $this->assertEquals('Doctrine\Tests\Models\CMS', $cm->namespace); - $this->assertInstanceOf(\ReflectionClass::class, $cm->reflClass); - $this->assertEquals(CMS\CmsUser::class, $cm->name); - $this->assertEquals('UserParent', $cm->rootEntityName); - $this->assertEquals([CMS\One::class, CMS\Two::class, CMS\Three::class], $cm->subClasses); - $this->assertEquals(['UserParent'], $cm->parentClasses); - $this->assertEquals(CMS\UserRepository::class, $cm->customRepositoryClassName); - $this->assertEquals(['name' => 'disc', 'type' => 'integer', 'fieldName' => 'disc'], $cm->discriminatorColumn); - $this->assertTrue($cm->associationMappings['phonenumbers']['type'] == ClassMetadata::ONE_TO_ONE); - $this->assertEquals(1, count($cm->associationMappings)); - $oneOneMapping = $cm->getAssociationMapping('phonenumbers'); - $this->assertTrue($oneOneMapping['fetch'] == ClassMetadata::FETCH_LAZY); - $this->assertEquals('phonenumbers', $oneOneMapping['fieldName']); - $this->assertEquals(CMS\CmsAddress::class, $oneOneMapping['targetEntity']); - $this->assertTrue($cm->isReadOnly); - $this->assertEquals(['dql' => ['name'=>'dql','query'=>'foo','dql'=>'foo']], $cm->namedQueries); + self::assertInstanceOf(\ReflectionClass::class, $cm->getReflectionClass()); + self::assertEquals(CMS\CmsUser::class, $cm->getClassName()); + self::assertEquals(CMS\CmsEmployee::class, $cm->getRootClassName()); + self::assertEquals('Doctrine\Tests\Models\CMS\UserRepository', $cm->getCustomRepositoryClassName()); + self::assertEquals( + [ + 'Doctrine\Tests\Models\CMS\One', + 'Doctrine\Tests\Models\CMS\Two', + 'Doctrine\Tests\Models\CMS\Three' + ], + $cm->getSubClasses() + ); + self::assertCount(1, $cm->getAncestorsIterator()); + self::assertEquals(CMS\CmsEmployee::class, $cm->getAncestorsIterator()->current()->getClassName()); + self::assertEquals($discrColumn, $cm->discriminatorColumn); + self::assertTrue($cm->isReadOnly()); + self::assertEquals(['dql' => 'foo'], $cm->getNamedQueries()); + self::assertCount(1, $cm->getDeclaredPropertiesIterator()); + self::assertInstanceOf(Mapping\OneToOneAssociationMetadata::class, $cm->getProperty('phonenumbers')); + + $oneOneMapping = $cm->getProperty('phonenumbers'); + + self::assertEquals(Mapping\FetchMode::LAZY, $oneOneMapping->getFetchMode()); + self::assertEquals(CMS\CmsAddress::class, $oneOneMapping->getTargetEntity()); } public function testFieldIsNullable() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $metadata = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $metadata->setTable(new Mapping\TableMetadata('cms_users')); // Explicit Nullable - $cm->mapField(['fieldName' => 'status', 'nullable' => true, 'type' => 'string', 'length' => 50]); - $this->assertTrue($cm->isNullable('status')); + $fieldMetadata = new Mapping\FieldMetadata('status'); + + $fieldMetadata->setType(Type::getType('string')); + $fieldMetadata->setLength(50); + $fieldMetadata->setNullable(true); + + $metadata->addProperty($fieldMetadata); + + $property = $metadata->getProperty('status'); + + self::assertTrue($property->isNullable()); // Explicit Not Nullable - $cm->mapField(['fieldName' => 'username', 'nullable' => false, 'type' => 'string', 'length' => 50]); - $this->assertFalse($cm->isNullable('username')); + $fieldMetadata = new Mapping\FieldMetadata('username'); + + $fieldMetadata->setType(Type::getType('string')); + $fieldMetadata->setLength(50); + $fieldMetadata->setNullable(false); + + $metadata->addProperty($fieldMetadata); + + $property = $metadata->getProperty('username'); + + self::assertFalse($property->isNullable()); // Implicit Not Nullable - $cm->mapField(['fieldName' => 'name', 'type' => 'string', 'length' => 50]); - $this->assertFalse($cm->isNullable('name'), "By default a field should not be nullable."); + $fieldMetadata = new Mapping\FieldMetadata('name'); + + $fieldMetadata->setType(Type::getType('string')); + $fieldMetadata->setLength(50); + + $metadata->addProperty($fieldMetadata); + + $property = $metadata->getProperty('name'); + + self::assertFalse($property->isNullable(), "By default a field should not be nullable."); } /** @@ -99,60 +181,93 @@ public function testMapAssociationInGlobalNamespace() { require_once __DIR__."/../../Models/Global/GlobalNamespaceModel.php"; - $cm = new ClassMetadata('DoctrineGlobal_Article'); - $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapManyToMany( - [ - 'fieldName' => 'author', - 'targetEntity' => 'DoctrineGlobal_User', - 'joinTable' => [ - 'name' => 'bar', - 'joinColumns' => [['name' => 'bar_id', 'referencedColumnName' => 'id']], - 'inverseJoinColumns' => [['name' => 'baz_id', 'referencedColumnName' => 'id']], - ], - ] - ); + $cm = new ClassMetadata(DoctrineGlobal_Article::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('doctrine_global_article')); + + $joinTable = new Mapping\JoinTableMetadata(); + $joinTable->setName('bar'); + + $joinColumn = new Mapping\JoinColumnMetadata(); + $joinColumn->setColumnName("bar_id"); + $joinColumn->setReferencedColumnName("id"); + + $joinTable->addJoinColumn($joinColumn); + + $joinColumn = new Mapping\JoinColumnMetadata(); + $joinColumn->setColumnName("baz_id"); + $joinColumn->setReferencedColumnName("id"); + + $joinTable->addInverseJoinColumn($joinColumn); + + $association = new Mapping\ManyToManyAssociationMetadata('author'); + + $association->setJoinTable($joinTable); + $association->setTargetEntity('DoctrineGlobal_User'); + + $cm->addProperty($association); - $this->assertEquals("DoctrineGlobal_User", $cm->associationMappings['author']['targetEntity']); + self::assertEquals("DoctrineGlobal_User", $cm->getProperty('author')->getTargetEntity()); } public function testMapManyToManyJoinTableDefaults() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapManyToMany( - [ - 'fieldName' => 'groups', - 'targetEntity' => 'CmsGroup' - ] - ); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); - $assoc = $cm->associationMappings['groups']; - $this->assertEquals( - [ - 'name' => 'cmsuser_cmsgroup', - 'joinColumns' => [['name' => 'cmsuser_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE']], - 'inverseJoinColumns' => [['name' => 'cmsgroup_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE']] - ], $assoc['joinTable']); - $this->assertTrue($assoc['isOnDeleteCascade']); + $association = new Mapping\ManyToManyAssociationMetadata('groups'); + + $association->setTargetEntity(CMS\CmsGroup::class); + + $cm->addProperty($association); + + $association = $cm->getProperty('groups'); + + $joinColumns = []; + + $joinColumn = new Mapping\JoinColumnMetadata(); + + $joinColumn->setColumnName("cmsuser_id"); + $joinColumn->setReferencedColumnName("id"); + $joinColumn->setOnDelete("CASCADE"); + + $joinColumns[] = $joinColumn; + + $inverseJoinColumns = []; + + $joinColumn = new Mapping\JoinColumnMetadata(); + + $joinColumn->setColumnName("cmsgroup_id"); + $joinColumn->setReferencedColumnName("id"); + $joinColumn->setOnDelete("CASCADE"); + + $inverseJoinColumns[] = $joinColumn; + + $joinTable = $association->getJoinTable(); + + self::assertEquals('cmsuser_cmsgroup', $joinTable->getName()); + self::assertEquals($joinColumns, $joinTable->getJoinColumns()); + self::assertEquals($inverseJoinColumns, $joinTable->getInverseJoinColumns()); } public function testSerializeManyToManyJoinTableCascade() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapManyToMany( - [ - 'fieldName' => 'groups', - 'targetEntity' => 'CmsGroup' - ] - ); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); - /* @var $assoc \Doctrine\ORM\Mapping\ManyToMany */ - $assoc = $cm->associationMappings['groups']; - $assoc = unserialize(serialize($assoc)); + $association = new Mapping\ManyToManyAssociationMetadata('groups'); - $this->assertTrue($assoc['isOnDeleteCascade']); + $association->setTargetEntity(CMS\CmsGroup::class); + + $cm->addProperty($association); + + $association = $cm->getProperty('groups'); + $association = unserialize(serialize($association)); + + $joinTable = $association->getJoinTable(); + + foreach ($joinTable->getJoinColumns() as $joinColumn) { + self::assertEquals('CASCADE', $joinColumn->getOnDelete()); + } } /** @@ -162,12 +277,13 @@ public function testSetDiscriminatorMapInGlobalNamespace() { require_once __DIR__."/../../Models/Global/GlobalNamespaceModel.php"; - $cm = new ClassMetadata('DoctrineGlobal_User'); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata('DoctrineGlobal_User', $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('doctrine_global_user')); + $cm->setDiscriminatorMap(['descr' => 'DoctrineGlobal_Article', 'foo' => 'DoctrineGlobal_User']); - $this->assertEquals("DoctrineGlobal_Article", $cm->discriminatorMap['descr']); - $this->assertEquals("DoctrineGlobal_User", $cm->discriminatorMap['foo']); + self::assertEquals("DoctrineGlobal_Article", $cm->discriminatorMap['descr']); + self::assertEquals("DoctrineGlobal_User", $cm->discriminatorMap['foo']); } /** @@ -177,11 +293,12 @@ public function testSetSubClassesInGlobalNamespace() { require_once __DIR__."/../../Models/Global/GlobalNamespaceModel.php"; - $cm = new ClassMetadata('DoctrineGlobal_User'); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata('DoctrineGlobal_User', $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('doctrine_global_user')); + $cm->setSubclasses(['DoctrineGlobal_Article']); - $this->assertEquals("DoctrineGlobal_Article", $cm->subClasses[0]); + self::assertEquals("DoctrineGlobal_Article", $cm->getSubClasses()[0]); } /** @@ -189,102 +306,181 @@ public function testSetSubClassesInGlobalNamespace() */ public function testSetInvalidVersionMapping_ThrowsException() { - $field = []; - $field['fieldName'] = 'foo'; - $field['type'] = 'string'; + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $property = new Mapping\VersionFieldMetadata('foo'); - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $cm->setVersionMapping($field); + $property->setDeclaringClass($cm); + $property->setColumnName('foo'); + $property->setType(Type::getType('string')); + + $this->expectException(MappingException::class); + + $cm->addProperty($property); } public function testGetSingleIdentifierFieldName_MultipleIdentifierEntity_ThrowsException() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); - $cm->isIdentifierComposite = true; + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); + + $fieldMetadata = new Mapping\FieldMetadata('name'); + $fieldMetadata->setType(Type::getType('string')); + + $cm->addProperty($fieldMetadata); + + $fieldMetadata = new Mapping\FieldMetadata('username'); + $fieldMetadata->setType(Type::getType('string')); + + $cm->addProperty($fieldMetadata); + + $cm->setIdentifier(['name', 'username']); + + $this->expectException(MappingException::class); - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); $cm->getSingleIdentifierFieldName(); } public function testGetSingleIdentifierFieldName_NoIdEntity_ThrowsException() { - $cm = new ClassMetadata(DDC6412File::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(DDC6412File::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('ddc6412_file')); $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $cm->getSingleIdentifierFieldName(); } public function testDuplicateAssociationMappingException() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); - $a1 = ['fieldName' => 'foo', 'sourceEntity' => 'stdClass', 'targetEntity' => 'stdClass', 'mappedBy' => 'foo']; - $a2 = ['fieldName' => 'foo', 'sourceEntity' => 'stdClass', 'targetEntity' => 'stdClass', 'mappedBy' => 'foo']; + $association = new Mapping\OneToOneAssociationMetadata('foo'); - $cm->addInheritedAssociationMapping($a1); - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $cm->addInheritedAssociationMapping($a2); + $association->setDeclaringClass($cm); + $association->setSourceEntity(\stdClass::class); + $association->setTargetEntity(\stdClass::class); + $association->setMappedBy('foo'); + + $cm->addInheritedProperty($association); + + $this->expectException(MappingException::class); + + $association = new Mapping\OneToOneAssociationMetadata('foo'); + + $association->setDeclaringClass($cm); + $association->setSourceEntity(\stdClass::class); + $association->setTargetEntity(\stdClass::class); + $association->setMappedBy('foo'); + + $cm->addInheritedProperty($association); } public function testDuplicateColumnName_ThrowsMappingException() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); - $cm->mapField(['fieldName' => 'name', 'columnName' => 'name']); + $fieldMetadata = new Mapping\FieldMetadata('name'); - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $cm->mapField(['fieldName' => 'username', 'columnName' => 'name']); + $fieldMetadata->setType(Type::getType('string')); + + $cm->addProperty($fieldMetadata); + + $this->expectException(MappingException::class); + + $fieldMetadata = new Mapping\FieldMetadata('username'); + + $fieldMetadata->setType(Type::getType('string')); + $fieldMetadata->setColumnName('name'); + + $cm->addProperty($fieldMetadata); } public function testDuplicateColumnName_DiscriminatorColumn_ThrowsMappingException() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); + + $fieldMetadata = new Mapping\FieldMetadata('name'); + + $fieldMetadata->setType(Type::getType('string')); + + $cm->addProperty($fieldMetadata); - $cm->mapField(['fieldName' => 'name', 'columnName' => 'name']); + $discrColumn = new DiscriminatorColumnMetadata(); + + $discrColumn->setColumnName('name'); + $discrColumn->setType(Type::getType('string')); + $discrColumn->setLength(255); $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $cm->setDiscriminatorColumn(['name' => 'name']); + + $cm->setDiscriminatorColumn($discrColumn); } public function testDuplicateColumnName_DiscriminatorColumn2_ThrowsMappingException() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); + + $discrColumn = new DiscriminatorColumnMetadata(); - $cm->setDiscriminatorColumn(['name' => 'name']); + $discrColumn->setColumnName('name'); + $discrColumn->setType(Type::getType('string')); + $discrColumn->setLength(255); + + $cm->setDiscriminatorColumn($discrColumn); $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $cm->mapField(['fieldName' => 'name', 'columnName' => 'name']); + + $fieldMetadata = new Mapping\FieldMetadata('name'); + + $fieldMetadata->setType(Type::getType('string')); + + $cm->addProperty($fieldMetadata); } public function testDuplicateFieldAndAssociationMapping1_ThrowsException() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); + + $fieldMetadata = new Mapping\FieldMetadata('name'); - $cm->mapField(['fieldName' => 'name', 'columnName' => 'name']); + $fieldMetadata->setType(Type::getType('string')); + + $cm->addProperty($fieldMetadata); $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $cm->mapOneToOne(['fieldName' => 'name', 'targetEntity' => 'CmsUser']); + + $association = new Mapping\OneToOneAssociationMetadata('name'); + + $association->setTargetEntity(CMS\CmsUser::class); + + $cm->addProperty($association); } public function testDuplicateFieldAndAssociationMapping2_ThrowsException() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); + + $association = new Mapping\OneToOneAssociationMetadata('name'); - $cm->mapOneToOne(['fieldName' => 'name', 'targetEntity' => 'CmsUser']); + $association->setTargetEntity(CMS\CmsUser::class); + + $cm->addProperty($association); $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $cm->mapField(['fieldName' => 'name', 'columnName' => 'name']); + + $fieldMetadata = new Mapping\FieldMetadata('name'); + + $fieldMetadata->setType(Type::getType('string')); + + $cm->addProperty($fieldMetadata); } /** @@ -292,124 +488,197 @@ public function testDuplicateFieldAndAssociationMapping2_ThrowsException() */ public function testGetTemporaryTableNameSchema() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); + + $tableMetadata = new Mapping\TableMetadata(); + + $tableMetadata->setSchema('foo'); + $tableMetadata->setName('bar'); - $cm->setTableName('foo.bar'); + $cm->setTable($tableMetadata); - $this->assertEquals('foo_bar_id_tmp', $cm->getTemporaryIdTableName()); + self::assertEquals('foo_bar_id_tmp', $cm->getTemporaryIdTableName()); } public function testDefaultTableName() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('CmsUser')); // When table's name is not given - $primaryTable = []; - $cm->setPrimaryTable($primaryTable); + self::assertEquals('CmsUser', $cm->getTableName()); + self::assertEquals('CmsUser', $cm->table->getName()); - $this->assertEquals('CmsUser', $cm->getTableName()); - $this->assertEquals('CmsUser', $cm->table['name']); + $cm = new ClassMetadata(CMS\CmsAddress::class, $this->metadataBuildingContext); - $cm = new ClassMetadata(CMS\CmsAddress::class); - $cm->initializeReflection(new RuntimeReflectionService()); // When joinTable's name is not given - $cm->mapManyToMany( - [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser', - 'inversedBy' => 'users', - 'joinTable' => [ - 'joinColumns' => [['referencedColumnName' => 'id']], - 'inverseJoinColumns' => [['referencedColumnName' => 'id']] - ] - ] - ); - $this->assertEquals('cmsaddress_cmsuser', $cm->associationMappings['user']['joinTable']['name']); + $joinTable = new Mapping\JoinTableMetadata(); + + $joinColumn = new Mapping\JoinColumnMetadata(); + $joinColumn->setReferencedColumnName("id"); + + $joinTable->addJoinColumn($joinColumn); + + $joinColumn = new Mapping\JoinColumnMetadata(); + $joinColumn->setReferencedColumnName("id"); + + $joinTable->addInverseJoinColumn($joinColumn); + + $association = new Mapping\ManyToManyAssociationMetadata('user'); + + $association->setJoinTable($joinTable); + $association->setTargetEntity(CMS\CmsUser::class); + $association->setInversedBy('users'); + + $cm->addProperty($association); + + $association = $cm->getProperty('user'); + + self::assertEquals('cmsaddress_cmsuser', $association->getJoinTable()->getName()); } public function testDefaultJoinColumnName() { - $cm = new ClassMetadata(CMS\CmsAddress::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsAddress::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_address')); // this is really dirty, but it's the simplest way to test whether // joinColumn's name will be automatically set to user_id - $cm->mapOneToOne( - [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser', - 'joinColumns' => [['referencedColumnName' => 'id']] - ] - ); - $this->assertEquals('user_id', $cm->associationMappings['user']['joinColumns'][0]['name']); + $joinColumns = []; - $cm = new ClassMetadata(CMS\CmsAddress::class); - $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapManyToMany( - [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser', - 'inversedBy' => 'users', - 'joinTable' => [ - 'name' => 'user_CmsUser', - 'joinColumns' => [['referencedColumnName' => 'id']], - 'inverseJoinColumns' => [['referencedColumnName' => 'id']] - ] - ] - ); - $this->assertEquals('cmsaddress_id', $cm->associationMappings['user']['joinTable']['joinColumns'][0]['name']); - $this->assertEquals('cmsuser_id', $cm->associationMappings['user']['joinTable']['inverseJoinColumns'][0]['name']); + $joinColumn = new JoinColumnMetadata(); + + $joinColumn->setReferencedColumnName('id'); + + $joinColumns[] = $joinColumn; + + $association = new Mapping\OneToOneAssociationMetadata('user'); + + $association->setJoinColumns($joinColumns); + $association->setTargetEntity(CMS\CmsUser::class); + + $cm->addProperty($association); + + $association = $cm->getProperty('user'); + $joinColumns = $association->getJoinColumns(); + $joinColumn = reset($joinColumns); + + self::assertEquals('user_id', $joinColumn->getColumnName()); + + $cm = new ClassMetadata(CMS\CmsAddress::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_address')); + + $joinTable = new Mapping\JoinTableMetadata(); + $joinTable->setName('user_CmsUser'); + + $joinColumn = new JoinColumnMetadata(); + $joinColumn->setReferencedColumnName('id'); + + $joinTable->addJoinColumn($joinColumn); + + $joinColumn = new JoinColumnMetadata(); + $joinColumn->setReferencedColumnName('id'); + + $joinTable->addInverseJoinColumn($joinColumn); + + $association = new Mapping\ManyToManyAssociationMetadata('user'); + + $association->setJoinTable($joinTable); + $association->setTargetEntity(CMS\CmsUser::class); + $association->setInversedBy('users'); + + $cm->addProperty($association); + + $association = $cm->getProperty('user'); + $joinTable = $association->getJoinTable(); + $joinColumns = $joinTable->getJoinColumns(); + $joinColumn = reset($joinColumns); + $inverseJoinColumns = $joinTable->getInverseJoinColumns(); + $inverseJoinColumn = reset($inverseJoinColumns); + + self::assertEquals('cmsaddress_id', $joinColumn->getColumnName()); + self::assertEquals('cmsuser_id', $inverseJoinColumn->getColumnName()); } /** * @group DDC-559 */ - public function testUnderscoreNamingStrategyDefaults() + public function testOneToOneUnderscoreNamingStrategyDefaults() { - $namingStrategy = new UnderscoreNamingStrategy(CASE_UPPER); - $oneToOneMetadata = new ClassMetadata(CMS\CmsAddress::class, $namingStrategy); - $manyToManyMetadata = new ClassMetadata(CMS\CmsAddress::class, $namingStrategy); + $namingStrategy = new UnderscoreNamingStrategy(CASE_UPPER); - $oneToOneMetadata->mapOneToOne( - [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser' - ] + $this->metadataBuildingContext = new Mapping\ClassMetadataBuildingContext( + $this->createMock(Mapping\ClassMetadataFactory::class), + new RuntimeReflectionService(), + $namingStrategy ); - $manyToManyMetadata->mapManyToMany( - [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser' - ] + $metadata = new ClassMetadata(CMS\CmsAddress::class, $this->metadataBuildingContext); + $metadata->setTable(new Mapping\TableMetadata('cms_address')); + + $association = new Mapping\OneToOneAssociationMetadata('user'); + + $association->setTargetEntity(CMS\CmsUser::class); + + $metadata->addProperty($association); + + $association = $metadata->getProperty('user'); + $joinColumns = $association->getJoinColumns(); + $joinColumn = reset($joinColumns); + + self::assertEquals('USER_ID', $joinColumn->getColumnName()); + self::assertEquals('ID', $joinColumn->getReferencedColumnName()); + } + + /** + * @group DDC-559 + */ + public function testManyToManyUnderscoreNamingStrategyDefaults() + { + $namingStrategy = new UnderscoreNamingStrategy(CASE_UPPER); + + $this->metadataBuildingContext = new Mapping\ClassMetadataBuildingContext( + $this->createMock(Mapping\ClassMetadataFactory::class), + new RuntimeReflectionService(), + $namingStrategy ); - $this->assertEquals(['USER_ID'=>'ID'], $oneToOneMetadata->associationMappings['user']['sourceToTargetKeyColumns']); - $this->assertEquals(['USER_ID'=>'USER_ID'], $oneToOneMetadata->associationMappings['user']['joinColumnFieldNames']); - $this->assertEquals(['ID'=>'USER_ID'], $oneToOneMetadata->associationMappings['user']['targetToSourceKeyColumns']); + $metadata = new ClassMetadata(CMS\CmsAddress::class, $this->metadataBuildingContext); + $metadata->setTable(new Mapping\TableMetadata('cms_address')); + + $association = new Mapping\ManyToManyAssociationMetadata('user'); + + $association->setTargetEntity(CMS\CmsUser::class); + + $metadata->addProperty($association); - $this->assertEquals('USER_ID', $oneToOneMetadata->associationMappings['user']['joinColumns'][0]['name']); - $this->assertEquals('ID', $oneToOneMetadata->associationMappings['user']['joinColumns'][0]['referencedColumnName']); + $association = $metadata->getProperty('user'); + $joinTable = $association->getJoinTable(); + $joinColumns = $joinTable->getJoinColumns(); + $joinColumn = reset($joinColumns); + $inverseJoinColumns = $joinTable->getInverseJoinColumns(); + $inverseJoinColumn = reset($inverseJoinColumns); + self::assertEquals('CMS_ADDRESS_CMS_USER', $joinTable->getName()); - $this->assertEquals('CMS_ADDRESS_CMS_USER', $manyToManyMetadata->associationMappings['user']['joinTable']['name']); + self::assertEquals('CMS_ADDRESS_ID', $joinColumn->getColumnName()); + self::assertEquals('ID', $joinColumn->getReferencedColumnName()); - $this->assertEquals(['CMS_ADDRESS_ID','CMS_USER_ID'], $manyToManyMetadata->associationMappings['user']['joinTableColumns']); - $this->assertEquals(['CMS_ADDRESS_ID'=>'ID'], $manyToManyMetadata->associationMappings['user']['relationToSourceKeyColumns']); - $this->assertEquals(['CMS_USER_ID'=>'ID'], $manyToManyMetadata->associationMappings['user']['relationToTargetKeyColumns']); + self::assertEquals('CMS_USER_ID', $inverseJoinColumn->getColumnName()); + self::assertEquals('ID', $inverseJoinColumn->getReferencedColumnName()); - $this->assertEquals('CMS_ADDRESS_ID', $manyToManyMetadata->associationMappings['user']['joinTable']['joinColumns'][0]['name']); - $this->assertEquals('CMS_USER_ID', $manyToManyMetadata->associationMappings['user']['joinTable']['inverseJoinColumns'][0]['name']); + $cm = new ClassMetadata('DoctrineGlobal_Article', $this->metadataBuildingContext); - $this->assertEquals('ID', $manyToManyMetadata->associationMappings['user']['joinTable']['joinColumns'][0]['referencedColumnName']); - $this->assertEquals('ID', $manyToManyMetadata->associationMappings['user']['joinTable']['inverseJoinColumns'][0]['referencedColumnName']); + $association = new Mapping\ManyToManyAssociationMetadata('author'); + $association->setTargetEntity(CMS\CmsUser::class); - $cm = new ClassMetadata('DoctrineGlobal_Article', $namingStrategy); - $cm->mapManyToMany(['fieldName' => 'author', 'targetEntity' => CMS\CmsUser::class]); - $this->assertEquals('DOCTRINE_GLOBAL_ARTICLE_CMS_USER', $cm->associationMappings['author']['joinTable']['name']); + $cm->addProperty($association); + + $association = $cm->getProperty('author'); + + self::assertEquals('DOCTRINE_GLOBAL_ARTICLE_CMS_USER', $association->getJoinTable()->getName()); } /** @@ -417,28 +686,22 @@ public function testUnderscoreNamingStrategyDefaults() */ public function testSetMultipleIdentifierSetsComposite() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); - $cm->mapField(['fieldName' => 'name']); - $cm->mapField(['fieldName' => 'username']); + $fieldMetadata = new Mapping\FieldMetadata('name'); + $fieldMetadata->setType(Type::getType('string')); - $cm->setIdentifier(['name', 'username']); - $this->assertTrue($cm->isIdentifierComposite); - } + $cm->addProperty($fieldMetadata); - /** - * @group DDC-944 - */ - public function testMappingNotFound() - { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $fieldMetadata = new Mapping\FieldMetadata('username'); + $fieldMetadata->setType(Type::getType('string')); - $this->expectException(MappingException::class); - $this->expectExceptionMessage("No mapping found for field 'foo' on class '" . CMS\CmsUser::class . "'."); + $cm->addProperty($fieldMetadata); + + $cm->setIdentifier(['name', 'username']); - $cm->getFieldMapping('foo'); + self::assertTrue($cm->isIdentifierComposite()); } /** @@ -446,12 +709,17 @@ public function testMappingNotFound() */ public function testJoinTableMappingDefaults() { - $cm = new ClassMetadata('DoctrineGlobal_Article'); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata('DoctrineGlobal_Article', $this->metadataBuildingContext); + + $association = new Mapping\ManyToManyAssociationMetadata('author'); + + $association->setTargetEntity(CMS\CmsUser::class); - $cm->mapManyToMany(['fieldName' => 'author', 'targetEntity' => CMS\CmsUser::class]); + $cm->addProperty($association); - $this->assertEquals('doctrineglobal_article_cmsuser', $cm->associationMappings['author']['joinTable']['name']); + $association = $cm->getProperty('author'); + + self::assertEquals('doctrineglobal_article_cmsuser', $association->getJoinTable()->getName()); } /** @@ -459,20 +727,17 @@ public function testJoinTableMappingDefaults() */ public function testMapIdentifierAssociation() { - $cm = new ClassMetadata(DDC117ArticleDetails::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(DDC117ArticleDetails::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata("ddc117_article_details")); - $cm->mapOneToOne( - [ - 'fieldName' => 'article', - 'id' => true, - 'targetEntity' => DDC117Article::class, - 'joinColumns' => [], - ] - ); + $association = new Mapping\OneToOneAssociationMetadata('article'); + + $association->setTargetEntity(DDC117Article::class); + $association->setPrimaryKey(true); + + $cm->addProperty($association); - $this->assertTrue($cm->containsForeignIdentifier, "Identifier Association should set 'containsForeignIdentifier' boolean flag."); - $this->assertEquals(["article"], $cm->identifier); + self::assertEquals(["article"], $cm->identifier); } /** @@ -480,21 +745,19 @@ public function testMapIdentifierAssociation() */ public function testOrphanRemovalIdentifierAssociation() { - $cm = new ClassMetadata(DDC117ArticleDetails::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(DDC117ArticleDetails::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata("ddc117_article_details")); $this->expectException(MappingException::class); $this->expectExceptionMessage('The orphan removal option is not allowed on an association that'); - $cm->mapOneToOne( - [ - 'fieldName' => 'article', - 'id' => true, - 'targetEntity' => DDC117Article::class, - 'orphanRemoval' => true, - 'joinColumns' => [], - ] - ); + $association = new Mapping\OneToOneAssociationMetadata('article'); + + $association->setTargetEntity(DDC117Article::class); + $association->setPrimaryKey(true); + $association->setOrphanRemoval(true); + + $cm->addProperty($association); } /** @@ -502,21 +765,19 @@ public function testOrphanRemovalIdentifierAssociation() */ public function testInverseIdentifierAssociation() { - $cm = new ClassMetadata(DDC117ArticleDetails::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(DDC117ArticleDetails::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata("ddc117_article_details")); $this->expectException(MappingException::class); $this->expectExceptionMessage('An inverse association is not allowed to be identifier in'); - $cm->mapOneToOne( - [ - 'fieldName' => 'article', - 'id' => true, - 'mappedBy' => 'details', // INVERSE! - 'targetEntity' => DDC117Article::class, - 'joinColumns' => [], - ] - ); + $association = new Mapping\OneToOneAssociationMetadata('article'); + + $association->setTargetEntity(DDC117Article::class); + $association->setPrimaryKey(true); + $association->setMappedBy('details'); + + $cm->addProperty($association); } /** @@ -524,20 +785,18 @@ public function testInverseIdentifierAssociation() */ public function testIdentifierAssociationManyToMany() { - $cm = new ClassMetadata(DDC117ArticleDetails::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(DDC117ArticleDetails::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata("ddc117_article_details")); $this->expectException(MappingException::class); $this->expectExceptionMessage('Many-to-many or one-to-many associations are not allowed to be identifier in'); - $cm->mapManyToMany( - [ - 'fieldName' => 'article', - 'id' => true, - 'targetEntity' => DDC117Article::class, - 'joinColumns' => [], - ] - ); + $association = new Mapping\ManyToManyAssociationMetadata('article'); + + $association->setTargetEntity(DDC117Article::class); + $association->setPrimaryKey(true); + + $cm->addProperty($association); } /** @@ -548,28 +807,26 @@ public function testEmptyFieldNameThrowsException() $this->expectException(MappingException::class); $this->expectExceptionMessage("The field or association mapping misses the 'fieldName' attribute in entity '" . CMS\CmsUser::class . "'."); - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); + + $fieldMetadata = new Mapping\FieldMetadata(''); + + $fieldMetadata->setType(Type::getType('string')); - $cm->mapField(['fieldName' => '']); + $cm->addProperty($fieldMetadata); } public function testRetrievalOfNamedQueries() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); + self::assertEquals(0, count($cm->getNamedQueries())); - $this->assertEquals(0, count($cm->getNamedQueries())); + $cm->addNamedQuery('userById', 'SELECT u FROM __CLASS__ u WHERE u.id = ?1'); - $cm->addNamedQuery( - [ - 'name' => 'userById', - 'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1' - ] - ); - - $this->assertEquals(1, count($cm->getNamedQueries())); + self::assertEquals(1, count($cm->getNamedQueries())); } /** @@ -577,11 +834,9 @@ public function testRetrievalOfNamedQueries() */ public function testRetrievalOfResultSetMappings() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); - + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); - $this->assertEquals(0, count($cm->getSqlResultSetMappings())); + self::assertEquals(0, count($cm->getSqlResultSetMappings())); $cm->addSqlResultSetMapping( [ @@ -594,24 +849,18 @@ public function testRetrievalOfResultSetMappings() ] ); - $this->assertEquals(1, count($cm->getSqlResultSetMappings())); + self::assertEquals(1, count($cm->getSqlResultSetMappings())); } public function testExistanceOfNamedQuery() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); - + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); - $cm->addNamedQuery( - [ - 'name' => 'all', - 'query' => 'SELECT u FROM __CLASS__ u' - ] - ); + $cm->addNamedQuery('all', 'SELECT u FROM __CLASS__ u'); - $this->assertTrue($cm->hasNamedQuery('all')); - $this->assertFalse($cm->hasNamedQuery('userById')); + self::assertTrue($cm->hasNamedQuery('all')); + self::assertFalse($cm->hasNamedQuery('userById')); } /** @@ -619,36 +868,38 @@ public function testExistanceOfNamedQuery() */ public function testRetrieveOfNamedNativeQuery() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); $cm->addNamedNativeQuery( + 'find-all', + 'SELECT * FROM cms_users', [ - 'name' => 'find-all', - 'query' => 'SELECT * FROM cms_users', - 'resultSetMapping' => 'result-mapping-name', - 'resultClass' => CMS\CmsUser::class, + 'resultSetMapping' => 'result-mapping-name', + 'resultClass' => CMS\CmsUser::class, ] ); $cm->addNamedNativeQuery( + 'find-by-id', + 'SELECT * FROM cms_users WHERE id = ?', [ - 'name' => 'find-by-id', - 'query' => 'SELECT * FROM cms_users WHERE id = ?', - 'resultClass' => '__CLASS__', - 'resultSetMapping' => 'result-mapping-name', + 'resultClass' => '__CLASS__', + 'resultSetMapping' => 'result-mapping-name', ] ); $mapping = $cm->getNamedNativeQuery('find-all'); - $this->assertEquals('SELECT * FROM cms_users', $mapping['query']); - $this->assertEquals('result-mapping-name', $mapping['resultSetMapping']); - $this->assertEquals(CMS\CmsUser::class, $mapping['resultClass']); + + self::assertEquals('SELECT * FROM cms_users', $mapping['query']); + self::assertEquals('result-mapping-name', $mapping['resultSetMapping']); + self::assertEquals(CMS\CmsUser::class, $mapping['resultClass']); $mapping = $cm->getNamedNativeQuery('find-by-id'); - $this->assertEquals('SELECT * FROM cms_users WHERE id = ?', $mapping['query']); - $this->assertEquals('result-mapping-name', $mapping['resultSetMapping']); - $this->assertEquals(CMS\CmsUser::class, $mapping['resultClass']); + + self::assertEquals('SELECT * FROM cms_users WHERE id = ?', $mapping['query']); + self::assertEquals('result-mapping-name', $mapping['resultSetMapping']); + self::assertEquals('__CLASS__', $mapping['resultClass']); } /** @@ -656,59 +907,103 @@ public function testRetrieveOfNamedNativeQuery() */ public function testRetrieveOfSqlResultSetMapping() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); $cm->addSqlResultSetMapping( [ - 'name' => 'find-all', - 'entities' => [ - [ - 'entityClass' => '__CLASS__', - 'fields' => [ - [ - 'name' => 'id', - 'column'=> 'id' - ], - [ - 'name' => 'name', - 'column'=> 'name' + 'name' => 'find-all', + 'entities' => [ + [ + 'entityClass' => '__CLASS__', + 'fields' => [ + [ + 'name' => 'id', + 'column'=> 'id' + ], + [ + 'name' => 'name', + 'column'=> 'name' + ] ] - ] - ], - [ - 'entityClass' => CMS\CmsEmail::class, - 'fields' => [ - [ - 'name' => 'id', - 'column'=> 'id' - ], - [ - 'name' => 'email', - 'column'=> 'email' + ], + [ + 'entityClass' => CMS\CmsEmail::class, + 'fields' => [ + [ + 'name' => 'id', + 'column'=> 'id' + ], + [ + 'name' => 'email', + 'column'=> 'email' + ] ] ] - ] - ], - 'columns' => [ - [ - 'name' => 'scalarColumn' - ] - ] + ], + 'columns' => [['name' => 'scalarColumn']] ] ); $mapping = $cm->getSqlResultSetMapping('find-all'); - $this->assertEquals(CMS\CmsUser::class, $mapping['entities'][0]['entityClass']); - $this->assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][0]['fields'][0]); - $this->assertEquals(['name'=>'name','column'=>'name'], $mapping['entities'][0]['fields'][1]); + self::assertEquals('__CLASS__', $mapping['entities'][0]['entityClass']); + self::assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][0]['fields'][0]); + self::assertEquals(['name'=>'name','column'=>'name'], $mapping['entities'][0]['fields'][1]); + + self::assertEquals(CMS\CmsEmail::class, $mapping['entities'][1]['entityClass']); + self::assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][1]['fields'][0]); + self::assertEquals(['name'=>'email','column'=>'email'], $mapping['entities'][1]['fields'][1]); + + self::assertEquals('scalarColumn', $mapping['columns'][0]['name']); + } + + /** + * @expectedException \Doctrine\ORM\Mapping\MappingException + * @expectedExceptionMessage Entity 'Doctrine\Tests\Models\ValueGenerators\DummyWithThreeProperties' has a composite identifier with with an Identity strategy. This is not supported. + */ + public function testCompositeIdentifierWithIdentityValueGenerator() : void + { + $classMetadata = new ClassMetadata(DummyWithThreeProperties::class, $this->metadataBuildingContext); + $classMetadata->setTable(new Mapping\TableMetadata()); + + $fooMetadata = new Mapping\FieldMetadata('a'); + $fooMetadata->setType(Type::getType(Type::INTEGER)); + $fooMetadata->setPrimaryKey(true); + $fooMetadata->setValueGenerator(new Mapping\ValueGeneratorMetadata(Mapping\GeneratorType::NONE)); + $classMetadata->addProperty($fooMetadata); - $this->assertEquals(CMS\CmsEmail::class, $mapping['entities'][1]['entityClass']); - $this->assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][1]['fields'][0]); - $this->assertEquals(['name'=>'email','column'=>'email'], $mapping['entities'][1]['fields'][1]); + $barMetadata = new Mapping\FieldMetadata('b'); + $barMetadata->setType(Type::getType(Type::INTEGER)); + $barMetadata->setPrimaryKey(true); + $barMetadata->setValueGenerator(new Mapping\ValueGeneratorMetadata(Mapping\GeneratorType::IDENTITY)); + $classMetadata->addProperty($barMetadata); - $this->assertEquals('scalarColumn', $mapping['columns'][0]['name']); + $classMetadata->validateValueGenerators(); + } + + /** + * @expectedException \Doctrine\ORM\Mapping\MappingException + * @expectedExceptionMessage Entity 'Doctrine\Tests\Models\ValueGenerators\DummyWithThreeProperties' has a an Identity strategy defined on a non-primary field. This is not supported. + */ + public function testNonPrimaryIdentityValueGenerator() : void + { + $classMetadata = new ClassMetadata(DummyWithThreeProperties::class, $this->metadataBuildingContext); + $classMetadata->setTable(new Mapping\TableMetadata()); + + $fooMetadata = new Mapping\FieldMetadata('a'); + $fooMetadata->setType(Type::getType(Type::INTEGER)); + $fooMetadata->setPrimaryKey(true); + $fooMetadata->setValueGenerator(new Mapping\ValueGeneratorMetadata(Mapping\GeneratorType::NONE)); + $classMetadata->addProperty($fooMetadata); + + $barMetadata = new Mapping\FieldMetadata('b'); + $barMetadata->setType(Type::getType(Type::INTEGER)); + $barMetadata->setPrimaryKey(false); + $barMetadata->setValueGenerator(new Mapping\ValueGeneratorMetadata(Mapping\GeneratorType::IDENTITY)); + $classMetadata->addProperty($barMetadata); + + $classMetadata->validateValueGenerators(); } /** @@ -716,22 +1011,22 @@ public function testRetrieveOfSqlResultSetMapping() */ public function testExistanceOfSqlResultSetMapping() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); $cm->addSqlResultSetMapping( [ - 'name' => 'find-all', - 'entities' => [ - [ - 'entityClass' => CMS\CmsUser::class, + 'name' => 'find-all', + 'entities' => [ + [ + 'entityClass' => CMS\CmsUser::class, + ], ], - ], ] ); - $this->assertTrue($cm->hasSqlResultSetMapping('find-all')); - $this->assertFalse($cm->hasSqlResultSetMapping('find-by-id')); + self::assertTrue($cm->hasSqlResultSetMapping('find-all')); + self::assertFalse($cm->hasSqlResultSetMapping('find-by-id')); } /** @@ -739,37 +1034,34 @@ public function testExistanceOfSqlResultSetMapping() */ public function testExistanceOfNamedNativeQuery() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); - + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); $cm->addNamedNativeQuery( + 'find-all', + 'SELECT * FROM cms_users', [ - 'name' => 'find-all', - 'query' => 'SELECT * FROM cms_users', - 'resultClass' => CMS\CmsUser::class, - 'resultSetMapping' => 'result-mapping-name' + 'resultClass' => CMS\CmsUser::class, ] ); - $this->assertTrue($cm->hasNamedNativeQuery('find-all')); - $this->assertFalse($cm->hasNamedNativeQuery('find-by-id')); + self::assertTrue($cm->hasNamedNativeQuery('find-all')); + self::assertFalse($cm->hasNamedNativeQuery('find-by-id')); } public function testRetrieveOfNamedQuery() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); + $cm->addNamedQuery('userById', 'SELECT u FROM __CLASS__ u WHERE u.id = ?1'); - $cm->addNamedQuery( - [ - 'name' => 'userById', - 'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1' - ] - ); + self::assertEquals('SELECT u FROM __CLASS__ u WHERE u.id = ?1', $cm->getNamedQuery('userById')); - $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1', $cm->getNamedQuery('userById')); + // Named queries are only resolved when created + $repo = new EntityRepository($this->getTestEntityManager(), $cm); + + self::assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1', $repo->createNamedQuery('userById')->getDQL()); } /** @@ -777,21 +1069,20 @@ public function testRetrieveOfNamedQuery() */ public function testRetrievalOfNamedNativeQueries() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); - $this->assertEquals(0, count($cm->getNamedNativeQueries())); + self::assertEquals(0, count($cm->getNamedNativeQueries())); $cm->addNamedNativeQuery( + 'find-all', + 'SELECT * FROM cms_users', [ - 'name' => 'find-all', - 'query' => 'SELECT * FROM cms_users', - 'resultClass' => CMS\CmsUser::class, - 'resultSetMapping' => 'result-mapping-name' + 'resultClass' => CMS\CmsUser::class, ] ); - $this->assertEquals(1, count($cm->getNamedNativeQueries())); + self::assertEquals(1, count($cm->getNamedNativeQueries())); } /** @@ -799,16 +1090,15 @@ public function testRetrievalOfNamedNativeQueries() */ public function testSerializeEntityListeners() { - $metadata = new ClassMetadata(CompanyContract::class); + $metadata = new ClassMetadata(CompanyContract::class, $this->metadataBuildingContext); - $metadata->initializeReflection(new RuntimeReflectionService()); - $metadata->addEntityListener(Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); - $metadata->addEntityListener(Events::postPersist, 'CompanyContractListener', 'postPersistHandler'); + $metadata->addEntityListener(Events::prePersist, CompanyContractListener::class, 'prePersistHandler'); + $metadata->addEntityListener(Events::postPersist, CompanyContractListener::class, 'postPersistHandler'); $serialize = serialize($metadata); $unserialize = unserialize($serialize); - $this->assertEquals($metadata->entityListeners, $unserialize->entityListeners); + self::assertEquals($metadata->entityListeners, $unserialize->entityListeners); } /** @@ -817,22 +1107,11 @@ public function testSerializeEntityListeners() */ public function testNamingCollisionNamedQueryShouldThrowException() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); - - $cm->addNamedQuery( - [ - 'name' => 'userById', - 'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1' - ] - ); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); - $cm->addNamedQuery( - [ - 'name' => 'userById', - 'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1' - ] - ); + $cm->addNamedQuery('userById', 'SELECT u FROM __CLASS__ u WHERE u.id = ?1'); + $cm->addNamedQuery('userById', 'SELECT u FROM __CLASS__ u WHERE u.id = ?1'); } /** @@ -843,24 +1122,22 @@ public function testNamingCollisionNamedQueryShouldThrowException() */ public function testNamingCollisionNamedNativeQueryShouldThrowException() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); $cm->addNamedNativeQuery( + 'find-all', + 'SELECT * FROM cms_users', [ - 'name' => 'find-all', - 'query' => 'SELECT * FROM cms_users', - 'resultClass' => CMS\CmsUser::class, - 'resultSetMapping' => 'result-mapping-name' + 'resultClass' => CMS\CmsUser::class, ] ); $cm->addNamedNativeQuery( + 'find-all', + 'SELECT * FROM cms_users', [ - 'name' => 'find-all', - 'query' => 'SELECT * FROM cms_users', - 'resultClass' => CMS\CmsUser::class, - 'resultSetMapping' => 'result-mapping-name' + 'resultClass' => CMS\CmsUser::class, ] ); } @@ -873,8 +1150,8 @@ public function testNamingCollisionNamedNativeQueryShouldThrowException() */ public function testNamingCollisionSqlResultSetMappingShouldThrowException() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); $cm->addSqlResultSetMapping( [ @@ -904,11 +1181,10 @@ public function testNamingCollisionSqlResultSetMappingShouldThrowException() */ public function testClassCaseSensitivity() { - $user = new CMS\CmsUser(); - $cm = new ClassMetadata(strtoupper(CMS\CmsUser::class)); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(strtoupper(CMS\CmsUser::class), $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); - $this->assertEquals(CMS\CmsUser::class, $cm->name); + self::assertEquals(CMS\CmsUser::class, $cm->getClassName()); } /** @@ -916,8 +1192,9 @@ public function testClassCaseSensitivity() */ public function testLifecycleCallbackNotFound() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); + $cm->addLifecycleCallback('notfound', 'postLoad'); $this->expectException(MappingException::class); @@ -931,50 +1208,19 @@ public function testLifecycleCallbackNotFound() */ public function testTargetEntityNotFound() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapManyToOne(['fieldName' => 'address', 'targetEntity' => 'UnknownClass']); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); - $this->expectException(MappingException::class); - $this->expectExceptionMessage("The target-entity Doctrine\\Tests\\Models\\CMS\\UnknownClass cannot be found in '" . CMS\CmsUser::class . "#address'."); + $association = new Mapping\ManyToOneAssociationMetadata('address'); - $cm->validateAssociations(); - } + $association->setTargetEntity('UnknownClass'); - /** - * @group DDC-1663 - * - * @expectedException \Doctrine\ORM\Mapping\MappingException - * @expectedExceptionMessage Query name on entity class 'Doctrine\Tests\Models\CMS\CmsUser' is not defined. - */ - public function testNameIsMandatoryForNamedQueryMappingException() - { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); - $cm->addNamedQuery( - [ - 'query' => 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', - ] - ); - } + $cm->addProperty($association); - /** - * @group DDC-1663 - * - * @expectedException \Doctrine\ORM\Mapping\MappingException - * @expectedExceptionMessage Query name on entity class 'Doctrine\Tests\Models\CMS\CmsUser' is not defined. - */ - public function testNameIsMandatoryForNameNativeQueryMappingException() - { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); - $cm->addNamedQuery( - [ - 'query' => 'SELECT * FROM cms_users', - 'resultClass' => CMS\CmsUser::class, - 'resultSetMapping' => 'result-mapping-name' - ] - ); + $this->expectException(MappingException::class); + $this->expectExceptionMessage("The target-entity 'UnknownClass' cannot be found in '" . CMS\CmsUser::class . "#address'."); + + $cm->validateAssociations(); } /** @@ -985,8 +1231,9 @@ public function testNameIsMandatoryForNameNativeQueryMappingException() */ public function testNameIsMandatoryForEntityNameSqlResultSetMappingException() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); + $cm->addSqlResultSetMapping( [ 'name' => 'find-all', @@ -999,17 +1246,6 @@ public function testNameIsMandatoryForEntityNameSqlResultSetMappingException() ); } - /** - * @expectedException \Doctrine\ORM\Mapping\MappingException - * @expectedExceptionMessage Discriminator column name on entity class 'Doctrine\Tests\Models\CMS\CmsUser' is not defined. - */ - public function testNameIsMandatoryForDiscriminatorColumnsMappingException() - { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); - $cm->setDiscriminatorColumn([]); - } - /** * @group DDC-984 * @group DDC-559 @@ -1017,32 +1253,38 @@ public function testNameIsMandatoryForDiscriminatorColumnsMappingException() */ public function testFullyQualifiedClassNameShouldBeGivenToNamingStrategy() { - $namingStrategy = new MyNamespacedNamingStrategy(); - $addressMetadata = new ClassMetadata(CMS\CmsAddress::class, $namingStrategy); - $articleMetadata = new ClassMetadata(DoctrineGlobal_Article::class, $namingStrategy); - $routingMetadata = new ClassMetadata(RoutingLeg::class, $namingStrategy); + $namingStrategy = new MyNamespacedNamingStrategy(); - $addressMetadata->initializeReflection(new RuntimeReflectionService()); - $articleMetadata->initializeReflection(new RuntimeReflectionService()); - $routingMetadata->initializeReflection(new RuntimeReflectionService()); - - $addressMetadata->mapManyToMany( - [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser' - ] + $this->metadataBuildingContext = new Mapping\ClassMetadataBuildingContext( + $this->createMock(Mapping\ClassMetadataFactory::class), + new RuntimeReflectionService(), + $namingStrategy ); - $articleMetadata->mapManyToMany( - [ - 'fieldName' => 'author', - 'targetEntity' => CMS\CmsUser::class - ] - ); + $addressMetadata = new ClassMetadata(CMS\CmsAddress::class, $this->metadataBuildingContext); + $addressMetadata->setTable(new Mapping\TableMetadata($namingStrategy->classToTableName(CMS\CmsAddress::class))); - $this->assertEquals('routing_routingleg', $routingMetadata->table['name']); - $this->assertEquals('cms_cmsaddress_cms_cmsuser', $addressMetadata->associationMappings['user']['joinTable']['name']); - $this->assertEquals('doctrineglobal_article_cms_cmsuser', $articleMetadata->associationMappings['author']['joinTable']['name']); + $articleMetadata = new ClassMetadata(DoctrineGlobal_Article::class, $this->metadataBuildingContext); + $articleMetadata->setTable(new Mapping\TableMetadata($namingStrategy->classToTableName(DoctrineGlobal_Article::class))); + + $routingMetadata = new ClassMetadata(RoutingLeg::class, $this->metadataBuildingContext); + $routingMetadata->setTable(new Mapping\TableMetadata($namingStrategy->classToTableName(RoutingLeg::class))); + + $association = new Mapping\ManyToManyAssociationMetadata('user'); + + $association->setTargetEntity(CMS\CmsUser::class); + + $addressMetadata->addProperty($association); + + $association = new Mapping\ManyToManyAssociationMetadata('author'); + + $association->setTargetEntity(CMS\CmsUser::class); + + $articleMetadata->addProperty($association); + + self::assertEquals('routing_routingleg', $routingMetadata->table->getName()); + self::assertEquals('cms_cmsaddress_cms_cmsuser', $addressMetadata->getProperty('user')->getJoinTable()->getName()); + self::assertEquals('doctrineglobal_article_cms_cmsuser', $articleMetadata->getProperty('author')->getJoinTable()->getName()); } /** @@ -1052,86 +1294,105 @@ public function testFullyQualifiedClassNameShouldBeGivenToNamingStrategy() public function testFullyQualifiedClassNameShouldBeGivenToNamingStrategyPropertyToColumnName() { $namingStrategy = new MyPrefixNamingStrategy(); - $metadata = new ClassMetadata(CMS\CmsAddress::class, $namingStrategy); - $metadata->initializeReflection(new RuntimeReflectionService()); + $this->metadataBuildingContext = new Mapping\ClassMetadataBuildingContext( + $this->createMock(Mapping\ClassMetadataFactory::class), + new RuntimeReflectionService(), + $namingStrategy + ); + + $metadata = new ClassMetadata(CMS\CmsAddress::class, $this->metadataBuildingContext); + $metadata->setTable(new Mapping\TableMetadata($namingStrategy->classToTableName(CMS\CmsAddress::class))); + + $fieldMetadata = new Mapping\FieldMetadata('country'); + + $fieldMetadata->setType(Type::getType('string')); + + $metadata->addProperty($fieldMetadata); - $metadata->mapField(['fieldName'=>'country']); - $metadata->mapField(['fieldName'=>'city']); + $fieldMetadata = new Mapping\FieldMetadata('city'); - $this->assertEquals($metadata->fieldNames, [ - 'cmsaddress_country' => 'country', - 'cmsaddress_city' => 'city' - ] + $fieldMetadata->setType(Type::getType('string')); + + $metadata->addProperty($fieldMetadata); + + self::assertEquals( + $metadata->fieldNames, + [ + 'cmsaddress_country' => 'country', + 'cmsaddress_city' => 'city' + ] ); } /** * @group DDC-1746 + * @expectedException \Doctrine\ORM\Mapping\MappingException + * @expectedExceptionMessage You have specified invalid cascade options for Doctrine\Tests\Models\CMS\CmsUser::$address: 'invalid'; available options: 'remove', 'persist', and 'refresh' */ public function testInvalidCascade() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); - $this->expectException(MappingException::class); - $this->expectExceptionMessage("You have specified invalid cascade options for " . CMS\CmsUser::class . "::\$address: 'invalid'; available options: 'remove', 'persist', 'refresh', 'merge', and 'detach'"); + $association = new Mapping\ManyToOneAssociationMetadata('address'); + + $association->setTargetEntity('UnknownClass'); + $association->setCascade(['invalid']); - $cm->mapManyToOne(['fieldName' => 'address', 'targetEntity' => 'UnknownClass', 'cascade' => ['invalid']]); + $cm->addProperty($association); } /** * @group DDC-964 - * @expectedException Doctrine\ORM\Mapping\MappingException - * @expectedExceptionMessage Invalid field override named 'invalidPropertyName' for class 'Doctrine\Tests\Models\DDC964\DDC964Admin + * @expectedException \Doctrine\ORM\Mapping\MappingException + * @expectedExceptionMessage Invalid field override named 'invalidPropertyName' for class 'Doctrine\Tests\Models\DDC964\DDC964Admin' */ public function testInvalidPropertyAssociationOverrideNameException() { - $cm = new ClassMetadata(DDC964Admin::class); - $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapManyToOne(['fieldName' => 'address', 'targetEntity' => 'DDC964Address']); + $cm = new ClassMetadata(DDC964Admin::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata("ddc964_admin")); + + $association = new Mapping\ManyToOneAssociationMetadata('address'); - $cm->setAssociationOverride('invalidPropertyName', []); + $association->setTargetEntity(DDC964Address::class); + + $cm->addProperty($association); + + $cm->setPropertyOverride(new Mapping\ManyToOneAssociationMetadata('invalidPropertyName')); } /** * @group DDC-964 - * @expectedException Doctrine\ORM\Mapping\MappingException + * @expectedException \Doctrine\ORM\Mapping\MappingException * @expectedExceptionMessage Invalid field override named 'invalidPropertyName' for class 'Doctrine\Tests\Models\DDC964\DDC964Guest'. */ public function testInvalidPropertyAttributeOverrideNameException() { - $cm = new ClassMetadata(DDC964Guest::class); - $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapField(['fieldName' => 'name']); + $cm = new ClassMetadata(DDC964Guest::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata("ddc964_guest")); - $cm->setAttributeOverride('invalidPropertyName', []); - } + $fieldMetadata = new Mapping\FieldMetadata('name'); + $fieldMetadata->setType(Type::getType('string')); - /** - * @group DDC-964 - * @expectedException Doctrine\ORM\Mapping\MappingException - * @expectedExceptionMessage The column type of attribute 'name' on class 'Doctrine\Tests\Models\DDC964\DDC964Guest' could not be changed. - */ - public function testInvalidOverrideAttributeFieldTypeException() - { - $cm = new ClassMetadata(DDC964Guest::class); - $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapField(['fieldName' => 'name', 'type'=>'string']); + $cm->addProperty($fieldMetadata); + + $fieldMetadata = new Mapping\FieldMetadata('invalidPropertyName'); + $fieldMetadata->setType(Type::getType('string')); - $cm->setAttributeOverride('name', ['type'=>'date']); + $cm->setPropertyOverride($fieldMetadata); } /** * @group DDC-1955 * - * @expectedException Doctrine\ORM\Mapping\MappingException + * @expectedException \Doctrine\ORM\Mapping\MappingException * @expectedExceptionMessage Entity Listener "\InvalidClassName" declared on "Doctrine\Tests\Models\CMS\CmsUser" not found. */ public function testInvalidEntityListenerClassException() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); $cm->addEntityListener(Events::postLoad, '\InvalidClassName', 'postLoadHandler'); } @@ -1139,51 +1400,55 @@ public function testInvalidEntityListenerClassException() /** * @group DDC-1955 * - * @expectedException Doctrine\ORM\Mapping\MappingException - * @expectedExceptionMessage Entity Listener "\Doctrine\Tests\Models\Company\CompanyContractListener" declared on "Doctrine\Tests\Models\CMS\CmsUser" has no method "invalidMethod". + * @expectedException \Doctrine\ORM\Mapping\MappingException + * @expectedExceptionMessage Entity Listener "Doctrine\Tests\Models\Company\CompanyContractListener" declared on "Doctrine\Tests\Models\CMS\CmsUser" has no method "invalidMethod". */ public function testInvalidEntityListenerMethodException() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); - $cm->addEntityListener(Events::postLoad, '\Doctrine\Tests\Models\Company\CompanyContractListener', 'invalidMethod'); + $cm->addEntityListener(Events::postLoad, 'Doctrine\Tests\Models\Company\CompanyContractListener', 'invalidMethod'); } public function testManyToManySelfReferencingNamingStrategyDefaults() { - $cm = new ClassMetadata(CustomTypeParent::class); - $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapManyToMany( - [ - 'fieldName' => 'friendsWithMe', - 'targetEntity' => 'CustomTypeParent' - ] - ); + $cm = new ClassMetadata(CustomTypeParent::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata("custom_type_parent")); - $this->assertEquals( - [ - 'name' => 'customtypeparent_customtypeparent', - 'joinColumns' => [['name' => 'customtypeparent_source', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE']], - 'inverseJoinColumns' => [['name' => 'customtypeparent_target', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE']], - ], - $cm->associationMappings['friendsWithMe']['joinTable'] - ); - $this->assertEquals(['customtypeparent_source', 'customtypeparent_target'], $cm->associationMappings['friendsWithMe']['joinTableColumns']); - $this->assertEquals(['customtypeparent_source' => 'id'], $cm->associationMappings['friendsWithMe']['relationToSourceKeyColumns']); - $this->assertEquals(['customtypeparent_target' => 'id'], $cm->associationMappings['friendsWithMe']['relationToTargetKeyColumns']); - } + $association = new Mapping\ManyToManyAssociationMetadata('friendsWithMe'); - /** - * @group DDC-2608 - */ - public function testSetSequenceGeneratorThrowsExceptionWhenSequenceNameIsMissing() - { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $association->setTargetEntity(CustomTypeParent::class); - $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $cm->setSequenceGeneratorDefinition([]); + $cm->addProperty($association); + + $association = $cm->getProperty('friendsWithMe'); + + $joinColumns = []; + + $joinColumn = new Mapping\JoinColumnMetadata(); + + $joinColumn->setColumnName("customtypeparent_source"); + $joinColumn->setReferencedColumnName("id"); + $joinColumn->setOnDelete("CASCADE"); + + $joinColumns[] = $joinColumn; + + $inverseJoinColumns = []; + + $joinColumn = new Mapping\JoinColumnMetadata(); + + $joinColumn->setColumnName("customtypeparent_target"); + $joinColumn->setReferencedColumnName("id"); + $joinColumn->setOnDelete("CASCADE"); + + $inverseJoinColumns[] = $joinColumn; + + $joinTable = $association->getJoinTable(); + + self::assertEquals('customtypeparent_customtypeparent', $joinTable->getName()); + self::assertEquals($joinColumns, $joinTable->getJoinColumns()); + self::assertEquals($inverseJoinColumns, $joinTable->getInverseJoinColumns()); } /** @@ -1191,12 +1456,23 @@ public function testSetSequenceGeneratorThrowsExceptionWhenSequenceNameIsMissing */ public function testQuotedSequenceName() { - $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata('cms_users')); - $cm->setSequenceGeneratorDefinition(['sequenceName' => '`foo`']); + $id = new Mapping\FieldMetadata('id'); + $id->setValueGenerator(new Mapping\ValueGeneratorMetadata( + Mapping\GeneratorType::SEQUENCE, + [ + 'sequenceName' => 'foo', + 'allocationSize' => 1, + ] + )); + $cm->addProperty($id); - $this->assertEquals(['sequenceName' => 'foo', 'quoted' => true], $cm->sequenceGeneratorDefinition); + self::assertEquals( + ['sequenceName' => 'foo', 'allocationSize' => 1], + $cm->getProperty('id')->getValueGenerator()->getDefinition() + ); } /** @@ -1204,97 +1480,60 @@ public function testQuotedSequenceName() */ public function testIsIdentifierMappedSuperClass() { - $class = new ClassMetadata(DDC2700MappedSuperClass::class); - - $this->assertFalse($class->isIdentifier('foo')); - } - - /** - * @group DDC-3120 - */ - public function testCanInstantiateInternalPhpClassSubclass() - { - $classMetadata = new ClassMetadata(MyArrayObjectEntity::class); + $class = new ClassMetadata(DDC2700MappedSuperClass::class, $this->metadataBuildingContext); - $this->assertInstanceOf(MyArrayObjectEntity::class, $classMetadata->newInstance()); + self::assertFalse($class->isIdentifier('foo')); } /** - * @group DDC-3120 + * @group embedded */ - public function testCanInstantiateInternalPhpClassSubclassFromUnserializedMetadata() - { - /* @var $classMetadata ClassMetadata */ - $classMetadata = unserialize(serialize(new ClassMetadata(MyArrayObjectEntity::class))); - - $classMetadata->wakeupReflection(new RuntimeReflectionService()); - - $this->assertInstanceOf(MyArrayObjectEntity::class, $classMetadata->newInstance()); - } - public function testWakeupReflectionWithEmbeddableAndStaticReflectionService() { - $classMetadata = new ClassMetadata(TestEntity1::class); + $metadata = new ClassMetadata(TestEntity1::class, $this->metadataBuildingContext); + $cm->setTable(new Mapping\TableMetadata("test_entity1")); - $classMetadata->mapEmbedded( + $metadata->mapEmbedded( [ - 'fieldName' => 'test', - 'class' => TestEntity1::class, - 'columnPrefix' => false, + 'fieldName' => 'test', + 'class' => TestEntity1::class, + 'columnPrefix' => false, ] ); - $field = [ - 'fieldName' => 'test.embeddedProperty', - 'type' => 'string', + $fieldMetadata = new Mapping\FieldMetadata('test.embeddedProperty'); + $fieldMetadata->setType(Type::getType('string')); + + $metadata->addProperty($fieldMetadata); + + /* + $mapping = [ 'originalClass' => TestEntity1::class, 'declaredField' => 'test', 'originalField' => 'embeddedProperty' ]; - $classMetadata->mapField($field); - $classMetadata->wakeupReflection(new StaticReflectionService()); + $metadata->addProperty('test.embeddedProperty', Type::getType('string'), $mapping); + */ - $this->assertEquals(['test' => null, 'test.embeddedProperty' => null], $classMetadata->getReflectionProperties()); - } + $metadata->wakeupReflection(new StaticReflectionService()); - public function testGetColumnNamesWithGivenFieldNames() - { - $metadata = new ClassMetadata(CMS\CmsUser::class); - $metadata->initializeReflection(new RuntimeReflectionService()); - - $metadata->mapField(['fieldName' => 'status', 'type' => 'string', 'columnName' => 'foo']); - $metadata->mapField(['fieldName' => 'username', 'type' => 'string', 'columnName' => 'bar']); - $metadata->mapField(['fieldName' => 'name', 'type' => 'string', 'columnName' => 'baz']); - - self::assertSame(['foo', 'baz'], $metadata->getColumnNames(['status', 'name'])); - } - - /** - * @group DDC-6460 - */ - public function testInlineEmbeddable() - { - $classMetadata = new ClassMetadata(TestEntity1::class); - - $classMetadata->mapEmbedded( + self::assertEquals( [ - 'fieldName' => 'test', - 'class' => TestEntity1::class, - 'columnPrefix' => false, - ] + 'test' => null, + 'test.embeddedProperty' => null + ], + $metadata->getReflectionProperties() ); - - $this->assertTrue($classMetadata->hasField('test')); } } /** - * @MappedSuperclass + * @ORM\MappedSuperclass */ class DDC2700MappedSuperClass { - /** @Column */ + /** @ORM\Column */ private $foo; } @@ -1323,7 +1562,3 @@ public function propertyToColumnName($propertyName, $className = null) return strtolower($this->classToTableName($className)) . '_' . $propertyName; } } - -class MyArrayObjectEntity extends \ArrayObject -{ -} diff --git a/tests/Doctrine/Tests/ORM/Mapping/DefaultQuoteStrategyTest.php b/tests/Doctrine/Tests/ORM/Mapping/DefaultQuoteStrategyTest.php deleted file mode 100644 index 765518c41bb..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/DefaultQuoteStrategyTest.php +++ /dev/null @@ -1,34 +0,0 @@ - - */ -class DefaultQuoteStrategyTest extends OrmTestCase -{ - /** - * @group DDC-3590 - * @group 1316 - */ - public function testGetJoinTableName() - { - $em = $this->_getTestEntityManager(); - $metadata = $em->getClassMetadata(NonPublicSchemaUser::class); - $strategy = new DefaultQuoteStrategy(); - /* @var $platform AbstractPlatform */ - $platform = $this->getMockForAbstractClass(AbstractPlatform::class); - - $this->assertSame( - 'readers.author_reader', - $strategy->getJoinTableName($metadata->associationMappings['readers'], $metadata, $platform) - ); - } -} diff --git a/tests/Doctrine/Tests/ORM/Mapping/EntityListenerResolverTest.php b/tests/Doctrine/Tests/ORM/Mapping/EntityListenerResolverTest.php index bef03b9ba16..773f8d541ad 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/EntityListenerResolverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/EntityListenerResolverTest.php @@ -1,5 +1,7 @@ resolver->resolve($className); - $this->assertInstanceOf($className, $object); - $this->assertSame($object, $this->resolver->resolve($className)); + self::assertInstanceOf($className, $object); + self::assertSame($object, $this->resolver->resolve($className)); } public function testRegisterAndResolve() @@ -38,7 +40,7 @@ public function testRegisterAndResolve() $this->resolver->register($object); - $this->assertSame($object, $this->resolver->resolve($className)); + self::assertSame($object, $this->resolver->resolve($className)); } public function testClearOne() @@ -49,19 +51,19 @@ public function testClearOne() $obj1 = $this->resolver->resolve($className1); $obj2 = $this->resolver->resolve($className2); - $this->assertInstanceOf($className1, $obj1); - $this->assertInstanceOf($className2, $obj2); + self::assertInstanceOf($className1, $obj1); + self::assertInstanceOf($className2, $obj2); - $this->assertSame($obj1, $this->resolver->resolve($className1)); - $this->assertSame($obj2, $this->resolver->resolve($className2)); + self::assertSame($obj1, $this->resolver->resolve($className1)); + self::assertSame($obj2, $this->resolver->resolve($className2)); $this->resolver->clear($className1); - $this->assertInstanceOf($className1, $this->resolver->resolve($className1)); - $this->assertInstanceOf($className2, $this->resolver->resolve($className2)); + self::assertInstanceOf($className1, $this->resolver->resolve($className1)); + self::assertInstanceOf($className2, $this->resolver->resolve($className2)); - $this->assertNotSame($obj1, $this->resolver->resolve($className1)); - $this->assertSame($obj2, $this->resolver->resolve($className2)); + self::assertNotSame($obj1, $this->resolver->resolve($className1)); + self::assertSame($obj2, $this->resolver->resolve($className2)); } public function testClearAll() @@ -72,19 +74,19 @@ public function testClearAll() $obj1 = $this->resolver->resolve($className1); $obj2 = $this->resolver->resolve($className2); - $this->assertInstanceOf($className1, $obj1); - $this->assertInstanceOf($className2, $obj2); + self::assertInstanceOf($className1, $obj1); + self::assertInstanceOf($className2, $obj2); - $this->assertSame($obj1, $this->resolver->resolve($className1)); - $this->assertSame($obj2, $this->resolver->resolve($className2)); + self::assertSame($obj1, $this->resolver->resolve($className1)); + self::assertSame($obj2, $this->resolver->resolve($className2)); $this->resolver->clear(); - $this->assertInstanceOf($className1, $this->resolver->resolve($className1)); - $this->assertInstanceOf($className2, $this->resolver->resolve($className2)); + self::assertInstanceOf($className1, $this->resolver->resolve($className1)); + self::assertInstanceOf($className2, $this->resolver->resolve($className2)); - $this->assertNotSame($obj1, $this->resolver->resolve($className1)); - $this->assertNotSame($obj2, $this->resolver->resolve($className2)); + self::assertNotSame($obj1, $this->resolver->resolve($className1)); + self::assertNotSame($obj2, $this->resolver->resolve($className2)); } /** @@ -95,4 +97,4 @@ public function testRegisterStringException() { $this->resolver->register('CompanyContractListener'); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Mapping/FieldBuilderTest.php b/tests/Doctrine/Tests/ORM/Mapping/FieldBuilderTest.php deleted file mode 100644 index 0ec0798aae1..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/FieldBuilderTest.php +++ /dev/null @@ -1,26 +0,0 @@ -createField('aField', 'string'); - - $fieldBuilder->generatedValue('CUSTOM'); - $fieldBuilder->setCustomIdGenerator('stdClass'); - - $fieldBuilder->build(); - - $this->assertEquals(ClassMetadataInfo::GENERATOR_TYPE_CUSTOM, $cmBuilder->getClassMetadata()->generatorType); - $this->assertEquals(['class' => 'stdClass'], $cmBuilder->getClassMetadata()->customGeneratorDefinition); - } -} diff --git a/tests/Doctrine/Tests/ORM/Mapping/NamingStrategy/JoinColumnClassNamingStrategy.php b/tests/Doctrine/Tests/ORM/Mapping/NamingStrategy/JoinColumnClassNamingStrategy.php index c4f967589f9..4808fcb37fa 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/NamingStrategy/JoinColumnClassNamingStrategy.php +++ b/tests/Doctrine/Tests/ORM/Mapping/NamingStrategy/JoinColumnClassNamingStrategy.php @@ -1,8 +1,10 @@ assertEquals($expected, $strategy->classToTableName($className)); + self::assertEquals($expected, $strategy->classToTableName($className)); } /** @@ -138,7 +140,7 @@ static public function dataPropertyToColumnName() */ public function testPropertyToColumnName(NamingStrategy $strategy, $expected, $propertyName) { - $this->assertEquals($expected, $strategy->propertyToColumnName($propertyName)); + self::assertEquals($expected, $strategy->propertyToColumnName($propertyName)); } /** @@ -166,7 +168,7 @@ static public function dataReferenceColumnName() */ public function testReferenceColumnName(NamingStrategy $strategy, $expected) { - $this->assertEquals($expected, $strategy->referenceColumnName()); + self::assertEquals($expected, $strategy->referenceColumnName()); } /** @@ -199,7 +201,7 @@ static public function dataJoinColumnName() */ public function testJoinColumnName(NamingStrategy $strategy, $expected, $propertyName, $className = null) { - $this->assertEquals($expected, $strategy->joinColumnName($propertyName, $className)); + self::assertEquals($expected, $strategy->joinColumnName($propertyName, $className)); } /** @@ -264,7 +266,7 @@ static public function dataJoinTableName() */ public function testJoinTableName(NamingStrategy $strategy, $expected, $ownerEntity, $associatedEntity, $propertyName = null) { - $this->assertEquals($expected, $strategy->joinTableName($ownerEntity, $associatedEntity, $propertyName)); + self::assertEquals($expected, $strategy->joinTableName($ownerEntity, $associatedEntity, $propertyName)); } /** @@ -317,6 +319,6 @@ static public function dataJoinKeyColumnName() */ public function testJoinKeyColumnName(NamingStrategy $strategy, $expected, $propertyEntityName, $referencedColumnName = null, $propertyName = null) { - $this->assertEquals($expected, $strategy->joinKeyColumnName($propertyEntityName, $referencedColumnName, $propertyName)); + self::assertEquals($expected, $strategy->joinKeyColumnName($propertyEntityName, $referencedColumnName, $propertyName)); } } diff --git a/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php deleted file mode 100644 index 04493dbc424..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php +++ /dev/null @@ -1,49 +0,0 @@ -createAnnotationDriver(); -// $driver->loadMetadataForClass("Doctrine\Tests\ORM\Mapping\Animal", $meta); -// $exporter = $cme->getExporter('php', $path); -// echo $exporter->exportClassMetadata($meta); - - return new PHPDriver($path); - } - - /** - * All class are entitier for php driver - * - * @group DDC-889 - */ - public function testinvalidEntityOrMappedSuperClassShouldMentionParentClasses() - { - self::assertInstanceOf(ClassMetadata::class, $this->createClassMetadata(DDC889Class::class)); - } - - /** - * @expectedException Doctrine\ORM\Cache\CacheException - * @expectedExceptionMessage Entity association field "Doctrine\Tests\ORM\Mapping\PHPSLC#foo" not configured as part of the second-level cache. - */ - public function testFailingSecondLevelCacheAssociation() - { - $mappingDriver = $this->_loadDriver(); - - $class = new ClassMetadata(Mapping\PHPSLC::class); - $mappingDriver->loadMetadataForClass(Mapping\PHPSLC::class, $class); - } -} diff --git a/tests/Doctrine/Tests/ORM/Mapping/QuoteStrategyTest.php b/tests/Doctrine/Tests/ORM/Mapping/QuoteStrategyTest.php deleted file mode 100644 index 2af97169c80..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/QuoteStrategyTest.php +++ /dev/null @@ -1,220 +0,0 @@ -_getTestEntityManager(); - $this->platform = $em->getConnection()->getDatabasePlatform(); - $this->strategy = new DefaultQuoteStrategy(); - } - - /** - * @param string $className - * @return \Doctrine\ORM\Mapping\ClassMetadata - */ - private function createClassMetadata($className) - { - $cm = new ClassMetadata($className); - $cm->initializeReflection(new RuntimeReflectionService()); - - return $cm; - } - - public function testConfiguration() - { - $em = $this->_getTestEntityManager(); - $config = $em->getConfiguration(); - - $this->assertInstanceOf(QuoteStrategy::class, $config->getQuoteStrategy()); - $this->assertInstanceOf(DefaultQuoteStrategy::class, $config->getQuoteStrategy()); - - $config->setQuoteStrategy(new MyQuoteStrategy()); - - $this->assertInstanceOf(QuoteStrategy::class, $config->getQuoteStrategy()); - $this->assertInstanceOf(MyQuoteStrategy::class, $config->getQuoteStrategy()); - } - - public function testGetColumnName() - { - $cm = $this->createClassMetadata(CmsUser::class); - $cm->mapField(['fieldName' => 'name', 'columnName' => '`name`']); - $cm->mapField(['fieldName' => 'id', 'columnName' => 'id']); - - $this->assertEquals('id' ,$this->strategy->getColumnName('id', $cm, $this->platform)); - $this->assertEquals('"name"' ,$this->strategy->getColumnName('name', $cm, $this->platform)); - } - - public function testGetTableName() - { - $cm = $this->createClassMetadata(CmsUser::class); - $cm->setPrimaryTable(['name'=>'`cms_user`']); - $this->assertEquals('"cms_user"', $this->strategy->getTableName($cm, $this->platform)); - - $cm = new ClassMetadata(CmsUser::class); - $cm->initializeReflection(new RuntimeReflectionService()); - $cm->setPrimaryTable(['name'=>'cms_user']); - $this->assertEquals('cms_user', $this->strategy->getTableName($cm, $this->platform)); - } - - public function testJoinTableName() - { - $cm1 = $this->createClassMetadata(CmsAddress::class); - $cm2 = $this->createClassMetadata(CmsAddress::class); - - $cm1->mapManyToMany( - [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser', - 'inversedBy' => 'users', - 'joinTable' => [ - 'name' => '`cmsaddress_cmsuser`' - ] - ] - ); - - $cm2->mapManyToMany( - [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser', - 'inversedBy' => 'users', - 'joinTable' => [ - 'name' => 'cmsaddress_cmsuser' - ] - ] - ); - - $this->assertEquals('"cmsaddress_cmsuser"', $this->strategy->getJoinTableName($cm1->associationMappings['user'], $cm1, $this->platform)); - $this->assertEquals('cmsaddress_cmsuser', $this->strategy->getJoinTableName($cm2->associationMappings['user'], $cm2, $this->platform)); - - } - - public function testIdentifierColumnNames() - { - $cm1 = $this->createClassMetadata(CmsAddress::class); - $cm2 = $this->createClassMetadata(CmsAddress::class); - - $cm1->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'columnName' => '`id`', - ] - ); - - $cm2->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'columnName' => 'id', - ] - ); - - $this->assertEquals(['"id"'], $this->strategy->getIdentifierColumnNames($cm1, $this->platform)); - $this->assertEquals(['id'], $this->strategy->getIdentifierColumnNames($cm2, $this->platform)); - } - - - public function testColumnAlias() - { - $i = 0; - $this->assertEquals('columnName_0', $this->strategy->getColumnAlias('columnName', $i++, $this->platform)); - $this->assertEquals('column_name_1', $this->strategy->getColumnAlias('column_name', $i++, $this->platform)); - $this->assertEquals('COLUMN_NAME_2', $this->strategy->getColumnAlias('COLUMN_NAME', $i++, $this->platform)); - $this->assertEquals('COLUMNNAME_3', $this->strategy->getColumnAlias('COLUMN-NAME-', $i++, $this->platform)); - } - - public function testQuoteIdentifierJoinColumns() - { - $cm = $this->createClassMetadata(DDC117ArticleDetails::class); - - $cm->mapOneToOne( - [ - 'id' => true, - 'fieldName' => 'article', - 'targetEntity' => DDC117Article::class, - 'joinColumns' => [ - [ - 'name' => '`article`' - ] - ], - ] - ); - - $this->assertEquals(['"article"'], $this->strategy->getIdentifierColumnNames($cm, $this->platform)); - } - - public function testJoinColumnName() - { - $cm = $this->createClassMetadata(DDC117ArticleDetails::class); - - $cm->mapOneToOne( - [ - 'id' => true, - 'fieldName' => 'article', - 'targetEntity' => DDC117Article::class, - 'joinColumns' => [ - [ - 'name' => '`article`' - ] - ], - ] - ); - - $joinColumn = $cm->associationMappings['article']['joinColumns'][0]; - $this->assertEquals('"article"',$this->strategy->getJoinColumnName($joinColumn, $cm, $this->platform)); - } - - public function testReferencedJoinColumnName() - { - $cm = $this->createClassMetadata(DDC117ArticleDetails::class); - - $cm->mapOneToOne( - [ - 'id' => true, - 'fieldName' => 'article', - 'targetEntity' => DDC117Article::class, - 'joinColumns' => [ - [ - 'name' => '`article`' - ] - ], - ] - ); - - $joinColumn = $cm->associationMappings['article']['joinColumns'][0]; - $this->assertEquals('"id"',$this->strategy->getReferencedJoinColumnName($joinColumn, $cm, $this->platform)); - } -} - -class MyQuoteStrategy extends DefaultQuoteStrategy -{ - -} diff --git a/tests/Doctrine/Tests/ORM/Mapping/Reflection/ReflectionPropertiesGetterTest.php b/tests/Doctrine/Tests/ORM/Mapping/Reflection/ReflectionPropertiesGetterTest.php deleted file mode 100644 index 29906d59b9d..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/Reflection/ReflectionPropertiesGetterTest.php +++ /dev/null @@ -1,129 +0,0 @@ -getProperties(ClassWithMixedProperties::class); - - $this->assertCount(5, $properties); - - foreach ($properties as $property) { - $this->assertInstanceOf('ReflectionProperty', $property); - } - } - - public function testRetrievedInstancesAreNotStatic() - { - $properties = (new ReflectionPropertiesGetter(new RuntimeReflectionService())) - ->getProperties(ClassWithMixedProperties::class); - - foreach ($properties as $property) { - $this->assertFalse($property->isStatic()); - } - } - - public function testExpectedKeys() - { - $properties = (new ReflectionPropertiesGetter(new RuntimeReflectionService())) - ->getProperties(ClassWithMixedProperties::class); - - $this->assertArrayHasKey( - "\0" . ClassWithMixedProperties::class . "\0" . 'privateProperty', - $properties - ); - $this->assertArrayHasKey( - "\0" . ClassWithMixedProperties::class . "\0" . 'privatePropertyOverride', - $properties - ); - $this->assertArrayHasKey( - "\0" . ParentClass::class . "\0" . 'privatePropertyOverride', - $properties - ); - $this->assertArrayHasKey( - "\0*\0protectedProperty", - $properties - ); - $this->assertArrayHasKey( - "publicProperty", - $properties - ); - } - - public function testPropertiesAreAccessible() - { - $object = new ClassWithMixedProperties(); - $properties = (new ReflectionPropertiesGetter(new RuntimeReflectionService())) - ->getProperties(ClassWithMixedProperties::class); - - foreach ($properties as $property) { - $this->assertSame($property->getName(), $property->getValue($object)); - } - } - - public function testPropertyGetterIsIdempotent() - { - $getter = (new ReflectionPropertiesGetter(new RuntimeReflectionService())); - - $this->assertSame( - $getter->getProperties(ClassWithMixedProperties::class), - $getter->getProperties(ClassWithMixedProperties::class) - ); - } - - public function testPropertyGetterWillSkipPropertiesNotRetrievedByTheRuntimeReflectionService() - { - /* @var $reflectionService ReflectionService|\PHPUnit_Framework_MockObject_MockObject */ - $reflectionService = $this->createMock(ReflectionService::class); - - $reflectionService - ->expects($this->exactly(2)) - ->method('getClass') - ->with($this->logicalOr(ClassWithMixedProperties::class, ParentClass::class)) - ->will($this->returnValueMap([ - [ClassWithMixedProperties::class, new ReflectionClass(ClassWithMixedProperties::class)], - [ParentClass::class, new ReflectionClass(ParentClass::class)], - ])); - - $reflectionService - ->expects($this->atLeastOnce()) - ->method('getAccessibleProperty'); - - $getter = (new ReflectionPropertiesGetter($reflectionService)); - - $this->assertEmpty($getter->getProperties(ClassWithMixedProperties::class)); - } - - public function testPropertyGetterWillSkipClassesNotRetrievedByTheRuntimeReflectionService() - { - /* @var $reflectionService ReflectionService|\PHPUnit_Framework_MockObject_MockObject */ - $reflectionService = $this->createMock(ReflectionService::class); - - $reflectionService - ->expects($this->once()) - ->method('getClass') - ->with(ClassWithMixedProperties::class); - - $reflectionService->expects($this->never())->method('getAccessibleProperty'); - - $getter = (new ReflectionPropertiesGetter($reflectionService)); - - $this->assertEmpty($getter->getProperties(ClassWithMixedProperties::class)); - } -} diff --git a/tests/Doctrine/Tests/ORM/Mapping/ReflectionEmbeddedPropertyTest.php b/tests/Doctrine/Tests/ORM/Mapping/ReflectionEmbeddedPropertyTest.php index 82761282ad4..503555b8628 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ReflectionEmbeddedPropertyTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ReflectionEmbeddedPropertyTest.php @@ -1,15 +1,16 @@ setValue($object, 'newValue'); - $this->assertSame('newValue', $embeddedPropertyReflection->getValue($object)); + self::assertSame('newValue', $embeddedPropertyReflection->getValue($object)); $embeddedPropertyReflection->setValue($object, 'changedValue'); - $this->assertSame('changedValue', $embeddedPropertyReflection->getValue($object)); + self::assertSame('changedValue', $embeddedPropertyReflection->getValue($object)); } /** @@ -62,7 +63,7 @@ public function testWillSkipReadingPropertiesFromNullEmbeddable( $instantiator = new Instantiator(); - $this->assertNull($embeddedPropertyReflection->getValue( + self::assertNull($embeddedPropertyReflection->getValue( $instantiator->instantiate($parentProperty->getDeclaringClass()->getName()) )); } diff --git a/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php deleted file mode 100644 index 3bc5a5d5d2e..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php +++ /dev/null @@ -1,43 +0,0 @@ -createClassMetadata(DDC889Class::class)); - } - - /** - * @group DDC-2825 - * @group 881 - */ - public function testSchemaDefinitionViaExplicitTableSchemaAnnotationProperty() - { - $this->markTestIncomplete(); - } - - /** - * @group DDC-2825 - * @group 881 - */ - public function testSchemaDefinitionViaSchemaDefinedInTableNameInTableAnnotationProperty() - { - $this->markTestIncomplete(); - } -} diff --git a/tests/Doctrine/Tests/ORM/Mapping/Symfony/AbstractDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/Symfony/AbstractDriverTest.php index 85b3b2138dd..57b82468e36 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/Symfony/AbstractDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/Symfony/AbstractDriverTest.php @@ -1,13 +1,16 @@ dir.'/Foo'.$this->getFileExtension()); - $this->assertEquals($filename, $driver->getLocator()->findMappingFile('MyNamespace\MySubnamespace\Entity\Foo')); + self::assertEquals($filename, $driver->getLocator()->findMappingFile('MyNamespace\MySubnamespace\Entity\Foo')); } public function testFindMappingFileInSubnamespace() @@ -31,7 +34,7 @@ public function testFindMappingFileInSubnamespace() ); touch($filename = $this->dir.'/Foo.Bar'.$this->getFileExtension()); - $this->assertEquals($filename, $driver->getLocator()->findMappingFile('MyNamespace\MySubnamespace\Entity\Foo\Bar')); + self::assertEquals($filename, $driver->getLocator()->findMappingFile('MyNamespace\MySubnamespace\Entity\Foo\Bar')); } public function testFindMappingFileNamespacedFoundFileNotFound() @@ -74,9 +77,9 @@ protected function tearDown() foreach ($iterator as $path) { if ($path->isDir()) { - @rmdir($path); + @rmdir((string) $path); } else { - @unlink($path); + @unlink((string) $path); } } diff --git a/tests/Doctrine/Tests/ORM/Mapping/Symfony/XmlDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/Symfony/XmlDriverTest.php index 2fa83681316..6a6d7c001d5 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/Symfony/XmlDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/Symfony/XmlDriverTest.php @@ -1,5 +1,7 @@ _loadDriver(); + $mappingDriver = $this->loadDriver(); + + $class = new ClassMetadata(CTI::class, $this->metadataBuildingContext); - $class = new ClassMetadata(CTI::class); - $class->initializeReflection(new RuntimeReflectionService()); - $mappingDriver->loadMetadataForClass(CTI::class, $class); + $mappingDriver->loadMetadataForClass(CTI::class, $class, $this->metadataBuildingContext); $expectedMap = [ 'foo' => CTIFoo::class, @@ -35,8 +37,8 @@ public function testClassTableInheritanceDiscriminatorMap() 'baz' => CTIBaz::class, ]; - $this->assertEquals(3, count($class->discriminatorMap)); - $this->assertEquals($expectedMap, $class->discriminatorMap); + self::assertEquals(3, count($class->discriminatorMap)); + self::assertEquals($expectedMap, $class->discriminatorMap); } /** @@ -45,16 +47,17 @@ public function testClassTableInheritanceDiscriminatorMap() */ public function testFailingSecondLevelCacheAssociation() { - $mappingDriver = $this->_loadDriver(); + $mappingDriver = $this->loadDriver(); - $class = new ClassMetadata(XMLSLC::class); - $mappingDriver->loadMetadataForClass(XMLSLC::class, $class); + $class = new ClassMetadata(XMLSLC::class, $this->metadataBuildingContext); + + $mappingDriver->loadMetadataForClass(XMLSLC::class, $class, $this->metadataBuildingContext); } public function testIdentifierWithAssociationKey() { - $driver = $this->_loadDriver(); - $em = $this->_getTestEntityManager(); + $driver = $this->loadDriver(); + $em = $this->getTestEntityManager(); $factory = new ClassMetadataFactory(); $em->getConfiguration()->setMetadataDriverImpl($driver); @@ -62,34 +65,39 @@ public function testIdentifierWithAssociationKey() $class = $factory->getMetadataFor(DDC117Translation::class); - $this->assertEquals(['language', 'article'], $class->identifier); - $this->assertArrayHasKey('article', $class->associationMappings); + self::assertEquals(['language', 'article'], $class->identifier); + self::assertArrayHasKey('article', iterator_to_array($class->getDeclaredPropertiesIterator())); + + $association = $class->getProperty('article'); - $this->assertArrayHasKey('id', $class->associationMappings['article']); - $this->assertTrue($class->associationMappings['article']['id']); + self::assertTrue($association->isPrimaryKey()); } + /** + * @group embedded + */ public function testEmbeddableMapping() { $class = $this->createClassMetadata(Name::class); - $this->assertEquals(true, $class->isEmbeddedClass); + self::assertEquals(true, $class->isEmbeddedClass); } /** + * @group embedded * @group DDC-3293 * @group DDC-3477 - * @group 1238 + * @group DDC-1238 */ public function testEmbeddedMappingsWithUseColumnPrefix() { $factory = new ClassMetadataFactory(); - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); - $em->getConfiguration()->setMetadataDriverImpl($this->_loadDriver()); + $em->getConfiguration()->setMetadataDriverImpl($this->loadDriver()); $factory->setEntityManager($em); - $this->assertEquals( + self::assertEquals( '__prefix__', $factory->getMetadataFor(DDC3293UserPrefixed::class) ->embeddedClasses['address']['columnPrefix'] @@ -97,35 +105,40 @@ public function testEmbeddedMappingsWithUseColumnPrefix() } /** + * @group embedded * @group DDC-3293 * @group DDC-3477 - * @group 1238 + * @group DDC-1238 */ public function testEmbeddedMappingsWithFalseUseColumnPrefix() { $factory = new ClassMetadataFactory(); - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); - $em->getConfiguration()->setMetadataDriverImpl($this->_loadDriver()); + $em->getConfiguration()->setMetadataDriverImpl($this->loadDriver()); $factory->setEntityManager($em); - $this->assertFalse( + self::assertFalse( $factory->getMetadataFor(DDC3293User::class) ->embeddedClasses['address']['columnPrefix'] ); } + /** + * @group embedded + */ public function testEmbeddedMapping() { $class = $this->createClassMetadata(Person::class); - $this->assertEquals( + self::assertEquals( [ 'name' => [ - 'class' => Name::class, - 'columnPrefix' => 'nm_', - 'declaredField' => null, - 'originalField' => null, + 'class' => Name::class, + 'columnPrefix' => 'nm_', + 'declaredField' => null, + 'originalField' => null, + 'declaringClass' => $class, ] ], $class->embeddedClasses @@ -155,7 +168,7 @@ public function testValidateXmlSchema($xmlMappingFile) $dom->load($xmlMappingFile); - $this->assertTrue($dom->schemaValidate($xsdSchemaFile)); + self::assertTrue($dom->schemaValidate($xsdSchemaFile)); } static public function dataValidSchema() diff --git a/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php deleted file mode 100644 index b6feb405290..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php +++ /dev/null @@ -1,90 +0,0 @@ -markTestSkipped('Please install Symfony YAML Component into the include path of your PHP installation.'); - } - - return new YamlDriver(__DIR__ . DIRECTORY_SEPARATOR . 'yaml'); - } - - /** - * @group DDC-671 - * - * Entities for this test are in AbstractMappingDriverTest - */ - public function testJoinTablesWithMappedSuperclassForYamlDriver() - { - $yamlDriver = $this->_loadDriver(); - $yamlDriver->getLocator()->addPaths([__DIR__ . DIRECTORY_SEPARATOR . 'yaml']); - - $em = $this->_getTestEntityManager(); - $em->getConfiguration()->setMetadataDriverImpl($yamlDriver); - $factory = new ClassMetadataFactory(); - $factory->setEntityManager($em); - - $classPage = new ClassMetadata(File::class); - $classPage = $factory->getMetadataFor(File::class); - $this->assertEquals(File::class, $classPage->associationMappings['parentDirectory']['sourceEntity']); - - $classDirectory = new ClassMetadata(Directory::class); - $classDirectory = $factory->getMetadataFor(Directory::class); - $this->assertEquals(Directory::class, $classDirectory->associationMappings['parentDirectory']['sourceEntity']); - } - - /** - * @group DDC-1468 - * - * @expectedException Doctrine\Common\Persistence\Mapping\MappingException - * @expectedExceptionMessage Invalid mapping file 'Doctrine.Tests.Models.Generic.SerializationModel.dcm.yml' for class 'Doctrine\Tests\Models\Generic\SerializationModel'. - */ - public function testInvalidMappingFileException() - { - $this->createClassMetadata(SerializationModel::class); - } - - /** - * @group DDC-2069 - */ - public function testSpacesShouldBeIgnoredWhenUseExplode() - { - $metadata = $this->createClassMetadata(DDC2069Entity::class); - $unique = $metadata->table['uniqueConstraints'][0]['columns']; - $indexes = $metadata->table['indexes'][0]['columns']; - - $nameField = $metadata->fieldMappings['name']; - $valueField = $metadata->fieldMappings['value']; - - $this->assertEquals('name', $unique[0]); - $this->assertEquals('value', $unique[1]); - - $this->assertEquals('value', $indexes[0]); - $this->assertEquals('name', $indexes[1]); - - $this->assertEquals(255, $nameField['length']); - $this->assertEquals(255, $valueField['length']); - } - -} - -class DDC2069Entity -{ - public $id; - - public $name; - - public $value; -} diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.CMS.CmsAddress.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.CMS.CmsAddress.php deleted file mode 100644 index 7238eb15a05..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.CMS.CmsAddress.php +++ /dev/null @@ -1,127 +0,0 @@ -setPrimaryTable( - [ - 'name' => 'company_person', - ] -); - -$metadata->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - ] -); - -$metadata->mapField( - [ - 'fieldName' => 'zip', - 'length' => 50, - ] -); - -$metadata->mapField( - [ - 'fieldName' => 'city', - 'length' => 50, - ] -); - -$metadata->mapOneToOne( - [ - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser', - 'joinColumns' => [['referencedColumnName' => 'id']] - ] -); - -$metadata->addNamedNativeQuery( - [ - 'name' => 'find-all', - 'query' => 'SELECT id, country, city FROM cms_addresses', - 'resultSetMapping' => 'mapping-find-all', - ] -); - -$metadata->addNamedNativeQuery( - [ - 'name' => 'find-by-id', - 'query' => 'SELECT * FROM cms_addresses WHERE id = ?', - 'resultClass' => CmsAddress::class, - ] -); - -$metadata->addNamedNativeQuery( - [ - 'name' => 'count', - 'query' => 'SELECT COUNT(*) AS count FROM cms_addresses', - 'resultSetMapping' => 'mapping-count', - ] -); - - -$metadata->addSqlResultSetMapping( - [ - 'name' => 'mapping-find-all', - 'columns' => [], - 'entities' => [ - [ - 'fields' => [ - [ - 'name' => 'id', - 'column' => 'id', - ], - [ - 'name' => 'city', - 'column' => 'city', - ], - [ - 'name' => 'country', - 'column' => 'country', - ], - ], - 'entityClass' => CmsAddress::class, - ], - ], - ] -); - -$metadata->addSqlResultSetMapping( - [ - 'name' => 'mapping-without-fields', - 'columns' => [], - 'entities' => [ - [ - 'entityClass' => CmsAddress::class, - 'fields' => [] - ] - ] - ] -); - -$metadata->addSqlResultSetMapping( - [ - 'name' => 'mapping-count', - 'columns' => [ - [ - 'name' => 'count', - ], - ] - ] -); - -$metadata->addEntityListener(Events::postPersist, 'CmsAddressListener', 'postPersist'); -$metadata->addEntityListener(Events::prePersist, 'CmsAddressListener', 'prePersist'); - -$metadata->addEntityListener(Events::postUpdate, 'CmsAddressListener', 'postUpdate'); -$metadata->addEntityListener(Events::preUpdate, 'CmsAddressListener', 'preUpdate'); - -$metadata->addEntityListener(Events::postRemove, 'CmsAddressListener', 'postRemove'); -$metadata->addEntityListener(Events::preRemove, 'CmsAddressListener', 'preRemove'); - -$metadata->addEntityListener(Events::preFlush, 'CmsAddressListener', 'preFlush'); -$metadata->addEntityListener(Events::postLoad, 'CmsAddressListener', 'postLoad'); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.CMS.CmsUser.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.CMS.CmsUser.php deleted file mode 100644 index 4b0075ecfe4..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.CMS.CmsUser.php +++ /dev/null @@ -1,213 +0,0 @@ -setPrimaryTable( - [ - 'name' => 'cms_users', - ] -); - -$metadata->addNamedNativeQuery( - [ - 'name' => 'fetchIdAndUsernameWithResultClass', - 'query' => 'SELECT id, username FROM cms_users WHERE username = ?', - 'resultClass' => CmsUser::class, - ] -); - -$metadata->addNamedNativeQuery( - [ - 'name' => 'fetchAllColumns', - 'query' => 'SELECT * FROM cms_users WHERE username = ?', - 'resultClass' => CmsUser::class, - ] -); - -$metadata->addNamedNativeQuery( - [ - 'name' => 'fetchJoinedAddress', - 'query' => 'SELECT u.id, u.name, u.status, a.id AS a_id, a.country, a.zip, a.city FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id WHERE u.username = ?', - 'resultSetMapping' => 'mappingJoinedAddress', - ] -); - -$metadata->addNamedNativeQuery( - [ - 'name' => 'fetchJoinedPhonenumber', - 'query' => 'SELECT id, name, status, phonenumber AS number FROM cms_users INNER JOIN cms_phonenumbers ON id = user_id WHERE username = ?', - 'resultSetMapping' => 'mappingJoinedPhonenumber', - ] -); - -$metadata->addNamedNativeQuery( - [ - 'name' => 'fetchUserPhonenumberCount', - 'query' => 'SELECT id, name, status, COUNT(phonenumber) AS numphones FROM cms_users INNER JOIN cms_phonenumbers ON id = user_id WHERE username IN (?) GROUP BY id, name, status, username ORDER BY username', - 'resultSetMapping' => 'mappingUserPhonenumberCount', - ] -); - -$metadata->addNamedNativeQuery( - [ - "name" => "fetchMultipleJoinsEntityResults", - "resultSetMapping" => "mappingMultipleJoinsEntityResults", - "query" => "SELECT u.id AS u_id, u.name AS u_name, u.status AS u_status, a.id AS a_id, a.zip AS a_zip, a.country AS a_country, COUNT(p.phonenumber) AS numphones FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id INNER JOIN cms_phonenumbers p ON u.id = p.user_id GROUP BY u.id, u.name, u.status, u.username, a.id, a.zip, a.country ORDER BY u.username" - ] -); - -$metadata->addSqlResultSetMapping( - [ - 'name' => 'mappingJoinedAddress', - 'columns' => [], - 'entities' => [ - [ - 'fields'=> [ - [ - 'name' => 'id', - 'column' => 'id', - ], - [ - 'name' => 'name', - 'column' => 'name', - ], - [ - 'name' => 'status', - 'column' => 'status', - ], - [ - 'name' => 'address.zip', - 'column' => 'zip', - ], - [ - 'name' => 'address.city', - 'column' => 'city', - ], - [ - 'name' => 'address.country', - 'column' => 'country', - ], - [ - 'name' => 'address.id', - 'column' => 'a_id', - ], - ], - 'entityClass' => CmsUser::class, - 'discriminatorColumn' => null - ], - ], - ] -); - -$metadata->addSqlResultSetMapping( - [ - 'name' => 'mappingJoinedPhonenumber', - 'columns' => [], - 'entities' => [ - [ - 'fields'=> [ - [ - 'name' => 'id', - 'column' => 'id', - ], - [ - 'name' => 'name', - 'column' => 'name', - ], - [ - 'name' => 'status', - 'column' => 'status', - ], - [ - 'name' => 'phonenumbers.phonenumber', - 'column' => 'number', - ], - ], - 'entityClass' => CmsUser::class, - 'discriminatorColumn' => null - ], - ], - ] -); - -$metadata->addSqlResultSetMapping( - [ - 'name' => 'mappingUserPhonenumberCount', - 'columns' => [], - 'entities' => [ - [ - 'fields' => [ - [ - 'name' => 'id', - 'column' => 'id', - ], - [ - 'name' => 'name', - 'column' => 'name', - ], - [ - 'name' => 'status', - 'column' => 'status', - ] - ], - 'entityClass' => CmsUser::class, - 'discriminatorColumn' => null - ] - ], - 'columns' => [ - [ - 'name' => 'numphones', - ] - ] - ] -); - -$metadata->addSqlResultSetMapping( - [ - 'name' => 'mappingMultipleJoinsEntityResults', - 'entities' => [ - [ - 'fields' => [ - [ - 'name' => 'id', - 'column' => 'u_id', - ], - [ - 'name' => 'name', - 'column' => 'u_name', - ], - [ - 'name' => 'status', - 'column' => 'u_status', - ] - ], - 'entityClass' => CmsUser::class, - 'discriminatorColumn' => null, - ], - [ - 'fields' => [ - [ - 'name' => 'id', - 'column' => 'a_id', - ], - [ - 'name' => 'zip', - 'column' => 'a_zip', - ], - [ - 'name' => 'country', - 'column' => 'a_country', - ], - ], - 'entityClass' => CmsAddress::class, - 'discriminatorColumn' => null, - ], - ], - 'columns' => [ - [ - 'name' => 'numphones', - ] - ] - ] -); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Cache.City.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Cache.City.php deleted file mode 100644 index 6ee9a78fc0b..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Cache.City.php +++ /dev/null @@ -1,73 +0,0 @@ -setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); -$metadata->setPrimaryTable(['name' => 'cache_city']); -$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_IDENTITY); -$metadata->setChangeTrackingPolicy(ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT); - -$metadata->enableCache( - [ - 'usage' => ClassMetadataInfo::CACHE_USAGE_READ_ONLY - ] -); - -$metadata->mapField( - [ - 'fieldName' => 'id', - 'type' => 'integer', - 'id' => true, - ] -); - -$metadata->mapField( - [ - 'fieldName' => 'name', - 'type' => 'string', - ] -); - - -$metadata->mapOneToOne( - [ - 'fieldName' => 'state', - 'targetEntity' => State::class, - 'inversedBy' => 'cities', - 'joinColumns' => - [ - [ - 'name' => 'state_id', - 'referencedColumnName' => 'id', - ] - ] - ] -); -$metadata->enableAssociationCache('state', [ - 'usage' => ClassMetadataInfo::CACHE_USAGE_READ_ONLY -] -); - -$metadata->mapManyToMany( - [ - 'fieldName' => 'travels', - 'targetEntity' => Travel::class, - 'mappedBy' => 'visitedCities', - ] -); - -$metadata->mapOneToMany( - [ - 'fieldName' => 'attractions', - 'targetEntity' => Attraction::class, - 'mappedBy' => 'city', - 'orderBy' => ['name' => 'ASC',], - ] -); -$metadata->enableAssociationCache('attractions', [ - 'usage' => ClassMetadataInfo::CACHE_USAGE_READ_ONLY -] -); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyContract.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyContract.php deleted file mode 100644 index 33389ce9530..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyContract.php +++ /dev/null @@ -1,48 +0,0 @@ -setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_JOINED); -$metadata->setTableName( 'company_contracts'); -$metadata->setDiscriminatorColumn( - [ - 'name' => 'discr', - 'type' => 'string', - ] -); - -$metadata->mapField( - [ - 'id' => true, - 'name' => 'id', - 'fieldName' => 'id', - ] -); - -$metadata->mapField( - [ - 'type' => 'boolean', - 'name' => 'completed', - 'fieldName' => 'completed', - ] -); - -$metadata->setDiscriminatorMap( - [ - "fix" => "CompanyFixContract", - "flexible" => "CompanyFlexContract", - "flexultra" => "CompanyFlexUltraContract" - ] -); - -$metadata->addEntityListener(\Doctrine\ORM\Events::postPersist, 'CompanyContractListener', 'postPersistHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); - -$metadata->addEntityListener(\Doctrine\ORM\Events::postUpdate, 'CompanyContractListener', 'postUpdateHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::preUpdate, 'CompanyContractListener', 'preUpdateHandler'); - -$metadata->addEntityListener(\Doctrine\ORM\Events::postRemove, 'CompanyContractListener', 'postRemoveHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::preRemove, 'CompanyContractListener', 'preRemoveHandler'); - -$metadata->addEntityListener(\Doctrine\ORM\Events::preFlush, 'CompanyContractListener', 'preFlushHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::postLoad, 'CompanyContractListener', 'postLoadHandler'); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFixContract.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFixContract.php deleted file mode 100644 index 3ea44ee7399..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFixContract.php +++ /dev/null @@ -1,9 +0,0 @@ -mapField( - [ - 'type' => 'integer', - 'name' => 'fixPrice', - 'fieldName' => 'fixPrice', - ] -); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFlexContract.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFlexContract.php deleted file mode 100644 index 7cc2b5504c9..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFlexContract.php +++ /dev/null @@ -1,17 +0,0 @@ -mapField( - [ - 'type' => 'integer', - 'name' => 'hoursWorked', - 'fieldName' => 'hoursWorked', - ] -); - -$metadata->mapField( - [ - 'type' => 'integer', - 'name' => 'pricePerHour', - 'fieldName' => 'pricePerHour', - ] -); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFlexUltraContract.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFlexUltraContract.php deleted file mode 100644 index 9e392416ded..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFlexUltraContract.php +++ /dev/null @@ -1,23 +0,0 @@ -mapField( - [ - 'type' => 'integer', - 'name' => 'maxPrice', - 'fieldName' => 'maxPrice', - ] -); -$metadata->addEntityListener(\Doctrine\ORM\Events::postPersist, 'CompanyContractListener', 'postPersistHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); - -$metadata->addEntityListener(\Doctrine\ORM\Events::postUpdate, 'CompanyContractListener', 'postUpdateHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::preUpdate, 'CompanyContractListener', 'preUpdateHandler'); - -$metadata->addEntityListener(\Doctrine\ORM\Events::postRemove, 'CompanyContractListener', 'postRemoveHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::preRemove, 'CompanyContractListener', 'preRemoveHandler'); - -$metadata->addEntityListener(\Doctrine\ORM\Events::preFlush, 'CompanyContractListener', 'preFlushHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::postLoad, 'CompanyContractListener', 'postLoadHandler'); - -$metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyFlexUltraContractListener', 'prePersistHandler1'); -$metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyFlexUltraContractListener', 'prePersistHandler2'); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyPerson.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyPerson.php deleted file mode 100644 index d92bd218b8f..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyPerson.php +++ /dev/null @@ -1,48 +0,0 @@ -setPrimaryTable( - [ - 'name' => 'company_person', - ] -); - -$metadata->addNamedNativeQuery( - [ - 'name' => 'fetchAllWithResultClass', - 'query' => 'SELECT id, name, discr FROM company_persons ORDER BY name', - 'resultClass' => CompanyPerson::class, - ] -); - -$metadata->addNamedNativeQuery( - [ - 'name' => 'fetchAllWithSqlResultSetMapping', - 'query' => 'SELECT id, name, discr AS discriminator FROM company_persons ORDER BY name', - 'resultSetMapping' => 'mappingFetchAll', - ] -); - -$metadata->addSqlResultSetMapping( - [ - 'name' => 'mappingFetchAll', - 'columns' => [], - 'entities' => [ - [ - 'fields' => [ - [ - 'name' => 'id', - 'column' => 'id', - ], - [ - 'name' => 'name', - 'column' => 'name', - ], - ], - 'entityClass' => CompanyPerson::class, - 'discriminatorColumn' => 'discriminator', - ], - ], - ] -); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC1476.DDC1476EntityWithDefaultFieldType.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC1476.DDC1476EntityWithDefaultFieldType.php deleted file mode 100644 index 62459aad000..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC1476.DDC1476EntityWithDefaultFieldType.php +++ /dev/null @@ -1,16 +0,0 @@ -mapField( - [ - 'id' => true, - 'fieldName' => 'id', - ] -); -$metadata->mapField( - [ - 'fieldName' => 'name' - ] -); -$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC2825.ExplicitSchemaAndTable.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC2825.ExplicitSchemaAndTable.php deleted file mode 100644 index 85128c9ae4a..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC2825.ExplicitSchemaAndTable.php +++ /dev/null @@ -1,21 +0,0 @@ -setPrimaryTable( - [ - 'name' => 'explicit_table', - 'schema' => 'explicit_schema', - ] -); - -$metadata->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - ] -); - -$metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_AUTO); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.php deleted file mode 100644 index fb2edfcfb26..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.php +++ /dev/null @@ -1,20 +0,0 @@ -setPrimaryTable( - [ - 'name' => 'implicit_schema.implicit_table', - ] -); - -$metadata->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - ] -); - -$metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_AUTO); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC3579.DDC3579Admin.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC3579.DDC3579Admin.php deleted file mode 100644 index 9b7c87b3e9b..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC3579.DDC3579Admin.php +++ /dev/null @@ -1,6 +0,0 @@ -setAssociationOverride('groups', [ - 'inversedBy' => 'admins' -] -); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC3579.DDC3579User.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC3579.DDC3579User.php deleted file mode 100644 index 49aeacb1eee..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC3579.DDC3579User.php +++ /dev/null @@ -1,33 +0,0 @@ -mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'user_id', - 'length' => 150, - ] -); - -$metadata->mapField( - [ - 'fieldName' => 'name', - 'type' => 'string', - 'columnName'=> 'user_name', - 'nullable' => true, - 'unique' => false, - 'length' => 250, - ] -); - -$metadata->mapManyToMany( - [ - 'fieldName' => 'groups', - 'targetEntity' => 'DDC3579Group' - ] -); - -$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC5934.DDC5934BaseContract.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC5934.DDC5934BaseContract.php deleted file mode 100644 index fca4bb1185e..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC5934.DDC5934BaseContract.php +++ /dev/null @@ -1,17 +0,0 @@ -mapField([ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'id', -]); - -$metadata->mapManyToMany([ - 'fieldName' => 'members', - 'targetEntity' => 'DDC5934Member', -]); - -$metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_AUTO); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC5934.DDC5934Contract.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC5934.DDC5934Contract.php deleted file mode 100644 index 3ecf178a63c..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC5934.DDC5934Contract.php +++ /dev/null @@ -1,7 +0,0 @@ -setAssociationOverride('members', [ - 'fetch' => ClassMetadata::FETCH_EXTRA_LAZY, -]); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869ChequePayment.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869ChequePayment.php deleted file mode 100644 index e97e16f9596..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869ChequePayment.php +++ /dev/null @@ -1,7 +0,0 @@ -mapField( - [ - 'fieldName' => 'serialNumber', - 'type' => 'string', - ] -); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869CreditCardPayment.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869CreditCardPayment.php deleted file mode 100644 index de9d8dae0ee..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869CreditCardPayment.php +++ /dev/null @@ -1,7 +0,0 @@ -mapField( - [ - 'fieldName' => 'creditCardNumber', - 'type' => 'string', - ] -); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869Payment.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869Payment.php deleted file mode 100644 index 1f3f12b2d5f..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869Payment.php +++ /dev/null @@ -1,22 +0,0 @@ -mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'id', - ] -); -$metadata->mapField( - [ - 'fieldName' => 'value', - 'type' => 'float', - ] -); -$metadata->isMappedSuperclass = true; -$metadata->setCustomRepositoryClass(DDC869PaymentRepository::class); -$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC889.DDC889Class.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC889.DDC889Class.php deleted file mode 100644 index e1161da1360..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC889.DDC889Class.php +++ /dev/null @@ -1,14 +0,0 @@ -mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'id', - ] -); - -//$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC889.DDC889Entity.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC889.DDC889Entity.php deleted file mode 100644 index a14f3e7ea1f..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC889.DDC889Entity.php +++ /dev/null @@ -1,3 +0,0 @@ -mapField( - [ - 'fieldName' => 'name', - 'type' => 'string', - ] -); -$metadata->isMappedSuperclass = true; -$metadata->setCustomRepositoryClass(DDC889SuperClass::class); -$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964Admin.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964Admin.php deleted file mode 100644 index 10175feca96..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964Admin.php +++ /dev/null @@ -1,29 +0,0 @@ -setAssociationOverride('address', - [ - 'joinColumns'=> [ - [ - 'name' => 'adminaddress_id', - 'referencedColumnName' => 'id', - ] - ] - ] -); - -$metadata->setAssociationOverride('groups', - [ - 'joinTable' => [ - 'name' => 'ddc964_users_admingroups', - 'joinColumns' => [ - [ - 'name' => 'adminuser_id', - ] - ], - - 'inverseJoinColumns' => [[ - 'name' => 'admingroup_id', - ]] - ] - ] -); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964Guest.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964Guest.php deleted file mode 100644 index 28f6f48c592..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964Guest.php +++ /dev/null @@ -1,16 +0,0 @@ -setAttributeOverride('id', [ - 'columnName' => 'guest_id', - 'type' => 'integer', - 'length' => 140, -] -); - -$metadata->setAttributeOverride('name', - [ - 'columnName' => 'guest_name', - 'nullable' => false, - 'unique' => true, - 'length' => 240, - ] -); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964User.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964User.php deleted file mode 100644 index dc445f1ca6c..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964User.php +++ /dev/null @@ -1,58 +0,0 @@ -mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'user_id', - 'length' => 150, - ] -); -$metadata->mapField( - [ - 'fieldName' => 'name', - 'type' => 'string', - 'columnName'=> 'user_name', - 'nullable' => true, - 'unique' => false, - 'length' => 250, - ] -); - -$metadata->mapManyToOne( - [ - 'fieldName' => 'address', - 'targetEntity' => 'DDC964Address', - 'cascade' => ['persist','merge'], - 'joinColumn' => ['name'=>'address_id', 'referencedColumnMame'=>'id'], - ] -); - -$metadata->mapManyToMany( - [ - 'fieldName' => 'groups', - 'targetEntity' => 'DDC964Group', - 'inversedBy' => 'users', - 'cascade' => ['persist','merge','detach'], - 'joinTable' => [ - 'name' => 'ddc964_users_groups', - 'joinColumns' => [ - [ - 'name'=>'user_id', - 'referencedColumnName'=>'id', - ] - ], - 'inverseJoinColumns'=> [ - [ - 'name'=>'group_id', - 'referencedColumnName'=>'id', - ] - ] - ] - ] -); - -$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.Animal.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.Animal.php deleted file mode 100644 index 5000a68a229..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.Animal.php +++ /dev/null @@ -1,38 +0,0 @@ -setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_SINGLE_TABLE); -$metadata->setDiscriminatorColumn( - [ - 'name' => 'dtype', - 'type' => 'string', - 'length' => 255, - 'fieldName' => 'dtype', - ] -); -$metadata->setDiscriminatorMap( - [ - 'cat' => Cat::class, - 'dog' => Dog::class, - ] -); -$metadata->setChangeTrackingPolicy(ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT); -$metadata->mapField( - [ - 'fieldName' => 'id', - 'type' => 'string', - 'length' => NULL, - 'precision' => 0, - 'scale' => 0, - 'nullable' => false, - 'unique' => false, - 'id' => true, - 'columnName' => 'id', - ] -); -$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_CUSTOM); -$metadata->setCustomGeneratorDefinition(["class" => "stdClass"]); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.Comment.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.Comment.php deleted file mode 100644 index a33ebbaeb37..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.Comment.php +++ /dev/null @@ -1,25 +0,0 @@ -setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); -$metadata->setPrimaryTable( - [ - 'indexes' => [ - ['columns' => ['content'], 'flags' => ['fulltext'], 'options'=> ['where' => 'content IS NOT NULL']] - ] - ] -); - -$metadata->mapField( - [ - 'fieldName' => 'content', - 'type' => 'text', - 'scale' => 0, - 'length' => NULL, - 'unique' => false, - 'nullable' => false, - 'precision' => 0, - 'columnName' => 'content', - ] -); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.DDC1170Entity.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.DDC1170Entity.php deleted file mode 100644 index dd442ceb0e4..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.DDC1170Entity.php +++ /dev/null @@ -1,20 +0,0 @@ -mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'columnDefinition' => 'INT unsigned NOT NULL', - ] -); - -$metadata->mapField( - [ - 'fieldName' => 'value', - 'columnDefinition' => 'VARCHAR(255) NOT NULL' - ] -); - -$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.DDC807Entity.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.DDC807Entity.php deleted file mode 100644 index c9d8ad9f29d..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.DDC807Entity.php +++ /dev/null @@ -1,19 +0,0 @@ -mapField( - [ - 'id' => true, - 'fieldName' => 'id', - ] -); - -$metadata->setDiscriminatorColumn( - [ - 'name' => "dtype", - 'columnDefinition' => "ENUM('ONE','TWO')" - ] -); - -$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.PHPSLC.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.PHPSLC.php deleted file mode 100644 index ad1ed23bfc7..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.PHPSLC.php +++ /dev/null @@ -1,16 +0,0 @@ -enableCache( - [ - 'usage' => ClassMetadataInfo::CACHE_USAGE_READ_ONLY - ] -); -$metadata->mapManyToOne( - [ - 'fieldName' => 'foo', - 'id' => true, - 'targetEntity' => 'PHPSLCFoo' - ] -); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.User.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.User.php deleted file mode 100644 index b716893b6fb..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.User.php +++ /dev/null @@ -1,149 +0,0 @@ -setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); -$metadata->setPrimaryTable( - [ - 'name' => 'cms_users', - ] -); -$metadata->setChangeTrackingPolicy(ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT); -$metadata->addLifecycleCallback('doStuffOnPrePersist', 'prePersist'); -$metadata->addLifecycleCallback('doOtherStuffOnPrePersistToo', 'prePersist'); -$metadata->addLifecycleCallback('doStuffOnPostPersist', 'postPersist'); -$metadata->addNamedQuery( - [ - 'name' => 'all', - 'query' => 'SELECT u FROM __CLASS__ u' - ] -); -$metadata->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'id', - 'options' => ['foo' => 'bar', 'unsigned' => false], - ] -); -$metadata->mapField( - [ - 'fieldName' => 'name', - 'type' => 'string', - 'length' => 50, - 'unique' => true, - 'nullable' => true, - 'columnName' => 'name', - 'options' => ['foo' => 'bar', 'baz' => ['key' => 'val'], 'fixed' => false], - ] -); -$metadata->mapField( - [ - 'fieldName' => 'email', - 'type' => 'string', - 'columnName' => 'user_email', - 'columnDefinition' => 'CHAR(32) NOT NULL', - ] -); -$mapping = ['fieldName' => 'version', 'type' => 'integer']; -$metadata->setVersionMapping($mapping); -$metadata->mapField($mapping); -$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); -$metadata->mapOneToOne( - [ - 'fieldName' => 'address', - 'targetEntity' => Address::class, - 'cascade' => - [ - 0 => 'remove', - ], - 'mappedBy' => NULL, - 'inversedBy' => 'user', - 'joinColumns' => - [ - 0 => - [ - 'name' => 'address_id', - 'referencedColumnName' => 'id', - 'onDelete' => 'CASCADE', - ], - ], - 'orphanRemoval' => false, - ] -); -$metadata->mapOneToMany( - [ - 'fieldName' => 'phonenumbers', - 'targetEntity' => Phonenumber::class, - 'cascade' => - [ - 1 => 'persist', - ], - 'mappedBy' => 'user', - 'orphanRemoval' => true, - 'orderBy' => - [ - 'number' => 'ASC', - ], - ] -); -$metadata->mapManyToMany( - [ - 'fieldName' => 'groups', - 'targetEntity' => Group::class, - 'cascade' => - [ - 0 => 'remove', - 1 => 'persist', - 2 => 'refresh', - 3 => 'merge', - 4 => 'detach', - ], - 'mappedBy' => NULL, - 'joinTable' => - [ - 'name' => 'cms_users_groups', - 'joinColumns' => - [ - 0 => - [ - 'name' => 'user_id', - 'referencedColumnName' => 'id', - 'unique' => false, - 'nullable' => false, - ], - ], - 'inverseJoinColumns' => - [ - 0 => - [ - 'name' => 'group_id', - 'referencedColumnName' => 'id', - 'columnDefinition' => 'INT NULL', - ], - ], - ], - 'orderBy' => NULL, - ] -); -$metadata->table['options'] = [ - 'foo' => 'bar', - 'baz' => ['key' => 'val'] -]; -$metadata->table['uniqueConstraints'] = [ - 'search_idx' => ['columns' => ['name', 'user_email'], 'options' => ['where' => 'name IS NOT NULL']], -]; -$metadata->table['indexes'] = [ - 'name_idx' => ['columns' => ['name']], 0 => ['columns' => ['user_email']] -]; -$metadata->setSequenceGeneratorDefinition( - [ - 'sequenceName' => 'tablename_seq', - 'allocationSize' => 100, - 'initialValue' => 1, - ] -); diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.CMS.CmsAddress.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.CMS.CmsAddress.dcm.xml index 7e7bd5aaa2f..1ca7a2fad25 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.CMS.CmsAddress.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.CMS.CmsAddress.dcm.xml @@ -4,7 +4,7 @@ http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> - + @@ -33,7 +33,7 @@ - + @@ -55,4 +55,4 @@ - \ No newline at end of file + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.CMS.CmsUser.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.CMS.CmsUser.dcm.xml index 122a45e6fe9..44396e85a17 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.CMS.CmsUser.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.CMS.CmsUser.dcm.xml @@ -108,21 +108,14 @@ - - - - - - - + + - - diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.dcm.xml index 3a89dd97369..3b378f5206e 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.dcm.xml @@ -5,7 +5,7 @@ xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping https://raw.github.com/doctrine/doctrine2/master/doctrine-mapping.xsd" > - + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC964.DDC964User.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC964.DDC964User.dcm.xml index 68db74b48e5..3a8042f0b8e 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC964.DDC964User.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC964.DDC964User.dcm.xml @@ -14,7 +14,6 @@ - @@ -22,8 +21,6 @@ - - diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.User.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.User.dcm.xml index bbf29aeaf70..e39093c5203 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.User.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.User.dcm.xml @@ -19,11 +19,7 @@ - - - - - + @@ -38,7 +34,7 @@ - + diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.CMS.CmsAddress.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.CMS.CmsAddress.dcm.yml deleted file mode 100644 index 712f089da99..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.CMS.CmsAddress.dcm.yml +++ /dev/null @@ -1,64 +0,0 @@ -Doctrine\Tests\Models\CMS\CmsAddress: - type: entity - table: cms_address - entityListeners: - CmsAddressListener: ~ - namedNativeQueries: - find-all: - resultSetMapping: mapping-find-all - query: SELECT id, country, city FROM cms_addresses - find-by-id: - name: find-by-id - resultClass: CmsAddress - query: SELECT * FROM cms_addresses WHERE id = ? - count: - name: count - resultSetMapping: mapping-count - query: SELECT COUNT(*) AS count FROM cms_addresses - - sqlResultSetMappings: - mapping-find-all: - entityResult: - address: - entityClass: CmsAddress - fieldResult: - 0: - name: id - column: id - 1: - name: city - column: city - 2: - name: country - column: country - mapping-without-fields: - name: mapping-without-fields - entityResult: - address: - entityClass: CmsAddress - mapping-count: - name: mapping-count - columnResult: - count: - name: count - id: - id: - type: integer - generator: - strategy: AUTO - fields: - country: - type: string - length: 50 - city: - type: string - length: 50 - zip: - type: string - length: 50 - oneToOne: - user: - targetEntity: CmsUser - inversedBy: address - joinColumn: - referencedColumnName: id diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.CMS.CmsUser.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.CMS.CmsUser.dcm.yml deleted file mode 100644 index 329e3d061dc..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.CMS.CmsUser.dcm.yml +++ /dev/null @@ -1,157 +0,0 @@ -Doctrine\Tests\Models\CMS\CmsUser: - type: entity - table: cms_users - namedQueries: - all: SELECT u FROM __CLASS__ u - namedNativeQueries: - fetchIdAndUsernameWithResultClass: - resultClass: CmsUser - query: SELECT id, username FROM cms_users WHERE username = ? - fetchAllColumns: - name: fetchAllColumns - resultClass: CmsUser - query: SELECT * FROM cms_users WHERE username = ? - fetchJoinedAddress: - name: fetchJoinedAddress - resultSetMapping: mappingJoinedAddress - query: SELECT u.id, u.name, u.status, a.id AS a_id, a.country, a.zip, a.city FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id WHERE u.username = ? - fetchJoinedPhonenumber: - name: fetchJoinedPhonenumber - resultSetMapping: mappingJoinedPhonenumber - query: SELECT id, name, status, phonenumber AS number FROM cms_users INNER JOIN cms_phonenumbers ON id = user_id WHERE username = ? - fetchUserPhonenumberCount: - name: fetchUserPhonenumberCount - resultSetMapping: mappingUserPhonenumberCount - query: SELECT id, name, status, COUNT(phonenumber) AS numphones FROM cms_users INNER JOIN cms_phonenumbers ON id = user_id WHERE username IN (?) GROUP BY id, name, status, username ORDER BY username - fetchMultipleJoinsEntityResults: - name: fetchMultipleJoinsEntityResults - resultSetMapping: mappingMultipleJoinsEntityResults - query: SELECT u.id AS u_id, u.name AS u_name, u.status AS u_status, a.id AS a_id, a.zip AS a_zip, a.country AS a_country, COUNT(p.phonenumber) AS numphones FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id INNER JOIN cms_phonenumbers p ON u.id = p.user_id GROUP BY u.id, u.name, u.status, u.username, a.id, a.zip, a.country ORDER BY u.username - - sqlResultSetMappings: - mappingJoinedAddress: - entityResult: - 0: - entityClass: __CLASS__ - fieldResult: - 0: - name: id - 1: - name: name - 2: - name: status - 3: - name: address.zip - 4: - name: address.city - 5: - name: address.country - 6: - name: address.id - column: a_id - mappingJoinedPhonenumber: - name: mappingJoinedPhonenumber - entityResult: - user: - entityClass: CmsUser - fieldResult: - 0: - name: id - 1: - name: name - 2: - name: status - 3: - name: phonenumbers.phonenumber - column: number - mappingUserPhonenumberCount: - name: mappingUserPhonenumberCount - columnResult: - 0: - name: numphones - entityResult: - user_0: - entityClass: CmsUser - fieldResult: - 0: - name: id - 1: - name: name - 2: - name: status - mappingMultipleJoinsEntityResults: - name: mappingMultipleJoinsEntityResults - columnResult: - 0: - name: numphones - entityResult: - 0: - entityClass: __CLASS__ - fieldResult: - 0: - name: id - column: u_id - 1: - name: name - column: u_name - 2: - name: status - column: u_status - 1: - entityClass: CmsAddress - fieldResult: - 0: - name: id - column: a_id - 1: - name: zip - column: a_zip - 2: - name: country - column: a_country - id: - id: - type: integer - generator: - strategy: AUTO - fields: - name: - type: string - length: 255 - username: - type: string - length: 255 - unique: true - status: - type: string - length: 50 - unique: true - oneToOne: - address: - targetEntity: CmsAddress - orphanRemoval: true - inversedBy: user - joinColumn: - name: address_id - referencedColumnName: id - cascade: [ persist ] - email: - targetEntity: CmsEmail - orphanRemoval: true - inversedBy: user - joinColumn: - nullable: true - referencedColumnName: id - cascade: [ persist ] - manyToMany: - groups: - targetEntity: CmsGroup - joinTable: - name: cms_users_groups - joinColumns: - user_id: - referencedColumnName: id - inverseJoinColumns: - group_id: - referencedColumnName: id - cascade: [ persist , detach, merge] diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Cache.City.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Cache.City.dcm.yml deleted file mode 100644 index 05286e0df56..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Cache.City.dcm.yml +++ /dev/null @@ -1,36 +0,0 @@ -Doctrine\Tests\Models\Cache\City: - type: entity - table: cache_city - cache: - usage : READ_ONLY - id: - id: - type: integer - id: true - generator: - strategy: IDENTITY - fields: - name: - type: string - manyToOne: - state: - targetEntity: Doctrine\Tests\Models\Cache\State - inversedBy: cities - joinColumns: - state_id: - referencedColumnName: id - cache: - usage : READ_ONLY - manyToMany: - travels: - targetEntity: Doctrine\Tests\Models\Cache\Travel - mappedBy: visitedCities - - oneToMany: - attractions: - targetEntity: Doctrine\Tests\Models\Cache\Attraction - mappedBy: city - cache: - usage : READ_ONLY - orderBy: - name: ASC \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyContract.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyContract.dcm.yml deleted file mode 100644 index 03b9d3bedeb..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyContract.dcm.yml +++ /dev/null @@ -1,32 +0,0 @@ -Doctrine\Tests\Models\Company\CompanyContract: - type: entity - table: company_contracts - inheritanceType: SINGLE_TABLE - discriminatorMap: - fix: CompanyFixContract - flexible: CompanyFlexContract - flexultra: CompanyFlexUltraContract - - entityListeners: - CompanyContractListener: - - preFlush: [preFlushHandler] - postLoad: [postLoadHandler] - - postPersist: [postPersistHandler] - prePersist: [prePersistHandler] - - postUpdate: [postUpdateHandler] - preUpdate: [preUpdateHandler] - - postRemove: [postRemoveHandler] - preRemove: [preRemoveHandler] - - id: - id: - type: integer - generator: - strategy: AUTO - fields: - completed: - type: boolean \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyFixContract.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyFixContract.dcm.yml deleted file mode 100644 index 83d0c75be19..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyFixContract.dcm.yml +++ /dev/null @@ -1,5 +0,0 @@ -Doctrine\Tests\Models\Company\CompanyFixContract: - type: entity - fields: - fixPrice: - type: integer \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyFlexContract.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyFlexContract.dcm.yml deleted file mode 100644 index ef1d2630633..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyFlexContract.dcm.yml +++ /dev/null @@ -1,7 +0,0 @@ -Doctrine\Tests\Models\Company\CompanyFlexContract: - type: entity - fields: - hoursWorked: - type: integer - pricePerHour: - type: integer \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyFlexUltraContract.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyFlexUltraContract.dcm.yml deleted file mode 100644 index 26ce8f3d5fd..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyFlexUltraContract.dcm.yml +++ /dev/null @@ -1,25 +0,0 @@ -Doctrine\Tests\Models\Company\CompanyFlexUltraContract: - type: entity - - entityListeners: - CompanyContractListener: - - preFlush: [preFlushHandler] - postLoad: [postLoadHandler] - - postPersist: [postPersistHandler] - prePersist: [prePersistHandler] - - postUpdate: [postUpdateHandler] - preUpdate: [preUpdateHandler] - - postRemove: [postRemoveHandler] - preRemove: [preRemoveHandler] - - CompanyFlexUltraContractListener: - - prePersist: [prePersistHandler1, prePersistHandler2] - - fields: - maxPrice: - type: integer \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyPerson.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyPerson.dcm.yml deleted file mode 100644 index 28eec43e391..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyPerson.dcm.yml +++ /dev/null @@ -1,74 +0,0 @@ -Doctrine\Tests\Models\Company\CompanyPerson: - type: entity - table: company_persons - inheritanceType: JOINED - discriminatorMap: - person: CompanyPerson - manager: CompanyManager - employee: CompanyEmployee - namedNativeQueries: - fetchAllWithResultClass: - resultClass: __CLASS__ - query: SELECT id, name, discr FROM company_persons ORDER BY name - fetchAllWithSqlResultSetMapping: - name: fetchAllWithSqlResultSetMapping - resultSetMapping: mappingFetchAll - query: SELECT id, name, discr AS discriminator FROM company_persons ORDER BY name - - sqlResultSetMappings: - mappingFetchAll: - entityResult: - 0: - entityClass: __CLASS__ - discriminatorColumn: discriminator - fieldResult: - 0: - name: id - 1: - name: name - id: - id: - type: integer - generator: - strategy: AUTO - fields: - name: - type: string - length: 255 - username: - type: string - length: 255 - unique: true - status: - type: string - length: 50 - unique: true - oneToOne: - address: - targetEntity: CmsAddress - orphanRemoval: true - inversedBy: user - joinColumn: - name: address_id - referencedColumnName: id - cascade: [ persist ] - email: - targetEntity: CmsEmail - orphanRemoval: true - inversedBy: user - joinColumn: - nullable: true - referencedColumnName: id - cascade: [ persist ] - manyToMany: - groups: - targetEntity: CmsGroup - joinTable: - name: cms_users_groups - joinColumns: - user_id: - referencedColumnName: id - inverseJoinColumns: - group_id: - referencedColumnName: id - cascade: [ persist , detach, merge] diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC1476.DDC1476EntityWithDefaultFieldType.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC1476.DDC1476EntityWithDefaultFieldType.dcm.yml deleted file mode 100644 index 674328cd526..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC1476.DDC1476EntityWithDefaultFieldType.dcm.yml +++ /dev/null @@ -1,8 +0,0 @@ -Doctrine\Tests\Models\DDC1476\DDC1476EntityWithDefaultFieldType: - type: entity - id: - id: - generator: - strategy: NONE - fields: - name: ~ diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC2825.ExplicitSchemaAndTable.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC2825.ExplicitSchemaAndTable.dcm.yml deleted file mode 100644 index f28adbb61f4..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC2825.ExplicitSchemaAndTable.dcm.yml +++ /dev/null @@ -1,8 +0,0 @@ -Doctrine\Tests\Models\DDC2825\ExplicitSchemaAndTable: - type: entity - table: explicit_table - schema: explicit_schema - id: - id: - generator: - strategy: AUTO diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.dcm.yml deleted file mode 100644 index bf072816cd7..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.dcm.yml +++ /dev/null @@ -1,7 +0,0 @@ -Doctrine\Tests\Models\DDC2825\SchemaAndTableInTableName: - type: entity - table: implicit_schema.implicit_table - id: - id: - generator: - strategy: AUTO diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC3579.DDC3579Admin.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC3579.DDC3579Admin.dcm.yml deleted file mode 100644 index 7420b14e66d..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC3579.DDC3579Admin.dcm.yml +++ /dev/null @@ -1,5 +0,0 @@ -Doctrine\Tests\Models\DDC3579\DDC3579Admin: - type: entity - associationOverride: - groups: - inversedBy: admins diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC3579.DDC3579User.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC3579.DDC3579User.dcm.yml deleted file mode 100644 index 63d095035f3..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC3579.DDC3579User.dcm.yml +++ /dev/null @@ -1,19 +0,0 @@ -Doctrine\Tests\Models\DDC3579\DDC3579User: - type: mappedSuperclass - id: - id: - type: integer - column: user_id - length: 150 - generator: - strategy: AUTO - fields: - name: - type: string - column: user_name - length: 250 - nullable: true - unique: false - manyToMany: - groups: - targetEntity: DDC3579Group diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC3711.DDC3711EntityA.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC3711.DDC3711EntityA.dcm.yml deleted file mode 100644 index c8a87331dcb..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC3711.DDC3711EntityA.dcm.yml +++ /dev/null @@ -1,23 +0,0 @@ -Doctrine\Tests\Models\DDC3711\DDC3711EntityA: - type: entity - table: ddc3711.entityA - id: - id1: - type: int - id2: - type: int - manyToMany: - entityB: - targetEntity: Doctrine\Tests\Models\DDC3711\DDC3711EntityB - joinTable: - name: link - joinColumns: - link_a_id1: - referencedColumnName: id1 - link_a_id2: - referencedColumnName: id2 - inverseJoinColumns: - link_b_id1: - referencedColumnName: id1 - link_b_id2: - referencedColumnName: id2 \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC3711.DDC3711EntityB.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC3711.DDC3711EntityB.dcm.yml deleted file mode 100644 index 24ec96932c6..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC3711.DDC3711EntityB.dcm.yml +++ /dev/null @@ -1,8 +0,0 @@ -Doctrine\Tests\Models\DDC3711\DDC3711EntityB: - type: entity - table: ddc3711.entityB - id: - id1: - type: int - id2: - type: int diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC5934.DDC5934BaseContract.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC5934.DDC5934BaseContract.dcm.yml deleted file mode 100644 index 2044c9be527..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC5934.DDC5934BaseContract.dcm.yml +++ /dev/null @@ -1,12 +0,0 @@ -Doctrine\Tests\Models\DDC5934\DDC5934BaseContract: - type: mappedSuperclass - id: - id: - type: integer - column: id - generator: - strategy: AUTO - manyToMany: - members: - targetEntity: DDC5934Member - inversedBy: contract diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC5934.DDC5934Contract.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC5934.DDC5934Contract.dcm.yml deleted file mode 100644 index 45ba145853e..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC5934.DDC5934Contract.dcm.yml +++ /dev/null @@ -1,5 +0,0 @@ -Doctrine\Tests\Models\DDC5934\DDC5934Contract: - type: entity - associationOverride: - members: - fetch: EXTRA_LAZY diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC869.DDC869ChequePayment.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC869.DDC869ChequePayment.dcm.yml deleted file mode 100644 index 94f26981756..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC869.DDC869ChequePayment.dcm.yml +++ /dev/null @@ -1,5 +0,0 @@ -Doctrine\Tests\Models\DDC869\DDC869ChequePayment: - type: entity - fields: - serialNumber: - type: string \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC869.DDC869CreditCardPayment.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC869.DDC869CreditCardPayment.dcm.yml deleted file mode 100644 index 153a99fa7e7..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC869.DDC869CreditCardPayment.dcm.yml +++ /dev/null @@ -1,5 +0,0 @@ -Doctrine\Tests\Models\DDC869\DDC869CreditCardPayment: - type: entity - fields: - creditCardNumber: - type: string \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC869.DDC869Payment.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC869.DDC869Payment.dcm.yml deleted file mode 100644 index b776664e1d1..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC869.DDC869Payment.dcm.yml +++ /dev/null @@ -1,12 +0,0 @@ -Doctrine\Tests\Models\DDC869\DDC869Payment: - type: mappedSuperclass - repositoryClass : Doctrine\Tests\Models\DDC869\DDC869PaymentRepository - id: - id: - type: integer - unsigned: true - generator: - strategy: AUTO - fields: - value: - type: float \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC889.DDC889Class.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC889.DDC889Class.dcm.yml deleted file mode 100644 index 567e5d585c5..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC889.DDC889Class.dcm.yml +++ /dev/null @@ -1,8 +0,0 @@ -Doctrine\Tests\Models\DDC889\DDC889Class: - type: class - id: - id: - type: integer - unsigned: true - generator: - strategy: AUTO \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC889.DDC889Entity.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC889.DDC889Entity.dcm.yml deleted file mode 100644 index aa932db214c..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC889.DDC889Entity.dcm.yml +++ /dev/null @@ -1,2 +0,0 @@ -Doctrine\Tests\Models\DDC889\DDC889Entity: - type: entity \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC889.DDC889SuperClass.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC889.DDC889SuperClass.dcm.yml deleted file mode 100644 index 7974d552d0c..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC889.DDC889SuperClass.dcm.yml +++ /dev/null @@ -1,5 +0,0 @@ -Doctrine\Tests\Models\DDC889\DDC889SuperClass: - type: mappedSuperclass - fields: - name: - type: string \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC964.DDC964Admin.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC964.DDC964Admin.dcm.yml deleted file mode 100644 index 0b8051d9644..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC964.DDC964Admin.dcm.yml +++ /dev/null @@ -1,17 +0,0 @@ -Doctrine\Tests\Models\DDC964\DDC964Admin: - type: entity - associationOverride: - address: - joinColumn: - adminaddress_id: - name: adminaddress_id - referencedColumnName: id - groups: - joinTable: - name: ddc964_users_admingroups - joinColumns: - adminuser_id: - referencedColumnName: id - inverseJoinColumns: - admingroup_id: - referencedColumnName: id \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC964.DDC964Guest.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC964.DDC964Guest.dcm.yml deleted file mode 100644 index ec7936f4a74..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC964.DDC964Guest.dcm.yml +++ /dev/null @@ -1,13 +0,0 @@ -Doctrine\Tests\Models\DDC964\DDC964Guest: - type: entity - attributeOverride: - id: - column: guest_id - type: integer - length: 140 - name: - column: guest_name - type: string - length: 240 - nullable: false - unique: true \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC964.DDC964User.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC964.DDC964User.dcm.yml deleted file mode 100644 index 3a9ebbf9d7e..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC964.DDC964User.dcm.yml +++ /dev/null @@ -1,35 +0,0 @@ -Doctrine\Tests\Models\DDC964\DDC964User: - type: mappedSuperclass - id: - id: - type: integer - column: user_id - length: 150 - generator: - strategy: AUTO - fields: - name: - type: string - column: user_name - length: 250 - nullable: true - unique: false - manyToOne: - address: - targetEntity: DDC964Address - joinColumn: - name: address_id - referencedColumnName: id - cascade: [ persist, merge ] - manyToMany: - groups: - targetEntity: DDC964Group - joinTable: - name: ddc964_users_groups - joinColumns: - user_id: - referencedColumnName: id - inverseJoinColumns: - group_id: - referencedColumnName: id - cascade: [ persist, merge, detach ] \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DirectoryTree.AbstractContentItem.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DirectoryTree.AbstractContentItem.dcm.yml deleted file mode 100644 index 9c573a561d2..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DirectoryTree.AbstractContentItem.dcm.yml +++ /dev/null @@ -1,14 +0,0 @@ -Doctrine\Tests\Models\DirectoryTree\AbstractContentItem: - type: mappedSuperclass - id: - id: - type: integer - unsigned: true - generator: - strategy: AUTO - fields: - name: - type: string - manyToOne: - parentDirectory: - targetEntity: Doctrine\Tests\Models\DirectoryTree\Directory diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DirectoryTree.Directory.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DirectoryTree.Directory.dcm.yml deleted file mode 100644 index d2b93d4901c..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DirectoryTree.Directory.dcm.yml +++ /dev/null @@ -1,6 +0,0 @@ -Doctrine\Tests\Models\DirectoryTree\Directory: - type: entity - fields: - path: - type: string - length: 255 diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DirectoryTree.File.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DirectoryTree.File.dcm.yml deleted file mode 100644 index cbc8edfec4f..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DirectoryTree.File.dcm.yml +++ /dev/null @@ -1,6 +0,0 @@ -Doctrine\Tests\Models\DirectoryTree\File: - type: entity - fields: - extension: - type: string - length: 10 diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Generic.SerializationModel.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Generic.SerializationModel.dcm.yml deleted file mode 100644 index 64f74b55f9b..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Generic.SerializationModel.dcm.yml +++ /dev/null @@ -1,13 +0,0 @@ -\stdClass: - type: entity - id: - id: - type: integer - unsigned: true - generator: - strategy: AUTO - fields: - array: - type: array - object: - type: object \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.Animal.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.Animal.dcm.yml deleted file mode 100644 index 7bdad824037..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.Animal.dcm.yml +++ /dev/null @@ -1,17 +0,0 @@ -Doctrine\Tests\ORM\Mapping\Animal: - type: entity - inheritanceType: SINGLE_TABLE - discriminatorMap: - cat: Cat - dog: Dog - discriminatorColumn: - type: string - name: discr - length: 32 - id: - id: - type: integer - generator: - strategy: CUSTOM - customIdGenerator: - class: stdClass diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.Comment.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.Comment.dcm.yml deleted file mode 100644 index f37bfdcc67b..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.Comment.dcm.yml +++ /dev/null @@ -1,11 +0,0 @@ -Doctrine\Tests\ORM\Mapping\Comment: - type: entity - fields: - content: - type: text - indexes: - 0: - columns: content - flags: fulltext - options: - where: "content IS NOT NULL" diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.DDC1170Entity.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.DDC1170Entity.dcm.yml deleted file mode 100644 index 8b2ac518bc9..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.DDC1170Entity.dcm.yml +++ /dev/null @@ -1,10 +0,0 @@ -Doctrine\Tests\ORM\Mapping\DDC1170Entity: - type: entity - id: - id: - columnDefinition: INT unsigned NOT NULL - generator: - strategy: NONE - fields: - value: - columnDefinition: VARCHAR(255) NOT NULL \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.DDC2069Entity.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.DDC2069Entity.dcm.yml deleted file mode 100644 index 5b16c12bc94..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.DDC2069Entity.dcm.yml +++ /dev/null @@ -1,15 +0,0 @@ -Doctrine\Tests\ORM\Mapping\DDC2069Entity: - type: entity - id: - id: ~ - fields: - name: - type: string ( 255 ) - value: - type: string ( 255 ) - uniqueConstraints: - 0: - columns: name, value - indexes: - 0: - columns: value, name diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.DDC807Entity.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.DDC807Entity.dcm.yml deleted file mode 100644 index 20db3c328e9..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.DDC807Entity.dcm.yml +++ /dev/null @@ -1,13 +0,0 @@ -Doctrine\Tests\ORM\Mapping\DDC807Entity: - type: entity - inheritanceType: SINGLE_TABLE - discriminatorMap: - ONE: DDC807SubClasse1 - TWO: DDC807SubClasse2 - discriminatorColumn: - name: dtype - columnDefinition: ENUM('ONE','TWO') - id: - id: - generator: - strategy: NONE \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.SingleTableEntityIncompleteDiscriminatorColumnMapping.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.SingleTableEntityIncompleteDiscriminatorColumnMapping.dcm.yml deleted file mode 100644 index 8c71ef7091f..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.SingleTableEntityIncompleteDiscriminatorColumnMapping.dcm.yml +++ /dev/null @@ -1,12 +0,0 @@ -Doctrine\Tests\ORM\Mapping\SingleTableEntityIncompleteDiscriminatorColumnMapping: - type: entity - inheritanceType: SINGLE_TABLE - discriminatorMap: - ONE: SingleTableEntityIncompleteDiscriminatorColumnMappingSub1 - TWO: SingleTableEntityIncompleteDiscriminatorColumnMappingSub2 - discriminatorColumn: - name: dtype - id: - id: - generator: - strategy: NONE \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.SingleTableEntityNoDiscriminatorColumnMapping.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.SingleTableEntityNoDiscriminatorColumnMapping.dcm.yml deleted file mode 100644 index 5cab520d1c4..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.SingleTableEntityNoDiscriminatorColumnMapping.dcm.yml +++ /dev/null @@ -1,10 +0,0 @@ -Doctrine\Tests\ORM\Mapping\SingleTableEntityNoDiscriminatorColumnMapping: - type: entity - inheritanceType: SINGLE_TABLE - discriminatorMap: - ONE: SingleTableEntityNoDiscriminatorColumnMappingSub1 - TWO: SingleTableEntityNoDiscriminatorColumnMappingSub2 - id: - id: - generator: - strategy: NONE \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.User.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.User.dcm.yml deleted file mode 100644 index e3a32ce76be..00000000000 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.User.dcm.yml +++ /dev/null @@ -1,85 +0,0 @@ -Doctrine\Tests\ORM\Mapping\User: - type: entity - table: cms_users - options: - foo: bar - baz: - key: val - namedQueries: - all: SELECT u FROM __CLASS__ u - id: - id: - type: integer - generator: - strategy: AUTO - sequenceGenerator: - sequenceName: tablename_seq - allocationSize: 100 - initialValue: 1 - options: - foo: bar - unsigned: false - fields: - name: - type: string - length: 50 - nullable: true - unique: true - options: - foo: bar - baz: - key: val - fixed: false - email: - type: string - column: user_email - columnDefinition: CHAR(32) NOT NULL - version: - type: integer - version: true - oneToOne: - address: - targetEntity: Address - inversedBy: user - joinColumn: - name: address_id - referencedColumnName: id - onDelete: CASCADE - cascade: [ remove ] - oneToMany: - phonenumbers: - targetEntity: Phonenumber - orphanRemoval: true - mappedBy: user - orderBy: - number: ASC - cascade: [ persist ] - manyToMany: - groups: - targetEntity: Group - joinTable: - name: cms_users_groups - joinColumns: - user_id: - referencedColumnName: id - nullable: false - unique: false - inverseJoinColumns: - group_id: - referencedColumnName: id - columnDefinition: INT NULL - cascade: - - all - lifecycleCallbacks: - prePersist: [ doStuffOnPrePersist, doOtherStuffOnPrePersistToo ] - postPersist: [ doStuffOnPostPersist ] - uniqueConstraints: - search_idx: - columns: name,user_email - options: - where: name IS NOT NULL - indexes: - name_idx: - columns: name - 0: - columns: user_email diff --git a/tests/Doctrine/Tests/ORM/ORMInvalidArgumentExceptionTest.php b/tests/Doctrine/Tests/ORM/ORMInvalidArgumentExceptionTest.php deleted file mode 100644 index b4d26907854..00000000000 --- a/tests/Doctrine/Tests/ORM/ORMInvalidArgumentExceptionTest.php +++ /dev/null @@ -1,61 +0,0 @@ -getMessage()); - } - - /** - * @return string[][] - */ - public function invalidEntityNames() - { - return [ - [null, 'Entity name must be a string, NULL given'], - [true, 'Entity name must be a string, boolean given'], - [123, 'Entity name must be a string, integer given'], - [123.45, 'Entity name must be a string, double given'], - [new \stdClass(), 'Entity name must be a string, object given'], - ]; - } -} diff --git a/tests/Doctrine/Tests/ORM/Performance/DDC2602Test.php b/tests/Doctrine/Tests/ORM/Performance/DDC2602Test.php index de8bedfc7d1..bdf4aafa908 100644 --- a/tests/Doctrine/Tests/ORM/Performance/DDC2602Test.php +++ b/tests/Doctrine/Tests/ORM/Performance/DDC2602Test.php @@ -1,13 +1,17 @@ _schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(DDC2602User::class), - $this->_em->getClassMetadata(DDC2602Biography::class), - $this->_em->getClassMetadata(DDC2602BiographyField::class), - $this->_em->getClassMetadata(DDC2602BiographyFieldChoice::class), + $this->em->getClassMetadata(DDC2602User::class), + $this->em->getClassMetadata(DDC2602Biography::class), + $this->em->getClassMetadata(DDC2602BiographyField::class), + $this->em->getClassMetadata(DDC2602BiographyFieldChoice::class), ] ); @@ -32,26 +36,26 @@ protected function tearDown() { parent::tearDown(); - $this->_schemaTool->dropSchema( + $this->schemaTool->dropSchema( [ - $this->_em->getClassMetadata(DDC2602User::class), - $this->_em->getClassMetadata(DDC2602Biography::class), - $this->_em->getClassMetadata(DDC2602BiographyField::class), - $this->_em->getClassMetadata(DDC2602BiographyFieldChoice::class), + $this->em->getClassMetadata(DDC2602User::class), + $this->em->getClassMetadata(DDC2602Biography::class), + $this->em->getClassMetadata(DDC2602BiographyField::class), + $this->em->getClassMetadata(DDC2602BiographyFieldChoice::class), ] ); } public function testIssue() { - $eventManager = $this->_em->getEventManager(); + $eventManager = $this->em->getEventManager(); $eventManager->addEventListener([Events::postLoad], new DDC2602PostLoadListener()); // Set maximum seconds this can run $this->setMaxRunningTime(1); $this - ->_em + ->em ->createQuery('SELECT u, b FROM Doctrine\Tests\ORM\Performance\DDC2602User u JOIN u.biography b') ->getResult(); } @@ -113,14 +117,14 @@ private function loadFixture() $biographyFieldChoice6->field = $biographyField2; $biographyFieldChoice6->label = 'Answer 2.2'; - $this->_em->persist($user1); - $this->_em->persist($user2); + $this->em->persist($user1); + $this->em->persist($user2); - $this->_em->persist($biographyField1); - $this->_em->persist($biographyField2); + $this->em->persist($biographyField1); + $this->em->persist($biographyField2); - $this->_em->flush(); - $this->_em->clear(); + $this->em->flush(); + $this->em->clear(); } } @@ -165,32 +169,32 @@ public function postLoad(LifecycleEventArgs $event) /** - * @Entity + * @ORM\Entity */ class DDC2602User { /** - * @Id @GeneratedValue - * @Column(type="integer") + * @ORM\Id @ORM\GeneratedValue + * @ORM\Column(type="integer") * * @var integer */ public $id; /** - * @Column(type="string", length=15) + * @ORM\Column(type="string", length=15) * * @var string */ public $name; /** - * @OneToOne( + * @ORM\OneToOne( * targetEntity="DDC2602Biography", * inversedBy="user", - * cascade={"persist", "merge", "refresh", "remove"} + * cascade={"persist", "refresh", "remove"} * ) - * @JoinColumn(nullable=false) + * @ORM\JoinColumn(nullable=false) * * @var DDC2602Biography */ @@ -198,23 +202,23 @@ class DDC2602User } /** - * @Entity + * @ORM\Entity */ class DDC2602Biography { /** - * @Id @GeneratedValue - * @Column(type="integer") + * @ORM\Id @ORM\GeneratedValue + * @ORM\Column(type="integer") * * @var integer */ public $id; /** - * @OneToOne( + * @ORM\OneToOne( * targetEntity="DDC2602User", * mappedBy="biography", - * cascade={"persist", "merge", "refresh"} + * cascade={"persist", "refresh"} * ) * * @var DDC2602User @@ -222,7 +226,7 @@ class DDC2602Biography public $user; /** - * @Column(type="text", nullable=true) + * @ORM\Column(type="text", nullable=true) * * @var string */ @@ -235,33 +239,33 @@ class DDC2602Biography } /** - * @Entity + * @ORM\Entity */ class DDC2602BiographyField { /** - * @Id @GeneratedValue - * @Column(type="integer") + * @ORM\Id @ORM\GeneratedValue + * @ORM\Column(type="integer") * * @var integer */ public $id; /** - * @Column(type="string", unique=true, length=100) + * @ORM\Column(type="string", unique=true, length=100) */ public $alias; /** - * @Column(type="string", length=100) + * @ORM\Column(type="string", length=100) */ public $label; /** - * @OneToMany( + * @ORM\OneToMany( * targetEntity="DDC2602BiographyFieldChoice", * mappedBy="field", - * cascade={"persist", "merge", "refresh"} + * cascade={"persist", "refresh"} * ) * * @var \Doctrine\Common\Collections\ArrayCollection @@ -279,29 +283,29 @@ public function __construct() } /** - * @Entity + * @ORM\Entity */ class DDC2602BiographyFieldChoice { /** - * @Id @GeneratedValue - * @Column(type="integer") + * @ORM\Id @ORM\GeneratedValue + * @ORM\Column(type="integer") * * @var integer */ public $id; /** - * @Column(type="string", unique=true, length=100) + * @ORM\Column(type="string", unique=true, length=100) */ public $label; /** - * @ManyToOne( + * @ORM\ManyToOne( * targetEntity="DDC2602BiographyField", * inversedBy="choiceList" * ) - * @JoinColumn(onDelete="CASCADE") + * @ORM\JoinColumn(onDelete="CASCADE") * * @var DDC2602BiographyField */ diff --git a/tests/Doctrine/Tests/ORM/Performance/SecondLevelCacheTest.php b/tests/Doctrine/Tests/ORM/Performance/SecondLevelCacheTest.php index f954d4f4791..092e3146f0a 100644 --- a/tests/Doctrine/Tests/ORM/Performance/SecondLevelCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Performance/SecondLevelCacheTest.php @@ -1,5 +1,7 @@ _getEntityManager(); + $em = $this->getEntityManager(); $em->getConnection()->getConfiguration()->setSQLLogger($logger); $em->getConfiguration()->setSQLLogger($logger); @@ -50,7 +53,7 @@ public function testFindEntityWithoutCache() $this->findEntity($em, __FUNCTION__); - $this->assertEquals(6002, $this->countQuery($em)); + self::assertEquals(6002, $this->countQuery($em)); } public function testFindEntityWithCache() @@ -61,7 +64,7 @@ public function testFindEntityWithCache() $this->findEntity($em, __FUNCTION__); - $this->assertEquals(502, $this->countQuery($em)); + self::assertEquals(502, $this->countQuery($em)); } public function testFindAllEntityWithoutCache() @@ -70,7 +73,7 @@ public function testFindAllEntityWithoutCache() $this->findAllEntity($em, __FUNCTION__); - $this->assertEquals(153, $this->countQuery($em)); + self::assertEquals(153, $this->countQuery($em)); } public function testFindAllEntityWithCache() @@ -81,7 +84,7 @@ public function testFindAllEntityWithCache() $this->findAllEntity($em, __FUNCTION__); - $this->assertEquals(53, $this->countQuery($em)); + self::assertEquals(53, $this->countQuery($em)); } public function testFindEntityOneToManyWithoutCache() @@ -90,7 +93,7 @@ public function testFindEntityOneToManyWithoutCache() $this->findEntityOneToMany($em, __FUNCTION__); - $this->assertEquals(502, $this->countQuery($em)); + self::assertEquals(502, $this->countQuery($em)); } public function testFindEntityOneToManyWithCache() @@ -101,7 +104,7 @@ public function testFindEntityOneToManyWithCache() $this->findEntityOneToMany($em, __FUNCTION__); - $this->assertEquals(472, $this->countQuery($em)); + self::assertEquals(472, $this->countQuery($em)); } public function testQueryEntityWithoutCache() @@ -110,7 +113,7 @@ public function testQueryEntityWithoutCache() $this->queryEntity($em, __FUNCTION__); - $this->assertEquals(602, $this->countQuery($em)); + self::assertEquals(602, $this->countQuery($em)); } public function testQueryEntityWithCache() @@ -121,7 +124,7 @@ public function testQueryEntityWithCache() $this->queryEntity($em, __FUNCTION__); - $this->assertEquals(503, $this->countQuery($em)); + self::assertEquals(503, $this->countQuery($em)); } private function queryEntity(EntityManagerInterface $em, $label) @@ -273,7 +276,7 @@ private function findAllEntity(EntityManagerInterface $em, $label) $list = $rep->findAll(); $em->clear(); - $this->assertCount($size, $list); + self::assertCount($size, $list); } printf("\n[%s] find %s countries (%s times)", number_format(microtime(true) - $startFind, 6), $size, $times); diff --git a/tests/Doctrine/Tests/ORM/PersistentCollectionTest.php b/tests/Doctrine/Tests/ORM/PersistentCollectionTest.php index 0e1c20f517e..38634cae05a 100644 --- a/tests/Doctrine/Tests/ORM/PersistentCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/PersistentCollectionTest.php @@ -1,5 +1,7 @@ _emMock = EntityManagerMock::create(new ConnectionMock([], new DriverMock())); + $this->emMock = EntityManagerMock::create(new ConnectionMock([], new DriverMock())); } /** @@ -40,18 +42,18 @@ protected function setUp() */ public function setUpPersistentCollection() { - $classMetaData = $this->_emMock->getClassMetadata(ECommerceCart::class); - $this->collection = new PersistentCollection($this->_emMock, $classMetaData, new ArrayCollection); + $classMetaData = $this->emMock->getClassMetadata(ECommerceCart::class); + $this->collection = new PersistentCollection($this->emMock, $classMetaData, new ArrayCollection); $this->collection->setInitialized(false); - $this->collection->setOwner(new ECommerceCart(), $classMetaData->getAssociationMapping('products')); + $this->collection->setOwner(new ECommerceCart(), $classMetaData->getProperty('products')); } public function testCanBePutInLazyLoadingMode() { - $class = $this->_emMock->getClassMetadata(ECommerceProduct::class); - $collection = new PersistentCollection($this->_emMock, $class, new ArrayCollection); + $class = $this->emMock->getClassMetadata(ECommerceProduct::class); + $collection = new PersistentCollection($this->emMock, $class, new ArrayCollection); $collection->setInitialized(false); - $this->assertFalse($collection->isInitialized()); + self::assertFalse($collection->isInitialized()); } /** @@ -61,7 +63,7 @@ public function testCurrentInitializesCollection() { $this->setUpPersistentCollection(); $this->collection->current(); - $this->assertTrue($this->collection->isInitialized()); + self::assertTrue($this->collection->isInitialized()); } /** @@ -71,7 +73,7 @@ public function testKeyInitializesCollection() { $this->setUpPersistentCollection(); $this->collection->key(); - $this->assertTrue($this->collection->isInitialized()); + self::assertTrue($this->collection->isInitialized()); } /** @@ -81,7 +83,7 @@ public function testNextInitializesCollection() { $this->setUpPersistentCollection(); $this->collection->next(); - $this->assertTrue($this->collection->isInitialized()); + self::assertTrue($this->collection->isInitialized()); } /** @@ -91,11 +93,11 @@ public function testNonObjects() { $this->setUpPersistentCollection(); - $this->assertEmpty($this->collection); + self::assertEmpty($this->collection); $this->collection->add("dummy"); - $this->assertNotEmpty($this->collection); + self::assertNotEmpty($this->collection); $product = new ECommerceProduct(); @@ -103,9 +105,9 @@ public function testNonObjects() $this->collection->set(2, "dummy"); $this->collection->set(3, null); - $this->assertSame($product, $this->collection->get(1)); - $this->assertSame("dummy", $this->collection->get(2)); - $this->assertSame(null, $this->collection->get(3)); + self::assertSame($product, $this->collection->get(1)); + self::assertSame("dummy", $this->collection->get(2)); + self::assertSame(null, $this->collection->get(3)); } /** @@ -116,10 +118,10 @@ public function testRemovingElementsAlsoRemovesKeys() $this->setUpPersistentCollection(); $this->collection->add('dummy'); - $this->assertEquals([0], array_keys($this->collection->toArray())); + self::assertEquals([0], array_keys($this->collection->toArray())); $this->collection->removeElement('dummy'); - $this->assertEquals([], array_keys($this->collection->toArray())); + self::assertEquals([], array_keys($this->collection->toArray())); } /** @@ -131,7 +133,7 @@ public function testClearWillAlsoClearKeys() $this->collection->add('dummy'); $this->collection->clear(); - $this->assertEquals([], array_keys($this->collection->toArray())); + self::assertEquals([], array_keys($this->collection->toArray())); } /** @@ -145,6 +147,6 @@ public function testClearWillAlsoResetKeyPositions() $this->collection->removeElement('dummy'); $this->collection->clear(); $this->collection->add('dummy'); - $this->assertEquals([0], array_keys($this->collection->toArray())); + self::assertEquals([0], array_keys($this->collection->toArray())); } } diff --git a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeParametersTest.php b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeParametersTest.php index 1694d97ce8f..a9d722aab7e 100644 --- a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeParametersTest.php +++ b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeParametersTest.php @@ -1,8 +1,11 @@ _em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); - $this->_em->getClassMetadata(Country::class); - $this->_em->getClassMetadata(Admin1::class); - $this->_em->getClassMetadata(Admin1AlternateName::class); + $this->em->getClassMetadata(Country::class); + $this->em->getClassMetadata(Admin1::class); + $this->em->getClassMetadata(Admin1AlternateName::class); - $this->_persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata(Admin1AlternateName::class)); + $this->persister = new BasicEntityPersister($this->em, $this->em->getClassMetadata(Admin1AlternateName::class)); } @@ -43,10 +46,10 @@ public function testExpandParametersWillExpandCompositeEntityKeys() $country = new Country("IT", "Italy"); $admin1 = new Admin1(10, "Rome", $country); - list ($values, $types) = $this->_persister->expandParameters(['admin1' => $admin1]); + list ($values, $types) = $this->persister->expandParameters(['admin1' => $admin1]); - $this->assertEquals(['integer', 'string'], $types); - $this->assertEquals([10, 'IT'], $values); + self::assertEquals([Type::getType('integer'), Type::getType('string')], $types); + self::assertEquals([10, 'IT'], $values); } public function testExpandCriteriaParametersWillExpandCompositeEntityKeys() @@ -57,9 +60,9 @@ public function testExpandCriteriaParametersWillExpandCompositeEntityKeys() $criteria = Criteria::create(); $criteria->andWhere(Criteria::expr()->eq("admin1", $admin1)); - list ($values, $types) = $this->_persister->expandCriteriaParameters($criteria); + list ($values, $types) = $this->persister->expandCriteriaParameters($criteria); - $this->assertEquals(['integer', 'string'], $types); - $this->assertEquals([10, 'IT'], $values); + self::assertEquals([Type::getType('integer'), Type::getType('string')], $types); + self::assertEquals([10, 'IT'], $values); } } diff --git a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeSqlTest.php b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeSqlTest.php index 9392b8ee507..639d62c27f4 100644 --- a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeSqlTest.php +++ b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeSqlTest.php @@ -1,7 +1,10 @@ _em = $this->_getTestEntityManager(); - $this->_persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata(Admin1AlternateName::class)); + $this->em = $this->getTestEntityManager(); + $this->persister = new BasicEntityPersister($this->em, $this->em->getClassMetadata(Admin1AlternateName::class)); } public function testSelectConditionStatementEq() { - $statement = $this->_persister->getSelectConditionStatementSQL('admin1', 1, [], Comparison::EQ); - $this->assertEquals('t0.admin1 = ? AND t0.country = ?', $statement); + $statement = $this->persister->getSelectConditionStatementSQL('admin1', 1, new OneToOneAssociationMetadata('admin1'), Comparison::EQ); + self::assertEquals('t0."admin1" = ? AND t0."country" = ?', $statement); } public function testSelectConditionStatementEqNull() { - $statement = $this->_persister->getSelectConditionStatementSQL('admin1', null, [], Comparison::IS); - $this->assertEquals('t0.admin1 IS NULL AND t0.country IS NULL', $statement); + $statement = $this->persister->getSelectConditionStatementSQL('admin1', null, new OneToOneAssociationMetadata('admin1'), Comparison::IS); + self::assertEquals('t0."admin1" IS NULL AND t0."country" IS NULL', $statement); } public function testSelectConditionStatementNeqNull() { - $statement = $this->_persister->getSelectConditionStatementSQL('admin1', null, [], Comparison::NEQ); - $this->assertEquals('t0.admin1 IS NOT NULL AND t0.country IS NOT NULL', $statement); + $statement = $this->persister->getSelectConditionStatementSQL('admin1', null, new OneToOneAssociationMetadata('admin1'), Comparison::NEQ); + self::assertEquals('t0."admin1" IS NOT NULL AND t0."country" IS NOT NULL', $statement); } /** @@ -53,6 +56,6 @@ public function testSelectConditionStatementNeqNull() */ public function testSelectConditionStatementIn() { - $this->_persister->getSelectConditionStatementSQL('admin1', [], [], Comparison::IN); + $this->persister->getSelectConditionStatementSQL('admin1', [], new OneToOneAssociationMetadata('admin1'), Comparison::IN); } } diff --git a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterTypeValueSqlTest.php b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterTypeValueSqlTest.php index ba1d18051e1..567df8c983e 100644 --- a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterTypeValueSqlTest.php +++ b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterTypeValueSqlTest.php @@ -1,10 +1,13 @@ _em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); - $this->_persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata(CustomTypeParent::class)); + $this->persister = new BasicEntityPersister( + $this->em, + $this->em->getClassMetadata(CustomTypeParent::class) + ); } public function testGetInsertSQLUsesTypeValuesSQL() { - $method = new \ReflectionMethod($this->_persister, 'getInsertSQL'); + $method = new \ReflectionMethod($this->persister, 'getInsertSQL'); $method->setAccessible(true); - $sql = $method->invoke($this->_persister); + $sql = $method->invoke($this->persister); - $this->assertEquals('INSERT INTO customtype_parents (customInteger, child_id) VALUES (ABS(?), ?)', $sql); + self::assertEquals('INSERT INTO "customtype_parents" ("customInteger", "child_id") VALUES (ABS(?), ?)', $sql); } public function testUpdateUsesTypeValuesSQL() { $child = new CustomTypeChild(); + $child->id = 1; $parent = new CustomTypeParent(); + $parent->id = 1; $parent->customInteger = 1; $parent->child = $child; - $this->_em->getUnitOfWork()->registerManaged($parent, ['id' => 1], ['customInteger' => 0, 'child' => null]); - $this->_em->getUnitOfWork()->registerManaged($child, ['id' => 1], []); + $this->em->getUnitOfWork()->registerManaged($parent, ['id' => 1], ['customInteger' => 0, 'child' => null]); + $this->em->getUnitOfWork()->registerManaged($child, ['id' => 1], []); - $this->_em->getUnitOfWork()->propertyChanged($parent, 'customInteger', 0, 1); - $this->_em->getUnitOfWork()->propertyChanged($parent, 'child', null, $child); + $this->em->getUnitOfWork()->propertyChanged($parent, 'customInteger', 0, 1); + $this->em->getUnitOfWork()->propertyChanged($parent, 'child', null, $child); - $this->_persister->update($parent); + $this->persister->update($parent); - $executeUpdates = $this->_em->getConnection()->getExecuteUpdates(); + $executeUpdates = $this->em->getConnection()->getExecuteUpdates(); - $this->assertEquals('UPDATE customtype_parents SET customInteger = ABS(?), child_id = ? WHERE id = ?', $executeUpdates[0]['query']); + self::assertEquals( + 'UPDATE "customtype_parents" SET "customInteger" = ABS(?), "child_id" = ? WHERE "id" = ?', + $executeUpdates[0]['query'] + ); } public function testGetSelectConditionSQLUsesTypeValuesSQL() { - $method = new \ReflectionMethod($this->_persister, 'getSelectConditionSQL'); + $method = new \ReflectionMethod($this->persister, 'getSelectConditionSQL'); $method->setAccessible(true); - $sql = $method->invoke($this->_persister, ['customInteger' => 1, 'child' => 1]); + $sql = $method->invoke($this->persister, ['customInteger' => 1, 'child' => 1]); - $this->assertEquals('t0.customInteger = ABS(?) AND t0.child_id = ?', $sql); + self::assertEquals('t0."customInteger" = ABS(?) AND t0."child_id" = ?', $sql); } /** @@ -94,11 +105,11 @@ public function testGetSelectConditionSQLUsesTypeValuesSQL() */ public function testStripNonAlphanumericCharactersFromSelectColumnListSQL() { - $persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata(NonAlphaColumnsEntity::class)); + $persister = new BasicEntityPersister($this->em, $this->em->getClassMetadata(NonAlphaColumnsEntity::class)); $method = new \ReflectionMethod($persister, 'getSelectColumnsSQL'); $method->setAccessible(true); - $this->assertEquals('t0."simple-entity-id" AS simpleentityid_1, t0."simple-entity-value" AS simpleentityvalue_2', $method->invoke($persister)); + self::assertEquals('t1."simple-entity-id" AS c0, t1."simple-entity-value" AS c2', $method->invoke($persister)); } /** @@ -106,20 +117,20 @@ public function testStripNonAlphanumericCharactersFromSelectColumnListSQL() */ public function testSelectConditionStatementIsNull() { - $statement = $this->_persister->getSelectConditionStatementSQL('test', null, [], Comparison::IS); - $this->assertEquals('test IS NULL', $statement); + $statement = $this->persister->getSelectConditionStatementSQL('test', null, new OneToOneAssociationMetadata('test'), Comparison::IS); + self::assertEquals('test IS NULL', $statement); } public function testSelectConditionStatementEqNull() { - $statement = $this->_persister->getSelectConditionStatementSQL('test', null, [], Comparison::EQ); - $this->assertEquals('test IS NULL', $statement); + $statement = $this->persister->getSelectConditionStatementSQL('test', null, new OneToOneAssociationMetadata('test'), Comparison::EQ); + self::assertEquals('test IS NULL', $statement); } public function testSelectConditionStatementNeqNull() { - $statement = $this->_persister->getSelectConditionStatementSQL('test', null, [], Comparison::NEQ); - $this->assertEquals('test IS NOT NULL', $statement); + $statement = $this->persister->getSelectConditionStatementSQL('test', null, new OneToOneAssociationMetadata('test'), Comparison::NEQ); + self::assertEquals('test IS NOT NULL', $statement); } /** @@ -127,38 +138,39 @@ public function testSelectConditionStatementNeqNull() */ public function testSelectConditionStatementWithMultipleValuesContainingNull() { - $this->assertEquals( - '(t0.id IN (?) OR t0.id IS NULL)', - $this->_persister->getSelectConditionStatementSQL('id', [null]) + self::assertEquals( + '(t0."id" IN (?) OR t0."id" IS NULL)', + $this->persister->getSelectConditionStatementSQL('id', [null]) ); - $this->assertEquals( - '(t0.id IN (?) OR t0.id IS NULL)', - $this->_persister->getSelectConditionStatementSQL('id', [null, 123]) + self::assertEquals( + '(t0."id" IN (?) OR t0."id" IS NULL)', + $this->persister->getSelectConditionStatementSQL('id', [null, 123]) ); - $this->assertEquals( - '(t0.id IN (?) OR t0.id IS NULL)', - $this->_persister->getSelectConditionStatementSQL('id', [123, null]) + self::assertEquals( + '(t0."id" IN (?) OR t0."id" IS NULL)', + $this->persister->getSelectConditionStatementSQL('id', [123, null]) ); } public function testCountCondition() { - $persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata(NonAlphaColumnsEntity::class)); + $persister = new BasicEntityPersister($this->em, $this->em->getClassMetadata(NonAlphaColumnsEntity::class)); // Using a criteria as array $statement = $persister->getCountSQL(['value' => 'bar']); - $this->assertEquals('SELECT COUNT(*) FROM "not-a-simple-entity" t0 WHERE t0."simple-entity-value" = ?', $statement); + self::assertEquals('SELECT COUNT(*) FROM "not-a-simple-entity" t0 WHERE t0."simple-entity-value" = ?', $statement); // Using a criteria object $criteria = new Criteria(Criteria::expr()->eq('value', 'bar')); $statement = $persister->getCountSQL($criteria); - $this->assertEquals('SELECT COUNT(*) FROM "not-a-simple-entity" t0 WHERE t0."simple-entity-value" = ?', $statement); + + self::assertEquals('SELECT COUNT(*) FROM "not-a-simple-entity" t0 WHERE t0."simple-entity-value" = ?', $statement); } public function testCountEntities() { - $this->assertEquals(0, $this->_persister->count()); + self::assertEquals(0, $this->persister->count()); } } diff --git a/tests/Doctrine/Tests/ORM/Persisters/JoinedSubclassPersisterTest.php b/tests/Doctrine/Tests/ORM/Persisters/JoinedSubclassPersisterTest.php deleted file mode 100644 index 4a4cec244a4..00000000000 --- a/tests/Doctrine/Tests/ORM/Persisters/JoinedSubclassPersisterTest.php +++ /dev/null @@ -1,44 +0,0 @@ -em = $this->_getTestEntityManager(); - $this->persister = new JoinedSubclassPersister($this->em, $this->em->getClassMetadata(RootClass::class)); - } - - /** - * @group DDC-3470 - */ - public function testExecuteInsertsWillReturnEmptySetWithNoQueuedInserts() - { - $this->assertSame([], $this->persister->executeInserts()); - } -} diff --git a/tests/Doctrine/Tests/ORM/Proxy/ProxyFactoryTest.php b/tests/Doctrine/Tests/ORM/Proxy/ProxyFactoryTest.php index 739a41f1807..f6c5d4af71c 100644 --- a/tests/Doctrine/Tests/ORM/Proxy/ProxyFactoryTest.php +++ b/tests/Doctrine/Tests/ORM/Proxy/ProxyFactoryTest.php @@ -1,13 +1,19 @@ connectionMock = new ConnectionMock([], new DriverMock()); - $this->emMock = EntityManagerMock::create($this->connectionMock); - $this->uowMock = new UnitOfWorkMock($this->emMock); + + $this->metadataBuildingContext = new ClassMetadataBuildingContext( + $this->createMock(ClassMetadataFactory::class), + new RuntimeReflectionService() + ); + $this->connectionMock = new ConnectionMock([], new DriverMock()); + $this->emMock = EntityManagerMock::create($this->connectionMock); + $this->uowMock = new UnitOfWorkMock($this->emMock); + $this->emMock->setUnitOfWork($this->uowMock); - $this->proxyFactory = new ProxyFactory($this->emMock, sys_get_temp_dir(), 'Proxies', AbstractProxyFactory::AUTOGENERATE_ALWAYS); + + $proxyConfiguration = new ProxyConfiguration(); + + $proxyConfiguration->setDirectory(sys_get_temp_dir()); + $proxyConfiguration->setNamespace('Proxies'); + $proxyConfiguration->setAutoGenerate(ProxyFactory::AUTOGENERATE_ALWAYS); + $proxyConfiguration->setResolver(new DefaultProxyResolver( + $proxyConfiguration->getNamespace(), + $proxyConfiguration->getDirectory() + )); + + $this->proxyFactory = new StaticProxyFactory($this->emMock, $proxyConfiguration); } public function testReferenceProxyDelegatesLoadingToThePersister() { $identifier = ['id' => 42]; $proxyClass = 'Proxies\__CG__\Doctrine\Tests\Models\ECommerce\ECommerceFeature'; - $persister = $this->getMockBuilder(BasicEntityPersister::class)->setMethods(['load'])->disableOriginalConstructor()->getMock(); - $this->uowMock->setEntityPersister(ECommerceFeature::class, $persister); + $classMetaData = $this->emMock->getClassMetadata(ECommerceFeature::class); - $proxy = $this->proxyFactory->getProxy(ECommerceFeature::class, $identifier); + $persister = $this + ->getMockBuilder(BasicEntityPersister::class) + ->setConstructorArgs([$this->emMock, $classMetaData]) + ->setMethods(['load']) + ->getMock(); $persister ->expects($this->atLeastOnce()) @@ -72,6 +103,10 @@ public function testReferenceProxyDelegatesLoadingToThePersister() ->with($this->equalTo($identifier), $this->isInstanceOf($proxyClass)) ->will($this->returnValue(new \stdClass())); + $this->uowMock->setEntityPersister(ECommerceFeature::class, $persister); + + $proxy = $this->proxyFactory->getProxy(ECommerceFeature::class, $identifier); + $proxy->getDescription(); } @@ -80,13 +115,13 @@ public function testReferenceProxyDelegatesLoadingToThePersister() */ public function testSkipAbstractClassesOnGeneration() { - $cm = new ClassMetadata(AbstractClass::class); - $cm->initializeReflection(new RuntimeReflectionService()); - $this->assertNotNull($cm->reflClass); + $cm = new ClassMetadata(AbstractClass::class, $this->metadataBuildingContext); + + self::assertNotNull($cm->getReflectionClass()); $num = $this->proxyFactory->generateProxyClasses([$cm]); - $this->assertEquals(0, $num, "No proxies generated."); + self::assertEquals(0, $num, "No proxies generated."); } /** @@ -94,26 +129,31 @@ public function testSkipAbstractClassesOnGeneration() */ public function testFailedProxyLoadingDoesNotMarkTheProxyAsInitialized() { - $persister = $this->getMockBuilder(BasicEntityPersister::class)->setMethods(['load'])->disableOriginalConstructor()->getMock(); - $this->uowMock->setEntityPersister(ECommerceFeature::class, $persister); + $classMetaData = $this->emMock->getClassMetadata(ECommerceFeature::class); - /* @var $proxy \Doctrine\Common\Proxy\Proxy */ - $proxy = $this->proxyFactory->getProxy(ECommerceFeature::class, ['id' => 42]); + $persister = $this + ->getMockBuilder(BasicEntityPersister::class) + ->setConstructorArgs([$this->emMock, $classMetaData]) + ->setMethods(['load']) + ->getMock(); $persister ->expects($this->atLeastOnce()) ->method('load') ->will($this->returnValue(null)); + $this->uowMock->setEntityPersister(ECommerceFeature::class, $persister); + + /* @var $proxy \Doctrine\Common\Proxy\Proxy */ + $proxy = $this->proxyFactory->getProxy(ECommerceFeature::class, ['id' => 42]); + try { $proxy->getDescription(); $this->fail('An exception was expected to be raised'); } catch (EntityNotFoundException $exception) { } - $this->assertFalse($proxy->__isInitialized()); - $this->assertInstanceOf('Closure', $proxy->__getInitializer(), 'The initializer wasn\'t removed'); - $this->assertInstanceOf('Closure', $proxy->__getCloner(), 'The cloner wasn\'t removed'); + self::assertFalse($proxy->__isInitialized()); } /** @@ -121,26 +161,31 @@ public function testFailedProxyLoadingDoesNotMarkTheProxyAsInitialized() */ public function testFailedProxyCloningDoesNotMarkTheProxyAsInitialized() { - $persister = $this->getMockBuilder(BasicEntityPersister::class)->setMethods(['load'])->disableOriginalConstructor()->getMock(); - $this->uowMock->setEntityPersister(ECommerceFeature::class, $persister); + $classMetaData = $this->emMock->getClassMetadata(ECommerceFeature::class); - /* @var $proxy \Doctrine\Common\Proxy\Proxy */ - $proxy = $this->proxyFactory->getProxy(ECommerceFeature::class, ['id' => 42]); + $persister = $this + ->getMockBuilder(BasicEntityPersister::class) + ->setConstructorArgs([$this->emMock, $classMetaData]) + ->setMethods(['load']) + ->getMock(); $persister ->expects($this->atLeastOnce()) ->method('load') ->will($this->returnValue(null)); + $this->uowMock->setEntityPersister(ECommerceFeature::class, $persister); + + /* @var $proxy \Doctrine\Common\Proxy\Proxy */ + $proxy = $this->proxyFactory->getProxy(ECommerceFeature::class, ['id' => 42]); + try { $cloned = clone $proxy; $this->fail('An exception was expected to be raised'); } catch (EntityNotFoundException $exception) { } - $this->assertFalse($proxy->__isInitialized()); - $this->assertInstanceOf('Closure', $proxy->__getInitializer(), 'The initializer wasn\'t removed'); - $this->assertInstanceOf('Closure', $proxy->__getCloner(), 'The cloner wasn\'t removed'); + self::assertFalse($proxy->__isInitialized()); } public function testProxyClonesParentFields() @@ -159,23 +204,19 @@ public function testProxyClonesParentFields() $persister = $this ->getMockBuilder(BasicEntityPersister::class) - ->setMethods(['load', 'getClassMetadata']) - ->disableOriginalConstructor() + ->setConstructorArgs([$this->emMock, $classMetaData]) + ->setMethods(['load']) ->getMock(); - $this->uowMock->setEntityPersister(CompanyEmployee::class, $persister); - - /* @var $proxy \Doctrine\Common\Proxy\Proxy */ - $proxy = $this->proxyFactory->getProxy(CompanyEmployee::class, ['id' => 42]); $persister ->expects(self::atLeastOnce()) ->method('load') ->willReturn($companyEmployee); - $persister - ->expects(self::atLeastOnce()) - ->method('getClassMetadata') - ->willReturn($classMetaData); + $this->uowMock->setEntityPersister(CompanyEmployee::class, $persister); + + /* @var $proxy \Doctrine\Common\Proxy\Proxy */ + $proxy = $this->proxyFactory->getProxy(CompanyEmployee::class, ['id' => 42]); /* @var $cloned CompanyEmployee */ $cloned = clone $proxy; diff --git a/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersJoinTest.php b/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersJoinTest.php index 9bc5bf5a0dc..06201b614e8 100644 --- a/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersJoinTest.php +++ b/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersJoinTest.php @@ -1,5 +1,7 @@ em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); } public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed) @@ -30,27 +32,29 @@ public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed) $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CustomTreeWalkerJoin::class]) ->useQueryCache(false); - $this->assertEquals($sqlToBeConfirmed, $query->getSql()); + $sqlGenerated = $query->getSql(); + $query->free(); } catch (\Exception $e) { $this->fail($e->getMessage() . ' at "' . $e->getFile() . '" on line ' . $e->getLine()); - } + + self::assertEquals($sqlToBeConfirmed, $sqlGenerated); } public function testAddsJoin() { - $this->assertSqlGeneration( + self::assertSqlGeneration( 'select u from Doctrine\Tests\Models\CMS\CmsUser u', - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c1_.id AS id_4, c1_.country AS country_5, c1_.zip AS zip_6, c1_.city AS city_7, c0_.email_id AS email_id_8, c1_.user_id AS user_id_9 FROM cms_users c0_ LEFT JOIN cms_addresses c1_ ON c0_.id = c1_.user_id" + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, t1."id" AS c4, t1."country" AS c5, t1."zip" AS c6, t1."city" AS c7, t0."email_id" AS c8, t1."user_id" AS c9 FROM "cms_users" t0 LEFT JOIN "cms_addresses" t1 ON t0."id" = t1."user_id"' ); } public function testDoesNotAddJoin() { - $this->assertSqlGeneration( + self::assertSqlGeneration( 'select a from Doctrine\Tests\Models\CMS\CmsAddress a', - "SELECT c0_.id AS id_0, c0_.country AS country_1, c0_.zip AS zip_2, c0_.city AS city_3, c0_.user_id AS user_id_4 FROM cms_addresses c0_" + 'SELECT t0."id" AS c0, t0."country" AS c1, t0."zip" AS c2, t0."city" AS c3, t0."user_id" AS c4 FROM "cms_addresses" t0' ); } } @@ -81,7 +85,7 @@ private function modifySelectStatement(Query\AST\SelectStatement $selectStatemen $identificationVariableDecl->joins[] = $join; $selectStatement->selectClause->selectExpressions[] = $selectExpression; - $entityManager = $this->_getQuery()->getEntityManager(); + $entityManager = $this->getQuery()->getEntityManager(); $userMetadata = $entityManager->getClassMetadata(CmsUser::class); $addressMetadata = $entityManager->getClassMetadata(CmsAddress::class); @@ -89,7 +93,7 @@ private function modifySelectStatement(Query\AST\SelectStatement $selectStatemen [ 'metadata' => $addressMetadata, 'parent' => $rangeVariableDecl->aliasIdentificationVariable, - 'relation' => $userMetadata->getAssociationMapping('address'), + 'relation' => $userMetadata->getProperty('address'), 'map' => null, 'nestingLevel' => 0, 'token' => null, diff --git a/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersTest.php b/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersTest.php index 4c2898141a7..cf391e53619 100644 --- a/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersTest.php +++ b/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersTest.php @@ -1,5 +1,7 @@ _em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); } public function generateSql($dqlToBeTested, $treeWalkers, $outputWalker) { - $query = $this->_em->createQuery($dqlToBeTested); + $query = $this->em->createQuery($dqlToBeTested); $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, $treeWalkers) ->useQueryCache(false); @@ -41,17 +43,19 @@ public function generateSql($dqlToBeTested, $treeWalkers, $outputWalker) public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed, $treeWalkers = [], $outputWalker = null) { try { - $this->assertEquals($sqlToBeConfirmed, $this->generateSql($dqlToBeTested, $treeWalkers, $outputWalker)); + $sqlGenerated = $this->generateSql($dqlToBeTested, $treeWalkers, $outputWalker); } catch (\Exception $e) { $this->fail($e->getMessage() . ' at "' . $e->getFile() . '" on line ' . $e->getLine()); } + + self::assertEquals($sqlToBeConfirmed, $sqlGenerated); } public function testSupportsQueriesWithoutWhere() { $this->assertSqlGeneration( 'select u from Doctrine\Tests\Models\CMS\CmsUser u', - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE c0_.id = 1", + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, t0."email_id" AS c4 FROM "cms_users" t0 WHERE t0."id" = 1', [CustomTreeWalker::class] ); } @@ -60,7 +64,7 @@ public function testSupportsQueriesWithMultipleConditionalExpressions() { $this->assertSqlGeneration( 'select u from Doctrine\Tests\Models\CMS\CmsUser u where u.name = :name or u.name = :otherName', - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE (c0_.name = ? OR c0_.name = ?) AND c0_.id = 1", + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, t0."email_id" AS c4 FROM "cms_users" t0 WHERE (t0."name" = ? OR t0."name" = ?) AND t0."id" = 1', [CustomTreeWalker::class] ); } @@ -69,7 +73,7 @@ public function testSupportsQueriesWithSimpleConditionalExpression() { $this->assertSqlGeneration( 'select u from Doctrine\Tests\Models\CMS\CmsUser u where u.name = :name', - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE c0_.name = ? AND c0_.id = 1", + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, t0."email_id" AS c4 FROM "cms_users" t0 WHERE t0."name" = ? AND t0."id" = 1', [CustomTreeWalker::class] ); } @@ -90,7 +94,7 @@ public function testSupportsSeveralHintsQueries() { $this->assertSqlGeneration( 'select u from Doctrine\Tests\Models\CMS\CmsUser u', - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c1_.id AS id_4, c1_.country AS country_5, c1_.zip AS zip_6, c1_.city AS city_7, c0_.email_id AS email_id_8, c1_.user_id AS user_id_9 FROM cms_users c0_ LEFT JOIN cms_addresses c1_ ON c0_.id = c1_.user_id WHERE c0_.id = 1", + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, t1."id" AS c4, t1."country" AS c5, t1."zip" AS c6, t1."city" AS c7, t0."email_id" AS c8, t1."user_id" AS c9 FROM "cms_users" t0 LEFT JOIN "cms_addresses" t1 ON t0."id" = t1."user_id" WHERE t0."id" = 1', [CustomTreeWalkerJoin::class, CustomTreeWalker::class] ); } @@ -113,10 +117,10 @@ public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) // Get the DQL aliases of all the classes we want to modify $dqlAliases = []; - foreach ($this->_getQueryComponents() as $dqlAlias => $comp) { + foreach ($this->getQueryComponents() as $dqlAlias => $comp) { // Hard-coded check just for demonstration: We want to modify the query if // it involves the CmsUser class. - if ($comp['metadata']->name == CmsUser::class) { + if ($comp['metadata']->getClassName() == CmsUser::class) { $dqlAliases[] = $dqlAlias; } } @@ -208,7 +212,7 @@ private function modifySelectStatement(Query\AST\SelectStatement $selectStatemen $identificationVariableDecl->joins[] = $join; $selectStatement->selectClause->selectExpressions[] = $selectExpression; - $entityManager = $this->_getQuery()->getEntityManager(); + $entityManager = $this->getQuery()->getEntityManager(); $userMetadata = $entityManager->getClassMetadata(CmsUser::class); $addressMetadata = $entityManager->getClassMetadata(CmsAddress::class); @@ -216,7 +220,7 @@ private function modifySelectStatement(Query\AST\SelectStatement $selectStatemen [ 'metadata' => $addressMetadata, 'parent' => $rangeVariableDecl->aliasIdentificationVariable, - 'relation' => $userMetadata->getAssociationMapping('address'), + 'relation' => $userMetadata->getProperty('address'), 'map' => null, 'nestingLevel' => 0, 'token' => null, diff --git a/tests/Doctrine/Tests/ORM/Query/DeleteSqlGenerationTest.php b/tests/Doctrine/Tests/ORM/Query/DeleteSqlGenerationTest.php index 8218339df35..35c94950d14 100644 --- a/tests/Doctrine/Tests/ORM/Query/DeleteSqlGenerationTest.php +++ b/tests/Doctrine/Tests/ORM/Query/DeleteSqlGenerationTest.php @@ -1,5 +1,7 @@ _em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); } public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed) { try { - $query = $this->_em->createQuery($dqlToBeTested); - parent::assertEquals($sqlToBeConfirmed, $query->getSql()); + $query = $this->em->createQuery($dqlToBeTested); + + $sqlGenerated = $query->getSql(); + $query->free(); } catch (\Exception $e) { $this->fail($e->getMessage()); } + + self::assertEquals($sqlToBeConfirmed, $sqlGenerated); } public function testSupportsDeleteWithoutWhereAndFrom() { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u', - 'DELETE FROM cms_users' + 'DELETE FROM "cms_users"' ); } @@ -48,7 +54,7 @@ public function testSupportsDeleteWithoutWhere() { $this->assertSqlGeneration( 'DELETE FROM Doctrine\Tests\Models\CMS\CmsUser u', - 'DELETE FROM cms_users' + 'DELETE FROM "cms_users"' ); } @@ -56,7 +62,7 @@ public function testSupportsWhereClause() { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1', - 'DELETE FROM cms_users WHERE id = ?' + 'DELETE FROM "cms_users" WHERE "id" = ?' ); } @@ -64,7 +70,7 @@ public function testSupportsWhereOrExpressions() { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = ?1 OR u.name = ?2', - 'DELETE FROM cms_users WHERE username = ? OR name = ?' + 'DELETE FROM "cms_users" WHERE "username" = ? OR "name" = ?' ); } @@ -72,52 +78,47 @@ public function testSupportsWhereNestedConditionalExpressions() { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1 OR ( u.username = ?2 OR u.name = ?3)', - 'DELETE FROM cms_users WHERE id = ? OR (username = ? OR name = ?)' + 'DELETE FROM "cms_users" WHERE "id" = ? OR ("username" = ? OR "name" = ?)' ); - - //$this->assertSqlGeneration( - // 'DELETE FROM Doctrine\Tests\Models\CMS\CmsUser WHERE id = ?1', - // 'DELETE FROM cms_users WHERE id = ?' - //); } public function testIsCaseAgnostic() { $this->assertSqlGeneration( - "delete from Doctrine\Tests\Models\CMS\CmsUser u where u.username = ?1", - "DELETE FROM cms_users WHERE username = ?" + 'delete from Doctrine\Tests\Models\CMS\CmsUser u where u.username = ?1', + 'DELETE FROM "cms_users" WHERE "username" = ?' ); } public function testSupportsAndCondition() { $this->assertSqlGeneration( - "DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = ?1 AND u.name = ?2", - "DELETE FROM cms_users WHERE username = ? AND name = ?" + 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = ?1 AND u.name = ?2', + 'DELETE FROM "cms_users" WHERE "username" = ? AND "name" = ?' ); } public function testSupportsWhereNot() { $this->assertSqlGeneration( - "DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE NOT u.id != ?1", - "DELETE FROM cms_users WHERE NOT id <> ?" + 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE NOT u.id != ?1', + 'DELETE FROM "cms_users" WHERE NOT "id" <> ?' ); } public function testSupportsWhereNotWithParentheses() { $this->assertSqlGeneration( - "DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE NOT ( u.id != ?1 )", - "DELETE FROM cms_users WHERE NOT (id <> ?)" + 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE NOT ( u.id != ?1 )', + 'DELETE FROM "cms_users" WHERE NOT ("id" <> ?)' ); } public function testSupportsWhereNotWithAndExpression() { $this->assertSqlGeneration( - "DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE NOT ( u.id != ?1 AND u.username = ?2 )", - "DELETE FROM cms_users WHERE NOT (id <> ? AND username = ?)" + 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE NOT ( u.id != ?1 AND u.username = ?2 )', + 'DELETE FROM "cms_users" WHERE NOT ("id" <> ? AND "username" = ?)' ); } @@ -125,66 +126,66 @@ public function testSupportsWhereNotWithAndExpression() public function testSupportsGreaterThanComparisonClause() { - // id = ? was already tested (see testDeleteWithWhere()) + // "id" = ? was already tested (see testDeleteWithWhere()) $this->assertSqlGeneration( - "DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id > ?1", - "DELETE FROM cms_users WHERE id > ?" + 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id > ?1', + 'DELETE FROM "cms_users" WHERE "id" > ?' ); } public function testSupportsGreaterThanOrEqualToComparisonClause() { $this->assertSqlGeneration( - "DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id >= ?1", - "DELETE FROM cms_users WHERE id >= ?" + 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id >= ?1', + 'DELETE FROM "cms_users" WHERE "id" >= ?' ); } public function testSupportsLessThanComparisonClause() { $this->assertSqlGeneration( - "DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id < ?1", - "DELETE FROM cms_users WHERE id < ?" + 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id < ?1', + 'DELETE FROM "cms_users" WHERE "id" < ?' ); } public function testSupportsLessThanOrEqualToComparisonClause() { $this->assertSqlGeneration( - "DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id <= ?1", - "DELETE FROM cms_users WHERE id <= ?" + 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id <= ?1', + 'DELETE FROM "cms_users" WHERE "id" <= ?' ); } public function testSupportsNotEqualToComparisonClause() { $this->assertSqlGeneration( - "DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id <> ?1", - "DELETE FROM cms_users WHERE id <> ?" + 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id <> ?1', + 'DELETE FROM "cms_users" WHERE "id" <> ?' ); } public function testSupportsNotEqualToComparisonClauseExpressedWithExclamationMark() { $this->assertSqlGeneration( - "DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id != ?1", - "DELETE FROM cms_users WHERE id <> ?" + 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id != ?1', + 'DELETE FROM "cms_users" WHERE "id" <> ?' ); } public function testSupportsNotBetweenClause() { $this->assertSqlGeneration( - "DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id NOT BETWEEN ?1 AND ?2", - "DELETE FROM cms_users WHERE id NOT BETWEEN ? AND ?" + 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id NOT BETWEEN ?1 AND ?2', + 'DELETE FROM "cms_users" WHERE "id" NOT BETWEEN ? AND ?' ); } public function testSupportsBetweenClauseUsedWithAndClause() { $this->assertSqlGeneration( - "DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id BETWEEN ?1 AND ?2 AND u.username != ?3", - "DELETE FROM cms_users WHERE id BETWEEN ? AND ? AND username <> ?" + 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id BETWEEN ?1 AND ?2 AND u.username != ?3', + 'DELETE FROM "cms_users" WHERE "id" BETWEEN ? AND ? AND "username" <> ?' ); } @@ -193,15 +194,15 @@ public function testSupportsNotLikeClause() // "WHERE" Expression LikeExpression $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username NOT LIKE ?1', - 'DELETE FROM cms_users WHERE username NOT LIKE ?' + 'DELETE FROM "cms_users" WHERE "username" NOT LIKE ?' ); } public function testSupportsLikeClauseWithEscapeExpression() { $this->assertSqlGeneration( - "DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username LIKE ?1 ESCAPE '\\'", - "DELETE FROM cms_users WHERE username LIKE ? ESCAPE '\\'" + 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username LIKE ?1 ESCAPE \'\\\'', + 'DELETE FROM "cms_users" WHERE "username" LIKE ? ESCAPE \'\\\'' ); } @@ -210,7 +211,7 @@ public function testSupportsIsNullClause() // "WHERE" Expression NullComparisonExpression $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IS NULL', - 'DELETE FROM cms_users WHERE name IS NULL' + 'DELETE FROM "cms_users" WHERE "name" IS NULL' ); } @@ -218,7 +219,7 @@ public function testSupportsIsNotNullClause() { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IS NOT NULL', - 'DELETE FROM cms_users WHERE name IS NOT NULL' + 'DELETE FROM "cms_users" WHERE "name" IS NOT NULL' ); } @@ -226,7 +227,7 @@ public function testSupportsAtomExpressionAsClause() { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE 1 = 1', - 'DELETE FROM cms_users WHERE 1 = 1' + 'DELETE FROM "cms_users" WHERE 1 = 1' ); } @@ -234,7 +235,7 @@ public function testSupportsParameterizedAtomExpression() { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE ?1 = 1', - 'DELETE FROM cms_users WHERE ? = 1' + 'DELETE FROM "cms_users" WHERE ? = 1' ); } @@ -242,7 +243,7 @@ public function testSupportsInClause() { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id IN ( ?1, ?2, ?3, ?4 )', - 'DELETE FROM cms_users WHERE id IN (?, ?, ?, ?)' + 'DELETE FROM "cms_users" WHERE "id" IN (?, ?, ?, ?)' ); } @@ -250,7 +251,7 @@ public function testSupportsNotInClause() { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id NOT IN ( ?1, ?2 )', - 'DELETE FROM cms_users WHERE id NOT IN (?, ?)' + 'DELETE FROM "cms_users" WHERE "id" NOT IN (?, ?)' ); } @@ -261,7 +262,7 @@ public function testSubselectTableAliasReferencing() { $this->assertSqlGeneration( 'DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE SIZE(u.groups) = 10', - 'DELETE FROM cms_users WHERE (SELECT COUNT(*) FROM cms_users_groups c0_ WHERE c0_.user_id = cms_users.id) = 10' + 'DELETE FROM "cms_users" WHERE (SELECT COUNT(*) FROM "cms_users_groups" t0 WHERE t0."user_id" = "cms_users"."id") = 10' ); } } diff --git a/tests/Doctrine/Tests/ORM/Query/ExprTest.php b/tests/Doctrine/Tests/ORM/Query/ExprTest.php index 37a4b70a657..f32c339dbd6 100644 --- a/tests/Doctrine/Tests/ORM/Query/ExprTest.php +++ b/tests/Doctrine/Tests/ORM/Query/ExprTest.php @@ -1,5 +1,7 @@ _em = $this->_getTestEntityManager(); - $this->_expr = new Expr; + $this->em = $this->getTestEntityManager(); + $this->expr = new Expr; } public function testAvgExpr() { - $this->assertEquals('AVG(u.id)', (string) $this->_expr->avg('u.id')); + self::assertEquals('AVG(u.id)', (string) $this->expr->avg('u.id')); } public function testMaxExpr() { - $this->assertEquals('MAX(u.id)', (string) $this->_expr->max('u.id')); + self::assertEquals('MAX(u.id)', (string) $this->expr->max('u.id')); } public function testMinExpr() { - $this->assertEquals('MIN(u.id)', (string) $this->_expr->min('u.id')); + self::assertEquals('MIN(u.id)', (string) $this->expr->min('u.id')); } public function testCountExpr() { - $this->assertEquals('MAX(u.id)', (string) $this->_expr->max('u.id')); + self::assertEquals('MAX(u.id)', (string) $this->expr->max('u.id')); } public function testCountDistinctExpr() { - $this->assertEquals('COUNT(DISTINCT u.id)', (string) $this->_expr->countDistinct('u.id')); + self::assertEquals('COUNT(DISTINCT u.id)', (string) $this->expr->countDistinct('u.id')); } public function testCountDistinctExprMulti() { - $this->assertEquals('COUNT(DISTINCT u.id, u.name)', (string) $this->_expr->countDistinct('u.id', 'u.name')); + self::assertEquals('COUNT(DISTINCT u.id, u.name)', (string) $this->expr->countDistinct('u.id', 'u.name')); } public function testExistsExpr() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u')->from('User', 'u')->where('u.name = ?1'); - $this->assertEquals('EXISTS(SELECT u FROM User u WHERE u.name = ?1)', (string) $this->_expr->exists($qb)); + self::assertEquals('EXISTS(SELECT u FROM User u WHERE u.name = ?1)', (string) $this->expr->exists($qb)); } public function testAllExpr() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u')->from('User', 'u')->where('u.name = ?1'); - $this->assertEquals('ALL(SELECT u FROM User u WHERE u.name = ?1)', (string) $this->_expr->all($qb)); + self::assertEquals('ALL(SELECT u FROM User u WHERE u.name = ?1)', (string) $this->expr->all($qb)); } public function testSomeExpr() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u')->from('User', 'u')->where('u.name = ?1'); - $this->assertEquals('SOME(SELECT u FROM User u WHERE u.name = ?1)', (string) $this->_expr->some($qb)); + self::assertEquals('SOME(SELECT u FROM User u WHERE u.name = ?1)', (string) $this->expr->some($qb)); } public function testAnyExpr() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u')->from('User', 'u')->where('u.name = ?1'); - $this->assertEquals('ANY(SELECT u FROM User u WHERE u.name = ?1)', (string) $this->_expr->any($qb)); + self::assertEquals('ANY(SELECT u FROM User u WHERE u.name = ?1)', (string) $this->expr->any($qb)); } public function testNotExpr() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u')->from('User', 'u')->where('u.name = ?1'); - $this->assertEquals('NOT(SELECT u FROM User u WHERE u.name = ?1)', (string) $this->_expr->not($qb)); + self::assertEquals('NOT(SELECT u FROM User u WHERE u.name = ?1)', (string) $this->expr->not($qb)); } public function testAndExpr() { - $this->assertEquals('1 = 1 AND 2 = 2', (string) $this->_expr->andX((string) $this->_expr->eq(1, 1), (string) $this->_expr->eq(2, 2))); + self::assertEquals('1 = 1 AND 2 = 2', (string) $this->expr->andX((string) $this->expr->eq(1, 1), (string) $this->expr->eq(2, 2))); } public function testIntelligentParenthesisPreventionAndExpr() { - $this->assertEquals( + self::assertEquals( '1 = 1 AND 2 = 2', - (string) $this->_expr->andX($this->_expr->orX($this->_expr->andX($this->_expr->eq(1, 1))), (string) $this->_expr->eq(2, 2)) + (string) $this->expr->andX($this->expr->orX($this->expr->andX($this->expr->eq(1, 1))), (string) $this->expr->eq(2, 2)) ); } public function testOrExpr() { - $this->assertEquals('1 = 1 OR 2 = 2', (string) $this->_expr->orX((string) $this->_expr->eq(1, 1), (string) $this->_expr->eq(2, 2))); + self::assertEquals('1 = 1 OR 2 = 2', (string) $this->expr->orX((string) $this->expr->eq(1, 1), (string) $this->expr->eq(2, 2))); } public function testAbsExpr() { - $this->assertEquals('ABS(1)', (string) $this->_expr->abs(1)); + self::assertEquals('ABS(1)', (string) $this->expr->abs(1)); } public function testProdExpr() { - $this->assertEquals('1 * 2', (string) $this->_expr->prod(1, 2)); + self::assertEquals('1 * 2', (string) $this->expr->prod(1, 2)); } public function testDiffExpr() { - $this->assertEquals('1 - 2', (string) $this->_expr->diff(1, 2)); + self::assertEquals('1 - 2', (string) $this->expr->diff(1, 2)); } public function testSumExpr() { - $this->assertEquals('1 + 2', (string) $this->_expr->sum(1, 2)); + self::assertEquals('1 + 2', (string) $this->expr->sum(1, 2)); } public function testQuotientExpr() { - $this->assertEquals('10 / 2', (string) $this->_expr->quot(10, 2)); + self::assertEquals('10 / 2', (string) $this->expr->quot(10, 2)); } public function testScopeInArithmeticExpr() { - $this->assertEquals('(100 - 20) / 2', (string) $this->_expr->quot($this->_expr->diff(100, 20), 2)); - $this->assertEquals('100 - (20 / 2)', (string) $this->_expr->diff(100, $this->_expr->quot(20, 2))); + self::assertEquals('(100 - 20) / 2', (string) $this->expr->quot($this->expr->diff(100, 20), 2)); + self::assertEquals('100 - (20 / 2)', (string) $this->expr->diff(100, $this->expr->quot(20, 2))); } public function testSquareRootExpr() { - $this->assertEquals('SQRT(1)', (string) $this->_expr->sqrt(1)); + self::assertEquals('SQRT(1)', (string) $this->expr->sqrt(1)); } public function testEqualExpr() { - $this->assertEquals('1 = 1', (string) $this->_expr->eq(1, 1)); + self::assertEquals('1 = 1', (string) $this->expr->eq(1, 1)); } public function testLikeExpr() { - $this->assertEquals('a.description LIKE :description', (string) $this->_expr->like('a.description', ':description')); + self::assertEquals('a.description LIKE :description', (string) $this->expr->like('a.description', ':description')); } public function testNotLikeExpr() { - $this->assertEquals('a.description NOT LIKE :description', (string) $this->_expr->notLike('a.description', ':description')); + self::assertEquals('a.description NOT LIKE :description', (string) $this->expr->notLike('a.description', ':description')); } public function testConcatExpr() { - $this->assertEquals('CONCAT(u.first_name, u.last_name)', (string) $this->_expr->concat('u.first_name', 'u.last_name')); - $this->assertEquals('CONCAT(u.first_name, u.middle_name, u.last_name)', (string) $this->_expr->concat('u.first_name', 'u.middle_name', 'u.last_name')); + self::assertEquals('CONCAT(u.first_name, u.last_name)', (string) $this->expr->concat('u.first_name', 'u.last_name')); + self::assertEquals('CONCAT(u.first_name, u.middle_name, u.last_name)', (string) $this->expr->concat('u.first_name', 'u.middle_name', 'u.last_name')); } public function testSubstringExpr() { - $this->assertEquals('SUBSTRING(a.title, 0, 25)', (string) $this->_expr->substring('a.title', 0, 25)); + self::assertEquals('SUBSTRING(a.title, 0, 25)', (string) $this->expr->substring('a.title', 0, 25)); } /** @@ -187,42 +189,42 @@ public function testSubstringExpr() */ public function testSubstringExprAcceptsTwoArguments() { - $this->assertEquals('SUBSTRING(a.title, 5)', (string) $this->_expr->substring('a.title', 5)); + self::assertEquals('SUBSTRING(a.title, 5)', (string) $this->expr->substring('a.title', 5)); } public function testLowerExpr() { - $this->assertEquals('LOWER(u.first_name)', (string) $this->_expr->lower('u.first_name')); + self::assertEquals('LOWER(u.first_name)', (string) $this->expr->lower('u.first_name')); } public function testUpperExpr() { - $this->assertEquals('UPPER(u.first_name)', (string) $this->_expr->upper('u.first_name')); + self::assertEquals('UPPER(u.first_name)', (string) $this->expr->upper('u.first_name')); } public function testLengthExpr() { - $this->assertEquals('LENGTH(u.first_name)', (string) $this->_expr->length('u.first_name')); + self::assertEquals('LENGTH(u.first_name)', (string) $this->expr->length('u.first_name')); } public function testGreaterThanExpr() { - $this->assertEquals('5 > 2', (string) $this->_expr->gt(5, 2)); + self::assertEquals('5 > 2', (string) $this->expr->gt(5, 2)); } public function testLessThanExpr() { - $this->assertEquals('2 < 5', (string) $this->_expr->lt(2, 5)); + self::assertEquals('2 < 5', (string) $this->expr->lt(2, 5)); } public function testStringLiteralExpr() { - $this->assertEquals("'word'", (string) $this->_expr->literal('word')); + self::assertEquals("'word'", (string) $this->expr->literal('word')); } public function testNumericLiteralExpr() { - $this->assertEquals(5, (string) $this->_expr->literal(5)); + self::assertEquals(5, (string) $this->expr->literal(5)); } /** @@ -231,107 +233,107 @@ public function testNumericLiteralExpr() */ public function testLiteralExprProperlyQuotesStrings() { - $this->assertEquals("'00010001'", (string) $this->_expr->literal('00010001')); + self::assertEquals("'00010001'", (string) $this->expr->literal('00010001')); } public function testGreaterThanOrEqualToExpr() { - $this->assertEquals('5 >= 2', (string) $this->_expr->gte(5, 2)); + self::assertEquals('5 >= 2', (string) $this->expr->gte(5, 2)); } public function testLessThanOrEqualTo() { - $this->assertEquals('2 <= 5', (string) $this->_expr->lte(2, 5)); + self::assertEquals('2 <= 5', (string) $this->expr->lte(2, 5)); } public function testBetweenExpr() { - $this->assertEquals('u.id BETWEEN 3 AND 6', (string) $this->_expr->between('u.id', 3, 6)); + self::assertEquals('u.id BETWEEN 3 AND 6', (string) $this->expr->between('u.id', 3, 6)); } public function testTrimExpr() { - $this->assertEquals('TRIM(u.id)', (string) $this->_expr->trim('u.id')); + self::assertEquals('TRIM(u.id)', (string) $this->expr->trim('u.id')); } public function testIsNullExpr() { - $this->assertEquals('u.id IS NULL', (string) $this->_expr->isNull('u.id')); + self::assertEquals('u.id IS NULL', (string) $this->expr->isNull('u.id')); } public function testIsNotNullExpr() { - $this->assertEquals('u.id IS NOT NULL', (string) $this->_expr->isNotNull('u.id')); + self::assertEquals('u.id IS NOT NULL', (string) $this->expr->isNotNull('u.id')); } public function testIsInstanceOfExpr() { - $this->assertEquals('u INSTANCE OF Doctrine\Tests\Models\Company\CompanyEmployee', (string) $this->_expr->isInstanceOf('u', CompanyEmployee::class)); + self::assertEquals('u INSTANCE OF Doctrine\Tests\Models\Company\CompanyEmployee', (string) $this->expr->isInstanceOf('u', CompanyEmployee::class)); } public function testIsMemberOfExpr() { - $this->assertEquals(':groupId MEMBER OF u.groups', (string) $this->_expr->isMemberOf(':groupId', 'u.groups')); + self::assertEquals(':groupId MEMBER OF u.groups', (string) $this->expr->isMemberOf(':groupId', 'u.groups')); } public function testInExpr() { - $this->assertEquals('u.id IN(1, 2, 3)', (string) $this->_expr->in('u.id', [1, 2, 3])); + self::assertEquals('u.id IN(1, 2, 3)', (string) $this->expr->in('u.id', [1, 2, 3])); } public function testInLiteralExpr() { - $this->assertEquals("u.type IN('foo', 'bar')", (string) $this->_expr->in('u.type', ['foo', 'bar'])); + self::assertEquals("u.type IN('foo', 'bar')", (string) $this->expr->in('u.type', ['foo', 'bar'])); } public function testNotInExpr() { - $this->assertEquals('u.id NOT IN(1, 2, 3)', (string) $this->_expr->notIn('u.id', [1, 2, 3])); + self::assertEquals('u.id NOT IN(1, 2, 3)', (string) $this->expr->notIn('u.id', [1, 2, 3])); } public function testNotInLiteralExpr() { - $this->assertEquals("u.type NOT IN('foo', 'bar')", (string) $this->_expr->notIn('u.type', ['foo', 'bar'])); + self::assertEquals("u.type NOT IN('foo', 'bar')", (string) $this->expr->notIn('u.type', ['foo', 'bar'])); } public function testAndxOrxExpr() { - $andExpr = $this->_expr->andX(); - $andExpr->add($this->_expr->eq(1, 1)); - $andExpr->add($this->_expr->lt(1, 5)); + $andExpr = $this->expr->andX(); + $andExpr->add($this->expr->eq(1, 1)); + $andExpr->add($this->expr->lt(1, 5)); - $orExpr = $this->_expr->orX(); + $orExpr = $this->expr->orX(); $orExpr->add($andExpr); - $orExpr->add($this->_expr->eq(1, 1)); + $orExpr->add($this->expr->eq(1, 1)); - $this->assertEquals('(1 = 1 AND 1 < 5) OR 1 = 1', (string) $orExpr); + self::assertEquals('(1 = 1 AND 1 < 5) OR 1 = 1', (string) $orExpr); } public function testOrxExpr() { - $orExpr = $this->_expr->orX(); - $orExpr->add($this->_expr->eq(1, 1)); - $orExpr->add($this->_expr->lt(1, 5)); + $orExpr = $this->expr->orX(); + $orExpr->add($this->expr->eq(1, 1)); + $orExpr->add($this->expr->lt(1, 5)); - $this->assertEquals('1 = 1 OR 1 < 5', (string) $orExpr); + self::assertEquals('1 = 1 OR 1 < 5', (string) $orExpr); } public function testOrderByCountExpr() { - $orderExpr = $this->_expr->desc('u.username'); + $orderExpr = $this->expr->desc('u.username'); - $this->assertEquals($orderExpr->count(), 1); - $this->assertEquals('u.username DESC', (string) $orderExpr); + self::assertEquals($orderExpr->count(), 1); + self::assertEquals('u.username DESC', (string) $orderExpr); } public function testOrderByOrder() { - $orderExpr = $this->_expr->desc('u.username'); - $this->assertEquals('u.username DESC', (string) $orderExpr); + $orderExpr = $this->expr->desc('u.username'); + self::assertEquals('u.username DESC', (string) $orderExpr); } public function testOrderByAsc() { - $orderExpr = $this->_expr->asc('u.username'); - $this->assertEquals('u.username ASC', (string) $orderExpr); + $orderExpr = $this->expr->asc('u.username'); + self::assertEquals('u.username ASC', (string) $orderExpr); } /** @@ -339,8 +341,8 @@ public function testOrderByAsc() */ public function testAddThrowsException() { - $orExpr = $this->_expr->orX(); - $orExpr->add($this->_expr->quot(5, 2)); + $orExpr = $this->expr->orX(); + $orExpr->add($this->expr->quot(5, 2)); } /** @@ -348,8 +350,8 @@ public function testAddThrowsException() */ public function testBooleanLiteral() { - $this->assertEquals('true', $this->_expr->literal(true)); - $this->assertEquals('false', $this->_expr->literal(false)); + self::assertEquals('true', $this->expr->literal(true)); + self::assertEquals('false', $this->expr->literal(false)); } @@ -361,74 +363,74 @@ public function testExpressionGetter() // Andx $andx = new Expr\Andx(['1 = 1', '2 = 2']); - $this->assertEquals(['1 = 1', '2 = 2'], $andx->getParts()); + self::assertEquals(['1 = 1', '2 = 2'], $andx->getParts()); // Comparison $comparison = new Expr\Comparison('foo', Expr\Comparison::EQ, 'bar'); - $this->assertEquals('foo', $comparison->getLeftExpr()); - $this->assertEquals('bar', $comparison->getRightExpr()); - $this->assertEquals(Expr\Comparison::EQ, $comparison->getOperator()); + self::assertEquals('foo', $comparison->getLeftExpr()); + self::assertEquals('bar', $comparison->getRightExpr()); + self::assertEquals(Expr\Comparison::EQ, $comparison->getOperator()); // From $from = new Expr\From('Foo', 'f', 'f.id'); - $this->assertEquals('f', $from->getAlias()); - $this->assertEquals('Foo', $from->getFrom()); - $this->assertEquals('f.id', $from->getIndexBy()); + self::assertEquals('f', $from->getAlias()); + self::assertEquals('Foo', $from->getFrom()); + self::assertEquals('f.id', $from->getIndexBy()); // Func $func = new Expr\Func('MAX', ['f.id']); - $this->assertEquals('MAX', $func->getName()); - $this->assertEquals(['f.id'], $func->getArguments()); + self::assertEquals('MAX', $func->getName()); + self::assertEquals(['f.id'], $func->getArguments()); // GroupBy $group = new Expr\GroupBy(['foo DESC', 'bar ASC']); - $this->assertEquals(['foo DESC', 'bar ASC'], $group->getParts()); + self::assertEquals(['foo DESC', 'bar ASC'], $group->getParts()); // Join $join = new Expr\Join(Expr\Join::INNER_JOIN, 'f.bar', 'b', Expr\Join::ON, 'b.bar_id = 1', 'b.bar_id'); - $this->assertEquals(Expr\Join::INNER_JOIN, $join->getJoinType()); - $this->assertEquals(Expr\Join::ON, $join->getConditionType()); - $this->assertEquals('b.bar_id = 1', $join->getCondition()); - $this->assertEquals('b.bar_id', $join->getIndexBy()); - $this->assertEquals('f.bar', $join->getJoin()); - $this->assertEquals('b', $join->getAlias()); + self::assertEquals(Expr\Join::INNER_JOIN, $join->getJoinType()); + self::assertEquals(Expr\Join::ON, $join->getConditionType()); + self::assertEquals('b.bar_id = 1', $join->getCondition()); + self::assertEquals('b.bar_id', $join->getIndexBy()); + self::assertEquals('f.bar', $join->getJoin()); + self::assertEquals('b', $join->getAlias()); // Literal $literal = new Expr\Literal(['foo']); - $this->assertEquals(['foo'], $literal->getParts()); + self::assertEquals(['foo'], $literal->getParts()); // Math $math = new Expr\Math(10, '+', 20); - $this->assertEquals(10, $math->getLeftExpr()); - $this->assertEquals(20, $math->getRightExpr()); - $this->assertEquals('+', $math->getOperator()); + self::assertEquals(10, $math->getLeftExpr()); + self::assertEquals(20, $math->getRightExpr()); + self::assertEquals('+', $math->getOperator()); // OrderBy $order = new Expr\OrderBy('foo', 'DESC'); - $this->assertEquals(['foo DESC'], $order->getParts()); + self::assertEquals(['foo DESC'], $order->getParts()); // Andx $orx = new Expr\Orx(['foo = 1', 'bar = 2']); - $this->assertEquals(['foo = 1', 'bar = 2'], $orx->getParts()); + self::assertEquals(['foo = 1', 'bar = 2'], $orx->getParts()); // Select $select = new Expr\Select(['foo', 'bar']); - $this->assertEquals(['foo', 'bar'], $select->getParts()); + self::assertEquals(['foo', 'bar'], $select->getParts()); } public function testAddEmpty() { - $andExpr = $this->_expr->andX(); - $andExpr->add($this->_expr->andX()); + $andExpr = $this->expr->andX(); + $andExpr->add($this->expr->andX()); - $this->assertEquals(0, $andExpr->count()); + self::assertEquals(0, $andExpr->count()); } public function testAddNull() { - $andExpr = $this->_expr->andX(); + $andExpr = $this->expr->andX(); $andExpr->add(null); - $this->assertEquals(0, $andExpr->count()); + self::assertEquals(0, $andExpr->count()); } } diff --git a/tests/Doctrine/Tests/ORM/Query/FilterCollectionTest.php b/tests/Doctrine/Tests/ORM/Query/FilterCollectionTest.php index 0e47f6e82d6..3c7f5deeb4b 100644 --- a/tests/Doctrine/Tests/ORM/Query/FilterCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Query/FilterCollectionTest.php @@ -1,5 +1,7 @@ em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); $this->em->getConfiguration()->addFilter('testFilter', MyFilter::class); } @@ -28,25 +30,25 @@ public function testEnable() { $filterCollection = $this->em->getFilters(); - $this->assertCount(0, $filterCollection->getEnabledFilters()); + self::assertCount(0, $filterCollection->getEnabledFilters()); $filterCollection->enable('testFilter'); $enabledFilters = $filterCollection->getEnabledFilters(); - $this->assertCount(1, $enabledFilters); - $this->assertContainsOnly(MyFilter::class, $enabledFilters); + self::assertCount(1, $enabledFilters); + self::assertContainsOnly(MyFilter::class, $enabledFilters); $filterCollection->disable('testFilter'); - $this->assertCount(0, $filterCollection->getEnabledFilters()); + self::assertCount(0, $filterCollection->getEnabledFilters()); } public function testHasFilter() { $filterCollection = $this->em->getFilters(); - $this->assertTrue($filterCollection->has('testFilter')); - $this->assertFalse($filterCollection->has('fakeFilter')); + self::assertTrue($filterCollection->has('testFilter')); + self::assertFalse($filterCollection->has('fakeFilter')); } /** @@ -56,11 +58,11 @@ public function testIsEnabled() { $filterCollection = $this->em->getFilters(); - $this->assertFalse($filterCollection->isEnabled('testFilter')); + self::assertFalse($filterCollection->isEnabled('testFilter')); $filterCollection->enable('testFilter'); - $this->assertTrue($filterCollection->isEnabled('testFilter')); + self::assertTrue($filterCollection->isEnabled('testFilter')); } /** @@ -77,7 +79,7 @@ public function testGetFilter() $filterCollection = $this->em->getFilters(); $filterCollection->enable('testFilter'); - $this->assertInstanceOf(MyFilter::class, $filterCollection->getFilter('testFilter')); + self::assertInstanceOf(MyFilter::class, $filterCollection->getFilter('testFilter')); } } diff --git a/tests/Doctrine/Tests/ORM/Query/LanguageRecognitionTest.php b/tests/Doctrine/Tests/ORM/Query/LanguageRecognitionTest.php index 064c0a799cb..d100d45f1b3 100644 --- a/tests/Doctrine/Tests/ORM/Query/LanguageRecognitionTest.php +++ b/tests/Doctrine/Tests/ORM/Query/LanguageRecognitionTest.php @@ -1,10 +1,13 @@ _em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); } public function assertValidDQL($dql, $debug = false) @@ -51,7 +54,7 @@ public function assertInvalidDQL($dql, $debug = false) public function parseDql($dql, $hints = []) { - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true); $query->setDQL($dql); @@ -69,17 +72,17 @@ public function parseDql($dql, $hints = []) public function testEmptyQueryString() { - $this->assertInvalidDQL(''); + self::assertInvalidDQL(''); } public function testPlainFromClauseWithAlias() { - $this->assertValidDQL('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertValidDQL('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u'); } public function testSelectSingleComponentWithAsterisk() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'); } /** @@ -89,7 +92,7 @@ public function testRejectsInvalidDQL($dql) { $this->expectException(QueryException::class); - $this->_em->getConfiguration()->setEntityNamespaces( + $this->em->getConfiguration()->setEntityNamespaces( [ 'Unknown' => 'Unknown', 'CMS' => 'Doctrine\Tests\Models\CMS' @@ -139,143 +142,143 @@ public function invalidDQL() public function testSelectSingleComponentWithMultipleColumns() { - $this->assertValidDQL('SELECT u.name, u.username FROM Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertValidDQL('SELECT u.name, u.username FROM Doctrine\Tests\Models\CMS\CmsUser u'); } public function testSelectMultipleComponentsUsingMultipleFrom() { - $this->assertValidDQL('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE u = p.user'); + self::assertValidDQL('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE u = p.user'); } public function testSelectMultipleComponentsWithAsterisk() { - $this->assertValidDQL('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.phonenumbers p'); + self::assertValidDQL('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.phonenumbers p'); } public function testSelectDistinctIsSupported() { - $this->assertValidDQL('SELECT DISTINCT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertValidDQL('SELECT DISTINCT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u'); } public function testAggregateFunctionInSelect() { - $this->assertValidDQL('SELECT COUNT(u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertValidDQL('SELECT COUNT(u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u'); } public function testMultipleParenthesisInSelect() { - $this->assertValidDQL('SELECT (((u.id))) as v FROM Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertValidDQL('SELECT (((u.id))) as v FROM Doctrine\Tests\Models\CMS\CmsUser u'); } public function testDuplicatedAliasInAggregateFunction() { - $this->assertInvalidDQL('SELECT COUNT(u.id) AS num, SUM(u.id) AS num FROM Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertInvalidDQL('SELECT COUNT(u.id) AS num, SUM(u.id) AS num FROM Doctrine\Tests\Models\CMS\CmsUser u'); } public function testAggregateFunctionWithDistinctInSelect() { - $this->assertValidDQL('SELECT COUNT(DISTINCT u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertValidDQL('SELECT COUNT(DISTINCT u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u'); } public function testFunctionalExpressionsSupportedInWherePart() { - $this->assertValidDQL("SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE TRIM(u.name) = 'someone'"); + self::assertValidDQL("SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE TRIM(u.name) = 'someone'"); } public function testArithmeticExpressionsSupportedInWherePart() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE ((u.id + 5000) * u.id + 3) < 10000000'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE ((u.id + 5000) * u.id + 3) < 10000000'); } public function testInExpressionSupportedInWherePart() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id IN (1, 2)'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id IN (1, 2)'); } public function testInExpressionWithoutSpacesSupportedInWherePart() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id IN (1,2,3)'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id IN (1,2,3)'); } public function testNotInExpressionSupportedInWherePart() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id NOT IN (1)'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id NOT IN (1)'); } public function testInExpressionWithSingleValuedAssociationPathExpression() { - $this->assertValidDQL("SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u WHERE u.avatar IN (?1, ?2)"); + self::assertValidDQL("SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u WHERE u.avatar IN (?1, ?2)"); } public function testInvalidInExpressionWithCollectionValuedAssociationPathExpression() { - $this->assertInvalidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.phonenumbers IN (?1, ?2)"); + self::assertInvalidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.phonenumbers IN (?1, ?2)"); } public function testInstanceOfExpressionSupportedInWherePart() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyEmployee'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyEmployee'); } public function testInstanceOfExpressionWithInputParamSupportedInWherePart() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF ?1'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF ?1'); } public function testNotInstanceOfExpressionSupportedInWherePart() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u NOT INSTANCE OF ?1'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u NOT INSTANCE OF ?1'); } public function testExistsExpressionSupportedInWherePart() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE EXISTS (SELECT p.phonenumber FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.phonenumber = 1234)'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE EXISTS (SELECT p.phonenumber FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.phonenumber = 1234)'); } public function testNotExistsExpressionSupportedInWherePart() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE NOT EXISTS (SELECT p.phonenumber FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.phonenumber = 1234)'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE NOT EXISTS (SELECT p.phonenumber FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.phonenumber = 1234)'); } public function testAggregateFunctionInHavingClause() { - $this->assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.phonenumbers p HAVING COUNT(p.phonenumber) > 2'); - $this->assertValidDQL("SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.phonenumbers p HAVING MAX(u.name) = 'romanb'"); + self::assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.phonenumbers p HAVING COUNT(p.phonenumber) > 2'); + self::assertValidDQL("SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.phonenumbers p HAVING MAX(u.name) = 'romanb'"); } public function testLeftJoin() { - $this->assertValidDQL('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.phonenumbers p'); + self::assertValidDQL('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.phonenumbers p'); } public function testJoin() { - $this->assertValidDQL('SELECT u,p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.phonenumbers p'); + self::assertValidDQL('SELECT u,p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.phonenumbers p'); } public function testInnerJoin() { - $this->assertValidDQL('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.phonenumbers p'); + self::assertValidDQL('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.phonenumbers p'); } public function testMultipleLeftJoin() { - $this->assertValidDQL('SELECT u, a, p FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a LEFT JOIN u.phonenumbers p'); + self::assertValidDQL('SELECT u, a, p FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a LEFT JOIN u.phonenumbers p'); } public function testMultipleInnerJoin() { - $this->assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles a INNER JOIN u.phonenumbers p'); + self::assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles a INNER JOIN u.phonenumbers p'); } public function testMixingOfJoins() { - $this->assertValidDQL('SELECT u.name, a.topic, p.phonenumber FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles a LEFT JOIN u.phonenumbers p'); + self::assertValidDQL('SELECT u.name, a.topic, p.phonenumber FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles a LEFT JOIN u.phonenumbers p'); } public function testJoinClassPathUsingWITH() { - $this->assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN Doctrine\Tests\Models\CMS\CmsArticle a WITH a.user = u.id'); + self::assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN Doctrine\Tests\Models\CMS\CmsArticle a WITH a.user = u.id'); } /** @@ -283,7 +286,7 @@ public function testJoinClassPathUsingWITH() */ public function testJoinClassPathUsingWHERE() { - $this->assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = u.id'); + self::assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = u.id'); } /** @@ -291,52 +294,52 @@ public function testJoinClassPathUsingWHERE() */ public function testDDC3701WHEREIsNotWITH() { - $this->assertInvalidDQL('SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c JOIN Doctrine\Tests\Models\Company\CompanyEmployee e WHERE e.id = c.salesPerson WHERE c.completed = true'); + self::assertInvalidDQL('SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c JOIN Doctrine\Tests\Models\Company\CompanyEmployee e WHERE e.id = c.salesPerson WHERE c.completed = true'); } public function testOrderBySingleColumn() { - $this->assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.name'); + self::assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.name'); } public function testOrderBySingleColumnAscending() { - $this->assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.name ASC'); + self::assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.name ASC'); } public function testOrderBySingleColumnDescending() { - $this->assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.name DESC'); + self::assertValidDQL('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.name DESC'); } public function testOrderByMultipleColumns() { - $this->assertValidDQL('SELECT u.name, u.username FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username DESC, u.name DESC'); + self::assertValidDQL('SELECT u.name, u.username FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username DESC, u.name DESC'); } public function testSubselectInInExpression() { - $this->assertValidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id NOT IN (SELECT u2.id FROM Doctrine\Tests\Models\CMS\CmsUser u2 WHERE u2.name = 'zYne')"); + self::assertValidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id NOT IN (SELECT u2.id FROM Doctrine\Tests\Models\CMS\CmsUser u2 WHERE u2.name = 'zYne')"); } public function testSubselectInSelectPart() { - $this->assertValidDQL("SELECT u.name, (SELECT COUNT(p.phonenumber) FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.phonenumber = 1234) pcount FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = 'jon'"); + self::assertValidDQL("SELECT u.name, (SELECT COUNT(p.phonenumber) FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.phonenumber = 1234) pcount FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = 'jon'"); } public function testArithmeticExpressionInSelectPart() { - $this->assertValidDQL("SELECT SUM(u.id) / COUNT(u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u"); + self::assertValidDQL("SELECT SUM(u.id) / COUNT(u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u"); } public function testArithmeticExpressionInSubselectPart() { - $this->assertValidDQL("SELECT (SELECT SUM(u.id) / COUNT(u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u2) value FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = 'jon'"); + self::assertValidDQL("SELECT (SELECT SUM(u.id) / COUNT(u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u2) value FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = 'jon'"); } public function testArithmeticExpressionWithParenthesisInSubselectPart() { - $this->assertValidDQL("SELECT (SELECT (SUM(u.id) / COUNT(u.id)) FROM Doctrine\Tests\Models\CMS\CmsUser u2) value FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = 'jon'"); + self::assertValidDQL("SELECT (SELECT (SUM(u.id) / COUNT(u.id)) FROM Doctrine\Tests\Models\CMS\CmsUser u2) value FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = 'jon'"); } /** @@ -344,8 +347,8 @@ public function testArithmeticExpressionWithParenthesisInSubselectPart() */ public function testSelectLiteralInSubselect() { - $this->assertValidDQL('SELECT (SELECT 1 FROM Doctrine\Tests\Models\CMS\CmsUser u2) value FROM Doctrine\Tests\Models\CMS\CmsUser u'); - $this->assertValidDQL('SELECT (SELECT 0 FROM Doctrine\Tests\Models\CMS\CmsUser u2) value FROM Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertValidDQL('SELECT (SELECT 1 FROM Doctrine\Tests\Models\CMS\CmsUser u2) value FROM Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertValidDQL('SELECT (SELECT 0 FROM Doctrine\Tests\Models\CMS\CmsUser u2) value FROM Doctrine\Tests\Models\CMS\CmsUser u'); } /** @@ -353,125 +356,125 @@ public function testSelectLiteralInSubselect() */ public function testConstantValueInSelect() { - $this->assertValidDQL("SELECT u.name, 'foo' AS bar FROM Doctrine\Tests\Models\CMS\CmsUser u", true); + self::assertValidDQL("SELECT u.name, 'foo' AS bar FROM Doctrine\Tests\Models\CMS\CmsUser u", true); } public function testDuplicateAliasInSubselectPart() { - $this->assertInvalidDQL("SELECT (SELECT SUM(u.id) / COUNT(u.id) AS foo FROM Doctrine\Tests\Models\CMS\CmsUser u2) foo FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = 'jon'"); + self::assertInvalidDQL("SELECT (SELECT SUM(u.id) / COUNT(u.id) AS foo FROM Doctrine\Tests\Models\CMS\CmsUser u2) foo FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = 'jon'"); } public function testPositionalInputParameter() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1'); } public function testNamedInputParameter() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :id'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :id'); } public function testJoinConditionOverrideNotSupported() { - $this->assertInvalidDQL("SELECT u.name, p FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.phonenumbers p ON p.phonenumber = '123 123'"); + self::assertInvalidDQL("SELECT u.name, p FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.phonenumbers p ON p.phonenumber = '123 123'"); } public function testIndexByClauseWithOneComponent() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u INDEX BY u.id'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u INDEX BY u.id'); } public function testIndexBySupportsJoins() { - $this->assertValidDQL('SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a INDEX BY a.id'); // INDEX BY is now referring to articles + self::assertValidDQL('SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a INDEX BY a.id'); // INDEX BY is now referring to articles } public function testIndexBySupportsJoins2() { - $this->assertValidDQL('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u INDEX BY u.id LEFT JOIN u.phonenumbers p INDEX BY p.phonenumber'); + self::assertValidDQL('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u INDEX BY u.id LEFT JOIN u.phonenumbers p INDEX BY p.phonenumber'); } public function testBetweenExpressionSupported() { - $this->assertValidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name BETWEEN 'jepso' AND 'zYne'"); + self::assertValidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name BETWEEN 'jepso' AND 'zYne'"); } public function testNotBetweenExpressionSupported() { - $this->assertValidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name NOT BETWEEN 'jepso' AND 'zYne'"); + self::assertValidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name NOT BETWEEN 'jepso' AND 'zYne'"); } public function testLikeExpression() { - $this->assertValidDQL("SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name LIKE 'z%'"); + self::assertValidDQL("SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name LIKE 'z%'"); } public function testNotLikeExpression() { - $this->assertValidDQL("SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name NOT LIKE 'z%'"); + self::assertValidDQL("SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name NOT LIKE 'z%'"); } public function testLikeExpressionWithCustomEscapeCharacter() { - $this->assertValidDQL("SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name LIKE 'z|%' ESCAPE '|'"); + self::assertValidDQL("SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name LIKE 'z|%' ESCAPE '|'"); } public function testFieldComparisonWithoutAlias() { - $this->assertInvalidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE id = 1"); + self::assertInvalidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE id = 1"); } public function testDuplicatedAliasDeclaration() { - $this->assertInvalidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles u WHERE u.id = 1"); + self::assertInvalidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles u WHERE u.id = 1"); } public function testImplicitJoinInWhereOnSingleValuedAssociationPathExpression() { // This should be allowed because avatar is a single-value association. // SQL: SELECT ... FROM forum_user fu INNER JOIN forum_avatar fa ON fu.avatar_id = fa.id WHERE fa.id = ? - $this->assertValidDQL("SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u JOIN u.avatar a WHERE a.id = ?1"); + self::assertValidDQL("SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u JOIN u.avatar a WHERE a.id = ?1"); } public function testImplicitJoinInWhereOnCollectionValuedPathExpression() { // This should be forbidden, because articles is a collection - $this->assertInvalidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.articles a WHERE a.title = ?"); + self::assertInvalidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.articles a WHERE a.title = ?"); } public function testInvalidSyntaxIsRejected() { - $this->assertInvalidDQL("FOOBAR CmsUser"); - $this->assertInvalidDQL("DELETE FROM Doctrine\Tests\Models\CMS\CmsUser.articles"); - $this->assertInvalidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.articles.comments"); + self::assertInvalidDQL("FOOBAR CmsUser"); + self::assertInvalidDQL("DELETE FROM Doctrine\Tests\Models\CMS\CmsUser.articles"); + self::assertInvalidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.articles.comments"); // Currently UNDEFINED OFFSET error - $this->assertInvalidDQL("SELECT c FROM CmsUser.articles.comments c"); + self::assertInvalidDQL("SELECT c FROM CmsUser.articles.comments c"); } public function testUpdateWorksWithOneField() { - $this->assertValidDQL("UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = 'someone'"); + self::assertValidDQL("UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = 'someone'"); } public function testUpdateWorksWithMultipleFields() { - $this->assertValidDQL("UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = 'someone', u.username = 'some'"); + self::assertValidDQL("UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = 'someone', u.username = 'some'"); } public function testUpdateSupportsConditions() { - $this->assertValidDQL("UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = 'someone' WHERE u.id = 5"); + self::assertValidDQL("UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = 'someone' WHERE u.id = 5"); } public function testDeleteAll() { - $this->assertValidDQL('DELETE FROM Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertValidDQL('DELETE FROM Doctrine\Tests\Models\CMS\CmsUser u'); } public function testDeleteWithCondition() { - $this->assertValidDQL('DELETE FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = 3'); + self::assertValidDQL('DELETE FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = 3'); } /** @@ -480,94 +483,94 @@ public function testDeleteWithCondition() */ public function testImplicitJoinWithCartesianProductAndConditionInWhere() { - $this->assertValidDQL("SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsArticle a WHERE u.name = a.topic"); + self::assertValidDQL("SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsArticle a WHERE u.name = a.topic"); } public function testAllExpressionWithCorrelatedSubquery() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id > ALL (SELECT u2.id FROM Doctrine\Tests\Models\CMS\CmsUser u2 WHERE u2.name = u.name)'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id > ALL (SELECT u2.id FROM Doctrine\Tests\Models\CMS\CmsUser u2 WHERE u2.name = u.name)'); } public function testCustomJoinsAndWithKeywordSupported() { - $this->assertValidDQL('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.phonenumbers p WITH p.phonenumber = 123 WHERE u.id = 1'); + self::assertValidDQL('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.phonenumbers p WITH p.phonenumber = 123 WHERE u.id = 1'); } public function testAnyExpressionWithCorrelatedSubquery() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id > ANY (SELECT u2.id FROM Doctrine\Tests\Models\CMS\CmsUser u2 WHERE u2.name = u.name)'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id > ANY (SELECT u2.id FROM Doctrine\Tests\Models\CMS\CmsUser u2 WHERE u2.name = u.name)'); } public function testSomeExpressionWithCorrelatedSubquery() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id > SOME (SELECT u2.id FROM Doctrine\Tests\Models\CMS\CmsUser u2 WHERE u2.name = u.name)'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id > SOME (SELECT u2.id FROM Doctrine\Tests\Models\CMS\CmsUser u2 WHERE u2.name = u.name)'); } public function testArithmeticExpressionWithoutParenthesisInWhereClause() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE SIZE(u.phonenumbers) + 1 > 10'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE SIZE(u.phonenumbers) + 1 > 10'); } public function testMemberOfExpression() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE :param MEMBER OF u.phonenumbers'); - //$this->assertValidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE 'Joe' MEMBER OF u.nicknames"); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE :param MEMBER OF u.phonenumbers'); + //self::assertValidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE 'Joe' MEMBER OF u.nicknames"); } public function testSizeFunction() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE SIZE(u.phonenumbers) > 1'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE SIZE(u.phonenumbers) > 1'); } public function testEmptyCollectionComparisonExpression() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.phonenumbers IS EMPTY'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.phonenumbers IS EMPTY'); } public function testSingleValuedAssociationFieldInWhere() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.address = ?1'); - $this->assertValidDQL('SELECT p FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.user = ?1'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.address = ?1'); + self::assertValidDQL('SELECT p FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.user = ?1'); } public function testBooleanLiteralInWhere() { - $this->assertValidDQL('SELECT b FROM Doctrine\Tests\Models\Generic\BooleanModel b WHERE b.booleanField = true'); + self::assertValidDQL('SELECT b FROM Doctrine\Tests\Models\Generic\BooleanModel b WHERE b.booleanField = true'); } public function testSubqueryInSelectExpression() { - $this->assertValidDQL('select u, (select max(p.phonenumber) from Doctrine\Tests\Models\CMS\CmsPhonenumber p) maxId from Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertValidDQL('select u, (select max(p.phonenumber) from Doctrine\Tests\Models\CMS\CmsPhonenumber p) maxId from Doctrine\Tests\Models\CMS\CmsUser u'); } public function testUsageOfQComponentOutsideSubquery() { - $this->assertInvalidDQL('select u, (select max(p.phonenumber) from Doctrine\Tests\Models\CMS\CmsPhonenumber p) maxId from Doctrine\Tests\Models\CMS\CmsUser u WHERE p.user = ?1'); + self::assertInvalidDQL('select u, (select max(p.phonenumber) from Doctrine\Tests\Models\CMS\CmsPhonenumber p) maxId from Doctrine\Tests\Models\CMS\CmsUser u WHERE p.user = ?1'); } public function testUnknownAbstractSchemaName() { - $this->assertInvalidDQL('SELECT u FROM UnknownClassName u'); + self::assertInvalidDQL('SELECT u FROM UnknownClassName u'); } public function testCorrectPartialObjectLoad() { - $this->assertValidDQL('SELECT PARTIAL u.{id,name} FROM Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertValidDQL('SELECT PARTIAL u.{id,name} FROM Doctrine\Tests\Models\CMS\CmsUser u'); } public function testIncorrectPartialObjectLoadBecauseOfMissingIdentifier() { - $this->assertInvalidDQL('SELECT PARTIAL u.{name} FROM Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertInvalidDQL('SELECT PARTIAL u.{name} FROM Doctrine\Tests\Models\CMS\CmsUser u'); } public function testScalarExpressionInSelect() { - $this->assertValidDQL('SELECT u, 42 + u.id AS someNumber FROM Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertValidDQL('SELECT u, 42 + u.id AS someNumber FROM Doctrine\Tests\Models\CMS\CmsUser u'); } public function testInputParameterInSelect() { - $this->assertValidDQL('SELECT u, u.id + ?1 AS someNumber FROM Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertValidDQL('SELECT u, u.id + ?1 AS someNumber FROM Doctrine\Tests\Models\CMS\CmsUser u'); } /** @@ -575,9 +578,9 @@ public function testInputParameterInSelect() */ public function testCustomFunctionsReturningStringInStringPrimary() { - $this->_em->getConfiguration()->addCustomStringFunction('CC', Query\AST\Functions\ConcatFunction::class); + $this->em->getConfiguration()->addCustomStringFunction('CC', Query\AST\Functions\ConcatFunction::class); - $this->assertValidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CC('%', u.name) LIKE '%foo%'", true); + self::assertValidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CC('%', u.name) LIKE '%foo%'", true); } /** @@ -585,7 +588,7 @@ public function testCustomFunctionsReturningStringInStringPrimary() */ public function testDQLKeywordInJoinIsAllowed() { - $this->assertValidDQL('SELECT u FROM ' . __NAMESPACE__ . '\DQLKeywordsModelUser u JOIN u.group g'); + self::assertValidDQL('SELECT u FROM ' . __NAMESPACE__ . '\DQLKeywordsModelUser u JOIN u.group g'); } /** @@ -593,13 +596,13 @@ public function testDQLKeywordInJoinIsAllowed() */ public function testDQLKeywordInConditionIsAllowed() { - $this->assertValidDQL('SELECT g FROM ' . __NAMESPACE__ . '\DQLKeywordsModelGroup g WHERE g.from=0'); + self::assertValidDQL('SELECT g FROM ' . __NAMESPACE__ . '\DQLKeywordsModelGroup g WHERE g.from=0'); } /* The exception is currently thrown in the SQLWalker, not earlier. public function testInverseSideSingleValuedAssociationPathNotAllowed() { - $this->assertInvalidDQL('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.address = ?1'); + self::assertInvalidDQL('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.address = ?1'); } */ @@ -608,7 +611,7 @@ public function testInverseSideSingleValuedAssociationPathNotAllowed() */ public function testSelectOnlyNonRootEntityAlias() { - $this->assertInvalidDQL('SELECT g FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g'); + self::assertInvalidDQL('SELECT g FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g'); } /** @@ -616,7 +619,7 @@ public function testSelectOnlyNonRootEntityAlias() */ public function testInputParameterSingleChar() { - $this->assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = :q'); + self::assertValidDQL('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = :q'); } /** @@ -624,7 +627,7 @@ public function testInputParameterSingleChar() */ public function testGroupBy() { - $this->assertValidDQL('SELECT g.id, count(u.id) FROM Doctrine\Tests\Models\CMS\CmsGroup g JOIN g.users u GROUP BY g.id'); + self::assertValidDQL('SELECT g.id, count(u.id) FROM Doctrine\Tests\Models\CMS\CmsGroup g JOIN g.users u GROUP BY g.id'); } /** @@ -632,7 +635,7 @@ public function testGroupBy() */ public function testGroupByIdentificationVariable() { - $this->assertValidDQL('SELECT g, count(u.id) FROM Doctrine\Tests\Models\CMS\CmsGroup g JOIN g.users u GROUP BY g'); + self::assertValidDQL('SELECT g, count(u.id) FROM Doctrine\Tests\Models\CMS\CmsGroup g JOIN g.users u GROUP BY g'); } /** @@ -640,7 +643,7 @@ public function testGroupByIdentificationVariable() */ public function testGroupByUnknownIdentificationVariable() { - $this->assertInvalidDQL('SELECT g, count(u.id) FROM Doctrine\Tests\Models\CMS\CmsGroup g JOIN g.users u GROUP BY m'); + self::assertInvalidDQL('SELECT g, count(u.id) FROM Doctrine\Tests\Models\CMS\CmsGroup g JOIN g.users u GROUP BY m'); } /** @@ -648,7 +651,7 @@ public function testGroupByUnknownIdentificationVariable() */ public function testSizeOfForeignKeyOneToManyPrimaryKeyEntity() { - $this->assertValidDQL("SELECT a, t FROM Doctrine\Tests\Models\DDC117\DDC117Article a JOIN a.translations t WHERE SIZE(a.translations) > 0"); + self::assertValidDQL("SELECT a, t FROM Doctrine\Tests\Models\DDC117\DDC117Article a JOIN a.translations t WHERE SIZE(a.translations) > 0"); } /** @@ -656,17 +659,17 @@ public function testSizeOfForeignKeyOneToManyPrimaryKeyEntity() */ public function testSizeOfForeignKeyManyToManyPrimaryKeyEntity() { - $this->assertValidDQL("SELECT e, t FROM Doctrine\Tests\Models\DDC117\DDC117Editor e JOIN e.reviewingTranslations t WHERE SIZE(e.reviewingTranslations) > 0"); + self::assertValidDQL("SELECT e, t FROM Doctrine\Tests\Models\DDC117\DDC117Editor e JOIN e.reviewingTranslations t WHERE SIZE(e.reviewingTranslations) > 0"); } public function testCaseSupportContainingNullIfExpression() { - $this->assertValidDQL("SELECT u.id, NULLIF(u.name, u.name) AS shouldBeNull FROM Doctrine\Tests\Models\CMS\CmsUser u"); + self::assertValidDQL("SELECT u.id, NULLIF(u.name, u.name) AS shouldBeNull FROM Doctrine\Tests\Models\CMS\CmsUser u"); } public function testCaseSupportContainingCoalesceExpression() { - $this->assertValidDQL("select COALESCE(NULLIF(u.name, ''), u.username) as Display FROM Doctrine\Tests\Models\CMS\CmsUser u"); + self::assertValidDQL("select COALESCE(NULLIF(u.name, ''), u.username) as Display FROM Doctrine\Tests\Models\CMS\CmsUser u"); } /** @@ -674,7 +677,7 @@ public function testCaseSupportContainingCoalesceExpression() */ public function testHavingSupportIsNullExpression() { - $this->assertValidDQL("SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING u.username IS NULL"); + self::assertValidDQL("SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING u.username IS NULL"); } /** @@ -682,7 +685,7 @@ public function testHavingSupportIsNullExpression() */ public function testHavingSupportResultVariableInNullComparisonExpression() { - $this->assertValidDQL("SELECT u AS user, SUM(a.id) AS score FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN Doctrine\Tests\Models\CMS\CmsAddress a WITH a.user = u GROUP BY u HAVING score IS NOT NULL AND score >= 5"); + self::assertValidDQL("SELECT u AS user, SUM(a.id) AS score FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN Doctrine\Tests\Models\CMS\CmsAddress a WITH a.user = u GROUP BY u HAVING score IS NOT NULL AND score >= 5"); } /** @@ -690,7 +693,7 @@ public function testHavingSupportResultVariableInNullComparisonExpression() */ public function testHavingSupportLikeExpression() { - $this->assertValidDQL("SELECT _u.id, count(_articles) as uuuu FROM Doctrine\Tests\Models\CMS\CmsUser _u LEFT JOIN _u.articles _articles GROUP BY _u HAVING uuuu LIKE '3'"); + self::assertValidDQL("SELECT _u.id, count(_articles) as uuuu FROM Doctrine\Tests\Models\CMS\CmsUser _u LEFT JOIN _u.articles _articles GROUP BY _u HAVING uuuu LIKE '3'"); } /** @@ -698,7 +701,7 @@ public function testHavingSupportLikeExpression() */ public function testNewLiteralExpression() { - $this->assertValidDQL("SELECT new " . __NAMESPACE__ . "\\DummyStruct(u.id, 'foo', 1, true) FROM Doctrine\Tests\Models\CMS\CmsUser u"); + self::assertValidDQL("SELECT new " . __NAMESPACE__ . "\\DummyStruct(u.id, 'foo', 1, true) FROM Doctrine\Tests\Models\CMS\CmsUser u"); } /** @@ -706,25 +709,25 @@ public function testNewLiteralExpression() */ public function testNewLiteralWithSubselectExpression() { - $this->assertValidDQL("SELECT new " . __NAMESPACE__ . "\\DummyStruct(u.id, 'foo', (SELECT 1 FROM Doctrine\Tests\Models\CMS\CmsUser su), true) FROM Doctrine\Tests\Models\CMS\CmsUser u"); + self::assertValidDQL("SELECT new " . __NAMESPACE__ . "\\DummyStruct(u.id, 'foo', (SELECT 1 FROM Doctrine\Tests\Models\CMS\CmsUser su), true) FROM Doctrine\Tests\Models\CMS\CmsUser u"); } } -/** @Entity */ +/** @ORM\Entity */ class DQLKeywordsModelUser { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ private $id; - /** @OneToOne(targetEntity="DQLKeywordsModelGroup") */ + /** @ORM\OneToOne(targetEntity="DQLKeywordsModelGroup") */ private $group; } -/** @Entity */ +/** @ORM\Entity */ class DQLKeywordsModelGroup { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ private $id; - /** @Column */ + /** @ORM\Column */ private $from; } diff --git a/tests/Doctrine/Tests/ORM/Query/LexerTest.php b/tests/Doctrine/Tests/ORM/Query/LexerTest.php index 904b8978786..3459d49cca6 100644 --- a/tests/Doctrine/Tests/ORM/Query/LexerTest.php +++ b/tests/Doctrine/Tests/ORM/Query/LexerTest.php @@ -1,5 +1,7 @@ moveNext(); $token = $lexer->lookahead; - $this->assertEquals($type, $token['type']); - $this->assertEquals($value, $token['value']); + self::assertEquals($type, $token['type']); + self::assertEquals($value, $token['value']); } public function testScannerRecognizesTerminalString() @@ -39,7 +41,7 @@ public function testScannerRecognizesTerminalString() $lexer->moveNext(); $token = $lexer->lookahead; - $this->assertEquals(Lexer::T_ALL, $token['type']); + self::assertEquals(Lexer::T_ALL, $token['type']); } public function testScannerRecognizesDecimalInteger() @@ -47,8 +49,8 @@ public function testScannerRecognizesDecimalInteger() $lexer = new Lexer('1234'); $lexer->moveNext(); $token = $lexer->lookahead; - $this->assertEquals(Lexer::T_INTEGER, $token['type']); - $this->assertEquals(1234, $token['value']); + self::assertEquals(Lexer::T_INTEGER, $token['type']); + self::assertEquals(1234, $token['value']); } public function testScannerRecognizesFloat() @@ -56,8 +58,8 @@ public function testScannerRecognizesFloat() $lexer = new Lexer('1.234'); $lexer->moveNext(); $token = $lexer->lookahead; - $this->assertEquals(Lexer::T_FLOAT, $token['type']); - $this->assertEquals(1.234, $token['value']); + self::assertEquals(Lexer::T_FLOAT, $token['type']); + self::assertEquals(1.234, $token['value']); } public function testScannerRecognizesFloatWithExponent() @@ -65,8 +67,8 @@ public function testScannerRecognizesFloatWithExponent() $lexer = new Lexer('1.2e3'); $lexer->moveNext(); $token = $lexer->lookahead; - $this->assertEquals(Lexer::T_FLOAT, $token['type']); - $this->assertEquals(1.2e3, $token['value']); + self::assertEquals(Lexer::T_FLOAT, $token['type']); + self::assertEquals(1.2e3, $token['value']); } public function testScannerRecognizesFloatWithExponent2() @@ -74,8 +76,8 @@ public function testScannerRecognizesFloatWithExponent2() $lexer = new Lexer('0.2e3'); $lexer->moveNext(); $token = $lexer->lookahead; - $this->assertEquals(Lexer::T_FLOAT, $token['type']); - $this->assertEquals(.2e3, $token['value']); + self::assertEquals(Lexer::T_FLOAT, $token['type']); + self::assertEquals(.2e3, $token['value']); } public function testScannerRecognizesFloatWithNegativeExponent() @@ -83,8 +85,8 @@ public function testScannerRecognizesFloatWithNegativeExponent() $lexer = new Lexer('7E-10'); $lexer->moveNext(); $token = $lexer->lookahead; - $this->assertEquals(Lexer::T_FLOAT, $token['type']); - $this->assertEquals(7E-10, $token['value']); + self::assertEquals(Lexer::T_FLOAT, $token['type']); + self::assertEquals(7E-10, $token['value']); } public function testScannerRecognizesFloatBig() @@ -92,8 +94,8 @@ public function testScannerRecognizesFloatBig() $lexer = new Lexer('123456789.01'); $lexer->moveNext(); $token = $lexer->lookahead; - $this->assertEquals(Lexer::T_FLOAT, $token['type']); - $this->assertEquals(1.2345678901e8, $token['value']); + self::assertEquals(Lexer::T_FLOAT, $token['type']); + self::assertEquals(1.2345678901e8, $token['value']); } public function testScannerRecognizesFloatContainingWhitespace() @@ -101,14 +103,14 @@ public function testScannerRecognizesFloatContainingWhitespace() $lexer = new Lexer('- 1.234e2'); $lexer->moveNext(); $token = $lexer->lookahead; - $this->assertEquals(Lexer::T_MINUS, $token['type']); - $this->assertEquals('-', $token['value']); + self::assertEquals(Lexer::T_MINUS, $token['type']); + self::assertEquals('-', $token['value']); $lexer->moveNext(); $token = $lexer->lookahead; - $this->assertEquals(Lexer::T_FLOAT, $token['type']); - $this->assertNotEquals(-1.234e2, $token['value']); - $this->assertEquals(1.234e2, $token['value']); + self::assertEquals(Lexer::T_FLOAT, $token['type']); + self::assertNotEquals(-1.234e2, $token['value']); + self::assertEquals(1.234e2, $token['value']); } public function testScannerRecognizesStringContainingWhitespace() @@ -116,8 +118,8 @@ public function testScannerRecognizesStringContainingWhitespace() $lexer = new Lexer("'This is a string.'"); $lexer->moveNext(); $token = $lexer->lookahead; - $this->assertEquals(Lexer::T_STRING, $token['type']); - $this->assertEquals("This is a string.", $token['value']); + self::assertEquals(Lexer::T_STRING, $token['type']); + self::assertEquals("This is a string.", $token['value']); } public function testScannerRecognizesStringContainingSingleQuotes() @@ -125,8 +127,8 @@ public function testScannerRecognizesStringContainingSingleQuotes() $lexer = new Lexer("'abc''defg'''"); $lexer->moveNext(); $token = $lexer->lookahead; - $this->assertEquals(Lexer::T_STRING, $token['type']); - $this->assertEquals("abc'defg'", $token['value']); + self::assertEquals(Lexer::T_STRING, $token['type']); + self::assertEquals("abc'defg'", $token['value']); } public function testScannerRecognizesInputParameter() @@ -134,8 +136,8 @@ public function testScannerRecognizesInputParameter() $lexer = new Lexer('?1'); $lexer->moveNext(); $token = $lexer->lookahead; - $this->assertEquals(Lexer::T_INPUT_PARAMETER, $token['type']); - $this->assertEquals('?1', $token['value']); + self::assertEquals(Lexer::T_INPUT_PARAMETER, $token['type']); + self::assertEquals('?1', $token['value']); } public function testScannerRecognizesNamedInputParameter() @@ -143,8 +145,8 @@ public function testScannerRecognizesNamedInputParameter() $lexer = new Lexer(':name'); $lexer->moveNext(); $token = $lexer->lookahead; - $this->assertEquals(Lexer::T_INPUT_PARAMETER, $token['type']); - $this->assertEquals(':name', $token['value']); + self::assertEquals(Lexer::T_INPUT_PARAMETER, $token['type']); + self::assertEquals(':name', $token['value']); } public function testScannerRecognizesNamedInputParameterStartingWithUnderscore() @@ -152,8 +154,8 @@ public function testScannerRecognizesNamedInputParameterStartingWithUnderscore() $lexer = new Lexer(':_name'); $lexer->moveNext(); $token = $lexer->lookahead; - $this->assertEquals(Lexer::T_INPUT_PARAMETER, $token['type']); - $this->assertEquals(':_name', $token['value']); + self::assertEquals(Lexer::T_INPUT_PARAMETER, $token['type']); + self::assertEquals(':_name', $token['value']); } public function testScannerTokenizesASimpleQueryCorrectly() @@ -222,12 +224,12 @@ public function testScannerTokenizesASimpleQueryCorrectly() foreach ($tokens as $expected) { $lexer->moveNext(); $actual = $lexer->lookahead; - $this->assertEquals($expected['value'], $actual['value']); - $this->assertEquals($expected['type'], $actual['type']); - $this->assertEquals($expected['position'], $actual['position']); + self::assertEquals($expected['value'], $actual['value']); + self::assertEquals($expected['type'], $actual['type']); + self::assertEquals($expected['position'], $actual['position']); } - $this->assertFalse($lexer->moveNext()); + self::assertFalse($lexer->moveNext()); } public function provideTokens() diff --git a/tests/Doctrine/Tests/ORM/Query/ParameterTypeInfererTest.php b/tests/Doctrine/Tests/ORM/Query/ParameterTypeInfererTest.php index b929f8d18a3..ad1e5325431 100644 --- a/tests/Doctrine/Tests/ORM/Query/ParameterTypeInfererTest.php +++ b/tests/Doctrine/Tests/ORM/Query/ParameterTypeInfererTest.php @@ -1,5 +1,7 @@ assertEquals($expected, ParameterTypeInferer::inferType($value)); + self::assertEquals($expected, ParameterTypeInferer::inferType($value)); } } diff --git a/tests/Doctrine/Tests/ORM/Query/ParserResultTest.php b/tests/Doctrine/Tests/ORM/Query/ParserResultTest.php index 1b74654430e..f47100e6d0b 100644 --- a/tests/Doctrine/Tests/ORM/Query/ParserResultTest.php +++ b/tests/Doctrine/Tests/ORM/Query/ParserResultTest.php @@ -1,13 +1,15 @@ assertInstanceOf(ResultSetMapping::class, $this->parserResult->getResultSetMapping()); + self::assertInstanceOf(ResultSetMapping::class, $this->parserResult->getResultSetMapping()); } public function testSetGetSqlExecutor() { - $this->assertNull($this->parserResult->getSqlExecutor()); + self::assertNull($this->parserResult->getSqlExecutor()); $executor = $this->getMockBuilder(AbstractSqlExecutor::class)->setMethods(['execute'])->getMock(); $this->parserResult->setSqlExecutor($executor); - $this->assertSame($executor, $this->parserResult->getSqlExecutor()); + self::assertSame($executor, $this->parserResult->getSqlExecutor()); } public function testGetSqlParameterPosition() { $this->parserResult->addParameterMapping(1, 1); $this->parserResult->addParameterMapping(1, 2); - $this->assertEquals([1, 2], $this->parserResult->getSqlParameterPositions(1)); + self::assertEquals([1, 2], $this->parserResult->getSqlParameterPositions(1)); } public function testGetParameterMappings() { - $this->assertInternalType('array', $this->parserResult->getParameterMappings()); + self::assertInternalType('array', $this->parserResult->getParameterMappings()); $this->parserResult->addParameterMapping(1, 1); $this->parserResult->addParameterMapping(1, 2); - $this->assertEquals([1 => [1, 2]], $this->parserResult->getParameterMappings()); + self::assertEquals([1 => [1, 2]], $this->parserResult->getParameterMappings()); } } diff --git a/tests/Doctrine/Tests/ORM/Query/ParserTest.php b/tests/Doctrine/Tests/ORM/Query/ParserTest.php index b290812fc85..cb13ee6dd71 100644 --- a/tests/Doctrine/Tests/ORM/Query/ParserTest.php +++ b/tests/Doctrine/Tests/ORM/Query/ParserTest.php @@ -1,5 +1,7 @@ createParser(CmsUser::class); - $this->assertEquals(CmsUser::class, $parser->AbstractSchemaName()); + self::assertEquals(CmsUser::class, $parser->AbstractSchemaName()); } /** @@ -31,7 +33,7 @@ public function testAbstractSchemaNameSupportsClassnamesWithLeadingBackslash() { $parser = $this->createParser('\\' . CmsUser::class); - $this->assertEquals('\\' . CmsUser::class, $parser->AbstractSchemaName()); + self::assertEquals('\\' . CmsUser::class, $parser->AbstractSchemaName()); } /** @@ -42,7 +44,7 @@ public function testAbstractSchemaNameSupportsIdentifier() { $parser = $this->createParser(\stdClass::class); - $this->assertEquals(\stdClass::class, $parser->AbstractSchemaName()); + self::assertEquals(\stdClass::class, $parser->AbstractSchemaName()); } /** @@ -55,7 +57,7 @@ public function testAbstractSchemaNameSupportsNamespaceAlias() $parser->getEntityManager()->getConfiguration()->addEntityNamespace('CMS', 'Doctrine\Tests\Models\CMS'); - $this->assertEquals(CmsUser::class, $parser->AbstractSchemaName()); + self::assertEquals(CmsUser::class, $parser->AbstractSchemaName()); } /** @@ -68,7 +70,7 @@ public function testAbstractSchemaNameSupportsNamespaceAliasWithRelativeClassnam $parser->getEntityManager()->getConfiguration()->addEntityNamespace('Model', 'Doctrine\Tests\Models'); - $this->assertEquals(CmsUser::class, $parser->AbstractSchemaName()); + self::assertEquals(CmsUser::class, $parser->AbstractSchemaName()); } /** @@ -136,7 +138,7 @@ public function invalidMatches() private function createParser($dql) { - $query = new Query($this->_getTestEntityManager()); + $query = new Query($this->getTestEntityManager()); $query->setDQL($dql); $parser = new Parser($query); diff --git a/tests/Doctrine/Tests/ORM/Query/QueryExpressionVisitorTest.php b/tests/Doctrine/Tests/ORM/Query/QueryExpressionVisitorTest.php index 0e306ab06ea..6a22b1113f8 100644 --- a/tests/Doctrine/Tests/ORM/Query/QueryExpressionVisitorTest.php +++ b/tests/Doctrine/Tests/ORM/Query/QueryExpressionVisitorTest.php @@ -1,5 +1,7 @@ */ -class QueryExpressionVisitorTest extends TestCase +class QueryExpressionVisitorTest extends DoctrineTestCase { /** * @var QueryExpressionVisitor @@ -40,9 +42,9 @@ protected function setUp() */ public function testWalkComparison(CriteriaComparison $criteriaExpr, $queryExpr, Parameter $parameter = null) { - $this->assertEquals($queryExpr, $this->visitor->walkComparison($criteriaExpr)); + self::assertEquals($queryExpr, $this->visitor->walkComparison($criteriaExpr)); if ($parameter) { - $this->assertEquals(new ArrayCollection([$parameter]), $this->visitor->getParameters()); + self::assertEquals(new ArrayCollection([$parameter]), $this->visitor->getParameters()); } } @@ -90,8 +92,8 @@ public function testWalkAndCompositeExpression() ) ); - $this->assertInstanceOf(QueryBuilder\Andx::class, $expr); - $this->assertCount(2, $expr->getParts()); + self::assertInstanceOf(QueryBuilder\Andx::class, $expr); + self::assertCount(2, $expr->getParts()); } public function testWalkOrCompositeExpression() @@ -104,13 +106,13 @@ public function testWalkOrCompositeExpression() ) ); - $this->assertInstanceOf(QueryBuilder\Orx::class, $expr); - $this->assertCount(2, $expr->getParts()); + self::assertInstanceOf(QueryBuilder\Orx::class, $expr); + self::assertCount(2, $expr->getParts()); } public function testWalkValue() { - $this->assertEquals('value', $this->visitor->walkValue(new Value('value'))); + self::assertEquals('value', $this->visitor->walkValue(new Value('value'))); } public function testClearParameters() @@ -119,6 +121,6 @@ public function testClearParameters() $this->visitor->clearParameters(); - $this->assertCount(0, $this->visitor->getParameters()); + self::assertCount(0, $this->visitor->getParameters()); } } diff --git a/tests/Doctrine/Tests/ORM/Query/QueryTest.php b/tests/Doctrine/Tests/ORM/Query/QueryTest.php index 5a2a295fe79..35ba24dc673 100644 --- a/tests/Doctrine/Tests/ORM/Query/QueryTest.php +++ b/tests/Doctrine/Tests/ORM/Query/QueryTest.php @@ -1,11 +1,12 @@ _em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); } public function testGetParameters() { - $query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username = ?1"); + $query = $this->em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username = ?1"); $parameters = new ArrayCollection(); - $this->assertEquals($parameters, $query->getParameters()); + self::assertEquals($parameters, $query->getParameters()); } public function testGetParameters_HasSomeAlready() { - $query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username = ?1"); + $query = $this->em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username = ?1"); $query->setParameter(2, 84); $parameters = new ArrayCollection(); $parameters->add(new Parameter(2, 84)); - $this->assertEquals($parameters, $query->getParameters()); + self::assertEquals($parameters, $query->getParameters()); } public function testSetParameters() { - $query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username = ?1"); + $query = $this->em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username = ?1"); $parameters = new ArrayCollection(); $parameters->add(new Parameter(1, 'foo')); @@ -54,37 +55,37 @@ public function testSetParameters() $query->setParameters($parameters); - $this->assertEquals($parameters, $query->getParameters()); + self::assertEquals($parameters, $query->getParameters()); } public function testFree() { - $query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username = ?1"); + $query = $this->em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username = ?1"); $query->setParameter(2, 84, \PDO::PARAM_INT); $query->free(); - $this->assertEquals(0, count($query->getParameters())); + self::assertEquals(0, count($query->getParameters())); } public function testClone() { $dql = "select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username = ?1"; - $query = $this->_em->createQuery($dql); + $query = $this->em->createQuery($dql); $query->setParameter(2, 84, \PDO::PARAM_INT); $query->setHint('foo', 'bar'); $cloned = clone $query; - $this->assertEquals($dql, $cloned->getDQL()); - $this->assertEquals(0, count($cloned->getParameters())); - $this->assertFalse($cloned->getHint('foo')); + self::assertEquals($dql, $cloned->getDQL()); + self::assertEquals(0, count($cloned->getParameters())); + self::assertFalse($cloned->getHint('foo')); } public function testFluentQueryInterface() { - $q = $this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a"); + $q = $this->em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a"); $q2 = $q->expireQueryCache(true) ->setQueryCacheLifetime(3600) ->setQueryCacheDriver(null) @@ -99,7 +100,7 @@ public function testFluentQueryInterface() ->setFirstResult(10) ->setMaxResults(10); - $this->assertSame($q2, $q); + self::assertSame($q2, $q); } /** @@ -107,14 +108,14 @@ public function testFluentQueryInterface() */ public function testHints() { - $q = $this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a"); + $q = $this->em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a"); $q->setHint('foo', 'bar')->setHint('bar', 'baz'); - $this->assertEquals('bar', $q->getHint('foo')); - $this->assertEquals('baz', $q->getHint('bar')); - $this->assertEquals(['foo' => 'bar', 'bar' => 'baz'], $q->getHints()); - $this->assertTrue($q->hasHint('foo')); - $this->assertFalse($q->hasHint('barFooBaz')); + self::assertEquals('bar', $q->getHint('foo')); + self::assertEquals('baz', $q->getHint('bar')); + self::assertEquals(['foo' => 'bar', 'bar' => 'baz'], $q->getHints()); + self::assertTrue($q->hasHint('foo')); + self::assertFalse($q->hasHint('barFooBaz')); } /** @@ -122,10 +123,10 @@ public function testHints() */ public function testQueryDefaultResultCache() { - $this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache()); - $q = $this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a"); + $this->em->getConfiguration()->setResultCacheImpl(new ArrayCache()); + $q = $this->em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a"); $q->useResultCache(true); - $this->assertSame($this->_em->getConfiguration()->getResultCacheImpl(), $q->getQueryCacheProfile()->getResultCacheDriver()); + self::assertSame($this->em->getConfiguration()->getResultCacheImpl(), $q->getQueryCacheProfile()->getResultCacheDriver()); } /** @@ -133,7 +134,7 @@ public function testQueryDefaultResultCache() **/ public function testIterateWithNoDistinctAndWrongSelectClause() { - $q = $this->_em->createQuery("select u, a from Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a"); + $q = $this->em->createQuery("select u, a from Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a"); $q->iterate(); } @@ -142,13 +143,13 @@ public function testIterateWithNoDistinctAndWrongSelectClause() **/ public function testIterateWithNoDistinctAndWithValidSelectClause() { - $q = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a"); + $q = $this->em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a"); $q->iterate(); } public function testIterateWithDistinct() { - $q = $this->_em->createQuery("SELECT DISTINCT u from Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a"); + $q = $this->em->createQuery("SELECT DISTINCT u from Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a"); self::assertInstanceOf(IterableResult::class, $q->iterate()); } @@ -164,15 +165,15 @@ public function testCollectionParameters() 9 => "St Julien" ]; - $query = $this->_em + $query = $this->em ->createQuery("SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a WHERE a.city IN (:cities)") ->setParameter('cities', $cities); $parameters = $query->getParameters(); $parameter = $parameters->first(); - $this->assertEquals('cities', $parameter->getName()); - $this->assertEquals($cities, $parameter->getValue()); + self::assertEquals('cities', $parameter->getName()); + self::assertEquals($cities, $parameter->getValue()); } /** @@ -180,16 +181,16 @@ public function testCollectionParameters() */ public function testProcessParameterValueClassMetadata() { - $query = $this->_em->createQuery("SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a WHERE a.city IN (:cities)"); - $this->assertEquals( + $query = $this->em->createQuery("SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a WHERE a.city IN (:cities)"); + self::assertEquals( CmsAddress::class, - $query->processParameterValue($this->_em->getClassMetadata(CmsAddress::class)) + $query->processParameterValue($this->em->getClassMetadata(CmsAddress::class)) ); } public function testDefaultQueryHints() { - $config = $this->_em->getConfiguration(); + $config = $this->em->getConfiguration(); $defaultHints = [ 'hint_name_1' => 'hint_value_1', 'hint_name_2' => 'hint_value_2', @@ -197,12 +198,12 @@ public function testDefaultQueryHints() ]; $config->setDefaultQueryHints($defaultHints); - $query = $this->_em->createQuery(); - $this->assertSame($config->getDefaultQueryHints(), $query->getHints()); - $this->_em->getConfiguration()->setDefaultQueryHint('hint_name_1', 'hint_another_value_1'); - $this->assertNotSame($config->getDefaultQueryHints(), $query->getHints()); + $query = $this->em->createQuery(); + self::assertSame($config->getDefaultQueryHints(), $query->getHints()); + $this->em->getConfiguration()->setDefaultQueryHint('hint_name_1', 'hint_another_value_1'); + self::assertNotSame($config->getDefaultQueryHints(), $query->getHints()); $q2 = clone $query; - $this->assertSame($config->getDefaultQueryHints(), $q2->getHints()); + self::assertSame($config->getDefaultQueryHints(), $q2->getHints()); } /** @@ -210,31 +211,31 @@ public function testDefaultQueryHints() */ public function testResultCacheCaching() { - $this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache()); - $this->_em->getConfiguration()->setQueryCacheImpl(new ArrayCache()); + $this->em->getConfiguration()->setResultCacheImpl(new ArrayCache()); + $this->em->getConfiguration()->setQueryCacheImpl(new ArrayCache()); /** @var DriverConnectionMock $driverConnectionMock */ - $driverConnectionMock = $this->_em->getConnection()->getWrappedConnection(); + $driverConnectionMock = $this->em->getConnection()->getWrappedConnection(); $stmt = new StatementArrayMock([ [ - 'id_0' => 1, + 'c0' => 1, ] ]); $driverConnectionMock->setStatementMock($stmt); - $res = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u") + $res = $this->em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u") ->useQueryCache(true) ->useResultCache(true, 60) //let it cache ->getResult(); - $this->assertCount(1, $res); + self::assertCount(1, $res); $driverConnectionMock->setStatementMock(null); - $res = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u") + $res = $this->em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u") ->useQueryCache(true) ->useResultCache(false) ->getResult(); - $this->assertCount(0, $res); + self::assertCount(0, $res); } /** @@ -242,9 +243,10 @@ public function testResultCacheCaching() */ public function testSetHydrationCacheProfileNull() { - $query = $this->_em->createQuery(); + $query = $this->em->createQuery(); $query->setHydrationCacheProfile(null); - $this->assertNull($query->getHydrationCacheProfile()); + + self::assertNull($query->getHydrationCacheProfile()); } /** @@ -252,29 +254,33 @@ public function testSetHydrationCacheProfileNull() */ public function testResultCacheEviction() { - $this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache()); + $this->em->getConfiguration()->setResultCacheImpl(new ArrayCache()); - $query = $this->_em->createQuery("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u") - ->useResultCache(true); + $query = $this->em + ->createQuery("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u") + ->useResultCache(true); /** @var DriverConnectionMock $driverConnectionMock */ - $driverConnectionMock = $this->_em->getConnection() - ->getWrappedConnection(); + $driverConnectionMock = $this->em->getConnection() + ->getWrappedConnection(); + + // Performs the query and sets up the initial cache + self::assertCount(0, $query->getResult()); - $driverConnectionMock->setStatementMock(new StatementArrayMock([['id_0' => 1]])); + $driverConnectionMock->setStatementMock(new StatementArrayMock([['c0' => 1]])); // Performs the query and sets up the initial cache - self::assertCount(1, $query->getResult()); + self::assertCount(1, $query->expireResultCache(true)->getResult()); - $driverConnectionMock->setStatementMock(new StatementArrayMock([['id_0' => 1], ['id_0' => 2]])); + $driverConnectionMock->setStatementMock(new StatementArrayMock([['c0' => 1], ['c0' => 2]])); // Retrieves cached data since expire flag is false and we have a cached result set - self::assertCount(1, $query->getResult()); + self::assertCount(1, $query->expireResultCache(false)->getResult()); // Performs the query and caches the result set since expire flag is true self::assertCount(2, $query->expireResultCache(true)->getResult()); - $driverConnectionMock->setStatementMock(new StatementArrayMock([['id_0' => 1]])); + $driverConnectionMock->setStatementMock(new StatementArrayMock([['c0' => 1]])); // Retrieves cached data since expire flag is false and we have a cached result set self::assertCount(2, $query->expireResultCache(false)->getResult()); @@ -285,7 +291,7 @@ public function testResultCacheEviction() */ public function testSelectJoinSubquery() { - $query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u JOIN (SELECT )"); + $query = $this->em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u JOIN (SELECT )"); $this->expectException(QueryException::class); $this->expectExceptionMessage('Subquery'); @@ -297,7 +303,7 @@ public function testSelectJoinSubquery() */ public function testSelectFromSubquery() { - $query = $this->_em->createQuery("select u from (select Doctrine\Tests\Models\CMS\CmsUser c) as u"); + $query = $this->em->createQuery("select u from (select Doctrine\Tests\Models\CMS\CmsUser c) as u"); $this->expectException(QueryException::class); $this->expectExceptionMessage('Subquery'); diff --git a/tests/Doctrine/Tests/ORM/Query/SelectSqlGenerationTest.php b/tests/Doctrine/Tests/ORM/Query/SelectSqlGenerationTest.php index c10afbb8961..42e38ad3c87 100644 --- a/tests/Doctrine/Tests/ORM/Query/SelectSqlGenerationTest.php +++ b/tests/Doctrine/Tests/ORM/Query/SelectSqlGenerationTest.php @@ -1,5 +1,7 @@ _em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); } /** @@ -42,14 +45,16 @@ protected function setUp() public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed, array $queryHints = [], array $queryParams = []) { try { - $query = $this->_em->createQuery($dqlToBeTested); + $query = $this->em->createQuery($dqlToBeTested); foreach ($queryParams AS $name => $value) { $query->setParameter($name, $value); } - $query->setHint(ORMQuery::HINT_FORCE_PARTIAL_LOAD, true) - ->useQueryCache(false); + $query + ->setHint(ORMQuery::HINT_FORCE_PARTIAL_LOAD, true) + ->useQueryCache(false) + ; foreach ($queryHints AS $name => $value) { $query->setHint($name, $value); @@ -57,16 +62,12 @@ public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed, array $qu $sqlGenerated = $query->getSQL(); - parent::assertEquals( - $sqlToBeConfirmed, - $sqlGenerated, - sprintf('"%s" is not equal of "%s"', $sqlGenerated, $sqlToBeConfirmed) - ); - $query->free(); } catch (\Exception $e) { $this->fail($e->getMessage() ."\n".$e->getTraceAsString()); } + + self::assertEquals($sqlToBeConfirmed, $sqlGenerated); } /** @@ -81,14 +82,16 @@ public function assertInvalidSqlGeneration($dqlToBeTested, $expectedException, a { $this->expectException($expectedException); - $query = $this->_em->createQuery($dqlToBeTested); + $query = $this->em->createQuery($dqlToBeTested); foreach ($queryParams AS $name => $value) { $query->setParameter($name, $value); } - $query->setHint(ORMQuery::HINT_FORCE_PARTIAL_LOAD, true) - ->useQueryCache(false); + $query + ->setHint(ORMQuery::HINT_FORCE_PARTIAL_LOAD, true) + ->useQueryCache(false) + ; foreach ($queryHints AS $name => $value) { $query->setHint($name, $value); @@ -108,7 +111,7 @@ public function testJoinWithRangeVariablePutsConditionIntoSqlWhereClause() { $this->assertSqlGeneration( 'SELECT c.id FROM Doctrine\Tests\Models\Company\CompanyPerson c JOIN Doctrine\Tests\Models\Company\CompanyPerson r WHERE c.spouse = r AND r.id = 42', - 'SELECT c0_.id AS id_0 FROM company_persons c0_ INNER JOIN company_persons c1_ WHERE c0_.spouse_id = c1_.id AND c1_.id = 42', + 'SELECT t0."id" AS c0 FROM "company_persons" t0 INNER JOIN "company_persons" t1 WHERE t0."spouse_id" = t1."id" AND t1."id" = 42', [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true] ); } @@ -125,7 +128,7 @@ public function testJoinWithRangeVariableAndInheritancePutsConditionIntoSqlWhere */ $this->assertSqlGeneration( 'SELECT c.id FROM Doctrine\Tests\Models\Company\CompanyPerson c JOIN Doctrine\Tests\Models\Company\CompanyPerson r WHERE c.spouse = r AND r.id = 42', - 'SELECT c0_.id AS id_0 FROM company_persons c0_ LEFT JOIN company_managers c1_ ON c0_.id = c1_.id LEFT JOIN company_employees c2_ ON c0_.id = c2_.id INNER JOIN company_persons c3_ LEFT JOIN company_managers c4_ ON c3_.id = c4_.id LEFT JOIN company_employees c5_ ON c3_.id = c5_.id WHERE c0_.spouse_id = c3_.id AND c3_.id = 42', + 'SELECT t0."id" AS c0 FROM "company_persons" t0 LEFT JOIN "company_managers" t1 ON t0."id" = t1."id" LEFT JOIN "company_employees" t2 ON t0."id" = t2."id" INNER JOIN "company_persons" t3 LEFT JOIN "company_managers" t4 ON t3."id" = t4."id" LEFT JOIN "company_employees" t5 ON t3."id" = t5."id" WHERE t0."spouse_id" = t3."id" AND t3."id" = 42', [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -134,7 +137,7 @@ public function testSupportsSelectForAllFields() { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0' ); } @@ -142,7 +145,7 @@ public function testSupportsSelectForOneField() { $this->assertSqlGeneration( 'SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u', - 'SELECT c0_.id AS id_0 FROM cms_users c0_' + 'SELECT t0."id" AS c0 FROM "cms_users" t0' ); } @@ -150,7 +153,7 @@ public function testSupportsSelectForOneNestedField() { $this->assertSqlGeneration( 'SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsArticle a JOIN a.user u', - 'SELECT c0_.id AS id_0 FROM cms_articles c1_ INNER JOIN cms_users c0_ ON c1_.user_id = c0_.id' + 'SELECT t0."id" AS c0 FROM "cms_articles" t1 INNER JOIN "cms_users" t0 ON t1."user_id" = t0."id"' ); } @@ -158,7 +161,7 @@ public function testSupportsSelectForAllNestedField() { $this->assertSqlGeneration( 'SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a JOIN a.user u ORDER BY u.name ASC', - 'SELECT c0_.id AS id_0, c0_.topic AS topic_1, c0_.text AS text_2, c0_.version AS version_3 FROM cms_articles c0_ INNER JOIN cms_users c1_ ON c0_.user_id = c1_.id ORDER BY c1_.name ASC' + 'SELECT t0."id" AS c0, t0."topic" AS c1, t0."text" AS c2, t0."version" AS c3 FROM "cms_articles" t0 INNER JOIN "cms_users" t1 ON t0."user_id" = t1."id" ORDER BY t1."name" ASC' ); } @@ -166,7 +169,7 @@ public function testNotExistsExpression() { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE NOT EXISTS (SELECT p.phonenumber FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.phonenumber = 1234)', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE NOT EXISTS (SELECT c1_.phonenumber FROM cms_phonenumbers c1_ WHERE c1_.phonenumber = 1234)' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE NOT EXISTS (SELECT t1."phonenumber" FROM "cms_phonenumbers" t1 WHERE t1."phonenumber" = 1234)' ); } @@ -174,7 +177,7 @@ public function testSupportsSelectForMultipleColumnsOfASingleComponent() { $this->assertSqlGeneration( 'SELECT u.username, u.name FROM Doctrine\Tests\Models\CMS\CmsUser u', - 'SELECT c0_.username AS username_0, c0_.name AS name_1 FROM cms_users c0_' + 'SELECT t0."username" AS c0, t0."name" AS c1 FROM "cms_users" t0' ); } @@ -182,7 +185,7 @@ public function testSupportsSelectUsingMultipleFromComponents() { $this->assertSqlGeneration( 'SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE u = p.user', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c1_.phonenumber AS phonenumber_4 FROM cms_users c0_, cms_phonenumbers c1_ WHERE c0_.id = c1_.user_id' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, t1."phonenumber" AS c4 FROM "cms_users" t0, "cms_phonenumbers" t1 WHERE t0."id" = t1."user_id"' ); } @@ -190,7 +193,7 @@ public function testSupportsJoinOnMultipleComponents() { $this->assertSqlGeneration( 'SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN Doctrine\Tests\Models\CMS\CmsPhonenumber p WITH u = p.user', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c1_.phonenumber AS phonenumber_4 FROM cms_users c0_ INNER JOIN cms_phonenumbers c1_ ON (c0_.id = c1_.user_id)' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, t1."phonenumber" AS c4 FROM "cms_users" t0 INNER JOIN "cms_phonenumbers" t1 ON (t0."id" = t1."user_id")' ); } @@ -198,12 +201,12 @@ public function testSupportsJoinOnMultipleComponentsWithJoinedInheritanceType() { $this->assertSqlGeneration( 'SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e JOIN Doctrine\Tests\Models\Company\CompanyManager m WITH e.id = m.id', - 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c0_.discr AS discr_5 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id INNER JOIN company_managers c2_ INNER JOIN company_employees c4_ ON c2_.id = c4_.id INNER JOIN company_persons c3_ ON c2_.id = c3_.id AND (c0_.id = c3_.id)' + 'SELECT t0."id" AS c0, t0."name" AS c1, t1."salary" AS c2, t1."department" AS c3, t1."startDate" AS c4, t0."discr" AS c5 FROM "company_employees" t1 INNER JOIN "company_persons" t0 ON t1."id" = t0."id" INNER JOIN "company_managers" t2 INNER JOIN "company_employees" t4 ON t2."id" = t4."id" INNER JOIN "company_persons" t3 ON t2."id" = t3."id" AND (t0."id" = t3."id")' ); $this->assertSqlGeneration( 'SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e LEFT JOIN Doctrine\Tests\Models\Company\CompanyManager m WITH e.id = m.id', - 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c0_.discr AS discr_5 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id LEFT JOIN company_managers c2_ INNER JOIN company_employees c4_ ON c2_.id = c4_.id INNER JOIN company_persons c3_ ON c2_.id = c3_.id ON (c0_.id = c3_.id)' + 'SELECT t0."id" AS c0, t0."name" AS c1, t1."salary" AS c2, t1."department" AS c3, t1."startDate" AS c4, t0."discr" AS c5 FROM "company_employees" t1 INNER JOIN "company_persons" t0 ON t1."id" = t0."id" LEFT JOIN "company_managers" t2 INNER JOIN "company_employees" t4 ON t2."id" = t4."id" INNER JOIN "company_persons" t3 ON t2."id" = t3."id" ON (t0."id" = t3."id")' ); } @@ -211,7 +214,7 @@ public function testSupportsSelectWithCollectionAssociationJoin() { $this->assertSqlGeneration( 'SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.phonenumbers p', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c1_.phonenumber AS phonenumber_4 FROM cms_users c0_ INNER JOIN cms_phonenumbers c1_ ON c0_.id = c1_.user_id' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, t1."phonenumber" AS c4 FROM "cms_users" t0 INNER JOIN "cms_phonenumbers" t1 ON t0."id" = t1."user_id"' ); } @@ -219,7 +222,7 @@ public function testSupportsSelectWithSingleValuedAssociationJoin() { $this->assertSqlGeneration( 'SELECT u, a FROM Doctrine\Tests\Models\Forum\ForumUser u JOIN u.avatar a', - 'SELECT f0_.id AS id_0, f0_.username AS username_1, f1_.id AS id_2 FROM forum_users f0_ INNER JOIN forum_avatars f1_ ON f0_.avatar_id = f1_.id' + 'SELECT t0."id" AS c0, t0."username" AS c1, t1."id" AS c2 FROM "forum_users" t0 INNER JOIN "forum_avatars" t1 ON t0."avatar_id" = t1."id"' ); } @@ -227,7 +230,7 @@ public function testSelectCorrelatedSubqueryComplexMathematicalExpression() { $this->assertSqlGeneration( 'SELECT (SELECT (count(p.phonenumber)+5)*10 FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p JOIN p.user ui WHERE ui.id = u.id) AS c FROM Doctrine\Tests\Models\CMS\CmsUser u', - 'SELECT (SELECT (count(c0_.phonenumber) + 5) * 10 AS sclr_1 FROM cms_phonenumbers c0_ INNER JOIN cms_users c1_ ON c0_.user_id = c1_.id WHERE c1_.id = c2_.id) AS sclr_0 FROM cms_users c2_' + 'SELECT (SELECT (count(t0."phonenumber") + 5) * 10 AS c1 FROM "cms_phonenumbers" t0 INNER JOIN "cms_users" t1 ON t0."user_id" = t1."id" WHERE t1."id" = t2."id") AS c0 FROM "cms_users" t2' ); } @@ -235,7 +238,7 @@ public function testSelectComplexMathematicalExpression() { $this->assertSqlGeneration( 'SELECT (count(p.phonenumber)+5)*10 FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p JOIN p.user ui WHERE ui.id = ?1', - 'SELECT (count(c0_.phonenumber) + 5) * 10 AS sclr_0 FROM cms_phonenumbers c0_ INNER JOIN cms_users c1_ ON c0_.user_id = c1_.id WHERE c1_.id = ?' + 'SELECT (count(t0."phonenumber") + 5) * 10 AS c0 FROM "cms_phonenumbers" t0 INNER JOIN "cms_users" t1 ON t0."user_id" = t1."id" WHERE t1."id" = ?' ); } @@ -246,7 +249,7 @@ public function testSingleAssociationPathExpressionInSubselect() { $this->assertSqlGeneration( 'SELECT (SELECT p.user FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.user = u) user_id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1', - 'SELECT (SELECT c0_.user_id FROM cms_phonenumbers c0_ WHERE c0_.user_id = c1_.id) AS sclr_0 FROM cms_users c1_ WHERE c1_.id = ?' + 'SELECT (SELECT t0."user_id" FROM "cms_phonenumbers" t0 WHERE t0."user_id" = t1."id") AS c0 FROM "cms_users" t1 WHERE t1."id" = ?' ); }*/ @@ -256,8 +259,8 @@ public function testSingleAssociationPathExpressionInSubselect() public function testConstantValueInSelect() { $this->assertSqlGeneration( - "SELECT u.name, 'foo' AS bar FROM Doctrine\Tests\Models\CMS\CmsUser u", - "SELECT c0_.name AS name_0, 'foo' AS sclr_1 FROM cms_users c0_" + 'SELECT u.name, \'foo\' AS bar FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT t0."name" AS c0, \'foo\' AS c1 FROM "cms_users" t0' ); } @@ -265,7 +268,7 @@ public function testSupportsOrderByWithAscAsDefault() { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u ORDER BY u.id', - 'SELECT f0_.id AS id_0, f0_.username AS username_1 FROM forum_users f0_ ORDER BY f0_.id ASC' + 'SELECT t0."id" AS c0, t0."username" AS c1 FROM "forum_users" t0 ORDER BY t0."id" ASC' ); } @@ -273,14 +276,14 @@ public function testSupportsOrderByAsc() { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u ORDER BY u.id asc', - 'SELECT f0_.id AS id_0, f0_.username AS username_1 FROM forum_users f0_ ORDER BY f0_.id ASC' + 'SELECT t0."id" AS c0, t0."username" AS c1 FROM "forum_users" t0 ORDER BY t0."id" ASC' ); } public function testSupportsOrderByDesc() { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u ORDER BY u.id desc', - 'SELECT f0_.id AS id_0, f0_.username AS username_1 FROM forum_users f0_ ORDER BY f0_.id DESC' + 'SELECT t0."id" AS c0, t0."username" AS c1 FROM "forum_users" t0 ORDER BY t0."id" DESC' ); } @@ -288,7 +291,7 @@ public function testSupportsSelectDistinct() { $this->assertSqlGeneration( 'SELECT DISTINCT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u', - 'SELECT DISTINCT c0_.name AS name_0 FROM cms_users c0_' + 'SELECT DISTINCT t0."name" AS c0 FROM "cms_users" t0' ); } @@ -296,7 +299,7 @@ public function testSupportsAggregateFunctionInSelectedFields() { $this->assertSqlGeneration( 'SELECT COUNT(u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u.id', - 'SELECT COUNT(c0_.id) AS sclr_0 FROM cms_users c0_ GROUP BY c0_.id' + 'SELECT COUNT(t0."id") AS c0 FROM "cms_users" t0 GROUP BY t0."id"' ); } @@ -304,33 +307,28 @@ public function testSupportsAggregateFunctionWithSimpleArithmetic() { $this->assertSqlGeneration( 'SELECT MAX(u.id + 4) * 2 FROM Doctrine\Tests\Models\CMS\CmsUser u', - 'SELECT MAX(c0_.id + 4) * 2 AS sclr_0 FROM cms_users c0_' + 'SELECT MAX(t0."id" + 4) * 2 AS c0 FROM "cms_users" t0' ); } /** * @group DDC-3276 */ - public function testSupportsAggregateCountFunctionWithSimpleArithmetic() + public function testSupportsAggregateCountFunctionWithSimpleArithmeticMySql() { - $connMock = $this->_em->getConnection(); - $orgPlatform = $connMock->getDatabasePlatform(); - - $connMock->setDatabasePlatform(new MySqlPlatform()); + $this->em->getConnection()->setDatabasePlatform(new MySqlPlatform()); $this->assertSqlGeneration( 'SELECT COUNT(CONCAT(u.id, u.name)) FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u.id', - 'SELECT COUNT(CONCAT(c0_.id, c0_.name)) AS sclr_0 FROM cms_users c0_ GROUP BY c0_.id' + 'SELECT COUNT(CONCAT(t0.`id`, t0.`name`)) AS c0 FROM `cms_users` t0 GROUP BY t0.`id`' ); - - $connMock->setDatabasePlatform($orgPlatform); } public function testSupportsWhereClauseWithPositionalParameter() { $this->assertSqlGeneration( 'select u from Doctrine\Tests\Models\Forum\ForumUser u where u.id = ?1', - 'SELECT f0_.id AS id_0, f0_.username AS username_1 FROM forum_users f0_ WHERE f0_.id = ?' + 'SELECT t0."id" AS c0, t0."username" AS c1 FROM "forum_users" t0 WHERE t0."id" = ?' ); } @@ -338,7 +336,7 @@ public function testSupportsWhereClauseWithNamedParameter() { $this->assertSqlGeneration( 'select u from Doctrine\Tests\Models\Forum\ForumUser u where u.username = :name', - 'SELECT f0_.id AS id_0, f0_.username AS username_1 FROM forum_users f0_ WHERE f0_.username = ?' + 'SELECT t0."id" AS c0, t0."username" AS c1 FROM "forum_users" t0 WHERE t0."username" = ?' ); } @@ -346,7 +344,7 @@ public function testSupportsWhereAndClauseWithNamedParameters() { $this->assertSqlGeneration( 'select u from Doctrine\Tests\Models\Forum\ForumUser u where u.username = :name and u.username = :name2', - 'SELECT f0_.id AS id_0, f0_.username AS username_1 FROM forum_users f0_ WHERE f0_.username = ? AND f0_.username = ?' + 'SELECT t0."id" AS c0, t0."username" AS c1 FROM "forum_users" t0 WHERE t0."username" = ? AND t0."username" = ?' ); } @@ -354,7 +352,7 @@ public function testSupportsCombinedWhereClauseWithNamedParameter() { $this->assertSqlGeneration( 'select u from Doctrine\Tests\Models\Forum\ForumUser u where (u.username = :name OR u.username = :name2) AND u.id = :id', - 'SELECT f0_.id AS id_0, f0_.username AS username_1 FROM forum_users f0_ WHERE (f0_.username = ? OR f0_.username = ?) AND f0_.id = ?' + 'SELECT t0."id" AS c0, t0."username" AS c1 FROM "forum_users" t0 WHERE (t0."username" = ? OR t0."username" = ?) AND t0."id" = ?' ); } @@ -362,7 +360,7 @@ public function testSupportsAggregateFunctionInASelectDistinct() { $this->assertSqlGeneration( 'SELECT COUNT(DISTINCT u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u', - 'SELECT COUNT(DISTINCT c0_.name) AS sclr_0 FROM cms_users c0_' + 'SELECT COUNT(DISTINCT t0."name") AS c0 FROM "cms_users" t0' ); } @@ -370,8 +368,8 @@ public function testSupportsAggregateFunctionInASelectDistinct() public function testSupportsASqlKeywordInAStringLiteralParam() { $this->assertSqlGeneration( - "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name LIKE '%foo OR bar%'", - "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE c0_.name LIKE '%foo OR bar%'" + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name LIKE \'%foo OR bar%\'', + 'SELECT t0."name" AS c0 FROM "cms_users" t0 WHERE t0."name" LIKE \'%foo OR bar%\'' ); } @@ -379,7 +377,7 @@ public function testSupportsArithmeticExpressionsInWherePart() { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE ((u.id + 5000) * u.id + 3) < 10000000', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE ((c0_.id + 5000) * c0_.id + 3) < 10000000' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE ((t0."id" + 5000) * t0."id" + 3) < 10000000' ); } @@ -387,7 +385,7 @@ public function testSupportsMultipleEntitiesInFromClause() { $this->assertSqlGeneration( 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsArticle a JOIN a.user u2 WHERE u.id = u2.id', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c1_.id AS id_4, c1_.topic AS topic_5, c1_.text AS text_6, c1_.version AS version_7 FROM cms_users c0_, cms_articles c1_ INNER JOIN cms_users c2_ ON c1_.user_id = c2_.id WHERE c0_.id = c2_.id' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, t1."id" AS c4, t1."topic" AS c5, t1."text" AS c6, t1."version" AS c7 FROM "cms_users" t0, "cms_articles" t1 INNER JOIN "cms_users" t2 ON t1."user_id" = t2."id" WHERE t0."id" = t2."id"' ); } @@ -395,7 +393,7 @@ public function testSupportsMultipleEntitiesInFromClauseUsingPathExpression() { $this->assertSqlGeneration( 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsArticle a WHERE u.id = a.user', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c1_.id AS id_4, c1_.topic AS topic_5, c1_.text AS text_6, c1_.version AS version_7 FROM cms_users c0_, cms_articles c1_ WHERE c0_.id = c1_.user_id' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, t1."id" AS c4, t1."topic" AS c5, t1."text" AS c6, t1."version" AS c7 FROM "cms_users" t0, "cms_articles" t1 WHERE t0."id" = t1."user_id"' ); } @@ -403,26 +401,34 @@ public function testSupportsPlainJoinWithoutClause() { $this->assertSqlGeneration( 'SELECT u.id, a.id from Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a', - 'SELECT c0_.id AS id_0, c1_.id AS id_1 FROM cms_users c0_ LEFT JOIN cms_articles c1_ ON c0_.id = c1_.user_id' + 'SELECT t0."id" AS c0, t1."id" AS c1 FROM "cms_users" t0 LEFT JOIN "cms_articles" t1 ON t0."id" = t1."user_id"' ); + $this->assertSqlGeneration( 'SELECT u.id, a.id from Doctrine\Tests\Models\CMS\CmsUser u JOIN u.articles a', - 'SELECT c0_.id AS id_0, c1_.id AS id_1 FROM cms_users c0_ INNER JOIN cms_articles c1_ ON c0_.id = c1_.user_id' + 'SELECT t0."id" AS c0, t1."id" AS c1 FROM "cms_users" t0 INNER JOIN "cms_articles" t1 ON t0."id" = t1."user_id"' ); } /** * @group DDC-135 */ - public function testSupportsJoinAndWithClauseRestriction() + public function testSupportsLeftJoinAndWithClauseRestriction() { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a WITH a.topic LIKE '%foo%'", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ LEFT JOIN cms_articles c1_ ON c0_.id = c1_.user_id AND (c1_.topic LIKE '%foo%')" + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a WITH a.topic LIKE \'%foo%\'', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 LEFT JOIN "cms_articles" t1 ON t0."id" = t1."user_id" AND (t1."topic" LIKE \'%foo%\')' ); + } + + /** + * @group DDC-135 + */ + public function testSupportsInnerJoinAndWithClauseRestriction() + { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles a WITH a.topic LIKE '%foo%'", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ INNER JOIN cms_articles c1_ ON c0_.id = c1_.user_id AND (c1_.topic LIKE '%foo%')" + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles a WITH a.topic LIKE \'%foo%\'', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 INNER JOIN "cms_articles" t1 ON t0."id" = t1."user_id" AND (t1."topic" LIKE \'%foo%\')' ); } @@ -434,24 +440,26 @@ public function testJoinOnClause_NotYetSupported_ThrowsException() { $this->expectException(QueryException::class); - $sql = $this->_em->createQuery( - "SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a ON a.topic LIKE '%foo%'" - )->getSql(); + $query = $this->em->createQuery( + 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a ON a.topic LIKE \'%foo%\'' + ); + + $query->getSql(); } public function testSupportsMultipleJoins() { $this->assertSqlGeneration( 'SELECT u.id, a.id, p.phonenumber, c.id from Doctrine\Tests\Models\CMS\CmsUser u JOIN u.articles a JOIN u.phonenumbers p JOIN a.comments c', - 'SELECT c0_.id AS id_0, c1_.id AS id_1, c2_.phonenumber AS phonenumber_2, c3_.id AS id_3 FROM cms_users c0_ INNER JOIN cms_articles c1_ ON c0_.id = c1_.user_id INNER JOIN cms_phonenumbers c2_ ON c0_.id = c2_.user_id INNER JOIN cms_comments c3_ ON c1_.id = c3_.article_id' + 'SELECT t0."id" AS c0, t1."id" AS c1, t2."phonenumber" AS c2, t3."id" AS c3 FROM "cms_users" t0 INNER JOIN "cms_articles" t1 ON t0."id" = t1."user_id" INNER JOIN "cms_phonenumbers" t2 ON t0."id" = t2."user_id" INNER JOIN "cms_comments" t3 ON t1."id" = t3."article_id"' ); } public function testSupportsTrimFunction() { $this->assertSqlGeneration( - "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE TRIM(TRAILING ' ' FROM u.name) = 'someone'", - "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE TRIM(TRAILING ' ' FROM c0_.name) = 'someone'" + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE TRIM(TRAILING \' \' FROM u.name) = \'someone\'', + 'SELECT t0."name" AS c0 FROM "cms_users" t0 WHERE TRIM(TRAILING \' \' FROM t0."name") = \'someone\'' ); } @@ -461,8 +469,8 @@ public function testSupportsTrimFunction() public function testSupportsTrimLeadingZeroString() { $this->assertSqlGeneration( - "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE TRIM(TRAILING '0' FROM u.name) != ''", - "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE TRIM(TRAILING '0' FROM c0_.name) <> ''" + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE TRIM(TRAILING \'0\' FROM u.name) != \'\'', + 'SELECT t0."name" AS c0 FROM "cms_users" t0 WHERE TRIM(TRAILING \'0\' FROM t0."name") <> \'\'' ); } @@ -470,8 +478,8 @@ public function testSupportsTrimLeadingZeroString() public function testSupportsBetweenClauseWithPositionalParameters() { $this->assertSqlGeneration( - "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id BETWEEN ?1 AND ?2", - "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE c0_.id BETWEEN ? AND ?" + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id BETWEEN ?1 AND ?2', + 'SELECT t0."name" AS c0 FROM "cms_users" t0 WHERE t0."id" BETWEEN ? AND ?' ); } @@ -481,26 +489,26 @@ public function testSupportsBetweenClauseWithPositionalParameters() public function testSupportsNotBetweenForSizeFunction() { $this->assertSqlGeneration( - "SELECT m.name FROM Doctrine\Tests\Models\StockExchange\Market m WHERE SIZE(m.stocks) NOT BETWEEN ?1 AND ?2", - "SELECT e0_.name AS name_0 FROM exchange_markets e0_ WHERE (SELECT COUNT(*) FROM exchange_stocks e1_ WHERE e1_.market_id = e0_.id) NOT BETWEEN ? AND ?" + 'SELECT m.name FROM Doctrine\Tests\Models\StockExchange\Market m WHERE SIZE(m.stocks) NOT BETWEEN ?1 AND ?2', + 'SELECT t0."name" AS c0 FROM "exchange_markets" t0 WHERE (SELECT COUNT(*) FROM "exchange_stocks" t1 WHERE t1."market_id" = t0."id") NOT BETWEEN ? AND ?' ); } public function testSupportsFunctionalExpressionsInWherePart() { $this->assertSqlGeneration( - "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE TRIM(u.name) = 'someone'", + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE TRIM(u.name) = \'someone\'', // String quoting in the SQL usually depends on the database platform. // This test works with a mock connection which uses ' for string quoting. - "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE TRIM(c0_.name) = 'someone'" + 'SELECT t0."name" AS c0 FROM "cms_users" t0 WHERE TRIM(t0."name") = \'someone\'' ); } public function testSupportsInstanceOfExpressionsInWherePart() { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyEmployee", - "SELECT c0_.id AS id_0, c0_.name AS name_1, c0_.discr AS discr_2 FROM company_persons c0_ WHERE c0_.discr IN ('employee')" + 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyEmployee', + 'SELECT t0."id" AS c0, t0."name" AS c1, t0."discr" AS c2 FROM "company_persons" t0 WHERE t0."discr" IN (\'employee\')' ); } @@ -508,8 +516,8 @@ public function testSupportsInstanceOfExpressionInWherePartWithMultipleValues() { // This also uses FQCNs starting with or without a backslash in the INSTANCE OF parameter $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF (Doctrine\Tests\Models\Company\CompanyEmployee, \Doctrine\Tests\Models\Company\CompanyManager)", - "SELECT c0_.id AS id_0, c0_.name AS name_1, c0_.discr AS discr_2 FROM company_persons c0_ WHERE c0_.discr IN ('employee', 'manager')" + 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF (Doctrine\Tests\Models\Company\CompanyEmployee, \Doctrine\Tests\Models\Company\CompanyManager)', + 'SELECT t0."id" AS c0, t0."name" AS c1, t0."discr" AS c2 FROM "company_persons" t0 WHERE t0."discr" IN (\'employee\', \'manager\')' ); } @@ -519,8 +527,8 @@ public function testSupportsInstanceOfExpressionInWherePartWithMultipleValues() public function testSupportsInstanceOfExpressionsInWherePartPrefixedSlash() { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF \Doctrine\Tests\Models\Company\CompanyEmployee", - "SELECT c0_.id AS id_0, c0_.name AS name_1, c0_.discr AS discr_2 FROM company_persons c0_ WHERE c0_.discr IN ('employee')" + 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF \Doctrine\Tests\Models\Company\CompanyEmployee', + 'SELECT t0."id" AS c0, t0."name" AS c1, t0."discr" AS c2 FROM "company_persons" t0 WHERE t0."discr" IN (\'employee\')' ); } @@ -530,33 +538,33 @@ public function testSupportsInstanceOfExpressionsInWherePartPrefixedSlash() public function testSupportsInstanceOfExpressionsInWherePartWithUnrelatedClass() { $this->assertInvalidSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF \Doctrine\Tests\Models\CMS\CmsUser", - QueryException::class + 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF \Doctrine\Tests\Models\CMS\CmsUser', + 'Doctrine\\ORM\\Query\\QueryException' ); } public function testSupportsInstanceOfExpressionsInWherePartInDeeperLevel() { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\Company\CompanyEmployee u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyManager", - "SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c0_.discr AS discr_5 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id WHERE c0_.discr IN ('manager')" + 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyEmployee u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyManager', + 'SELECT t0."id" AS c0, t0."name" AS c1, t1."salary" AS c2, t1."department" AS c3, t1."startDate" AS c4, t0."discr" AS c5 FROM "company_employees" t1 INNER JOIN "company_persons" t0 ON t1."id" = t0."id" WHERE t0."discr" IN (\'manager\')' ); } public function testSupportsInstanceOfExpressionsInWherePartInDeepestLevel() { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\Company\CompanyManager u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyManager", - "SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c0_.discr AS discr_6 FROM company_managers c2_ INNER JOIN company_employees c1_ ON c2_.id = c1_.id INNER JOIN company_persons c0_ ON c2_.id = c0_.id WHERE c0_.discr IN ('manager')" + 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyManager u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyManager', + 'SELECT t0."id" AS c0, t0."name" AS c1, t1."salary" AS c2, t1."department" AS c3, t1."startDate" AS c4, t2."title" AS c5, t0."discr" AS c6 FROM "company_managers" t2 INNER JOIN "company_employees" t1 ON t2."id" = t1."id" INNER JOIN "company_persons" t0 ON t2."id" = t0."id" WHERE t0."discr" IN (\'manager\')' ); } public function testSupportsInstanceOfExpressionsUsingInputParameterInWherePart() { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF ?1", - "SELECT c0_.id AS id_0, c0_.name AS name_1, c0_.discr AS discr_2 FROM company_persons c0_ WHERE c0_.discr IN (?)", - [], [1 => $this->_em->getClassMetadata(CompanyEmployee::class)] + 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF ?1', + 'SELECT t0."id" AS c0, t0."name" AS c1, t0."discr" AS c2 FROM "company_persons" t0 WHERE t0."discr" IN (?)', + [], [1 => $this->em->getClassMetadata(CompanyEmployee::class)] ); } @@ -564,8 +572,8 @@ public function testSupportsInstanceOfExpressionsUsingInputParameterInWherePart( public function testSupportsSingleValuedInExpressionWithoutSpacesInWherePart() { $this->assertSqlGeneration( - "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE IDENTITY(u.email) IN(46)", - "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE c0_.email_id IN (46)" + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE IDENTITY(u.email) IN(46)', + 'SELECT t0."name" AS c0 FROM "cms_users" t0 WHERE t0."email_id" IN (46)' ); } @@ -573,7 +581,7 @@ public function testSupportsMultipleValuedInExpressionInWherePart() { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id IN (1, 2)', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE c0_.id IN (1, 2)' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE t0."id" IN (1, 2)' ); } @@ -581,7 +589,7 @@ public function testSupportsNotInExpressionInWherePart() { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE :id NOT IN (1)', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE ? NOT IN (1)' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE ? NOT IN (1)' ); } @@ -591,8 +599,8 @@ public function testSupportsNotInExpressionInWherePart() public function testSupportsNotInExpressionForModFunction() { $this->assertSqlGeneration( - "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE MOD(u.id, 5) NOT IN(1,3,4)", - "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE MOD(c0_.id, 5) NOT IN (1, 3, 4)" + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE MOD(u.id, 5) NOT IN(1,3,4)', + 'SELECT t0."name" AS c0 FROM "cms_users" t0 WHERE MOD(t0."id", 5) NOT IN (1, 3, 4)' ); } @@ -600,7 +608,7 @@ public function testInExpressionWithSingleValuedAssociationPathExpressionInWhere { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u WHERE u.avatar IN (?1, ?2)', - 'SELECT f0_.id AS id_0, f0_.username AS username_1 FROM forum_users f0_ WHERE f0_.avatar_id IN (?, ?)' + 'SELECT t0."id" AS c0, t0."username" AS c1 FROM "forum_users" t0 WHERE t0."avatar_id" IN (?, ?)' ); } @@ -608,44 +616,46 @@ public function testInvalidInExpressionWithSingleValuedAssociationPathExpression { // We do not support SingleValuedAssociationPathExpression on inverse side $this->assertInvalidSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.address IN (?1, ?2)", - QueryException::class + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.address IN (?1, ?2)', + 'Doctrine\ORM\Query\QueryException' ); } - public function testSupportsConcatFunctionForMysqlAndPostgresql() + public function testSupportsConcatFunctionMysql() { - $connMock = $this->_em->getConnection(); - $orgPlatform = $connMock->getDatabasePlatform(); + $this->em->getConnection()->setDatabasePlatform(new MySqlPlatform()); - $connMock->setDatabasePlatform(new MySqlPlatform()); $this->assertSqlGeneration( - "SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CONCAT(u.name, 's') = ?1", - "SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE CONCAT(c0_.name, 's') = ?" + 'SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CONCAT(u.name, \'s\') = ?1', + 'SELECT t0.`id` AS c0 FROM `cms_users` t0 WHERE CONCAT(t0.`name`, \'s\') = ?' ); + $this->assertSqlGeneration( - "SELECT CONCAT(u.id, u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1", - "SELECT CONCAT(c0_.id, c0_.name) AS sclr_0 FROM cms_users c0_ WHERE c0_.id = ?" + 'SELECT CONCAT(u.id, u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1', + 'SELECT CONCAT(t0.`id`, t0.`name`) AS c0 FROM `cms_users` t0 WHERE t0.`id` = ?' ); + } + + public function testSupportsConcatFunctionPgSql() + { + $this->em->getConnection()->setDatabasePlatform(new PostgreSqlPlatform()); - $connMock->setDatabasePlatform(new PostgreSqlPlatform()); $this->assertSqlGeneration( - "SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CONCAT(u.name, 's') = ?1", - "SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE c0_.name || 's' = ?" + 'SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CONCAT(u.name, \'s\') = ?1', + 'SELECT t0."id" AS c0 FROM "cms_users" t0 WHERE t0."name" || \'s\' = ?' ); + $this->assertSqlGeneration( - "SELECT CONCAT(u.id, u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1", - "SELECT c0_.id || c0_.name AS sclr_0 FROM cms_users c0_ WHERE c0_.id = ?" + 'SELECT CONCAT(u.id, u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1', + 'SELECT t0."id" || t0."name" AS c0 FROM "cms_users" t0 WHERE t0."id" = ?' ); - - $connMock->setDatabasePlatform($orgPlatform); } public function testSupportsExistsExpressionInWherePartWithCorrelatedSubquery() { $this->assertSqlGeneration( 'SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE EXISTS (SELECT p.phonenumber FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.phonenumber = u.id)', - 'SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE EXISTS (SELECT c1_.phonenumber FROM cms_phonenumbers c1_ WHERE c1_.phonenumber = c0_.id)' + 'SELECT t0."id" AS c0 FROM "cms_users" t0 WHERE EXISTS (SELECT t1."phonenumber" FROM "cms_phonenumbers" t1 WHERE t1."phonenumber" = t0."id")' ); } @@ -656,22 +666,23 @@ public function testSubqueriesInComparisonExpression() { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE (u.id >= (SELECT u2.id FROM Doctrine\Tests\Models\CMS\CmsUser u2 WHERE u2.name = :name)) AND (u.id <= (SELECT u3.id FROM Doctrine\Tests\Models\CMS\CmsUser u3 WHERE u3.name = :name))', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE (c0_.id >= (SELECT c1_.id FROM cms_users c1_ WHERE c1_.name = ?)) AND (c0_.id <= (SELECT c2_.id FROM cms_users c2_ WHERE c2_.name = ?))' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE (t0."id" >= (SELECT t1."id" FROM "cms_users" t1 WHERE t1."name" = ?)) AND (t0."id" <= (SELECT t2."id" FROM "cms_users" t2 WHERE t2."name" = ?))' ); } public function testSupportsMemberOfExpressionOneToMany() { // "Get all users who have $phone as a phonenumber." (*cough* doesnt really make sense...) - $q = $this->_em->createQuery('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE :param MEMBER OF u.phonenumbers'); + $q = $this->em->createQuery('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE :param MEMBER OF u.phonenumbers'); + $q->setHint(ORMQuery::HINT_FORCE_PARTIAL_LOAD, true); $phone = new CmsPhonenumber(); $phone->phonenumber = 101; $q->setParameter('param', $phone); - $this->assertEquals( - 'SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE EXISTS (SELECT 1 FROM cms_phonenumbers c1_ WHERE c0_.id = c1_.user_id AND c1_.phonenumber = ?)', + self::assertEquals( + 'SELECT t0."id" AS c0 FROM "cms_users" t0 WHERE EXISTS (SELECT 1 FROM "cms_phonenumbers" t1 WHERE t0."id" = t1."user_id" AND t1."phonenumber" = ?)', $q->getSql() ); } @@ -679,22 +690,23 @@ public function testSupportsMemberOfExpressionOneToMany() public function testSupportsMemberOfExpressionManyToMany() { // "Get all users who are members of $group." - $q = $this->_em->createQuery('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE :param MEMBER OF u.groups'); + $q = $this->em->createQuery('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE :param MEMBER OF u.groups'); + $q->setHint(ORMQuery::HINT_FORCE_PARTIAL_LOAD, true); $group = new CmsGroup(); $group->id = 101; $q->setParameter('param', $group); - $this->assertEquals( - 'SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE EXISTS (SELECT 1 FROM cms_users_groups c1_ INNER JOIN cms_groups c2_ ON c1_.group_id = c2_.id WHERE c1_.user_id = c0_.id AND c2_.id IN (?))', + self::assertEquals( + 'SELECT t0."id" AS c0 FROM "cms_users" t0 WHERE EXISTS (SELECT 1 FROM "cms_users_groups" t1 INNER JOIN "cms_groups" t2 ON t1."group_id" = t2."id" WHERE t1."user_id" = t0."id" AND t2."id" = ?)', $q->getSql() ); } public function testSupportsMemberOfExpressionManyToManyParameterArray() { - $q = $this->_em->createQuery('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE :param MEMBER OF u.groups'); + $q = $this->em->createQuery('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE :param MEMBER OF u.groups'); $q->setHint(ORMQuery::HINT_FORCE_PARTIAL_LOAD, true); $group = new CmsGroup(); @@ -703,8 +715,8 @@ public function testSupportsMemberOfExpressionManyToManyParameterArray() $group2->id = 105; $q->setParameter('param', [$group, $group2]); - $this->assertEquals( - 'SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE EXISTS (SELECT 1 FROM cms_users_groups c1_ INNER JOIN cms_groups c2_ ON c1_.group_id = c2_.id WHERE c1_.user_id = c0_.id AND c2_.id IN (?))', + self::assertEquals( + 'SELECT t0."id" AS c0 FROM "cms_users" t0 WHERE EXISTS (SELECT 1 FROM "cms_users_groups" t1 INNER JOIN "cms_groups" t2 ON t1."group_id" = t2."id" WHERE t1."user_id" = t0."id" AND t2."id" = ?)', $q->getSql() ); } @@ -713,12 +725,19 @@ public function testSupportsMemberOfExpressionSelfReferencing() { // "Get all persons who have $person as a friend." // Tough one: Many-many self-referencing ("friends") with class table inheritance - $q = $this->_em->createQuery('SELECT p FROM Doctrine\Tests\Models\Company\CompanyPerson p WHERE :param MEMBER OF p.friends'); + $q = $this->em->createQuery('SELECT p FROM Doctrine\Tests\Models\Company\CompanyPerson p WHERE :param MEMBER OF p.friends'); + $person = new CompanyPerson(); - $this->_em->getClassMetadata(get_class($person))->setIdentifierValues($person, ['id' => 101]); + + $unitOfWork = $this->em->getUnitOfWork(); + $persister = $unitOfWork->getEntityPersister(get_class($person)); + + $persister->setIdentifier($person, ['id' => 101]); + $q->setParameter('param', $person); - $this->assertEquals( - 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.title AS title_2, c2_.salary AS salary_3, c2_.department AS department_4, c2_.startDate AS startDate_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c1_.car_id AS car_id_8 FROM company_persons c0_ LEFT JOIN company_managers c1_ ON c0_.id = c1_.id LEFT JOIN company_employees c2_ ON c0_.id = c2_.id WHERE EXISTS (SELECT 1 FROM company_persons_friends c3_ INNER JOIN company_persons c4_ ON c3_.friend_id = c4_.id WHERE c3_.person_id = c0_.id AND c4_.id IN (?))', + + self::assertEquals( + 'SELECT t0."id" AS c0, t0."name" AS c1, t1."title" AS c2, t2."salary" AS c3, t2."department" AS c4, t2."startDate" AS c5, t0."discr" AS c6, t0."spouse_id" AS c7, t1."car_id" AS c8 FROM "company_persons" t0 LEFT JOIN "company_managers" t1 ON t0."id" = t1."id" LEFT JOIN "company_employees" t2 ON t0."id" = t2."id" WHERE EXISTS (SELECT 1 FROM "company_persons_friends" t3 INNER JOIN "company_persons" t4 ON t3."friend_id" = t4."id" WHERE t3."person_id" = t0."id" AND t4."id" = ?)', $q->getSql() ); } @@ -726,44 +745,46 @@ public function testSupportsMemberOfExpressionSelfReferencing() public function testSupportsMemberOfWithSingleValuedAssociation() { // Impossible example, but it illustrates the purpose - $q = $this->_em->createQuery('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.email MEMBER OF u.groups'); - - $this->assertEquals( - 'SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE EXISTS (SELECT 1 FROM cms_users_groups c1_ INNER JOIN cms_groups c2_ ON c1_.group_id = c2_.id WHERE c1_.user_id = c0_.id AND c2_.id IN (c0_.email_id))', - $q->getSql() + $this->assertSqlGeneration( + 'SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.email MEMBER OF u.groups', + 'SELECT t0."id" AS c0 FROM "cms_users" t0 WHERE EXISTS (SELECT 1 FROM "cms_users_groups" t1 INNER JOIN "cms_groups" t2 ON t1."group_id" = t2."id" WHERE t1."user_id" = t0."id" AND t2."id" = t0."email_id")' ); } public function testSupportsMemberOfWithIdentificationVariable() { // Impossible example, but it illustrates the purpose - $q = $this->_em->createQuery('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u MEMBER OF u.groups'); - - $this->assertEquals( - 'SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE EXISTS (SELECT 1 FROM cms_users_groups c1_ INNER JOIN cms_groups c2_ ON c1_.group_id = c2_.id WHERE c1_.user_id = c0_.id AND c2_.id IN (c0_.id))', - $q->getSql() + $this->assertSqlGeneration( + 'SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u MEMBER OF u.groups', + 'SELECT t0."id" AS c0 FROM "cms_users" t0 WHERE EXISTS (SELECT 1 FROM "cms_users_groups" t1 INNER JOIN "cms_groups" t2 ON t1."group_id" = t2."id" WHERE t1."user_id" = t0."id" AND t2."id" = t0."id")' ); } public function testSupportsCurrentDateFunction() { - $q = $this->_em->createQuery('SELECT d.id FROM Doctrine\Tests\Models\Generic\DateTimeModel d WHERE d.datetime > current_date()'); - $q->setHint(ORMQuery::HINT_FORCE_PARTIAL_LOAD, true); - $this->assertEquals('SELECT d0_.id AS id_0 FROM date_time_model d0_ WHERE d0_.col_datetime > CURRENT_DATE', $q->getSql()); + $this->assertSqlGeneration( + 'SELECT d.id FROM Doctrine\Tests\Models\Generic\DateTimeModel d WHERE d.datetime > current_date()', + 'SELECT t0."id" AS c0 FROM "date_time_model" t0 WHERE t0."col_datetime" > CURRENT_DATE', + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true] + ); } public function testSupportsCurrentTimeFunction() { - $q = $this->_em->createQuery('SELECT d.id FROM Doctrine\Tests\Models\Generic\DateTimeModel d WHERE d.time > current_time()'); - $q->setHint(ORMQuery::HINT_FORCE_PARTIAL_LOAD, true); - $this->assertEquals('SELECT d0_.id AS id_0 FROM date_time_model d0_ WHERE d0_.col_time > CURRENT_TIME', $q->getSql()); + $this->assertSqlGeneration( + 'SELECT d.id FROM Doctrine\Tests\Models\Generic\DateTimeModel d WHERE d.time > current_time()', + 'SELECT t0."id" AS c0 FROM "date_time_model" t0 WHERE t0."col_time" > CURRENT_TIME', + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true] + ); } public function testSupportsCurrentTimestampFunction() { - $q = $this->_em->createQuery('SELECT d.id FROM Doctrine\Tests\Models\Generic\DateTimeModel d WHERE d.datetime > current_timestamp()'); - $q->setHint(ORMQuery::HINT_FORCE_PARTIAL_LOAD, true); - $this->assertEquals('SELECT d0_.id AS id_0 FROM date_time_model d0_ WHERE d0_.col_datetime > CURRENT_TIMESTAMP', $q->getSql()); + $this->assertSqlGeneration( + 'SELECT d.id FROM Doctrine\Tests\Models\Generic\DateTimeModel d WHERE d.datetime > current_timestamp()', + 'SELECT t0."id" AS c0 FROM "date_time_model" t0 WHERE t0."col_datetime" > CURRENT_TIMESTAMP', + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true] + ); } public function testExistsExpressionInWhereCorrelatedSubqueryAssocCondition() @@ -777,9 +798,9 @@ public function testExistsExpressionInWhereCorrelatedSubqueryAssocCondition() FROM Doctrine\Tests\Models\CMS\CmsEmployee spouseEmp WHERE spouseEmp = emp.spouse)', // SQL - 'SELECT DISTINCT c0_.id AS id_0, c0_.name AS name_1 FROM cms_employees c0_' + 'SELECT DISTINCT t0."id" AS c0, t0."name" AS c1 FROM "cms_employees" t0' . ' WHERE EXISTS (' - . 'SELECT c1_.id FROM cms_employees c1_ WHERE c1_.id = c0_.spouse_id' + . 'SELECT t1."id" FROM "cms_employees" t1 WHERE t1."id" = t0."spouse_id"' . ')' ); } @@ -795,97 +816,103 @@ public function testExistsExpressionWithSimpleSelectReturningScalar() FROM Doctrine\Tests\Models\CMS\CmsEmployee spouseEmp WHERE spouseEmp = emp.spouse)', // SQL - 'SELECT DISTINCT c0_.id AS id_0, c0_.name AS name_1 FROM cms_employees c0_' + 'SELECT DISTINCT t0."id" AS c0, t0."name" AS c1 FROM "cms_employees" t0' . ' WHERE EXISTS (' - . 'SELECT 1 AS sclr_2 FROM cms_employees c1_ WHERE c1_.id = c0_.spouse_id' + . 'SELECT 1 AS c2 FROM "cms_employees" t1 WHERE t1."id" = t0."spouse_id"' . ')' ); } public function testLimitFromQueryClass() { - $q = $this->_em + $q = $this->em ->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u') ->setMaxResults(10); - $this->assertEquals('SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ LIMIT 10', $q->getSql()); + self::assertEquals( + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, t0."email_id" AS c4 FROM "cms_users" t0 LIMIT 10', + $q->getSql() + ); } public function testLimitAndOffsetFromQueryClass() { - $q = $this->_em + $q = $this->em ->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u') ->setMaxResults(10) ->setFirstResult(0); - $this->assertEquals('SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ LIMIT 10 OFFSET 0', $q->getSql()); + self::assertEquals( + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, t0."email_id" AS c4 FROM "cms_users" t0 LIMIT 10 OFFSET 0', + $q->getSql() + ); } public function testSizeFunction() { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE SIZE(u.phonenumbers) > 1", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE (SELECT COUNT(*) FROM cms_phonenumbers c1_ WHERE c1_.user_id = c0_.id) > 1" + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE SIZE(u.phonenumbers) > 1', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE (SELECT COUNT(*) FROM "cms_phonenumbers" t1 WHERE t1."user_id" = t0."id") > 1' ); } public function testSizeFunctionSupportsManyToMany() { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE SIZE(u.groups) > 1", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE (SELECT COUNT(*) FROM cms_users_groups c1_ WHERE c1_.user_id = c0_.id) > 1" + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE SIZE(u.groups) > 1', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE (SELECT COUNT(*) FROM "cms_users_groups" t1 WHERE t1."user_id" = t0."id") > 1' ); } public function testEmptyCollectionComparisonExpression() { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.phonenumbers IS EMPTY", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE (SELECT COUNT(*) FROM cms_phonenumbers c1_ WHERE c1_.user_id = c0_.id) = 0" + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.phonenumbers IS EMPTY', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE (SELECT COUNT(*) FROM "cms_phonenumbers" t1 WHERE t1."user_id" = t0."id") = 0' ); $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.phonenumbers IS NOT EMPTY", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE (SELECT COUNT(*) FROM cms_phonenumbers c1_ WHERE c1_.user_id = c0_.id) > 0" + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.phonenumbers IS NOT EMPTY', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE (SELECT COUNT(*) FROM "cms_phonenumbers" t1 WHERE t1."user_id" = t0."id") > 0' ); } public function testNestedExpressions() { $this->assertSqlGeneration( - "select u from Doctrine\Tests\Models\CMS\CmsUser u where u.id > 10 and u.id < 42 and ((u.id * 2) > 5)", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE c0_.id > 10 AND c0_.id < 42 AND ((c0_.id * 2) > 5)" + 'select u from Doctrine\Tests\Models\CMS\CmsUser u where u.id > 10 and u.id < 42 and ((u.id * 2) > 5)', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE t0."id" > 10 AND t0."id" < 42 AND ((t0."id" * 2) > 5)' ); } public function testNestedExpressions2() { $this->assertSqlGeneration( - "select u from Doctrine\Tests\Models\CMS\CmsUser u where (u.id > 10) and (u.id < 42 and ((u.id * 2) > 5)) or u.id <> 42", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE (c0_.id > 10) AND (c0_.id < 42 AND ((c0_.id * 2) > 5)) OR c0_.id <> 42" + 'select u from Doctrine\Tests\Models\CMS\CmsUser u where (u.id > 10) and (u.id < 42 and ((u.id * 2) > 5)) or u.id <> 42', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE (t0."id" > 10) AND (t0."id" < 42 AND ((t0."id" * 2) > 5)) OR t0."id" <> 42' ); } public function testNestedExpressions3() { $this->assertSqlGeneration( - "select u from Doctrine\Tests\Models\CMS\CmsUser u where (u.id > 10) and (u.id between 1 and 10 or u.id in (1, 2, 3, 4, 5))", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE (c0_.id > 10) AND (c0_.id BETWEEN 1 AND 10 OR c0_.id IN (1, 2, 3, 4, 5))" + 'select u from Doctrine\Tests\Models\CMS\CmsUser u where (u.id > 10) and (u.id between 1 and 10 or u.id in (1, 2, 3, 4, 5))', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE (t0."id" > 10) AND (t0."id" BETWEEN 1 AND 10 OR t0."id" IN (1, 2, 3, 4, 5))' ); } public function testOrderByCollectionAssociationSize() { $this->assertSqlGeneration( - "select u, size(u.articles) as numArticles from Doctrine\Tests\Models\CMS\CmsUser u order by numArticles", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, (SELECT COUNT(*) FROM cms_articles c1_ WHERE c1_.user_id = c0_.id) AS sclr_4 FROM cms_users c0_ ORDER BY sclr_4 ASC" + 'select u, size(u.articles) as numArticles from Doctrine\Tests\Models\CMS\CmsUser u order by numArticles', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, (SELECT COUNT(*) FROM "cms_articles" t1 WHERE t1."user_id" = t0."id") AS c4 FROM "cms_users" t0 ORDER BY c4 ASC' ); } public function testOrderBySupportsSingleValuedPathExpressionOwningSide() { $this->assertSqlGeneration( - "select a from Doctrine\Tests\Models\CMS\CmsArticle a order by a.user", - "SELECT c0_.id AS id_0, c0_.topic AS topic_1, c0_.text AS text_2, c0_.version AS version_3 FROM cms_articles c0_ ORDER BY c0_.user_id ASC" + 'select a from Doctrine\Tests\Models\CMS\CmsArticle a order by a.user', + 'SELECT t0."id" AS c0, t0."topic" AS c1, t0."text" AS c2, t0."version" AS c3 FROM "cms_articles" t0 ORDER BY t0."user_id" ASC' ); } @@ -894,70 +921,65 @@ public function testOrderBySupportsSingleValuedPathExpressionOwningSide() */ public function testOrderBySupportsSingleValuedPathExpressionInverseSide() { - $q = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u order by u.address"); + $q = $this->em->createQuery('select u from Doctrine\Tests\Models\CMS\CmsUser u order by u.address'); + $q->getSQL(); } public function testBooleanLiteralInWhereOnSqlite() { - $oldPlat = $this->_em->getConnection()->getDatabasePlatform(); - $this->_em->getConnection()->setDatabasePlatform(new SqlitePlatform()); + $this->em->getConnection()->setDatabasePlatform(new SqlitePlatform()); $this->assertSqlGeneration( - "SELECT b FROM Doctrine\Tests\Models\Generic\BooleanModel b WHERE b.booleanField = true", - "SELECT b0_.id AS id_0, b0_.booleanField AS booleanField_1 FROM boolean_model b0_ WHERE b0_.booleanField = 1" + 'SELECT b FROM Doctrine\Tests\Models\Generic\BooleanModel b WHERE b.booleanField = true', + 'SELECT t0."id" AS c0, t0."booleanField" AS c1 FROM "boolean_model" t0 WHERE t0."booleanField" = 1' ); $this->assertSqlGeneration( - "SELECT b FROM Doctrine\Tests\Models\Generic\BooleanModel b WHERE b.booleanField = false", - "SELECT b0_.id AS id_0, b0_.booleanField AS booleanField_1 FROM boolean_model b0_ WHERE b0_.booleanField = 0" + 'SELECT b FROM Doctrine\Tests\Models\Generic\BooleanModel b WHERE b.booleanField = false', + 'SELECT t0."id" AS c0, t0."booleanField" AS c1 FROM "boolean_model" t0 WHERE t0."booleanField" = 0' ); - - $this->_em->getConnection()->setDatabasePlatform($oldPlat); } public function testBooleanLiteralInWhereOnPostgres() { - $oldPlat = $this->_em->getConnection()->getDatabasePlatform(); - $this->_em->getConnection()->setDatabasePlatform(new PostgreSqlPlatform()); + $this->em->getConnection()->setDatabasePlatform(new PostgreSqlPlatform()); $this->assertSqlGeneration( - "SELECT b FROM Doctrine\Tests\Models\Generic\BooleanModel b WHERE b.booleanField = true", - "SELECT b0_.id AS id_0, b0_.booleanField AS booleanfield_1 FROM boolean_model b0_ WHERE b0_.booleanField = true" + 'SELECT b FROM Doctrine\Tests\Models\Generic\BooleanModel b WHERE b.booleanField = true', + 'SELECT t0."id" AS c0, t0."booleanField" AS c1 FROM "boolean_model" t0 WHERE t0."booleanField" = true' ); $this->assertSqlGeneration( - "SELECT b FROM Doctrine\Tests\Models\Generic\BooleanModel b WHERE b.booleanField = false", - "SELECT b0_.id AS id_0, b0_.booleanField AS booleanfield_1 FROM boolean_model b0_ WHERE b0_.booleanField = false" + 'SELECT b FROM Doctrine\Tests\Models\Generic\BooleanModel b WHERE b.booleanField = false', + 'SELECT t0."id" AS c0, t0."booleanField" AS c1 FROM "boolean_model" t0 WHERE t0."booleanField" = false' ); - - $this->_em->getConnection()->setDatabasePlatform($oldPlat); } public function testSingleValuedAssociationFieldInWhere() { $this->assertSqlGeneration( - "SELECT p FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.user = ?1", - "SELECT c0_.phonenumber AS phonenumber_0 FROM cms_phonenumbers c0_ WHERE c0_.user_id = ?" + 'SELECT p FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.user = ?1', + 'SELECT t0."phonenumber" AS c0 FROM "cms_phonenumbers" t0 WHERE t0."user_id" = ?' ); } public function testSingleValuedAssociationNullCheckOnOwningSide() { $this->assertSqlGeneration( - "SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a WHERE a.user IS NULL", - "SELECT c0_.id AS id_0, c0_.country AS country_1, c0_.zip AS zip_2, c0_.city AS city_3 FROM cms_addresses c0_ WHERE c0_.user_id IS NULL" + 'SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a WHERE a.user IS NULL', + 'SELECT t0."id" AS c0, t0."country" AS c1, t0."zip" AS c2, t0."city" AS c3 FROM "cms_addresses" t0 WHERE t0."user_id" IS NULL' ); } // Null check on inverse side has to happen through explicit JOIN. - // "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.address IS NULL" + // 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.address IS NULL' // where the CmsUser is the inverse side is not supported. public function testSingleValuedAssociationNullCheckOnInverseSide() { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.address a WHERE a.id IS NULL", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ LEFT JOIN cms_addresses c1_ ON c0_.id = c1_.user_id WHERE c1_.id IS NULL" + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.address a WHERE a.id IS NULL', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 LEFT JOIN "cms_addresses" t1 ON t0."id" = t1."user_id" WHERE t1."id" IS NULL' ); } @@ -968,30 +990,30 @@ public function testSingleValuedAssociationNullCheckOnInverseSide() public function testStringFunctionLikeExpression() { $this->assertSqlGeneration( - "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE LOWER(u.name) LIKE '%foo OR bar%'", - "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE LOWER(c0_.name) LIKE '%foo OR bar%'" + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE LOWER(u.name) LIKE \'%foo OR bar%\'', + 'SELECT t0."name" AS c0 FROM "cms_users" t0 WHERE LOWER(t0."name") LIKE \'%foo OR bar%\'' ); $this->assertSqlGeneration( - "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE LOWER(u.name) LIKE :str", - "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE LOWER(c0_.name) LIKE ?" + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE LOWER(u.name) LIKE :str', + 'SELECT t0."name" AS c0 FROM "cms_users" t0 WHERE LOWER(t0."name") LIKE ?' ); $this->assertSqlGeneration( - "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CONCAT(UPPER(u.name), '_moo') LIKE :str", - "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE UPPER(c0_.name) || '_moo' LIKE ?" + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CONCAT(UPPER(u.name), \'_moo\') LIKE :str', + 'SELECT t0."name" AS c0 FROM "cms_users" t0 WHERE UPPER(t0."name") || \'_moo\' LIKE ?' ); // DDC-1572 $this->assertSqlGeneration( - "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE UPPER(u.name) LIKE UPPER(:str)", - "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE UPPER(c0_.name) LIKE UPPER(?)" + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE UPPER(u.name) LIKE UPPER(:str)', + 'SELECT t0."name" AS c0 FROM "cms_users" t0 WHERE UPPER(t0."name") LIKE UPPER(?)' ); $this->assertSqlGeneration( - "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE UPPER(LOWER(u.name)) LIKE UPPER(LOWER(:str))", - "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE UPPER(LOWER(c0_.name)) LIKE UPPER(LOWER(?))" + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE UPPER(LOWER(u.name)) LIKE UPPER(LOWER(:str))', + 'SELECT t0."name" AS c0 FROM "cms_users" t0 WHERE UPPER(LOWER(t0."name")) LIKE UPPER(LOWER(?))' ); $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a WITH a.topic LIKE u.name", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ LEFT JOIN cms_articles c1_ ON c0_.id = c1_.user_id AND (c1_.topic LIKE c0_.name)" + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a WITH a.topic LIKE u.name', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 LEFT JOIN "cms_articles" t1 ON t0."id" = t1."user_id" AND (t1."topic" LIKE t0."name")' ); } @@ -1001,17 +1023,17 @@ public function testStringFunctionLikeExpression() public function testStringFunctionNotLikeExpression() { $this->assertSqlGeneration( - "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE LOWER(u.name) NOT LIKE '%foo OR bar%'", - "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE LOWER(c0_.name) NOT LIKE '%foo OR bar%'" + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE LOWER(u.name) NOT LIKE \'%foo OR bar%\'', + 'SELECT t0."name" AS c0 FROM "cms_users" t0 WHERE LOWER(t0."name") NOT LIKE \'%foo OR bar%\'' ); $this->assertSqlGeneration( - "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE UPPER(LOWER(u.name)) NOT LIKE UPPER(LOWER(:str))", - "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE UPPER(LOWER(c0_.name)) NOT LIKE UPPER(LOWER(?))" + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE UPPER(LOWER(u.name)) NOT LIKE UPPER(LOWER(:str))', + 'SELECT t0."name" AS c0 FROM "cms_users" t0 WHERE UPPER(LOWER(t0."name")) NOT LIKE UPPER(LOWER(?))' ); $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a WITH a.topic NOT LIKE u.name", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ LEFT JOIN cms_articles c1_ ON c0_.id = c1_.user_id AND (c1_.topic NOT LIKE c0_.name)" + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a WITH a.topic NOT LIKE u.name', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 LEFT JOIN "cms_articles" t1 ON t0."id" = t1."user_id" AND (t1."topic" NOT LIKE t0."name")' ); } @@ -1021,17 +1043,16 @@ public function testStringFunctionNotLikeExpression() public function testOrderedCollectionFetchJoined() { $this->assertSqlGeneration( - "SELECT r, l FROM Doctrine\Tests\Models\Routing\RoutingRoute r JOIN r.legs l", - "SELECT r0_.id AS id_0, r1_.id AS id_1, r1_.departureDate AS departureDate_2, r1_.arrivalDate AS arrivalDate_3 FROM RoutingRoute r0_ INNER JOIN RoutingRouteLegs r2_ ON r0_.id = r2_.route_id INNER JOIN RoutingLeg r1_ ON r1_.id = r2_.leg_id ". - "ORDER BY r1_.departureDate ASC" + 'SELECT r, l FROM Doctrine\Tests\Models\Routing\RoutingRoute r JOIN r.legs l', + 'SELECT t0."id" AS c0, t1."id" AS c1, t1."departureDate" AS c2, t1."arrivalDate" AS c3 FROM "RoutingRoute" t0 INNER JOIN "RoutingRouteLegs" t2 ON t0."id" = t2."route_id" INNER JOIN "RoutingLeg" t1 ON t1."id" = t2."leg_id" ORDER BY t1."departureDate" ASC' ); } public function testSubselectInSelect() { $this->assertSqlGeneration( - "SELECT u.name, (SELECT COUNT(p.phonenumber) FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.phonenumber = 1234) pcount FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = 'jon'", - "SELECT c0_.name AS name_0, (SELECT COUNT(c1_.phonenumber) AS sclr_2 FROM cms_phonenumbers c1_ WHERE c1_.phonenumber = 1234) AS sclr_1 FROM cms_users c0_ WHERE c0_.name = 'jon'" + 'SELECT u.name, (SELECT COUNT(p.phonenumber) FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.phonenumber = 1234) pcount FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = \'jon\'', + 'SELECT t0."name" AS c0, (SELECT COUNT(t1."phonenumber") AS c2 FROM "cms_phonenumbers" t1 WHERE t1."phonenumber" = 1234) AS c1 FROM "cms_users" t0 WHERE t0."name" = \'jon\'' ); } @@ -1041,14 +1062,13 @@ public function testSubselectInSelect() */ public function testPessimisticWriteLockQueryHint() { - if ($this->_em->getConnection()->getDatabasePlatform() instanceof SqlitePlatform) { + if ($this->em->getConnection()->getDatabasePlatform() instanceof SqlitePlatform) { $this->markTestSkipped('SqLite does not support Row locking at all.'); } $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'gblanco'", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 ". - "FROM cms_users c0_ WHERE c0_.username = 'gblanco' FOR UPDATE", + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = \'gblanco\'', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE t0."username" = \'gblanco\' FOR UPDATE', [ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_WRITE] ); } @@ -1059,12 +1079,11 @@ public function testPessimisticWriteLockQueryHint() */ public function testPessimisticReadLockQueryHintPostgreSql() { - $this->_em->getConnection()->setDatabasePlatform(new PostgreSqlPlatform()); + $this->em->getConnection()->setDatabasePlatform(new PostgreSqlPlatform()); $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'gblanco'", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 ". - "FROM cms_users c0_ WHERE c0_.username = 'gblanco' FOR SHARE", + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = \'gblanco\'', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE t0."username" = \'gblanco\' FOR SHARE', [ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_READ] ); } @@ -1076,9 +1095,8 @@ public function testPessimisticReadLockQueryHintPostgreSql() public function testLockModeNoneQueryHint() { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'gblanco'", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 ". - "FROM cms_users c0_ WHERE c0_.username = 'gblanco'", + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = \'gblanco\'', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE t0."username" = \'gblanco\'', [ORMQuery::HINT_LOCK_MODE => LockMode::NONE] ); } @@ -1089,8 +1107,8 @@ public function testLockModeNoneQueryHint() public function testSupportSelectWithMoreThan10InputParameters() { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1 OR u.id = ?2 OR u.id = ?3 OR u.id = ?4 OR u.id = ?5 OR u.id = ?6 OR u.id = ?7 OR u.id = ?8 OR u.id = ?9 OR u.id = ?10 OR u.id = ?11", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE c0_.id = ? OR c0_.id = ? OR c0_.id = ? OR c0_.id = ? OR c0_.id = ? OR c0_.id = ? OR c0_.id = ? OR c0_.id = ? OR c0_.id = ? OR c0_.id = ? OR c0_.id = ?" + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1 OR u.id = ?2 OR u.id = ?3 OR u.id = ?4 OR u.id = ?5 OR u.id = ?6 OR u.id = ?7 OR u.id = ?8 OR u.id = ?9 OR u.id = ?10 OR u.id = ?11', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE t0."id" = ? OR t0."id" = ? OR t0."id" = ? OR t0."id" = ? OR t0."id" = ? OR t0."id" = ? OR t0."id" = ? OR t0."id" = ? OR t0."id" = ? OR t0."id" = ? OR t0."id" = ?' ); } @@ -1100,12 +1118,11 @@ public function testSupportSelectWithMoreThan10InputParameters() */ public function testPessimisticReadLockQueryHintMySql() { - $this->_em->getConnection()->setDatabasePlatform(new MySqlPlatform()); + $this->em->getConnection()->setDatabasePlatform(new MySqlPlatform()); $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'gblanco'", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 ". - "FROM cms_users c0_ WHERE c0_.username = 'gblanco' LOCK IN SHARE MODE", + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = \'gblanco\'', + 'SELECT t0.`id` AS c0, t0.`status` AS c1, t0.`username` AS c2, t0.`name` AS c3 FROM `cms_users` t0 WHERE t0.`username` = \'gblanco\' LOCK IN SHARE MODE', [ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_READ] ); } @@ -1116,12 +1133,11 @@ public function testPessimisticReadLockQueryHintMySql() */ public function testPessimisticReadLockQueryHintOracle() { - $this->_em->getConnection()->setDatabasePlatform(new OraclePlatform()); + $this->em->getConnection()->setDatabasePlatform(new OraclePlatform()); $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'gblanco'", - "SELECT c0_.id AS ID_0, c0_.status AS STATUS_1, c0_.username AS USERNAME_2, c0_.name AS NAME_3 ". - "FROM cms_users c0_ WHERE c0_.username = 'gblanco' FOR UPDATE", + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = \'gblanco\'', + 'SELECT t0."id" AS C0, t0."status" AS C1, t0."username" AS C2, t0."name" AS C3 FROM "cms_users" t0 WHERE t0."username" = \'gblanco\' FOR UPDATE', [ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_READ] ); } @@ -1131,12 +1147,12 @@ public function testPessimisticReadLockQueryHintOracle() */ public function testSupportToCustomDQLFunctions() { - $config = $this->_em->getConfiguration(); + $config = $this->em->getConfiguration(); $config->addCustomNumericFunction('MYABS', MyAbsFunction::class); $this->assertSqlGeneration( 'SELECT MYABS(p.phonenumber) FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p', - 'SELECT ABS(c0_.phonenumber) AS sclr_0 FROM cms_phonenumbers c0_' + 'SELECT ABS(t0."phonenumber") AS c0 FROM "cms_phonenumbers" t0' ); $config->setCustomNumericFunctions([]); @@ -1149,7 +1165,7 @@ public function testMappedSuperclassAssociationJoin() { $this->assertSqlGeneration( 'SELECT f FROM Doctrine\Tests\Models\DirectoryTree\File f JOIN f.parentDirectory d WHERE f.id = ?1', - 'SELECT f0_.id AS id_0, f0_.extension AS extension_1, f0_.name AS name_2 FROM "file" f0_ INNER JOIN Directory d1_ ON f0_.parentDirectory_id = d1_.id WHERE f0_.id = ?' + 'SELECT t0."id" AS c0, t0."name" AS c1, t0."extension" AS c2 FROM "file" t0 INNER JOIN "Directory" t1 ON t0."parentDirectory_id" = t1."id" WHERE t0."id" = ?' ); } @@ -1160,7 +1176,7 @@ public function testGroupBy() { $this->assertSqlGeneration( 'SELECT g.id, count(u.id) FROM Doctrine\Tests\Models\CMS\CmsGroup g JOIN g.users u GROUP BY g.id', - 'SELECT c0_.id AS id_0, count(c1_.id) AS sclr_1 FROM cms_groups c0_ INNER JOIN cms_users_groups c2_ ON c0_.id = c2_.group_id INNER JOIN cms_users c1_ ON c1_.id = c2_.user_id GROUP BY c0_.id' + 'SELECT t0."id" AS c0, count(t1."id") AS c1 FROM "cms_groups" t0 INNER JOIN "cms_users_groups" t2 ON t0."id" = t2."group_id" INNER JOIN "cms_users" t1 ON t1."id" = t2."user_id" GROUP BY t0."id"' ); } @@ -1171,23 +1187,23 @@ public function testGroupByIdentificationVariable() { $this->assertSqlGeneration( 'SELECT g, count(u.id) FROM Doctrine\Tests\Models\CMS\CmsGroup g JOIN g.users u GROUP BY g', - 'SELECT c0_.id AS id_0, c0_.name AS name_1, count(c1_.id) AS sclr_2 FROM cms_groups c0_ INNER JOIN cms_users_groups c2_ ON c0_.id = c2_.group_id INNER JOIN cms_users c1_ ON c1_.id = c2_.user_id GROUP BY c0_.id, c0_.name' + 'SELECT t0."id" AS c0, t0."name" AS c1, count(t1."id") AS c2 FROM "cms_groups" t0 INNER JOIN "cms_users_groups" t2 ON t0."id" = t2."group_id" INNER JOIN "cms_users" t1 ON t1."id" = t2."user_id" GROUP BY t0."id", t0."name"' ); } public function testCaseContainingNullIf() { $this->assertSqlGeneration( - "SELECT NULLIF(g.id, g.name) AS NullIfEqual FROM Doctrine\Tests\Models\CMS\CmsGroup g", - 'SELECT NULLIF(c0_.id, c0_.name) AS sclr_0 FROM cms_groups c0_' + 'SELECT NULLIF(g.id, g.name) AS NullIfEqual FROM Doctrine\Tests\Models\CMS\CmsGroup g', + 'SELECT NULLIF(t0."id", t0."name") AS c0 FROM "cms_groups" t0' ); } public function testCaseContainingCoalesce() { $this->assertSqlGeneration( - "SELECT COALESCE(NULLIF(u.name, ''), u.username) as Display FROM Doctrine\Tests\Models\CMS\CmsUser u", - "SELECT COALESCE(NULLIF(c0_.name, ''), c0_.username) AS sclr_0 FROM cms_users c0_" + 'SELECT COALESCE(NULLIF(u.name, \'\'), u.username) as Display FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT COALESCE(NULLIF(t0."name", \'\'), t0."username") AS c0 FROM "cms_users" t0' ); } @@ -1197,16 +1213,17 @@ public function testCaseContainingCoalesce() public function testSubSelectDiscriminator() { $this->assertSqlGeneration( - "SELECT u.name, (SELECT COUNT(cfc.id) total FROM Doctrine\Tests\Models\Company\CompanyFixContract cfc) as cfc_count FROM Doctrine\Tests\Models\CMS\CmsUser u", - "SELECT c0_.name AS name_0, (SELECT COUNT(c1_.id) AS sclr_2 FROM company_contracts c1_ WHERE c1_.discr IN ('fix')) AS sclr_1 FROM cms_users c0_" + 'SELECT u.name, (SELECT COUNT(cfc.id) total FROM Doctrine\Tests\Models\Company\CompanyFixContract cfc) as cfc_count FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT t0."name" AS c0, (SELECT COUNT(t1."id") AS c2 FROM "company_contracts" t1 WHERE t1."discr" IN (\'fix\')) AS c1 FROM "cms_users" t0' ); } public function testIdVariableResultVariableReuse() { $exceptionThrown = false; + try { - $query = $this->_em->createQuery("SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IN (SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u)"); + $query = $this->em->createQuery('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IN (SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u)'); $query->getSql(); $query->free(); @@ -1214,31 +1231,31 @@ public function testIdVariableResultVariableReuse() $exceptionThrown = true; } - $this->assertTrue($exceptionThrown); + self::assertTrue($exceptionThrown); } public function testSubSelectAliasesFromOuterQuery() { $this->assertSqlGeneration( - "SELECT uo, (SELECT ui.name FROM Doctrine\Tests\Models\CMS\CmsUser ui WHERE ui.id = uo.id) AS bar FROM Doctrine\Tests\Models\CMS\CmsUser uo", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, (SELECT c1_.name FROM cms_users c1_ WHERE c1_.id = c0_.id) AS sclr_4 FROM cms_users c0_" + 'SELECT uo, (SELECT ui.name FROM Doctrine\Tests\Models\CMS\CmsUser ui WHERE ui.id = uo.id) AS bar FROM Doctrine\Tests\Models\CMS\CmsUser uo', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, (SELECT t1."name" FROM "cms_users" t1 WHERE t1."id" = t0."id") AS c4 FROM "cms_users" t0' ); } public function testSubSelectAliasesFromOuterQueryWithSubquery() { $this->assertSqlGeneration( - "SELECT uo, (SELECT ui.name FROM Doctrine\Tests\Models\CMS\CmsUser ui WHERE ui.id = uo.id AND ui.name IN (SELECT uii.name FROM Doctrine\Tests\Models\CMS\CmsUser uii)) AS bar FROM Doctrine\Tests\Models\CMS\CmsUser uo", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, (SELECT c1_.name FROM cms_users c1_ WHERE c1_.id = c0_.id AND c1_.name IN (SELECT c2_.name FROM cms_users c2_)) AS sclr_4 FROM cms_users c0_" + 'SELECT uo, (SELECT ui.name FROM Doctrine\Tests\Models\CMS\CmsUser ui WHERE ui.id = uo.id AND ui.name IN (SELECT uii.name FROM Doctrine\Tests\Models\CMS\CmsUser uii)) AS bar FROM Doctrine\Tests\Models\CMS\CmsUser uo', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, (SELECT t1."name" FROM "cms_users" t1 WHERE t1."id" = t0."id" AND t1."name" IN (SELECT t2."name" FROM "cms_users" t2)) AS c4 FROM "cms_users" t0' ); } public function testSubSelectAliasesFromOuterQueryReuseInWhereClause() { $this->assertSqlGeneration( - "SELECT uo, (SELECT ui.name FROM Doctrine\Tests\Models\CMS\CmsUser ui WHERE ui.id = uo.id) AS bar FROM Doctrine\Tests\Models\CMS\CmsUser uo WHERE bar = ?0", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, (SELECT c1_.name FROM cms_users c1_ WHERE c1_.id = c0_.id) AS sclr_4 FROM cms_users c0_ WHERE sclr_4 = ?" + 'SELECT uo, (SELECT ui.name FROM Doctrine\Tests\Models\CMS\CmsUser ui WHERE ui.id = uo.id) AS bar FROM Doctrine\Tests\Models\CMS\CmsUser uo WHERE bar = ?0', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, (SELECT t1."name" FROM "cms_users" t1 WHERE t1."id" = t0."id") AS c4 FROM "cms_users" t0 WHERE c4 = ?' ); } @@ -1248,72 +1265,72 @@ public function testSubSelectAliasesFromOuterQueryReuseInWhereClause() public function testSelectForeignKeyPKWithoutFields() { $this->assertSqlGeneration( - "SELECT t, s, l FROM Doctrine\Tests\Models\DDC117\DDC117Link l INNER JOIN l.target t INNER JOIN l.source s", - "SELECT d0_.article_id AS article_id_0, d0_.title AS title_1, d1_.article_id AS article_id_2, d1_.title AS title_3, d2_.source_id AS source_id_4, d2_.target_id AS target_id_5 FROM DDC117Link d2_ INNER JOIN DDC117Article d0_ ON d2_.target_id = d0_.article_id INNER JOIN DDC117Article d1_ ON d2_.source_id = d1_.article_id" + 'SELECT t, s, l FROM Doctrine\Tests\Models\DDC117\DDC117Link l INNER JOIN l.target t INNER JOIN l.source s', + 'SELECT t0."article_id" AS c0, t0."title" AS c1, t1."article_id" AS c2, t1."title" AS c3, t2."source_id" AS c4, t2."target_id" AS c5 FROM "DDC117Link" t2 INNER JOIN "DDC117Article" t0 ON t2."target_id" = t0."article_id" INNER JOIN "DDC117Article" t1 ON t2."source_id" = t1."article_id"' ); } public function testGeneralCaseWithSingleWhenClause() { $this->assertSqlGeneration( - "SELECT g.id, CASE WHEN ((g.id / 2) > 18) THEN 1 ELSE 0 END AS test FROM Doctrine\Tests\Models\CMS\CmsGroup g", - "SELECT c0_.id AS id_0, CASE WHEN ((c0_.id / 2) > 18) THEN 1 ELSE 0 END AS sclr_1 FROM cms_groups c0_" + 'SELECT g.id, CASE WHEN ((g.id / 2) > 18) THEN 1 ELSE 0 END AS test FROM Doctrine\Tests\Models\CMS\CmsGroup g', + 'SELECT t0."id" AS c0, CASE WHEN ((t0."id" / 2) > 18) THEN 1 ELSE 0 END AS c1 FROM "cms_groups" t0' ); } public function testGeneralCaseWithMultipleWhenClause() { $this->assertSqlGeneration( - "SELECT g.id, CASE WHEN (g.id / 2 < 10) THEN 2 WHEN ((g.id / 2) > 20) THEN 1 ELSE 0 END AS test FROM Doctrine\Tests\Models\CMS\CmsGroup g", - "SELECT c0_.id AS id_0, CASE WHEN (c0_.id / 2 < 10) THEN 2 WHEN ((c0_.id / 2) > 20) THEN 1 ELSE 0 END AS sclr_1 FROM cms_groups c0_" + 'SELECT g.id, CASE WHEN (g.id / 2 < 10) THEN 2 WHEN ((g.id / 2) > 20) THEN 1 ELSE 0 END AS test FROM Doctrine\Tests\Models\CMS\CmsGroup g', + 'SELECT t0."id" AS c0, CASE WHEN (t0."id" / 2 < 10) THEN 2 WHEN ((t0."id" / 2) > 20) THEN 1 ELSE 0 END AS c1 FROM "cms_groups" t0' ); } public function testSimpleCaseWithSingleWhenClause() { $this->assertSqlGeneration( - "SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id = CASE g.name WHEN 'admin' THEN 1 ELSE 2 END", - "SELECT c0_.id AS id_0, c0_.name AS name_1 FROM cms_groups c0_ WHERE c0_.id = CASE c0_.name WHEN 'admin' THEN 1 ELSE 2 END" + 'SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id = CASE g.name WHEN \'admin\' THEN 1 ELSE 2 END', + 'SELECT t0."id" AS c0, t0."name" AS c1 FROM "cms_groups" t0 WHERE t0."id" = CASE t0."name" WHEN \'admin\' THEN 1 ELSE 2 END' ); } public function testSimpleCaseWithMultipleWhenClause() { $this->assertSqlGeneration( - "SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id = (CASE g.name WHEN 'admin' THEN 1 WHEN 'moderator' THEN 2 ELSE 3 END)", - "SELECT c0_.id AS id_0, c0_.name AS name_1 FROM cms_groups c0_ WHERE c0_.id = (CASE c0_.name WHEN 'admin' THEN 1 WHEN 'moderator' THEN 2 ELSE 3 END)" + 'SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id = (CASE g.name WHEN \'admin\' THEN 1 WHEN \'moderator\' THEN 2 ELSE 3 END)', + 'SELECT t0."id" AS c0, t0."name" AS c1 FROM "cms_groups" t0 WHERE t0."id" = (CASE t0."name" WHEN \'admin\' THEN 1 WHEN \'moderator\' THEN 2 ELSE 3 END)' ); } public function testGeneralCaseWithSingleWhenClauseInSubselect() { $this->assertSqlGeneration( - "SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id IN (SELECT CASE WHEN ((g2.id / 2) > 18) THEN 2 ELSE 1 END FROM Doctrine\Tests\Models\CMS\CmsGroup g2)", - "SELECT c0_.id AS id_0, c0_.name AS name_1 FROM cms_groups c0_ WHERE c0_.id IN (SELECT CASE WHEN ((c1_.id / 2) > 18) THEN 2 ELSE 1 END AS sclr_2 FROM cms_groups c1_)" + 'SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id IN (SELECT CASE WHEN ((g2.id / 2) > 18) THEN 2 ELSE 1 END FROM Doctrine\Tests\Models\CMS\CmsGroup g2)', + 'SELECT t0."id" AS c0, t0."name" AS c1 FROM "cms_groups" t0 WHERE t0."id" IN (SELECT CASE WHEN ((t1."id" / 2) > 18) THEN 2 ELSE 1 END AS c2 FROM "cms_groups" t1)' ); } public function testGeneralCaseWithMultipleWhenClauseInSubselect() { $this->assertSqlGeneration( - "SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id IN (SELECT CASE WHEN (g.id / 2 < 10) THEN 3 WHEN ((g.id / 2) > 20) THEN 2 ELSE 1 END FROM Doctrine\Tests\Models\CMS\CmsGroup g2)", - "SELECT c0_.id AS id_0, c0_.name AS name_1 FROM cms_groups c0_ WHERE c0_.id IN (SELECT CASE WHEN (c0_.id / 2 < 10) THEN 3 WHEN ((c0_.id / 2) > 20) THEN 2 ELSE 1 END AS sclr_2 FROM cms_groups c1_)" + 'SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id IN (SELECT CASE WHEN (g.id / 2 < 10) THEN 3 WHEN ((g.id / 2) > 20) THEN 2 ELSE 1 END FROM Doctrine\Tests\Models\CMS\CmsGroup g2)', + 'SELECT t0."id" AS c0, t0."name" AS c1 FROM "cms_groups" t0 WHERE t0."id" IN (SELECT CASE WHEN (t0."id" / 2 < 10) THEN 3 WHEN ((t0."id" / 2) > 20) THEN 2 ELSE 1 END AS c2 FROM "cms_groups" t1)' ); } public function testSimpleCaseWithSingleWhenClauseInSubselect() { $this->assertSqlGeneration( - "SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id IN (SELECT CASE g2.name WHEN 'admin' THEN 1 ELSE 2 END FROM Doctrine\Tests\Models\CMS\CmsGroup g2)", - "SELECT c0_.id AS id_0, c0_.name AS name_1 FROM cms_groups c0_ WHERE c0_.id IN (SELECT CASE c1_.name WHEN 'admin' THEN 1 ELSE 2 END AS sclr_2 FROM cms_groups c1_)" + 'SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id IN (SELECT CASE g2.name WHEN \'admin\' THEN 1 ELSE 2 END FROM Doctrine\Tests\Models\CMS\CmsGroup g2)', + 'SELECT t0."id" AS c0, t0."name" AS c1 FROM "cms_groups" t0 WHERE t0."id" IN (SELECT CASE t1."name" WHEN \'admin\' THEN 1 ELSE 2 END AS c2 FROM "cms_groups" t1)' ); } public function testSimpleCaseWithMultipleWhenClauseInSubselect() { $this->assertSqlGeneration( - "SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id IN (SELECT CASE g2.name WHEN 'admin' THEN 1 WHEN 'moderator' THEN 2 ELSE 3 END FROM Doctrine\Tests\Models\CMS\CmsGroup g2)", - "SELECT c0_.id AS id_0, c0_.name AS name_1 FROM cms_groups c0_ WHERE c0_.id IN (SELECT CASE c1_.name WHEN 'admin' THEN 1 WHEN 'moderator' THEN 2 ELSE 3 END AS sclr_2 FROM cms_groups c1_)" + 'SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id IN (SELECT CASE g2.name WHEN \'admin\' THEN 1 WHEN \'moderator\' THEN 2 ELSE 3 END FROM Doctrine\Tests\Models\CMS\CmsGroup g2)', + 'SELECT t0."id" AS c0, t0."name" AS c1 FROM "cms_groups" t0 WHERE t0."id" IN (SELECT CASE t1."name" WHEN \'admin\' THEN 1 WHEN \'moderator\' THEN 2 ELSE 3 END AS c2 FROM "cms_groups" t1)' ); } @@ -1323,8 +1340,8 @@ public function testSimpleCaseWithMultipleWhenClauseInSubselect() public function testSimpleCaseWithStringPrimary() { $this->assertSqlGeneration( - "SELECT g.id, CASE WHEN ((g.id / 2) > 18) THEN 'Foo' ELSE 'Bar' END AS test FROM Doctrine\Tests\Models\CMS\CmsGroup g", - "SELECT c0_.id AS id_0, CASE WHEN ((c0_.id / 2) > 18) THEN 'Foo' ELSE 'Bar' END AS sclr_1 FROM cms_groups c0_" + 'SELECT g.id, CASE WHEN ((g.id / 2) > 18) THEN \'Foo\' ELSE \'Bar\' END AS test FROM Doctrine\Tests\Models\CMS\CmsGroup g', + 'SELECT t0."id" AS c0, CASE WHEN ((t0."id" / 2) > 18) THEN \'Foo\' ELSE \'Bar\' END AS c1 FROM "cms_groups" t0' ); } @@ -1334,50 +1351,50 @@ public function testSimpleCaseWithStringPrimary() public function testCaseNegativeValuesInThenExpression() { $this->assertSqlGeneration( - "SELECT CASE g.name WHEN 'admin' THEN - 1 ELSE - 2 END FROM Doctrine\Tests\Models\CMS\CmsGroup g", - "SELECT CASE c0_.name WHEN 'admin' THEN -1 ELSE -2 END AS sclr_0 FROM cms_groups c0_" + 'SELECT CASE g.name WHEN \'admin\' THEN - 1 ELSE - 2 END FROM Doctrine\Tests\Models\CMS\CmsGroup g', + 'SELECT CASE t0."name" WHEN \'admin\' THEN -1 ELSE -2 END AS c0 FROM "cms_groups" t0' ); $this->assertSqlGeneration( - "SELECT CASE g.name WHEN 'admin' THEN - 2 WHEN 'guest' THEN - 1 ELSE 0 END FROM Doctrine\Tests\Models\CMS\CmsGroup g", - "SELECT CASE c0_.name WHEN 'admin' THEN -2 WHEN 'guest' THEN -1 ELSE 0 END AS sclr_0 FROM cms_groups c0_" + 'SELECT CASE g.name WHEN \'admin\' THEN - 2 WHEN \'guest\' THEN - 1 ELSE 0 END FROM Doctrine\Tests\Models\CMS\CmsGroup g', + 'SELECT CASE t0."name" WHEN \'admin\' THEN -2 WHEN \'guest\' THEN -1 ELSE 0 END AS c0 FROM "cms_groups" t0' ); $this->assertSqlGeneration( - "SELECT CASE g.name WHEN 'admin' THEN (- 1) ELSE (- 2) END FROM Doctrine\Tests\Models\CMS\CmsGroup g", - "SELECT CASE c0_.name WHEN 'admin' THEN (-1) ELSE (-2) END AS sclr_0 FROM cms_groups c0_" + 'SELECT CASE g.name WHEN \'admin\' THEN (- 1) ELSE (- 2) END FROM Doctrine\Tests\Models\CMS\CmsGroup g', + 'SELECT CASE t0."name" WHEN \'admin\' THEN (-1) ELSE (-2) END AS c0 FROM "cms_groups" t0' ); $this->assertSqlGeneration( - "SELECT CASE g.name WHEN 'admin' THEN ( - :value) ELSE ( + :value) END FROM Doctrine\Tests\Models\CMS\CmsGroup g", - "SELECT CASE c0_.name WHEN 'admin' THEN (-?) ELSE (+?) END AS sclr_0 FROM cms_groups c0_" + 'SELECT CASE g.name WHEN \'admin\' THEN ( - :value) ELSE ( + :value) END FROM Doctrine\Tests\Models\CMS\CmsGroup g', + 'SELECT CASE t0."name" WHEN \'admin\' THEN (-?) ELSE (+?) END AS c0 FROM "cms_groups" t0' ); $this->assertSqlGeneration( - "SELECT CASE g.name WHEN 'admin' THEN ( - g.id) ELSE ( + g.id) END FROM Doctrine\Tests\Models\CMS\CmsGroup g", - "SELECT CASE c0_.name WHEN 'admin' THEN (-c0_.id) ELSE (+c0_.id) END AS sclr_0 FROM cms_groups c0_" + 'SELECT CASE g.name WHEN \'admin\' THEN ( - g.id) ELSE ( + g.id) END FROM Doctrine\Tests\Models\CMS\CmsGroup g', + 'SELECT CASE t0."name" WHEN \'admin\' THEN (-t0."id") ELSE (+t0."id") END AS c0 FROM "cms_groups" t0' ); } public function testIdentityFunctionWithCompositePrimaryKey() { $this->assertSqlGeneration( - "SELECT IDENTITY(p.poi, 'long') AS long FROM Doctrine\Tests\Models\Navigation\NavPhotos p", - "SELECT n0_.poi_long AS sclr_0 FROM navigation_photos n0_" + 'SELECT IDENTITY(p.poi, \'long\') AS long FROM Doctrine\Tests\Models\Navigation\NavPhotos p', + 'SELECT t0."poi_long" AS c0 FROM "navigation_photos" t0' ); $this->assertSqlGeneration( - "SELECT IDENTITY(p.poi, 'lat') AS lat FROM Doctrine\Tests\Models\Navigation\NavPhotos p", - "SELECT n0_.poi_lat AS sclr_0 FROM navigation_photos n0_" + 'SELECT IDENTITY(p.poi, \'lat\') AS lat FROM Doctrine\Tests\Models\Navigation\NavPhotos p', + 'SELECT t0."poi_lat" AS c0 FROM "navigation_photos" t0' ); $this->assertSqlGeneration( - "SELECT IDENTITY(p.poi, 'long') AS long, IDENTITY(p.poi, 'lat') AS lat FROM Doctrine\Tests\Models\Navigation\NavPhotos p", - "SELECT n0_.poi_long AS sclr_0, n0_.poi_lat AS sclr_1 FROM navigation_photos n0_" + 'SELECT IDENTITY(p.poi, \'long\') AS long, IDENTITY(p.poi, \'lat\') AS lat FROM Doctrine\Tests\Models\Navigation\NavPhotos p', + 'SELECT t0."poi_long" AS c0, t0."poi_lat" AS c1 FROM "navigation_photos" t0' ); $this->assertInvalidSqlGeneration( - "SELECT IDENTITY(p.poi, 'invalid') AS invalid FROM Doctrine\Tests\Models\Navigation\NavPhotos p", + 'SELECT IDENTITY(p.poi, \'invalid\') AS invalid FROM Doctrine\Tests\Models\Navigation\NavPhotos p', QueryException::class ); } @@ -1388,13 +1405,13 @@ public function testIdentityFunctionWithCompositePrimaryKey() public function testPartialWithAssociationIdentifier() { $this->assertSqlGeneration( - "SELECT PARTIAL l.{_source, _target} FROM Doctrine\Tests\Models\Legacy\LegacyUserReference l", - 'SELECT l0_.iUserIdSource AS iUserIdSource_0, l0_.iUserIdTarget AS iUserIdTarget_1 FROM legacy_users_reference l0_' + 'SELECT PARTIAL l.{source, target} FROM Doctrine\Tests\Models\Legacy\LegacyUserReference l', + 'SELECT t0."iUserIdSource" AS c0, t0."iUserIdTarget" AS c1 FROM "legacy_users_reference" t0' ); $this->assertSqlGeneration( - "SELECT PARTIAL l.{_description, _source, _target} FROM Doctrine\Tests\Models\Legacy\LegacyUserReference l", - 'SELECT l0_.description AS description_0, l0_.iUserIdSource AS iUserIdSource_1, l0_.iUserIdTarget AS iUserIdTarget_2 FROM legacy_users_reference l0_' + 'SELECT PARTIAL l.{description, source, target} FROM Doctrine\Tests\Models\Legacy\LegacyUserReference l', + 'SELECT t0."description" AS c0, t0."iUserIdSource" AS c1, t0."iUserIdTarget" AS c2 FROM "legacy_users_reference" t0' ); } @@ -1404,8 +1421,8 @@ public function testPartialWithAssociationIdentifier() public function testIdentityFunctionInSelectClause() { $this->assertSqlGeneration( - "SELECT IDENTITY(u.email) as email_id FROM Doctrine\Tests\Models\CMS\CmsUser u", - "SELECT c0_.email_id AS sclr_0 FROM cms_users c0_" + 'SELECT IDENTITY(u.email) as email_id FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT t0."email_id" AS c0 FROM "cms_users" t0' ); } @@ -1414,13 +1431,13 @@ public function testIdentityFunctionInJoinedSubclass() //relation is in the subclass (CompanyManager) we are querying $this->assertSqlGeneration( 'SELECT m, IDENTITY(m.car) as car_id FROM Doctrine\Tests\Models\Company\CompanyManager m', - 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c2_.car_id AS sclr_6, c0_.discr AS discr_7 FROM company_managers c2_ INNER JOIN company_employees c1_ ON c2_.id = c1_.id INNER JOIN company_persons c0_ ON c2_.id = c0_.id' + 'SELECT t0."id" AS c0, t0."name" AS c1, t1."salary" AS c2, t1."department" AS c3, t1."startDate" AS c4, t2."title" AS c5, t2."car_id" AS c6, t0."discr" AS c7 FROM "company_managers" t2 INNER JOIN "company_employees" t1 ON t2."id" = t1."id" INNER JOIN "company_persons" t0 ON t2."id" = t0."id"' ); //relation is in the base class (CompanyPerson). $this->assertSqlGeneration( 'SELECT m, IDENTITY(m.spouse) as spouse_id FROM Doctrine\Tests\Models\Company\CompanyManager m', - 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c0_.spouse_id AS sclr_6, c0_.discr AS discr_7 FROM company_managers c2_ INNER JOIN company_employees c1_ ON c2_.id = c1_.id INNER JOIN company_persons c0_ ON c2_.id = c0_.id' + 'SELECT t0."id" AS c0, t0."name" AS c1, t1."salary" AS c2, t1."department" AS c3, t1."startDate" AS c4, t2."title" AS c5, t0."spouse_id" AS c6, t0."discr" AS c7 FROM "company_managers" t2 INNER JOIN "company_employees" t1 ON t2."id" = t1."id" INNER JOIN "company_persons" t0 ON t2."id" = t0."id"' ); } @@ -1430,7 +1447,7 @@ public function testIdentityFunctionInJoinedSubclass() public function testIdentityFunctionDoesNotAcceptStateField() { $this->assertInvalidSqlGeneration( - "SELECT IDENTITY(u.name) as name FROM Doctrine\Tests\Models\CMS\CmsUser u", + 'SELECT IDENTITY(u.name) as name FROM Doctrine\Tests\Models\CMS\CmsUser u', QueryException::class ); } @@ -1442,7 +1459,7 @@ public function testInheritanceTypeJoinInRootClassWithDisabledForcePartialLoad() { $this->assertSqlGeneration( 'SELECT p FROM Doctrine\Tests\Models\Company\CompanyPerson p', - 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.title AS title_2, c2_.salary AS salary_3, c2_.department AS department_4, c2_.startDate AS startDate_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c1_.car_id AS car_id_8 FROM company_persons c0_ LEFT JOIN company_managers c1_ ON c0_.id = c1_.id LEFT JOIN company_employees c2_ ON c0_.id = c2_.id', + 'SELECT t0."id" AS c0, t0."name" AS c1, t1."title" AS c2, t2."salary" AS c3, t2."department" AS c4, t2."startDate" AS c5, t0."discr" AS c6, t0."spouse_id" AS c7, t1."car_id" AS c8 FROM "company_persons" t0 LEFT JOIN "company_managers" t1 ON t0."id" = t1."id" LEFT JOIN "company_employees" t2 ON t0."id" = t2."id"', [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -1454,7 +1471,7 @@ public function testInheritanceTypeJoinInRootClassWithEnabledForcePartialLoad() { $this->assertSqlGeneration( 'SELECT p FROM Doctrine\Tests\Models\Company\CompanyPerson p', - 'SELECT c0_.id AS id_0, c0_.name AS name_1, c0_.discr AS discr_2 FROM company_persons c0_', + 'SELECT t0."id" AS c0, t0."name" AS c1, t0."discr" AS c2 FROM "company_persons" t0', [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true] ); } @@ -1466,7 +1483,7 @@ public function testInheritanceTypeJoinInChildClassWithDisabledForcePartialLoad( { $this->assertSqlGeneration( 'SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e', - 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c2_.car_id AS car_id_8 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id LEFT JOIN company_managers c2_ ON c1_.id = c2_.id', + 'SELECT t0."id" AS c0, t0."name" AS c1, t1."salary" AS c2, t1."department" AS c3, t1."startDate" AS c4, t2."title" AS c5, t0."discr" AS c6, t0."spouse_id" AS c7, t2."car_id" AS c8 FROM "company_employees" t1 INNER JOIN "company_persons" t0 ON t1."id" = t0."id" LEFT JOIN "company_managers" t2 ON t1."id" = t2."id"', [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -1478,7 +1495,7 @@ public function testInheritanceTypeJoinInChildClassWithEnabledForcePartialLoad() { $this->assertSqlGeneration( 'SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e', - 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c0_.discr AS discr_5 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id', + 'SELECT t0."id" AS c0, t0."name" AS c1, t1."salary" AS c2, t1."department" AS c3, t1."startDate" AS c4, t0."discr" AS c5 FROM "company_employees" t1 INNER JOIN "company_persons" t0 ON t1."id" = t0."id"', [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true] ); } @@ -1490,7 +1507,7 @@ public function testInheritanceTypeJoinInLeafClassWithDisabledForcePartialLoad() { $this->assertSqlGeneration( 'SELECT m FROM Doctrine\Tests\Models\Company\CompanyManager m', - 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c2_.car_id AS car_id_8 FROM company_managers c2_ INNER JOIN company_employees c1_ ON c2_.id = c1_.id INNER JOIN company_persons c0_ ON c2_.id = c0_.id', + 'SELECT t0."id" AS c0, t0."name" AS c1, t1."salary" AS c2, t1."department" AS c3, t1."startDate" AS c4, t2."title" AS c5, t0."discr" AS c6, t0."spouse_id" AS c7, t2."car_id" AS c8 FROM "company_managers" t2 INNER JOIN "company_employees" t1 ON t2."id" = t1."id" INNER JOIN "company_persons" t0 ON t2."id" = t0."id"', [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -1502,7 +1519,7 @@ public function testInheritanceTypeJoinInLeafClassWithEnabledForcePartialLoad() { $this->assertSqlGeneration( 'SELECT m FROM Doctrine\Tests\Models\Company\CompanyManager m', - 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c0_.discr AS discr_6 FROM company_managers c2_ INNER JOIN company_employees c1_ ON c2_.id = c1_.id INNER JOIN company_persons c0_ ON c2_.id = c0_.id', + 'SELECT t0."id" AS c0, t0."name" AS c1, t1."salary" AS c2, t1."department" AS c3, t1."startDate" AS c4, t2."title" AS c5, t0."discr" AS c6 FROM "company_managers" t2 INNER JOIN "company_employees" t1 ON t2."id" = t1."id" INNER JOIN "company_persons" t0 ON t2."id" = t0."id"', [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true] ); } @@ -1514,7 +1531,7 @@ public function testInheritanceTypeSingleTableInRootClassWithDisabledForcePartia { $this->assertSqlGeneration( 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c', - "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6, c0_.salesPerson_id AS salesPerson_id_7 FROM company_contracts c0_ WHERE c0_.discr IN ('fix', 'flexible', 'flexultra')", + 'SELECT t0."id" AS c0, t0."completed" AS c1, t0."fixPrice" AS c2, t0."hoursWorked" AS c3, t0."pricePerHour" AS c4, t0."maxPrice" AS c5, t0."discr" AS c6, t0."salesPerson_id" AS c7 FROM "company_contracts" t0 WHERE t0."discr" IN (\'fix\', \'flexible\', \'flexultra\')', [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -1526,7 +1543,7 @@ public function testInheritanceTypeSingleTableInRootClassWithEnabledForcePartial { $this->assertSqlGeneration( 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c', - "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6 FROM company_contracts c0_ WHERE c0_.discr IN ('fix', 'flexible', 'flexultra')", + 'SELECT t0."id" AS c0, t0."completed" AS c1, t0."fixPrice" AS c2, t0."hoursWorked" AS c3, t0."pricePerHour" AS c4, t0."maxPrice" AS c5, t0."discr" AS c6 FROM "company_contracts" t0 WHERE t0."discr" IN (\'fix\', \'flexible\', \'flexultra\')', [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true] ); } @@ -1538,7 +1555,7 @@ public function testInheritanceTypeSingleTableInChildClassWithDisabledForceParti { $this->assertSqlGeneration( 'SELECT fc FROM Doctrine\Tests\Models\Company\CompanyFlexContract fc', - "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.hoursWorked AS hoursWorked_2, c0_.pricePerHour AS pricePerHour_3, c0_.maxPrice AS maxPrice_4, c0_.discr AS discr_5, c0_.salesPerson_id AS salesPerson_id_6 FROM company_contracts c0_ WHERE c0_.discr IN ('flexible', 'flexultra')", + 'SELECT t0."id" AS c0, t0."completed" AS c1, t0."hoursWorked" AS c2, t0."pricePerHour" AS c3, t0."maxPrice" AS c4, t0."discr" AS c5, t0."salesPerson_id" AS c6 FROM "company_contracts" t0 WHERE t0."discr" IN (\'flexible\', \'flexultra\')', [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -1550,7 +1567,7 @@ public function testInheritanceTypeSingleTableInChildClassWithEnabledForcePartia { $this->assertSqlGeneration( 'SELECT fc FROM Doctrine\Tests\Models\Company\CompanyFlexContract fc', - "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.hoursWorked AS hoursWorked_2, c0_.pricePerHour AS pricePerHour_3, c0_.maxPrice AS maxPrice_4, c0_.discr AS discr_5 FROM company_contracts c0_ WHERE c0_.discr IN ('flexible', 'flexultra')", + 'SELECT t0."id" AS c0, t0."completed" AS c1, t0."hoursWorked" AS c2, t0."pricePerHour" AS c3, t0."maxPrice" AS c4, t0."discr" AS c5 FROM "company_contracts" t0 WHERE t0."discr" IN (\'flexible\', \'flexultra\')', [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true] ); } @@ -1562,7 +1579,7 @@ public function testInheritanceTypeSingleTableInLeafClassWithDisabledForcePartia { $this->assertSqlGeneration( 'SELECT fuc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract fuc', - "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.hoursWorked AS hoursWorked_2, c0_.pricePerHour AS pricePerHour_3, c0_.maxPrice AS maxPrice_4, c0_.discr AS discr_5, c0_.salesPerson_id AS salesPerson_id_6 FROM company_contracts c0_ WHERE c0_.discr IN ('flexultra')", + 'SELECT t0."id" AS c0, t0."completed" AS c1, t0."hoursWorked" AS c2, t0."pricePerHour" AS c3, t0."maxPrice" AS c4, t0."discr" AS c5, t0."salesPerson_id" AS c6 FROM "company_contracts" t0 WHERE t0."discr" IN (\'flexultra\')', [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -1574,7 +1591,7 @@ public function testInheritanceTypeSingleTableInLeafClassWithEnabledForcePartial { $this->assertSqlGeneration( 'SELECT fuc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract fuc', - "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.hoursWorked AS hoursWorked_2, c0_.pricePerHour AS pricePerHour_3, c0_.maxPrice AS maxPrice_4, c0_.discr AS discr_5 FROM company_contracts c0_ WHERE c0_.discr IN ('flexultra')", + 'SELECT t0."id" AS c0, t0."completed" AS c1, t0."hoursWorked" AS c2, t0."pricePerHour" AS c3, t0."maxPrice" AS c4, t0."discr" AS c5 FROM "company_contracts" t0 WHERE t0."discr" IN (\'flexultra\')', [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true] ); } @@ -1586,7 +1603,7 @@ public function testSelfReferenceWithOneToOneDoesNotDuplicateAlias() { $this->assertSqlGeneration( 'SELECT p, pp FROM Doctrine\Tests\Models\Company\CompanyPerson p JOIN p.spouse pp', - "SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.title AS title_2, c2_.salary AS salary_3, c2_.department AS department_4, c2_.startDate AS startDate_5, c3_.id AS id_6, c3_.name AS name_7, c4_.title AS title_8, c5_.salary AS salary_9, c5_.department AS department_10, c5_.startDate AS startDate_11, c0_.discr AS discr_12, c0_.spouse_id AS spouse_id_13, c1_.car_id AS car_id_14, c3_.discr AS discr_15, c3_.spouse_id AS spouse_id_16, c4_.car_id AS car_id_17 FROM company_persons c0_ LEFT JOIN company_managers c1_ ON c0_.id = c1_.id LEFT JOIN company_employees c2_ ON c0_.id = c2_.id INNER JOIN company_persons c3_ ON c0_.spouse_id = c3_.id LEFT JOIN company_managers c4_ ON c3_.id = c4_.id LEFT JOIN company_employees c5_ ON c3_.id = c5_.id", + 'SELECT t0."id" AS c0, t0."name" AS c1, t1."title" AS c2, t2."salary" AS c3, t2."department" AS c4, t2."startDate" AS c5, t3."id" AS c6, t3."name" AS c7, t4."title" AS c8, t5."salary" AS c9, t5."department" AS c10, t5."startDate" AS c11, t0."discr" AS c12, t0."spouse_id" AS c13, t1."car_id" AS c14, t3."discr" AS c15, t3."spouse_id" AS c16, t4."car_id" AS c17 FROM "company_persons" t0 LEFT JOIN "company_managers" t1 ON t0."id" = t1."id" LEFT JOIN "company_employees" t2 ON t0."id" = t2."id" INNER JOIN "company_persons" t3 ON t0."spouse_id" = t3."id" LEFT JOIN "company_managers" t4 ON t3."id" = t4."id" LEFT JOIN "company_employees" t5 ON t3."id" = t5."id"', [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -1598,7 +1615,7 @@ public function testAliasDoesNotExceedPlatformDefinedLength() { $this->assertSqlGeneration( 'SELECT m FROM ' . __NAMESPACE__ . '\\DDC1384Model m', - "SELECT d0_.aVeryLongIdentifierThatShouldBeShortenedByTheSQLWalker_fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo AS ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo_0 FROM DDC1384Model d0_" + 'SELECT t0."aVeryLongIdentifierThatShouldBeShortenedByTheSQLWalker_fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo" AS c0 FROM "DDC1384Model" t0' ); } @@ -1610,7 +1627,7 @@ public function testIssue331() { $this->assertSqlGeneration( 'SELECT e.name FROM Doctrine\Tests\Models\Company\CompanyEmployee e', - 'SELECT c0_.name AS name_0 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id' + 'SELECT t0."name" AS c0 FROM "company_employees" t1 INNER JOIN "company_persons" t0 ON t1."id" = t0."id"' ); } /** @@ -1619,8 +1636,8 @@ public function testIssue331() public function testForeignKeyAsPrimaryKeySubselect() { $this->assertSqlGeneration( - "SELECT s FROM Doctrine\Tests\Models\DDC117\DDC117Article s WHERE EXISTS (SELECT r FROM Doctrine\Tests\Models\DDC117\DDC117Reference r WHERE r.source = s)", - "SELECT d0_.article_id AS article_id_0, d0_.title AS title_1 FROM DDC117Article d0_ WHERE EXISTS (SELECT d1_.source_id, d1_.target_id FROM DDC117Reference d1_ WHERE d1_.source_id = d0_.article_id)" + 'SELECT s FROM Doctrine\Tests\Models\DDC117\DDC117Article s WHERE EXISTS (SELECT r FROM Doctrine\Tests\Models\DDC117\DDC117Reference r WHERE r.source = s)', + 'SELECT t0."article_id" AS c0, t0."title" AS c1 FROM "DDC117Article" t0 WHERE EXISTS (SELECT t1."source_id", t1."target_id" FROM "DDC117Reference" t1 WHERE t1."source_id" = t0."article_id")' ); } @@ -1631,12 +1648,12 @@ public function testSelectWithArithmeticExpressionBeforeField() { $this->assertSqlGeneration( 'SELECT - e.value AS value, e.id FROM ' . __NAMESPACE__ . '\DDC1474Entity e', - 'SELECT -d0_.value AS sclr_0, d0_.id AS id_1 FROM DDC1474Entity d0_' + 'SELECT -t0."value" AS c0, t0."id" AS c1 FROM "DDC1474Entity" t0' ); $this->assertSqlGeneration( 'SELECT e.id, + e.value AS value FROM ' . __NAMESPACE__ . '\DDC1474Entity e', - 'SELECT d0_.id AS id_0, +d0_.value AS sclr_1 FROM DDC1474Entity d0_' + 'SELECT t0."id" AS c0, +t0."value" AS c1 FROM "DDC1474Entity" t0' ); } @@ -1647,12 +1664,12 @@ public function testGroupByAllFieldsWhenObjectHasForeignKeys() { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ GROUP BY c0_.id, c0_.status, c0_.username, c0_.name, c0_.email_id' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 GROUP BY t0."id", t0."status", t0."username", t0."name", t0."email_id"' ); $this->assertSqlGeneration( 'SELECT e FROM Doctrine\Tests\Models\CMS\CmsEmployee e GROUP BY e', - 'SELECT c0_.id AS id_0, c0_.name AS name_1 FROM cms_employees c0_ GROUP BY c0_.id, c0_.name, c0_.spouse_id' + 'SELECT t0."id" AS c0, t0."name" AS c1 FROM "cms_employees" t0 GROUP BY t0."id", t0."name", t0."spouse_id"' ); } @@ -1663,7 +1680,7 @@ public function testGroupBySupportsResultVariable() { $this->assertSqlGeneration( 'SELECT u, u.status AS st FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY st', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.status AS status_4 FROM cms_users c0_ GROUP BY c0_.status' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, t0."status" AS c4 FROM "cms_users" t0 GROUP BY t0."status"' ); } @@ -1674,7 +1691,7 @@ public function testGroupBySupportsIdentificationVariable() { $this->assertSqlGeneration( 'SELECT u AS user FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY user', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ GROUP BY id_0, status_1, username_2, name_3' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 GROUP BY c0, c1, c2, c3' ); } @@ -1685,19 +1702,19 @@ public function testSupportsBitComparison() { $this->assertSqlGeneration( 'SELECT BIT_OR(4,2), BIT_AND(4,2), u FROM Doctrine\Tests\Models\CMS\CmsUser u', - 'SELECT (4 | 2) AS sclr_0, (4 & 2) AS sclr_1, c0_.id AS id_2, c0_.status AS status_3, c0_.username AS username_4, c0_.name AS name_5 FROM cms_users c0_' + 'SELECT (4 | 2) AS c0, (4 & 2) AS c1, t0."id" AS c2, t0."status" AS c3, t0."username" AS c4, t0."name" AS c5 FROM "cms_users" t0' ); $this->assertSqlGeneration( 'SELECT BIT_OR(u.id,2), BIT_AND(u.id,2) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE BIT_OR(u.id,2) > 0', - 'SELECT (c0_.id | 2) AS sclr_0, (c0_.id & 2) AS sclr_1 FROM cms_users c0_ WHERE (c0_.id | 2) > 0' + 'SELECT (t0."id" | 2) AS c0, (t0."id" & 2) AS c1 FROM "cms_users" t0 WHERE (t0."id" | 2) > 0' ); $this->assertSqlGeneration( 'SELECT BIT_OR(u.id,2), BIT_AND(u.id,2) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE BIT_AND(u.id , 4) > 0', - 'SELECT (c0_.id | 2) AS sclr_0, (c0_.id & 2) AS sclr_1 FROM cms_users c0_ WHERE (c0_.id & 4) > 0' + 'SELECT (t0."id" | 2) AS c0, (t0."id" & 2) AS c1 FROM "cms_users" t0 WHERE (t0."id" & 4) > 0' ); $this->assertSqlGeneration( 'SELECT BIT_OR(u.id,2), BIT_AND(u.id,2) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE BIT_OR(u.id , 2) > 0 OR BIT_AND(u.id , 4) > 0', - 'SELECT (c0_.id | 2) AS sclr_0, (c0_.id & 2) AS sclr_1 FROM cms_users c0_ WHERE (c0_.id | 2) > 0 OR (c0_.id & 4) > 0' + 'SELECT (t0."id" | 2) AS c0, (t0."id" & 2) AS c1 FROM "cms_users" t0 WHERE (t0."id" | 2) > 0 OR (t0."id" & 4) > 0' ); } @@ -1708,22 +1725,22 @@ public function testParenthesesOnTheLeftHandOfComparison() { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u where ( (u.id + u.id) * u.id ) > 100', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE ((c0_.id + c0_.id) * c0_.id) > 100' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE ((t0."id" + t0."id") * t0."id") > 100' ); $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u where (u.id + u.id) * u.id > 100', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE (c0_.id + c0_.id) * c0_.id > 100' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE (t0."id" + t0."id") * t0."id" > 100' ); $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u where 100 < (u.id + u.id) * u.id ', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE 100 < (c0_.id + c0_.id) * c0_.id' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE 100 < (t0."id" + t0."id") * t0."id"' ); } public function testSupportsParenthesisExpressionInSubSelect() { $this->assertSqlGeneration( 'SELECT u.id, (SELECT (1000*SUM(subU.id)/SUM(subU.id)) FROM Doctrine\Tests\Models\CMS\CmsUser subU where subU.id = u.id) AS subSelect FROM Doctrine\Tests\Models\CMS\CmsUser u', - 'SELECT c0_.id AS id_0, (SELECT (1000 * SUM(c1_.id) / SUM(c1_.id)) FROM cms_users c1_ WHERE c1_.id = c0_.id) AS sclr_1 FROM cms_users c0_' + 'SELECT t0."id" AS c0, (SELECT (1000 * SUM(t1."id") / SUM(t1."id")) FROM "cms_users" t1 WHERE t1."id" = t0."id") AS c1 FROM "cms_users" t0' ); } @@ -1734,27 +1751,27 @@ public function testSupportsSubSqlFunction() { $this->assertSqlGeneration( 'SELECT u1 FROM Doctrine\Tests\Models\CMS\CmsUser u1 WHERE u1.name IN ( SELECT TRIM(u2.name) FROM Doctrine\Tests\Models\CMS\CmsUser u2 )', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE c0_.name IN (SELECT TRIM(c1_.name) AS sclr_4 FROM cms_users c1_)' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE t0."name" IN (SELECT TRIM(t1."name") AS c4 FROM "cms_users" t1)' ); $this->assertSqlGeneration( 'SELECT u1 FROM Doctrine\Tests\Models\CMS\CmsUser u1 WHERE u1.name IN ( SELECT TRIM(u2.name) FROM Doctrine\Tests\Models\CMS\CmsUser u2 WHERE LOWER(u2.name) LIKE \'%fabio%\')', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE c0_.name IN (SELECT TRIM(c1_.name) AS sclr_4 FROM cms_users c1_ WHERE LOWER(c1_.name) LIKE \'%fabio%\')' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE t0."name" IN (SELECT TRIM(t1."name") AS c4 FROM "cms_users" t1 WHERE LOWER(t1."name") LIKE \'%fabio%\')' ); $this->assertSqlGeneration( 'SELECT u1 FROM Doctrine\Tests\Models\CMS\CmsUser u1 WHERE u1.email IN ( SELECT TRIM(IDENTITY(u2.email)) FROM Doctrine\Tests\Models\CMS\CmsUser u2 )', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE c0_.email_id IN (SELECT TRIM(c1_.email_id) AS sclr_4 FROM cms_users c1_)' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE t0."email_id" IN (SELECT TRIM(t1."email_id") AS c4 FROM "cms_users" t1)' ); $this->assertSqlGeneration( 'SELECT u1 FROM Doctrine\Tests\Models\CMS\CmsUser u1 WHERE u1.email IN ( SELECT IDENTITY(u2.email) FROM Doctrine\Tests\Models\CMS\CmsUser u2 )', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE c0_.email_id IN (SELECT c1_.email_id AS sclr_4 FROM cms_users c1_)' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE t0."email_id" IN (SELECT t1."email_id" AS c4 FROM "cms_users" t1)' ); $this->assertSqlGeneration( 'SELECT u1 FROM Doctrine\Tests\Models\CMS\CmsUser u1 WHERE COUNT(u1.id) = ( SELECT SUM(u2.id) FROM Doctrine\Tests\Models\CMS\CmsUser u2 )', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE COUNT(c0_.id) = (SELECT SUM(c1_.id) AS sclr_4 FROM cms_users c1_)' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE COUNT(t0."id") = (SELECT SUM(t1."id") AS c4 FROM "cms_users" t1)' ); $this->assertSqlGeneration( 'SELECT u1 FROM Doctrine\Tests\Models\CMS\CmsUser u1 WHERE COUNT(u1.id) <= ( SELECT SUM(u2.id) + COUNT(u2.email) FROM Doctrine\Tests\Models\CMS\CmsUser u2 )', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE COUNT(c0_.id) <= (SELECT SUM(c1_.id) + COUNT(c1_.email_id) AS sclr_4 FROM cms_users c1_)' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE COUNT(t0."id") <= (SELECT SUM(t1."id") + COUNT(t1."email_id") AS c4 FROM "cms_users" t1)' ); } @@ -1764,33 +1781,33 @@ public function testSupportsSubSqlFunction() public function testSupportsNewOperator() { $this->assertSqlGeneration( - "SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(u.name, e.email, a.city) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a", - "SELECT c0_.name AS sclr_0, c1_.email AS sclr_1, c2_.city AS sclr_2 FROM cms_users c0_ INNER JOIN cms_emails c1_ ON c0_.email_id = c1_.id INNER JOIN cms_addresses c2_ ON c0_.id = c2_.user_id" + 'SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(u.name, e.email, a.city) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a', + 'SELECT t0."name" AS c0, t1."email" AS c1, t2."city" AS c2 FROM "cms_users" t0 INNER JOIN "cms_emails" t1 ON t0."email_id" = t1."id" INNER JOIN "cms_addresses" t2 ON t0."id" = t2."user_id"' ); $this->assertSqlGeneration( - "SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(u.name, e.email, a.id + u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a", - "SELECT c0_.name AS sclr_0, c1_.email AS sclr_1, c2_.id + c0_.id AS sclr_2 FROM cms_users c0_ INNER JOIN cms_emails c1_ ON c0_.email_id = c1_.id INNER JOIN cms_addresses c2_ ON c0_.id = c2_.user_id" + 'SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(u.name, e.email, a.id + u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a', + 'SELECT t0."name" AS c0, t1."email" AS c1, t2."id" + t0."id" AS c2 FROM "cms_users" t0 INNER JOIN "cms_emails" t1 ON t0."email_id" = t1."id" INNER JOIN "cms_addresses" t2 ON t0."id" = t2."user_id"' ); $this->assertSqlGeneration( - "SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(u.name, e.email, a.city, COUNT(p)) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a JOIN u.phonenumbers p", - "SELECT c0_.name AS sclr_0, c1_.email AS sclr_1, c2_.city AS sclr_2, COUNT(c3_.phonenumber) AS sclr_3 FROM cms_users c0_ INNER JOIN cms_emails c1_ ON c0_.email_id = c1_.id INNER JOIN cms_addresses c2_ ON c0_.id = c2_.user_id INNER JOIN cms_phonenumbers c3_ ON c0_.id = c3_.user_id" + 'SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(u.name, e.email, a.city, COUNT(p)) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a JOIN u.phonenumbers p', + 'SELECT t0."name" AS c0, t1."email" AS c1, t2."city" AS c2, COUNT(t3."phonenumber") AS c3 FROM "cms_users" t0 INNER JOIN "cms_emails" t1 ON t0."email_id" = t1."id" INNER JOIN "cms_addresses" t2 ON t0."id" = t2."user_id" INNER JOIN "cms_phonenumbers" t3 ON t0."id" = t3."user_id"' ); $this->assertSqlGeneration( - "SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(u.name, e.email, a.city, COUNT(p) + u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a JOIN u.phonenumbers p", - "SELECT c0_.name AS sclr_0, c1_.email AS sclr_1, c2_.city AS sclr_2, COUNT(c3_.phonenumber) + c0_.id AS sclr_3 FROM cms_users c0_ INNER JOIN cms_emails c1_ ON c0_.email_id = c1_.id INNER JOIN cms_addresses c2_ ON c0_.id = c2_.user_id INNER JOIN cms_phonenumbers c3_ ON c0_.id = c3_.user_id" + 'SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(u.name, e.email, a.city, COUNT(p) + u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a JOIN u.phonenumbers p', + 'SELECT t0."name" AS c0, t1."email" AS c1, t2."city" AS c2, COUNT(t3."phonenumber") + t0."id" AS c3 FROM "cms_users" t0 INNER JOIN "cms_emails" t1 ON t0."email_id" = t1."id" INNER JOIN "cms_addresses" t2 ON t0."id" = t2."user_id" INNER JOIN "cms_phonenumbers" t3 ON t0."id" = t3."user_id"' ); $this->assertSqlGeneration( - "SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(a.id, a.country, a.city), new Doctrine\Tests\Models\CMS\CmsAddressDTO(u.name, e.email) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a ORDER BY u.name", - "SELECT c0_.id AS sclr_0, c0_.country AS sclr_1, c0_.city AS sclr_2, c1_.name AS sclr_3, c2_.email AS sclr_4 FROM cms_users c1_ INNER JOIN cms_emails c2_ ON c1_.email_id = c2_.id INNER JOIN cms_addresses c0_ ON c1_.id = c0_.user_id ORDER BY c1_.name ASC" + 'SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(a.id, a.country, a.city), new Doctrine\Tests\Models\CMS\CmsAddressDTO(u.name, e.email) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a ORDER BY u.name', + 'SELECT t0."id" AS c0, t0."country" AS c1, t0."city" AS c2, t1."name" AS c3, t2."email" AS c4 FROM "cms_users" t1 INNER JOIN "cms_emails" t2 ON t1."email_id" = t2."id" INNER JOIN "cms_addresses" t0 ON t1."id" = t0."user_id" ORDER BY t1."name" ASC' ); $this->assertSqlGeneration( - "SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(a.id, (SELECT 1 FROM Doctrine\Tests\Models\CMS\CmsUser su), a.country, a.city), new Doctrine\Tests\Models\CMS\CmsAddressDTO(u.name, e.email) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a ORDER BY u.name", - "SELECT c0_.id AS sclr_0, (SELECT 1 AS sclr_2 FROM cms_users c1_) AS sclr_1, c0_.country AS sclr_3, c0_.city AS sclr_4, c2_.name AS sclr_5, c3_.email AS sclr_6 FROM cms_users c2_ INNER JOIN cms_emails c3_ ON c2_.email_id = c3_.id INNER JOIN cms_addresses c0_ ON c2_.id = c0_.user_id ORDER BY c2_.name ASC" + 'SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(a.id, (SELECT 1 FROM Doctrine\Tests\Models\CMS\CmsUser su), a.country, a.city), new Doctrine\Tests\Models\CMS\CmsAddressDTO(u.name, e.email) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a ORDER BY u.name', + 'SELECT t0."id" AS c0, (SELECT 1 AS c2 FROM "cms_users" t1) AS c1, t0."country" AS c3, t0."city" AS c4, t2."name" AS c5, t3."email" AS c6 FROM "cms_users" t2 INNER JOIN "cms_emails" t3 ON t2."email_id" = t3."id" INNER JOIN "cms_addresses" t0 ON t2."id" = t0."user_id" ORDER BY t2."name" ASC' ); } @@ -1800,38 +1817,38 @@ public function testSupportsNewOperator() public function testWhereFunctionIsNullComparisonExpression() { $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE IDENTITY(u.email) IS NULL", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE c0_.email_id IS NULL" + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE IDENTITY(u.email) IS NULL', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE t0."email_id" IS NULL' ); $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE NULLIF(u.name, 'FabioBatSilva') IS NULL AND IDENTITY(u.email) IS NOT NULL", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE NULLIF(c0_.name, 'FabioBatSilva') IS NULL AND c0_.email_id IS NOT NULL" + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE NULLIF(u.name, \'FabioBatSilva\') IS NULL AND IDENTITY(u.email) IS NOT NULL', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE NULLIF(t0."name", \'FabioBatSilva\') IS NULL AND t0."email_id" IS NOT NULL' ); $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE IDENTITY(u.email) IS NOT NULL", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE c0_.email_id IS NOT NULL" + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE IDENTITY(u.email) IS NOT NULL', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE t0."email_id" IS NOT NULL' ); $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE NULLIF(u.name, 'FabioBatSilva') IS NOT NULL", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE NULLIF(c0_.name, 'FabioBatSilva') IS NOT NULL" + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE NULLIF(u.name, \'FabioBatSilva\') IS NOT NULL', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE NULLIF(t0."name", \'FabioBatSilva\') IS NOT NULL' ); $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE COALESCE(u.name, u.id) IS NOT NULL", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE COALESCE(c0_.name, c0_.id) IS NOT NULL" + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE COALESCE(u.name, u.id) IS NOT NULL', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE COALESCE(t0."name", t0."id") IS NOT NULL' ); $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE COALESCE(u.id, IDENTITY(u.email)) IS NOT NULL", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE COALESCE(c0_.id, c0_.email_id) IS NOT NULL" + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE COALESCE(u.id, IDENTITY(u.email)) IS NOT NULL', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE COALESCE(t0."id", t0."email_id") IS NOT NULL' ); $this->assertSqlGeneration( - "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE COALESCE(IDENTITY(u.email), NULLIF(u.name, 'FabioBatSilva')) IS NOT NULL", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE COALESCE(c0_.email_id, NULLIF(c0_.name, 'FabioBatSilva')) IS NOT NULL" + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE COALESCE(IDENTITY(u.email), NULLIF(u.name, \'FabioBatSilva\')) IS NOT NULL', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 WHERE COALESCE(t0."email_id", NULLIF(t0."name", \'FabioBatSilva\')) IS NOT NULL' ); } @@ -1845,7 +1862,7 @@ public function testCustomTypeValueSql() $this->assertSqlGeneration( 'SELECT p.customInteger FROM Doctrine\Tests\Models\CustomType\CustomTypeParent p WHERE p.id = 1', - 'SELECT -(c0_.customInteger) AS customInteger_0 FROM customtype_parents c0_ WHERE c0_.id = 1' + 'SELECT -(t0."customInteger") AS c0 FROM "customtype_parents" t0 WHERE t0."id" = 1' ); } @@ -1859,7 +1876,7 @@ public function testCustomTypeValueSqlIgnoresIdentifierColumn() $this->assertSqlGeneration( 'SELECT p.id FROM Doctrine\Tests\Models\CustomType\CustomTypeParent p WHERE p.id = 1', - 'SELECT c0_.id AS id_0 FROM customtype_parents c0_ WHERE c0_.id = 1' + 'SELECT t0."id" AS c0 FROM "customtype_parents" t0 WHERE t0."id" = 1' ); } @@ -1873,7 +1890,7 @@ public function testCustomTypeValueSqlForAllFields() $this->assertSqlGeneration( 'SELECT p FROM Doctrine\Tests\Models\CustomType\CustomTypeParent p', - 'SELECT c0_.id AS id_0, -(c0_.customInteger) AS customInteger_1 FROM customtype_parents c0_' + 'SELECT t0."id" AS c0, -(t0."customInteger") AS c1 FROM "customtype_parents" t0' ); } @@ -1887,7 +1904,7 @@ public function testCustomTypeValueSqlForPartialObject() $this->assertSqlGeneration( 'SELECT partial p.{id, customInteger} FROM Doctrine\Tests\Models\CustomType\CustomTypeParent p', - 'SELECT c0_.id AS id_0, -(c0_.customInteger) AS customInteger_1 FROM customtype_parents c0_' + 'SELECT t0."id" AS c0, -(t0."customInteger") AS c1 FROM "customtype_parents" t0' ); } @@ -1898,7 +1915,7 @@ public function testMultipleFromAndInheritanceCondition() { $this->assertSqlGeneration( 'SELECT fix, flex FROM Doctrine\Tests\Models\Company\CompanyFixContract fix, Doctrine\Tests\Models\Company\CompanyFlexContract flex', - "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c1_.id AS id_3, c1_.completed AS completed_4, c1_.hoursWorked AS hoursWorked_5, c1_.pricePerHour AS pricePerHour_6, c1_.maxPrice AS maxPrice_7, c0_.discr AS discr_8, c1_.discr AS discr_9 FROM company_contracts c0_, company_contracts c1_ WHERE (c0_.discr IN ('fix') AND c1_.discr IN ('flexible', 'flexultra'))" + 'SELECT t0."id" AS c0, t0."completed" AS c1, t0."fixPrice" AS c2, t1."id" AS c3, t1."completed" AS c4, t1."hoursWorked" AS c5, t1."pricePerHour" AS c6, t1."maxPrice" AS c7, t0."discr" AS c8, t1."discr" AS c9 FROM "company_contracts" t0, "company_contracts" t1 WHERE (t0."discr" IN (\'fix\') AND t1."discr" IN (\'flexible\', \'flexultra\'))' ); } @@ -1909,15 +1926,15 @@ public function testOrderByClauseSupportsSimpleArithmeticExpression() { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.id + 1 ', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ ORDER BY c0_.id + 1 ASC' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 ORDER BY t0."id" + 1 ASC' ); $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY ( ( (u.id + 1) * (u.id - 1) ) / 2)', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ ORDER BY (((c0_.id + 1) * (c0_.id - 1)) / 2) ASC' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 ORDER BY (((t0."id" + 1) * (t0."id" - 1)) / 2) ASC' ); $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY ((u.id + 5000) * u.id + 3) ', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ ORDER BY ((c0_.id + 5000) * c0_.id + 3) ASC' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 ORDER BY ((t0."id" + 5000) * t0."id" + 3) ASC' ); } @@ -1925,7 +1942,7 @@ public function testOrderByClauseSupportsFunction() { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY CONCAT(u.username, u.name) ', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ ORDER BY c0_.username || c0_.name ASC' + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3 FROM "cms_users" t0 ORDER BY t0."username" || t0."name" ASC' ); } @@ -1936,17 +1953,17 @@ public function testStripNonAlphanumericCharactersFromAlias() { $this->assertSqlGeneration( 'SELECT e FROM Doctrine\Tests\Models\Generic\NonAlphaColumnsEntity e', - 'SELECT n0_."simple-entity-id" AS simpleentityid_0, n0_."simple-entity-value" AS simpleentityvalue_1 FROM "not-a-simple-entity" n0_' + 'SELECT t0."simple-entity-id" AS c0, t0."simple-entity-value" AS c1 FROM "not-a-simple-entity" t0' ); $this->assertSqlGeneration( 'SELECT e.value FROM Doctrine\Tests\Models\Generic\NonAlphaColumnsEntity e ORDER BY e.value', - 'SELECT n0_."simple-entity-value" AS simpleentityvalue_0 FROM "not-a-simple-entity" n0_ ORDER BY n0_."simple-entity-value" ASC' + 'SELECT t0."simple-entity-value" AS c0 FROM "not-a-simple-entity" t0 ORDER BY t0."simple-entity-value" ASC' ); $this->assertSqlGeneration( 'SELECT TRIM(e.value) FROM Doctrine\Tests\Models\Generic\NonAlphaColumnsEntity e ORDER BY e.value', - 'SELECT TRIM(n0_."simple-entity-value") AS sclr_0 FROM "not-a-simple-entity" n0_ ORDER BY n0_."simple-entity-value" ASC' + 'SELECT TRIM(t0."simple-entity-value") AS c0 FROM "not-a-simple-entity" t0 ORDER BY t0."simple-entity-value" ASC' ); } @@ -1957,17 +1974,17 @@ public function testColumnNameWithNumbersAndNonAlphanumericCharacters() { $this->assertSqlGeneration( 'SELECT e FROM Doctrine\Tests\Models\Quote\NumericEntity e', - 'SELECT t0_."1:1" AS 11_0, t0_."2:2" AS 22_1 FROM table t0_' + 'SELECT t0."1:1" AS c0, t0."2:2" AS c1 FROM "table" t0' ); $this->assertSqlGeneration( 'SELECT e.value FROM Doctrine\Tests\Models\Quote\NumericEntity e', - 'SELECT t0_."2:2" AS 22_0 FROM table t0_' + 'SELECT t0."2:2" AS c0 FROM "table" t0' ); $this->assertSqlGeneration( 'SELECT TRIM(e.value) FROM Doctrine\Tests\Models\Quote\NumericEntity e', - 'SELECT TRIM(t0_."2:2") AS sclr_0 FROM table t0_' + 'SELECT TRIM(t0."2:2") AS c0 FROM "table" t0' ); } @@ -1978,7 +1995,7 @@ public function testQuotedTableDeclaration() { $this->assertSqlGeneration( 'SELECT u FROM Doctrine\Tests\Models\Quote\User u', - 'SELECT q0_."user-id" AS userid_0, q0_."user-name" AS username_1 FROM "quote-user" q0_' + 'SELECT t0."user-id" AS c0, t0."user-name" AS c1 FROM "quote-user" t0' ); } @@ -1989,32 +2006,32 @@ public function testQuotedWalkJoinVariableDeclaration() { $this->assertSqlGeneration( 'SELECT u, a FROM Doctrine\Tests\Models\Quote\User u JOIN u.address a', - 'SELECT q0_."user-id" AS userid_0, q0_."user-name" AS username_1, q1_."address-id" AS addressid_2, q1_."address-zip" AS addresszip_3, q1_.type AS type_4 FROM "quote-user" q0_ INNER JOIN "quote-address" q1_ ON q0_."address-id" = q1_."address-id" AND q1_.type IN (\'simple\', \'full\')' + 'SELECT t0."user-id" AS c0, t0."user-name" AS c1, t1."address-id" AS c2, t1."address-zip" AS c3, t1."type" AS c4 FROM "quote-user" t0 INNER JOIN "quote-address" t1 ON t0."address-id" = t1."address-id" AND t1."type" IN (\'simple\', \'full\')' ); $this->assertSqlGeneration( 'SELECT u, p FROM Doctrine\Tests\Models\Quote\User u JOIN u.phones p', - 'SELECT q0_."user-id" AS userid_0, q0_."user-name" AS username_1, q1_."phone-number" AS phonenumber_2 FROM "quote-user" q0_ INNER JOIN "quote-phone" q1_ ON q0_."user-id" = q1_."user-id"' + 'SELECT t0."user-id" AS c0, t0."user-name" AS c1, t1."phone-number" AS c2 FROM "quote-user" t0 INNER JOIN "quote-phone" t1 ON t0."user-id" = t1."user-id"' ); $this->assertSqlGeneration( 'SELECT u, g FROM Doctrine\Tests\Models\Quote\User u JOIN u.groups g', - 'SELECT q0_."user-id" AS userid_0, q0_."user-name" AS username_1, q1_."group-id" AS groupid_2, q1_."group-name" AS groupname_3 FROM "quote-user" q0_ INNER JOIN "quote-users-groups" q2_ ON q0_."user-id" = q2_."user-id" INNER JOIN "quote-group" q1_ ON q1_."group-id" = q2_."group-id"' + 'SELECT t0."user-id" AS c0, t0."user-name" AS c1, t1."group-id" AS c2, t1."group-name" AS c3 FROM "quote-user" t0 INNER JOIN "quote-users-groups" t2 ON t0."user-id" = t2."user-id" INNER JOIN "quote-group" t1 ON t1."group-id" = t2."group-id"' ); $this->assertSqlGeneration( 'SELECT a, u FROM Doctrine\Tests\Models\Quote\Address a JOIN a.user u', - 'SELECT q0_."address-id" AS addressid_0, q0_."address-zip" AS addresszip_1, q1_."user-id" AS userid_2, q1_."user-name" AS username_3, q0_.type AS type_4 FROM "quote-address" q0_ INNER JOIN "quote-user" q1_ ON q0_."user-id" = q1_."user-id" WHERE q0_.type IN (\'simple\', \'full\')' + 'SELECT t0."address-id" AS c0, t0."address-zip" AS c1, t1."user-id" AS c2, t1."user-name" AS c3, t0."type" AS c4 FROM "quote-address" t0 INNER JOIN "quote-user" t1 ON t0."user-id" = t1."user-id" WHERE t0."type" IN (\'simple\', \'full\')' ); $this->assertSqlGeneration( 'SELECT g, u FROM Doctrine\Tests\Models\Quote\Group g JOIN g.users u', - 'SELECT q0_."group-id" AS groupid_0, q0_."group-name" AS groupname_1, q1_."user-id" AS userid_2, q1_."user-name" AS username_3 FROM "quote-group" q0_ INNER JOIN "quote-users-groups" q2_ ON q0_."group-id" = q2_."group-id" INNER JOIN "quote-user" q1_ ON q1_."user-id" = q2_."user-id"' + 'SELECT t0."group-id" AS c0, t0."group-name" AS c1, t1."user-id" AS c2, t1."user-name" AS c3 FROM "quote-group" t0 INNER JOIN "quote-users-groups" t2 ON t0."group-id" = t2."group-id" INNER JOIN "quote-user" t1 ON t1."user-id" = t2."user-id"' ); $this->assertSqlGeneration( 'SELECT g, p FROM Doctrine\Tests\Models\Quote\Group g JOIN g.parent p', - 'SELECT q0_."group-id" AS groupid_0, q0_."group-name" AS groupname_1, q1_."group-id" AS groupid_2, q1_."group-name" AS groupname_3 FROM "quote-group" q0_ INNER JOIN "quote-group" q1_ ON q0_."parent-id" = q1_."group-id"' + 'SELECT t0."group-id" AS c0, t0."group-name" AS c1, t1."group-id" AS c2, t1."group-name" AS c3 FROM "quote-group" t0 INNER JOIN "quote-group" t1 ON t0."parent-id" = t1."group-id"' ); } @@ -2025,17 +2042,17 @@ public function testCaseThenParameterArithmeticExpression() { $this->assertSqlGeneration( 'SELECT SUM(CASE WHEN e.salary <= :value THEN e.salary - :value WHEN e.salary >= :value THEN :value - e.salary ELSE 0 END) FROM Doctrine\Tests\Models\Company\CompanyEmployee e', - 'SELECT SUM(CASE WHEN c0_.salary <= ? THEN c0_.salary - ? WHEN c0_.salary >= ? THEN ? - c0_.salary ELSE 0 END) AS sclr_0 FROM company_employees c0_ INNER JOIN company_persons c1_ ON c0_.id = c1_.id' + 'SELECT SUM(CASE WHEN t0."salary" <= ? THEN t0."salary" - ? WHEN t0."salary" >= ? THEN ? - t0."salary" ELSE 0 END) AS c0 FROM "company_employees" t0 INNER JOIN "company_persons" t1 ON t0."id" = t1."id"' ); $this->assertSqlGeneration( 'SELECT SUM(CASE WHEN e.salary <= :value THEN e.salary - :value WHEN e.salary >= :value THEN :value - e.salary ELSE e.salary + 0 END) FROM Doctrine\Tests\Models\Company\CompanyEmployee e', - 'SELECT SUM(CASE WHEN c0_.salary <= ? THEN c0_.salary - ? WHEN c0_.salary >= ? THEN ? - c0_.salary ELSE c0_.salary + 0 END) AS sclr_0 FROM company_employees c0_ INNER JOIN company_persons c1_ ON c0_.id = c1_.id' + 'SELECT SUM(CASE WHEN t0."salary" <= ? THEN t0."salary" - ? WHEN t0."salary" >= ? THEN ? - t0."salary" ELSE t0."salary" + 0 END) AS c0 FROM "company_employees" t0 INNER JOIN "company_persons" t1 ON t0."id" = t1."id"' ); $this->assertSqlGeneration( 'SELECT SUM(CASE WHEN e.salary <= :value THEN (e.salary - :value) WHEN e.salary >= :value THEN (:value - e.salary) ELSE (e.salary + :value) END) FROM Doctrine\Tests\Models\Company\CompanyEmployee e', - 'SELECT SUM(CASE WHEN c0_.salary <= ? THEN (c0_.salary - ?) WHEN c0_.salary >= ? THEN (? - c0_.salary) ELSE (c0_.salary + ?) END) AS sclr_0 FROM company_employees c0_ INNER JOIN company_persons c1_ ON c0_.id = c1_.id' + 'SELECT SUM(CASE WHEN t0."salary" <= ? THEN (t0."salary" - ?) WHEN t0."salary" >= ? THEN (? - t0."salary") ELSE (t0."salary" + ?) END) AS c0 FROM "company_employees" t0 INNER JOIN "company_persons" t1 ON t0."id" = t1."id"' ); } @@ -2046,59 +2063,72 @@ public function testCaseThenFunction() { $this->assertSqlGeneration( 'SELECT CASE WHEN LENGTH(u.name) <> 0 THEN CONCAT(u.id, u.name) ELSE u.id END AS name FROM Doctrine\Tests\Models\CMS\CmsUser u', - 'SELECT CASE WHEN LENGTH(c0_.name) <> 0 THEN c0_.id || c0_.name ELSE c0_.id END AS sclr_0 FROM cms_users c0_' + 'SELECT CASE WHEN LENGTH(t0."name") <> 0 THEN t0."id" || t0."name" ELSE t0."id" END AS c0 FROM "cms_users" t0' ); $this->assertSqlGeneration( 'SELECT CASE WHEN LENGTH(u.name) <> LENGTH(TRIM(u.name)) THEN TRIM(u.name) ELSE u.name END AS name FROM Doctrine\Tests\Models\CMS\CmsUser u', - 'SELECT CASE WHEN LENGTH(c0_.name) <> LENGTH(TRIM(c0_.name)) THEN TRIM(c0_.name) ELSE c0_.name END AS sclr_0 FROM cms_users c0_' + 'SELECT CASE WHEN LENGTH(t0."name") <> LENGTH(TRIM(t0."name")) THEN TRIM(t0."name") ELSE t0."name" END AS c0 FROM "cms_users" t0' ); $this->assertSqlGeneration( 'SELECT CASE WHEN LENGTH(u.name) > :value THEN SUBSTRING(u.name, 0, :value) ELSE TRIM(u.name) END AS name FROM Doctrine\Tests\Models\CMS\CmsUser u', - 'SELECT CASE WHEN LENGTH(c0_.name) > ? THEN SUBSTRING(c0_.name FROM 0 FOR ?) ELSE TRIM(c0_.name) END AS sclr_0 FROM cms_users c0_' + 'SELECT CASE WHEN LENGTH(t0."name") > ? THEN SUBSTRING(t0."name" FROM 0 FOR ?) ELSE TRIM(t0."name") END AS c0 FROM "cms_users" t0' ); } /** * @group DDC-2268 */ - public function testSupportsMoreThanTwoParametersInConcatFunction() + public function testSupportsMoreThanTwoParametersInConcatFunctionMySql() { - $connMock = $this->_em->getConnection(); - $orgPlatform = $connMock->getDatabasePlatform(); + $this->em->getConnection()->setDatabasePlatform(new MySqlPlatform()); - $connMock->setDatabasePlatform(new MySqlPlatform()); - $this->assertSqlGeneration( - "SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CONCAT(u.name, u.status, 's') = ?1", - "SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE CONCAT(c0_.name, c0_.status, 's') = ?" - ); - $this->assertSqlGeneration( - "SELECT CONCAT(u.id, u.name, u.status) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1", - "SELECT CONCAT(c0_.id, c0_.name, c0_.status) AS sclr_0 FROM cms_users c0_ WHERE c0_.id = ?" - ); + $this->assertSqlGeneration( + 'SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CONCAT(u.name, u.status, \'s\') = ?1', + 'SELECT t0.`id` AS c0 FROM `cms_users` t0 WHERE CONCAT(t0.`name`, t0.`status`, \'s\') = ?' + ); - $connMock->setDatabasePlatform(new PostgreSqlPlatform()); - $this->assertSqlGeneration( - "SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CONCAT(u.name, u.status, 's') = ?1", - "SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE c0_.name || c0_.status || 's' = ?" - ); - $this->assertSqlGeneration( - "SELECT CONCAT(u.id, u.name, u.status) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1", - "SELECT c0_.id || c0_.name || c0_.status AS sclr_0 FROM cms_users c0_ WHERE c0_.id = ?" - ); + $this->assertSqlGeneration( + 'SELECT CONCAT(u.id, u.name, u.status) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1', + 'SELECT CONCAT(t0.`id`, t0.`name`, t0.`status`) AS c0 FROM `cms_users` t0 WHERE t0.`id` = ?' + ); + } - $connMock->setDatabasePlatform(new SQLServerPlatform()); - $this->assertSqlGeneration( - "SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CONCAT(u.name, u.status, 's') = ?1", - "SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE (c0_.name + c0_.status + 's') = ?" + /** + * @group DDC-2268 + */ + public function testSupportsMoreThanTwoParametersInConcatFunctionPgSql() + { + $this->em->getConnection()->setDatabasePlatform(new PostgreSqlPlatform()); + + $this->assertSqlGeneration( + 'SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CONCAT(u.name, u.status, \'s\') = ?1', + 'SELECT t0."id" AS c0 FROM "cms_users" t0 WHERE t0."name" || t0."status" || \'s\' = ?' + ); + + $this->assertSqlGeneration( + 'SELECT CONCAT(u.id, u.name, u.status) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1', + 'SELECT t0."id" || t0."name" || t0."status" AS c0 FROM "cms_users" t0 WHERE t0."id" = ?' + ); + } + + /** + * @group DDC-2268 + */ + public function testSupportsMoreThanTwoParametersInConcatFunctionSqlServer() + { + $this->em->getConnection()->setDatabasePlatform(new SQLServerPlatform()); + + $this->assertSqlGeneration( + 'SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CONCAT(u.name, u.status, \'s\') = ?1', + 'SELECT t0.[id] AS c0 FROM [cms_users] t0 WHERE (t0.[name] + t0.[status] + \'s\') = ?' ); + $this->assertSqlGeneration( - "SELECT CONCAT(u.id, u.name, u.status) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1", - "SELECT (c0_.id + c0_.name + c0_.status) AS sclr_0 FROM cms_users c0_ WHERE c0_.id = ?" + 'SELECT CONCAT(u.id, u.name, u.status) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1', + 'SELECT (t0.[id] + t0.[name] + t0.[status]) AS c0 FROM [cms_users] t0 WHERE t0.[id] = ?' ); - - $connMock->setDatabasePlatform($orgPlatform); } /** @@ -2108,17 +2138,17 @@ public function testArithmeticPriority() { $this->assertSqlGeneration( 'SELECT 100/(2*2) FROM Doctrine\Tests\Models\CMS\CmsUser u', - 'SELECT 100 / (2 * 2) AS sclr_0 FROM cms_users c0_' + 'SELECT 100 / (2 * 2) AS c0 FROM "cms_users" t0' ); $this->assertSqlGeneration( 'SELECT (u.id / (u.id * 2)) FROM Doctrine\Tests\Models\CMS\CmsUser u', - 'SELECT (c0_.id / (c0_.id * 2)) AS sclr_0 FROM cms_users c0_' + 'SELECT (t0."id" / (t0."id" * 2)) AS c0 FROM "cms_users" t0' ); $this->assertSqlGeneration( 'SELECT 100/(2*2) + (u.id / (u.id * 2)) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE (u.id / (u.id * 2)) > 0', - 'SELECT 100 / (2 * 2) + (c0_.id / (c0_.id * 2)) AS sclr_0 FROM cms_users c0_ WHERE (c0_.id / (c0_.id * 2)) > 0' + 'SELECT 100 / (2 * 2) + (t0."id" / (t0."id" * 2)) AS c0 FROM "cms_users" t0 WHERE (t0."id" / (t0."id" * 2)) > 0' ); } @@ -2129,12 +2159,12 @@ public function testOrderByClauseShouldReplaceOrderByRelationMapping() { $this->assertSqlGeneration( 'SELECT r, b FROM Doctrine\Tests\Models\Routing\RoutingRoute r JOIN r.bookings b', - 'SELECT r0_.id AS id_0, r1_.id AS id_1, r1_.passengerName AS passengerName_2 FROM RoutingRoute r0_ INNER JOIN RoutingRouteBooking r1_ ON r0_.id = r1_.route_id ORDER BY r1_.passengerName ASC' + 'SELECT t0."id" AS c0, t1."id" AS c1, t1."passengerName" AS c2 FROM "RoutingRoute" t0 INNER JOIN "RoutingRouteBooking" t1 ON t0."id" = t1."route_id" ORDER BY t1."passengerName" ASC' ); $this->assertSqlGeneration( 'SELECT r, b FROM Doctrine\Tests\Models\Routing\RoutingRoute r JOIN r.bookings b ORDER BY b.passengerName DESC', - 'SELECT r0_.id AS id_0, r1_.id AS id_1, r1_.passengerName AS passengerName_2 FROM RoutingRoute r0_ INNER JOIN RoutingRouteBooking r1_ ON r0_.id = r1_.route_id ORDER BY r1_.passengerName DESC' + 'SELECT t0."id" AS c0, t1."id" AS c1, t1."passengerName" AS c2 FROM "RoutingRoute" t0 INNER JOIN "RoutingRouteBooking" t1 ON t0."id" = t1."route_id" ORDER BY t1."passengerName" DESC' ); } @@ -2145,12 +2175,12 @@ public function testHavingSupportIsNullExpression() { $this->assertSqlGeneration( 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING u.username IS NULL', - 'SELECT c0_.name AS name_0 FROM cms_users c0_ HAVING c0_.username IS NULL' + 'SELECT t0."name" AS c0 FROM "cms_users" t0 HAVING t0."username" IS NULL' ); $this->assertSqlGeneration( 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING MAX(u.name) IS NULL', - 'SELECT c0_.name AS name_0 FROM cms_users c0_ HAVING MAX(c0_.name) IS NULL' + 'SELECT t0."name" AS c0 FROM "cms_users" t0 HAVING MAX(t0."name") IS NULL' ); } @@ -2161,7 +2191,7 @@ public function testClassTableInheritanceJoinWithConditionAppliesToBaseTable() { $this->assertSqlGeneration( 'SELECT e.id FROM Doctrine\Tests\Models\Company\CompanyOrganization o JOIN o.events e WITH e.id = ?1', - 'SELECT c0_.id AS id_0 FROM company_organizations c1_ INNER JOIN (company_events c0_ LEFT JOIN company_auctions c2_ ON c0_.id = c2_.id LEFT JOIN company_raffles c3_ ON c0_.id = c3_.id) ON c1_.id = c0_.org_id AND (c0_.id = ?)', + 'SELECT t0."id" AS c0 FROM "company_organizations" t1 INNER JOIN ("company_events" t0 LEFT JOIN "company_auctions" t2 ON t0."id" = t2."id" LEFT JOIN "company_raffles" t3 ON t0."id" = t3."id") ON t1."id" = t0."org_id" AND (t0."id" = ?)', [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -2174,7 +2204,7 @@ public function testSingleTableInheritanceLeftJoinWithCondition() // Regression test for the bug $this->assertSqlGeneration( 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyEmployee e LEFT JOIN Doctrine\Tests\Models\Company\CompanyContract c WITH c.salesPerson = e.id', - "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6 FROM company_employees c1_ INNER JOIN company_persons c2_ ON c1_.id = c2_.id LEFT JOIN company_contracts c0_ ON (c0_.salesPerson_id = c2_.id) AND c0_.discr IN ('fix', 'flexible', 'flexultra')" + 'SELECT t0."id" AS c0, t0."completed" AS c1, t0."fixPrice" AS c2, t0."hoursWorked" AS c3, t0."pricePerHour" AS c4, t0."maxPrice" AS c5, t0."discr" AS c6 FROM "company_employees" t1 INNER JOIN "company_persons" t2 ON t1."id" = t2."id" LEFT JOIN "company_contracts" t0 ON (t0."salesPerson_id" = t2."id") AND t0."discr" IN (\'fix\', \'flexible\', \'flexultra\')' ); } @@ -2186,7 +2216,7 @@ public function testSingleTableInheritanceLeftJoinWithConditionAndWhere() // Ensure other WHERE predicates are passed through to the main WHERE clause $this->assertSqlGeneration( 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyEmployee e LEFT JOIN Doctrine\Tests\Models\Company\CompanyContract c WITH c.salesPerson = e.id WHERE e.salary > 1000', - "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6 FROM company_employees c1_ INNER JOIN company_persons c2_ ON c1_.id = c2_.id LEFT JOIN company_contracts c0_ ON (c0_.salesPerson_id = c2_.id) AND c0_.discr IN ('fix', 'flexible', 'flexultra') WHERE c1_.salary > 1000" + 'SELECT t0."id" AS c0, t0."completed" AS c1, t0."fixPrice" AS c2, t0."hoursWorked" AS c3, t0."pricePerHour" AS c4, t0."maxPrice" AS c5, t0."discr" AS c6 FROM "company_employees" t1 INNER JOIN "company_persons" t2 ON t1."id" = t2."id" LEFT JOIN "company_contracts" t0 ON (t0."salesPerson_id" = t2."id") AND t0."discr" IN (\'fix\', \'flexible\', \'flexultra\') WHERE t1."salary" > 1000' ); } @@ -2198,7 +2228,7 @@ public function testSingleTableInheritanceInnerJoinWithCondition() // Test inner joins too $this->assertSqlGeneration( 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyEmployee e INNER JOIN Doctrine\Tests\Models\Company\CompanyContract c WITH c.salesPerson = e.id', - "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6 FROM company_employees c1_ INNER JOIN company_persons c2_ ON c1_.id = c2_.id INNER JOIN company_contracts c0_ ON (c0_.salesPerson_id = c2_.id) AND c0_.discr IN ('fix', 'flexible', 'flexultra')" + 'SELECT t0."id" AS c0, t0."completed" AS c1, t0."fixPrice" AS c2, t0."hoursWorked" AS c3, t0."pricePerHour" AS c4, t0."maxPrice" AS c5, t0."discr" AS c6 FROM "company_employees" t1 INNER JOIN "company_persons" t2 ON t1."id" = t2."id" INNER JOIN "company_contracts" t0 ON (t0."salesPerson_id" = t2."id") AND t0."discr" IN (\'fix\', \'flexible\', \'flexultra\')' ); } @@ -2211,7 +2241,7 @@ public function testSingleTableInheritanceLeftJoinNonAssociationWithConditionAnd // the where clause when not joining onto that table $this->assertSqlGeneration( 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c LEFT JOIN Doctrine\Tests\Models\Company\CompanyEmployee e WITH e.id = c.salesPerson WHERE c.completed = true', - "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6 FROM company_contracts c0_ LEFT JOIN company_employees c1_ INNER JOIN company_persons c2_ ON c1_.id = c2_.id ON (c2_.id = c0_.salesPerson_id) WHERE (c0_.completed = 1) AND c0_.discr IN ('fix', 'flexible', 'flexultra')" + 'SELECT t0."id" AS c0, t0."completed" AS c1, t0."fixPrice" AS c2, t0."hoursWorked" AS c3, t0."pricePerHour" AS c4, t0."maxPrice" AS c5, t0."discr" AS c6 FROM "company_contracts" t0 LEFT JOIN "company_employees" t1 INNER JOIN "company_persons" t2 ON t1."id" = t2."id" ON (t2."id" = t0."salesPerson_id") WHERE (t0."completed" = 1) AND t0."discr" IN (\'fix\', \'flexible\', \'flexultra\')' ); } @@ -2225,7 +2255,7 @@ public function testSingleTableInheritanceJoinCreatesOnCondition() // via a join association $this->assertSqlGeneration( 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c JOIN c.salesPerson s WHERE c.completed = true', - "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6 FROM company_contracts c0_ INNER JOIN company_employees c1_ ON c0_.salesPerson_id = c1_.id LEFT JOIN company_persons c2_ ON c1_.id = c2_.id WHERE (c0_.completed = 1) AND c0_.discr IN ('fix', 'flexible', 'flexultra')" + 'SELECT t0."id" AS c0, t0."completed" AS c1, t0."fixPrice" AS c2, t0."hoursWorked" AS c3, t0."pricePerHour" AS c4, t0."maxPrice" AS c5, t0."discr" AS c6 FROM "company_contracts" t0 INNER JOIN "company_employees" t1 ON t0."salesPerson_id" = t1."id" LEFT JOIN "company_persons" t2 ON t1."id" = t2."id" WHERE (t0."completed" = 1) AND t0."discr" IN (\'fix\', \'flexible\', \'flexultra\')' ); } @@ -2239,7 +2269,7 @@ public function testSingleTableInheritanceCreatesOnConditionAndWhere() // into the ON clause of the join $this->assertSqlGeneration( 'SELECT e, COUNT(c) FROM Doctrine\Tests\Models\Company\CompanyEmployee e JOIN e.contracts c WHERE e.department = :department', - "SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, COUNT(c2_.id) AS sclr_5, c0_.discr AS discr_6 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id INNER JOIN company_contract_employees c3_ ON c1_.id = c3_.employee_id INNER JOIN company_contracts c2_ ON c2_.id = c3_.contract_id AND c2_.discr IN ('fix', 'flexible', 'flexultra') WHERE c1_.department = ?", + 'SELECT t0."id" AS c0, t0."name" AS c1, t1."salary" AS c2, t1."department" AS c3, t1."startDate" AS c4, COUNT(t2."id") AS c5, t0."discr" AS c6 FROM "company_employees" t1 INNER JOIN "company_persons" t0 ON t1."id" = t0."id" INNER JOIN "company_contract_employees" t3 ON t1."id" = t3."employee_id" INNER JOIN "company_contracts" t2 ON t2."id" = t3."contract_id" AND t2."discr" IN (\'fix\', \'flexible\', \'flexultra\') WHERE t1."department" = ?', [], ['department' => 'foobar'] ); @@ -2252,7 +2282,7 @@ public function testHavingSupportResultVariableInExpression() { $this->assertSqlGeneration( 'SELECT u.name AS foo FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING foo IN (?1)', - 'SELECT c0_.name AS name_0 FROM cms_users c0_ HAVING name_0 IN (?)' + 'SELECT t0."name" AS c0 FROM "cms_users" t0 HAVING c0 IN (?)' ); } @@ -2262,8 +2292,8 @@ public function testHavingSupportResultVariableInExpression() public function testHavingSupportResultVariableLikeExpression() { $this->assertSqlGeneration( - "SELECT u.name AS foo FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING foo LIKE '3'", - "SELECT c0_.name AS name_0 FROM cms_users c0_ HAVING name_0 LIKE '3'" + 'SELECT u.name AS foo FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING foo LIKE \'3\'', + 'SELECT t0."name" AS c0 FROM "cms_users" t0 HAVING c0 LIKE \'3\'' ); } @@ -2273,8 +2303,8 @@ public function testHavingSupportResultVariableLikeExpression() public function testHavingSupportResultVariableNullComparisonExpression() { $this->assertSqlGeneration( - "SELECT u AS user, SUM(a.id) AS score FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN Doctrine\Tests\Models\CMS\CmsAddress a WITH a.user = u GROUP BY u HAVING score IS NOT NULL AND score >= 5", - "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, SUM(c1_.id) AS sclr_4 FROM cms_users c0_ LEFT JOIN cms_addresses c1_ ON (c1_.user_id = c0_.id) GROUP BY c0_.id, c0_.status, c0_.username, c0_.name, c0_.email_id HAVING sclr_4 IS NOT NULL AND sclr_4 >= 5" + 'SELECT u AS user, SUM(a.id) AS score FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN Doctrine\Tests\Models\CMS\CmsAddress a WITH a.user = u GROUP BY u HAVING score IS NOT NULL AND score >= 5', + 'SELECT t0."id" AS c0, t0."status" AS c1, t0."username" AS c2, t0."name" AS c3, SUM(t1."id") AS c4 FROM "cms_users" t0 LEFT JOIN "cms_addresses" t1 ON (t1."user_id" = t0."id") GROUP BY t0."id", t0."status", t0."username", t0."name", t0."email_id" HAVING c4 IS NOT NULL AND c4 >= 5' ); } @@ -2285,12 +2315,13 @@ public function testHavingSupportResultVariableInAggregateFunction() { $this->assertSqlGeneration( 'SELECT COUNT(u.name) AS countName FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING countName IS NULL', - 'SELECT COUNT(c0_.name) AS sclr_0 FROM cms_users c0_ HAVING sclr_0 IS NULL' + 'SELECT COUNT(t0."name") AS c0 FROM "cms_users" t0 HAVING c0 IS NULL' ); } /** * GitHub issue #4764: https://github.com/doctrine/doctrine2/issues/4764 + * * @group DDC-3907 * @dataProvider mathematicOperatorsProvider */ @@ -2298,7 +2329,7 @@ public function testHavingRegressionUsingVariableWithMathOperatorsExpression($op { $this->assertSqlGeneration( 'SELECT COUNT(u.name) AS countName FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING 1 ' . $operator . ' countName > 0', - 'SELECT COUNT(c0_.name) AS sclr_0 FROM cms_users c0_ HAVING 1 ' . $operator . ' sclr_0 > 0' + 'SELECT COUNT(t0."name") AS c0 FROM "cms_users" t0 HAVING 1 ' . $operator . ' c0 > 0' ); } @@ -2339,34 +2370,34 @@ public function parse(Parser $parser) } } /** - * @Entity + * @ORM\Entity */ class DDC1384Model { /** - * @Id - * @Column(type="integer") - * @GeneratedValue + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue */ protected $aVeryLongIdentifierThatShouldBeShortenedByTheSQLWalker_fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo; } /** - * @Entity + * @ORM\Entity */ class DDC1474Entity { /** - * @Id - * @Column(type="integer") - * @GeneratedValue() + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue() */ protected $id; /** - * @column(type="float") + * @ORM\Column(type="float") */ private $value; diff --git a/tests/Doctrine/Tests/ORM/Query/SqlWalkerTest.php b/tests/Doctrine/Tests/ORM/Query/SqlWalkerTest.php index e23ee0117f8..d9a4bfa3292 100644 --- a/tests/Doctrine/Tests/ORM/Query/SqlWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Query/SqlWalkerTest.php @@ -1,5 +1,7 @@ sqlWalker = new SqlWalker(new Query($this->_getTestEntityManager()), new ParserResult(), []); + $this->sqlWalker = new SqlWalker(new Query($this->getTestEntityManager()), new ParserResult(), []); } /** @@ -32,7 +34,7 @@ protected function setUp() */ public function testGetSQLTableAlias($tableName, $expectedAlias) { - $this->assertSame($expectedAlias, $this->sqlWalker->getSQLTableAlias($tableName)); + self::assertSame($expectedAlias, $this->sqlWalker->getSQLTableAlias($tableName)); } /** @@ -40,7 +42,7 @@ public function testGetSQLTableAlias($tableName, $expectedAlias) */ public function testGetSQLTableAliasIsSameForMultipleCalls($tableName) { - $this->assertSame( + self::assertSame( $this->sqlWalker->getSQLTableAlias($tableName), $this->sqlWalker->getSQLTableAlias($tableName) ); @@ -54,9 +56,9 @@ public function testGetSQLTableAliasIsSameForMultipleCalls($tableName) public function getColumnNamesAndSqlAliases() { return [ - ['aaaaa', 'a0_'], - ['table', 't0_'], - ['çtable', 't0_'], + ['aaaaa', 't0'], + ['table', 't0'], + ['çtable', 't0'], ]; } } diff --git a/tests/Doctrine/Tests/ORM/Query/UpdateSqlGenerationTest.php b/tests/Doctrine/Tests/ORM/Query/UpdateSqlGenerationTest.php index 7044929e940..8c02adfc037 100644 --- a/tests/Doctrine/Tests/ORM/Query/UpdateSqlGenerationTest.php +++ b/tests/Doctrine/Tests/ORM/Query/UpdateSqlGenerationTest.php @@ -1,5 +1,7 @@ - * @author Janne Vanhala - * @author Konsta Vesterinen - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link http://www.phpdoctrine.org - * @since 2.0 - * @version $Revision$ - * @todo 1) [romanb] We might want to split the SQL generation tests into multiple - * testcases later since we'll have a lot of them and we might want to have special SQL - * generation tests for some dbms specific SQL syntaxes. + * @author Guilherme Blanco + * @author Janne Vanhala + * @author Konsta Vesterinen + * @since 2.0 */ class UpdateSqlGenerationTest extends OrmTestCase { - private $_em; + private $em; protected function setUp() { if (DBALType::hasType('negative_to_positive')) { @@ -31,137 +27,140 @@ protected function setUp() { DBALType::addType('negative_to_positive', NegativeToPositiveType::class); } - $this->_em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); } public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed) { try { - $query = $this->_em->createQuery($dqlToBeTested); - parent::assertEquals($sqlToBeConfirmed, $query->getSql()); + $query = $this->em->createQuery($dqlToBeTested); + $sqlGenerated = $query->getSql(); + $query->free(); } catch (\Exception $e) { $this->fail($e->getMessage()); } + + self::assertEquals($sqlToBeConfirmed, $sqlGenerated); } public function testSupportsQueriesWithoutWhere() { - $this->assertSqlGeneration( + self::assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1', - 'UPDATE cms_users SET name = ?' + 'UPDATE "cms_users" SET "name" = ?' ); } public function testSupportsMultipleFieldsWithoutWhere() { - $this->assertSqlGeneration( + self::assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1, u.username = ?2', - 'UPDATE cms_users SET name = ?, username = ?' + 'UPDATE "cms_users" SET "name" = ?, "username" = ?' ); } public function testSupportsWhereClauses() { - $this->assertSqlGeneration( + self::assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.id = ?2', - 'UPDATE cms_users SET name = ? WHERE id = ?' + 'UPDATE "cms_users" SET "name" = ? WHERE "id" = ?' ); } public function testSupportsWhereClausesOnTheUpdatedField() { - $this->assertSqlGeneration( + self::assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.name = ?2', - 'UPDATE cms_users SET name = ? WHERE name = ?' + 'UPDATE "cms_users" SET "name" = ? WHERE "name" = ?' ); } public function testSupportsMultipleWhereClause() { - $this->assertSqlGeneration( + self::assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.name = ?2 AND u.status = ?3', - 'UPDATE cms_users SET name = ? WHERE name = ? AND status = ?' + 'UPDATE "cms_users" SET "name" = ? WHERE "name" = ? AND "status" = ?' ); } public function testSupportsInClause() { - $this->assertSqlGeneration( + self::assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.id IN (1, 3, 4)', - 'UPDATE cms_users SET name = ? WHERE id IN (1, 3, 4)' + 'UPDATE "cms_users" SET "name" = ? WHERE "id" IN (1, 3, 4)' ); } public function testSupportsParametrizedInClause() { - $this->assertSqlGeneration( + self::assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.id IN (?2, ?3, ?4)', - 'UPDATE cms_users SET name = ? WHERE id IN (?, ?, ?)' + 'UPDATE "cms_users" SET "name" = ? WHERE "id" IN (?, ?, ?)' ); } public function testSupportsNotInClause() { - $this->assertSqlGeneration( + self::assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.id NOT IN (1, 3, 4)', - 'UPDATE cms_users SET name = ? WHERE id NOT IN (1, 3, 4)' + 'UPDATE "cms_users" SET "name" = ? WHERE "id" NOT IN (1, 3, 4)' ); } public function testSupportsGreaterThanClause() { - $this->assertSqlGeneration( + self::assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = ?1 WHERE u.id > ?2', - 'UPDATE cms_users SET status = ? WHERE id > ?' + 'UPDATE "cms_users" SET "status" = ? WHERE "id" > ?' ); } public function testSupportsGreaterThanOrEqualToClause() { - $this->assertSqlGeneration( + self::assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = ?1 WHERE u.id >= ?2', - 'UPDATE cms_users SET status = ? WHERE id >= ?' + 'UPDATE "cms_users" SET "status" = ? WHERE "id" >= ?' ); } public function testSupportsLessThanClause() { - $this->assertSqlGeneration( + self::assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = ?1 WHERE u.id < ?2', - 'UPDATE cms_users SET status = ? WHERE id < ?' + 'UPDATE "cms_users" SET "status" = ? WHERE "id" < ?' ); } public function testSupportsLessThanOrEqualToClause() { - $this->assertSqlGeneration( + self::assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = ?1 WHERE u.id <= ?2', - 'UPDATE cms_users SET status = ? WHERE id <= ?' + 'UPDATE "cms_users" SET "status" = ? WHERE "id" <= ?' ); } public function testSupportsBetweenClause() { - $this->assertSqlGeneration( + self::assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = ?1 WHERE u.id BETWEEN :from AND :to', - 'UPDATE cms_users SET status = ? WHERE id BETWEEN ? AND ?' + 'UPDATE "cms_users" SET "status" = ? WHERE "id" BETWEEN ? AND ?' ); } public function testSingleValuedAssociationFieldInWhere() { - $this->assertSqlGeneration( - "UPDATE Doctrine\Tests\Models\CMS\CmsPhonenumber p SET p.phonenumber = 1234 WHERE p.user = ?1", - "UPDATE cms_phonenumbers SET phonenumber = 1234 WHERE user_id = ?" + self::assertSqlGeneration( + 'UPDATE Doctrine\Tests\Models\CMS\CmsPhonenumber p SET p.phonenumber = 1234 WHERE p.user = ?1', + 'UPDATE "cms_phonenumbers" SET "phonenumber" = 1234 WHERE "user_id" = ?' ); } public function testSingleValuedAssociationFieldInSetClause() { - $this->assertSqlGeneration( - "update Doctrine\Tests\Models\CMS\CmsComment c set c.article = null where c.article=?1", - "UPDATE cms_comments SET article_id = NULL WHERE article_id = ?" + self::assertSqlGeneration( + 'UPDATE Doctrine\Tests\Models\CMS\CmsComment c SET c.article = null WHERE c.article = ?1', + 'UPDATE "cms_comments" SET "article_id" = NULL WHERE "article_id" = ?' ); } @@ -170,25 +169,25 @@ public function testSingleValuedAssociationFieldInSetClause() */ public function testSubselectTableAliasReferencing() { - $this->assertSqlGeneration( - "UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = 'inactive' WHERE SIZE(u.groups) = 10", - "UPDATE cms_users SET status = 'inactive' WHERE (SELECT COUNT(*) FROM cms_users_groups c0_ WHERE c0_.user_id = cms_users.id) = 10" + self::assertSqlGeneration( + 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = \'inactive\' WHERE SIZE(u.groups) = 10', + 'UPDATE "cms_users" SET "status" = \'inactive\' WHERE (SELECT COUNT(*) FROM "cms_users_groups" t0 WHERE t0."user_id" = "cms_users"."id") = 10' ); } public function testCustomTypeValueSqlCompletelyIgnoredInUpdateStatements() { - $this->assertSqlGeneration( + self::assertSqlGeneration( 'UPDATE Doctrine\Tests\Models\CustomType\CustomTypeParent p SET p.customInteger = 1 WHERE p.id = 1', - 'UPDATE customtype_parents SET customInteger = 1 WHERE id = 1' + 'UPDATE "customtype_parents" SET "customInteger" = 1 WHERE "id" = 1' ); } public function testUpdateWithSubselectAsNewValue() { - $this->assertSqlGeneration( - "UPDATE Doctrine\Tests\Models\Company\CompanyFixContract fc SET fc.fixPrice = (SELECT ce2.salary FROM Doctrine\Tests\Models\Company\CompanyEmployee ce2 WHERE ce2.id = 2) WHERE fc.id = 1", - "UPDATE company_contracts SET fixPrice = (SELECT c0_.salary FROM company_employees c0_ INNER JOIN company_persons c1_ ON c0_.id = c1_.id LEFT JOIN company_managers c2_ ON c0_.id = c2_.id WHERE c1_.id = 2) WHERE (id = 1) AND discr IN ('fix')" + self::assertSqlGeneration( + 'UPDATE Doctrine\Tests\Models\Company\CompanyFixContract fc SET fc.fixPrice = (SELECT ce2.salary FROM Doctrine\Tests\Models\Company\CompanyEmployee ce2 WHERE ce2.id = 2) WHERE fc.id = 1', + 'UPDATE "company_contracts" SET "fixPrice" = (SELECT t0."salary" FROM "company_employees" t0 INNER JOIN "company_persons" t1 ON t0."id" = t1."id" LEFT JOIN "company_managers" t2 ON t0."id" = t2."id" WHERE t1."id" = 2) WHERE ("id" = 1) AND "discr" IN (\'fix\')' ); } } diff --git a/tests/Doctrine/Tests/ORM/QueryBuilderTest.php b/tests/Doctrine/Tests/ORM/QueryBuilderTest.php index 7da2c663caa..743bcd8f211 100644 --- a/tests/Doctrine/Tests/ORM/QueryBuilderTest.php +++ b/tests/Doctrine/Tests/ORM/QueryBuilderTest.php @@ -1,5 +1,7 @@ _em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); } protected function assertValidQueryBuilder(QueryBuilder $qb, $expectedDql) @@ -40,108 +42,108 @@ protected function assertValidQueryBuilder(QueryBuilder $qb, $expectedDql) $dql = $qb->getDQL(); $q = $qb->getQuery(); - $this->assertEquals($expectedDql, $dql); + self::assertEquals($expectedDql, $dql); } public function testSelectSetsType() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->delete(CmsUser::class, 'u') ->select('u.id', 'u.username'); - $this->assertEquals($qb->getType(), QueryBuilder::SELECT); + self::assertEquals($qb->getType(), QueryBuilder::SELECT); } public function testEmptySelectSetsType() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->delete(CmsUser::class, 'u') ->select(); - $this->assertEquals($qb->getType(), QueryBuilder::SELECT); + self::assertEquals($qb->getType(), QueryBuilder::SELECT); } public function testDeleteSetsType() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->from(CmsUser::class, 'u') ->delete(); - $this->assertEquals($qb->getType(), QueryBuilder::DELETE); + self::assertEquals($qb->getType(), QueryBuilder::DELETE); } public function testUpdateSetsType() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->from(CmsUser::class, 'u') ->update(); - $this->assertEquals($qb->getType(), QueryBuilder::UPDATE); + self::assertEquals($qb->getType(), QueryBuilder::UPDATE); } public function testSimpleSelect() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->from(CmsUser::class, 'u') ->select('u.id', 'u.username'); - $this->assertValidQueryBuilder($qb, 'SELECT u.id, u.username FROM Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertValidQueryBuilder($qb, 'SELECT u.id, u.username FROM Doctrine\Tests\Models\CMS\CmsUser u'); } public function testSimpleDelete() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->delete(CmsUser::class, 'u'); - $this->assertValidQueryBuilder($qb, 'DELETE Doctrine\Tests\Models\CMS\CmsUser u'); + self::assertValidQueryBuilder($qb, 'DELETE Doctrine\Tests\Models\CMS\CmsUser u'); } public function testSimpleSelectWithFromIndexBy() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->from(CmsUser::class, 'u', 'u.id') ->select('u.id', 'u.username'); - $this->assertValidQueryBuilder($qb, 'SELECT u.id, u.username FROM Doctrine\Tests\Models\CMS\CmsUser u INDEX BY u.id'); + self::assertValidQueryBuilder($qb, 'SELECT u.id, u.username FROM Doctrine\Tests\Models\CMS\CmsUser u INDEX BY u.id'); } public function testSimpleSelectWithIndexBy() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->from(CmsUser::class, 'u') ->indexBy('u', 'u.id') ->select('u.id', 'u.username'); - $this->assertValidQueryBuilder($qb, 'SELECT u.id, u.username FROM Doctrine\Tests\Models\CMS\CmsUser u INDEX BY u.id'); + self::assertValidQueryBuilder($qb, 'SELECT u.id, u.username FROM Doctrine\Tests\Models\CMS\CmsUser u INDEX BY u.id'); } public function testSimpleUpdate() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->update(CmsUser::class, 'u') ->set('u.username', ':username'); - $this->assertValidQueryBuilder($qb, 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.username = :username'); + self::assertValidQueryBuilder($qb, 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.username = :username'); } public function testInnerJoin() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u', 'a') ->from(CmsUser::class, 'u') ->innerJoin('u.articles', 'a'); - $this->assertValidQueryBuilder($qb, 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles a'); + self::assertValidQueryBuilder($qb, 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles a'); } public function testComplexInnerJoin() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u', 'a') ->from(CmsUser::class, 'u') ->innerJoin('u.articles', 'a', 'ON', 'u.id = a.author_id'); - $this->assertValidQueryBuilder( + self::assertValidQueryBuilder( $qb, 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles a ON u.id = a.author_id' ); @@ -149,12 +151,12 @@ public function testComplexInnerJoin() public function testComplexInnerJoinWithIndexBy() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u', 'a') ->from(CmsUser::class, 'u') ->innerJoin('u.articles', 'a', 'ON', 'u.id = a.author_id', 'a.name'); - $this->assertValidQueryBuilder( + self::assertValidQueryBuilder( $qb, 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles a INDEX BY a.name ON u.id = a.author_id' ); @@ -162,59 +164,59 @@ public function testComplexInnerJoinWithIndexBy() public function testLeftJoin() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u', 'a') ->from(CmsUser::class, 'u') ->leftJoin('u.articles', 'a'); - $this->assertValidQueryBuilder($qb, 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a'); + self::assertValidQueryBuilder($qb, 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a'); } public function testLeftJoinWithIndexBy() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u', 'a') ->from(CmsUser::class, 'u') ->leftJoin('u.articles', 'a', null, null, 'a.name'); - $this->assertValidQueryBuilder($qb, 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a INDEX BY a.name'); + self::assertValidQueryBuilder($qb, 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a INDEX BY a.name'); } public function testMultipleFrom() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u', 'g') ->from(CmsUser::class, 'u') ->from(CmsGroup::class, 'g'); - $this->assertValidQueryBuilder($qb, 'SELECT u, g FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsGroup g'); + self::assertValidQueryBuilder($qb, 'SELECT u, g FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsGroup g'); } public function testMultipleFromWithIndexBy() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u', 'g') ->from(CmsUser::class, 'u') ->from(CmsGroup::class, 'g') ->indexBy('g', 'g.id'); - $this->assertValidQueryBuilder($qb, 'SELECT u, g FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsGroup g INDEX BY g.id'); + self::assertValidQueryBuilder($qb, 'SELECT u, g FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsGroup g INDEX BY g.id'); } public function testMultipleFromWithJoin() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u', 'g') ->from(CmsUser::class, 'u') ->from(CmsGroup::class, 'g') ->innerJoin('u.articles', 'a', 'ON', 'u.id = a.author_id'); - $this->assertValidQueryBuilder($qb, 'SELECT u, g FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles a ON u.id = a.author_id, Doctrine\Tests\Models\CMS\CmsGroup g'); + self::assertValidQueryBuilder($qb, 'SELECT u, g FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles a ON u.id = a.author_id, Doctrine\Tests\Models\CMS\CmsGroup g'); } public function testMultipleFromWithMultipleJoin() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u', 'g') ->from(CmsUser::class, 'u') ->from(CmsArticle::class, 'a') @@ -222,55 +224,55 @@ public function testMultipleFromWithMultipleJoin() ->leftJoin('u.address', 'ad') ->innerJoin('a.comments', 'c'); - $this->assertValidQueryBuilder($qb, 'SELECT u, g FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.groups g LEFT JOIN u.address ad, Doctrine\Tests\Models\CMS\CmsArticle a INNER JOIN a.comments c'); + self::assertValidQueryBuilder($qb, 'SELECT u, g FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.groups g LEFT JOIN u.address ad, Doctrine\Tests\Models\CMS\CmsArticle a INNER JOIN a.comments c'); } public function testWhere() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->where('u.id = :uid'); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid'); } public function testComplexAndWhere() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->where('u.id = :uid OR u.id = :uid2 OR u.id = :uid3') ->andWhere('u.name = :name'); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE (u.id = :uid OR u.id = :uid2 OR u.id = :uid3) AND u.name = :name'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE (u.id = :uid OR u.id = :uid2 OR u.id = :uid3) AND u.name = :name'); } public function testAndWhere() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->where('u.id = :uid') ->andWhere('u.id = :uid2'); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid AND u.id = :uid2'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid AND u.id = :uid2'); } public function testOrWhere() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->where('u.id = :uid') ->orWhere('u.id = :uid2'); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid OR u.id = :uid2'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid OR u.id = :uid2'); } public function testComplexAndWhereOrWhereNesting() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') ->where('u.id = :uid') @@ -279,90 +281,90 @@ public function testComplexAndWhereOrWhereNesting() ->orWhere('u.name = :name1', 'u.name = :name2') ->andWhere('u.name <> :noname'); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE (((u.id = :uid OR u.id = :uid2) AND u.id = :uid3) OR u.name = :name1 OR u.name = :name2) AND u.name <> :noname'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE (((u.id = :uid OR u.id = :uid2) AND u.id = :uid3) OR u.name = :name1 OR u.name = :name2) AND u.name <> :noname'); } public function testAndWhereIn() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') ->where('u.id = :uid') ->andWhere($qb->expr()->in('u.id', [1, 2, 3])); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid AND u.id IN(1, 2, 3)'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid AND u.id IN(1, 2, 3)'); } public function testOrWhereIn() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') ->where('u.id = :uid') ->orWhere($qb->expr()->in('u.id', [1, 2, 3])); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid OR u.id IN(1, 2, 3)'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid OR u.id IN(1, 2, 3)'); } public function testAndWhereNotIn() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') ->where('u.id = :uid') ->andWhere($qb->expr()->notIn('u.id', [1, 2, 3])); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid AND u.id NOT IN(1, 2, 3)'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid AND u.id NOT IN(1, 2, 3)'); } public function testOrWhereNotIn() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') ->where('u.id = :uid') ->orWhere($qb->expr()->notIn('u.id', [1, 2, 3])); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid OR u.id NOT IN(1, 2, 3)'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid OR u.id NOT IN(1, 2, 3)'); } public function testGroupBy() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->groupBy('u.id') ->addGroupBy('u.username'); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u.id, u.username'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u.id, u.username'); } public function testHaving() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->groupBy('u.id') ->having('COUNT(u.id) > 1'); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u.id HAVING COUNT(u.id) > 1'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u.id HAVING COUNT(u.id) > 1'); } public function testAndHaving() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->groupBy('u.id') ->having('COUNT(u.id) > 1') ->andHaving('COUNT(u.id) < 1'); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u.id HAVING COUNT(u.id) > 1 AND COUNT(u.id) < 1'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u.id HAVING COUNT(u.id) > 1 AND COUNT(u.id) < 1'); } public function testOrHaving() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->groupBy('u.id') @@ -370,54 +372,54 @@ public function testOrHaving() ->andHaving('COUNT(u.id) < 1') ->orHaving('COUNT(u.id) > 1'); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u.id HAVING (COUNT(u.id) > 1 AND COUNT(u.id) < 1) OR COUNT(u.id) > 1'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u.id HAVING (COUNT(u.id) > 1 AND COUNT(u.id) < 1) OR COUNT(u.id) > 1'); } public function testOrderBy() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->orderBy('u.username', 'ASC'); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username ASC'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username ASC'); } public function testOrderByWithExpression() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') ->orderBy($qb->expr()->asc('u.username')); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username ASC'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username ASC'); } public function testAddOrderBy() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->orderBy('u.username', 'ASC') ->addOrderBy('u.username', 'DESC'); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username ASC, u.username DESC'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username ASC, u.username DESC'); } public function testAddOrderByWithExpression() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') ->orderBy('u.username', 'ASC') ->addOrderBy($qb->expr()->desc('u.username')); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username ASC, u.username DESC'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username ASC, u.username DESC'); } public function testAddCriteriaWhere() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u'); @@ -426,13 +428,13 @@ public function testAddCriteriaWhere() $qb->addCriteria($criteria); - $this->assertEquals('u.field = :field', (string) $qb->getDQLPart('where')); - $this->assertNotNull($qb->getParameter('field')); + self::assertEquals('u.field = :field', (string) $qb->getDQLPart('where')); + self::assertNotNull($qb->getParameter('field')); } public function testAddMultipleSameCriteriaWhere() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('alias1')->from(CmsUser::class, 'alias1'); $criteria = new Criteria(); @@ -443,9 +445,9 @@ public function testAddMultipleSameCriteriaWhere() $qb->addCriteria($criteria); - $this->assertEquals('alias1.field = :field AND alias1.field = :field_1', (string) $qb->getDQLPart('where')); - $this->assertNotNull($qb->getParameter('field')); - $this->assertNotNull($qb->getParameter('field_1')); + self::assertEquals('alias1.field = :field AND alias1.field = :field_1', (string) $qb->getDQLPart('where')); + self::assertNotNull($qb->getParameter('field')); + self::assertNotNull($qb->getParameter('field_1')); } /** @@ -453,7 +455,7 @@ public function testAddMultipleSameCriteriaWhere() */ public function testAddCriteriaWhereWithMultipleParametersWithSameField() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('alias1')->from(CmsUser::class, 'alias1'); $criteria = new Criteria(); @@ -462,9 +464,9 @@ public function testAddCriteriaWhereWithMultipleParametersWithSameField() $qb->addCriteria($criteria); - $this->assertEquals('alias1.field = :field AND alias1.field > :field_1', (string) $qb->getDQLPart('where')); - $this->assertSame('value1', $qb->getParameter('field')->getValue()); - $this->assertSame('value2', $qb->getParameter('field_1')->getValue()); + self::assertEquals('alias1.field = :field AND alias1.field > :field_1', (string) $qb->getDQLPart('where')); + self::assertSame('value1', $qb->getParameter('field')->getValue()); + self::assertSame('value2', $qb->getParameter('field_1')->getValue()); } /** @@ -472,7 +474,7 @@ public function testAddCriteriaWhereWithMultipleParametersWithSameField() */ public function testAddCriteriaWhereWithMultipleParametersWithDifferentFields() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('alias1')->from(CmsUser::class, 'alias1'); $criteria = new Criteria(); @@ -481,9 +483,9 @@ public function testAddCriteriaWhereWithMultipleParametersWithDifferentFields() $qb->addCriteria($criteria); - $this->assertEquals('alias1.field1 = :field1 AND alias1.field2 > :field2', (string) $qb->getDQLPart('where')); - $this->assertSame('value1', $qb->getParameter('field1')->getValue()); - $this->assertSame('value2', $qb->getParameter('field2')->getValue()); + self::assertEquals('alias1.field1 = :field1 AND alias1.field2 > :field2', (string) $qb->getDQLPart('where')); + self::assertSame('value1', $qb->getParameter('field1')->getValue()); + self::assertSame('value2', $qb->getParameter('field2')->getValue()); } /** @@ -491,7 +493,7 @@ public function testAddCriteriaWhereWithMultipleParametersWithDifferentFields() */ public function testAddCriteriaWhereWithMultipleParametersWithSubpathsAndDifferentProperties() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('alias1')->from(CmsUser::class, 'alias1'); $criteria = new Criteria(); @@ -500,9 +502,9 @@ public function testAddCriteriaWhereWithMultipleParametersWithSubpathsAndDiffere $qb->addCriteria($criteria); - $this->assertEquals('alias1.field1 = :field1 AND alias1.field2 > :field2', (string) $qb->getDQLPart('where')); - $this->assertSame('value1', $qb->getParameter('field1')->getValue()); - $this->assertSame('value2', $qb->getParameter('field2')->getValue()); + self::assertEquals('alias1.field1 = :field1 AND alias1.field2 > :field2', (string) $qb->getDQLPart('where')); + self::assertSame('value1', $qb->getParameter('field1')->getValue()); + self::assertSame('value2', $qb->getParameter('field2')->getValue()); } /** @@ -510,7 +512,7 @@ public function testAddCriteriaWhereWithMultipleParametersWithSubpathsAndDiffere */ public function testAddCriteriaWhereWithMultipleParametersWithSubpathsAndSameProperty() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('alias1')->from(CmsUser::class, 'alias1'); $criteria = new Criteria(); @@ -519,14 +521,14 @@ public function testAddCriteriaWhereWithMultipleParametersWithSubpathsAndSamePro $qb->addCriteria($criteria); - $this->assertEquals('alias1.field1 = :field1 AND alias1.field1 > :field1_1', (string) $qb->getDQLPart('where')); - $this->assertSame('value1', $qb->getParameter('field1')->getValue()); - $this->assertSame('value2', $qb->getParameter('field1_1')->getValue()); + self::assertEquals('alias1.field1 = :field1 AND alias1.field1 > :field1_1', (string) $qb->getDQLPart('where')); + self::assertSame('value1', $qb->getParameter('field1')->getValue()); + self::assertSame('value2', $qb->getParameter('field1_1')->getValue()); } public function testAddCriteriaOrder() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u'); @@ -535,8 +537,8 @@ public function testAddCriteriaOrder() $qb->addCriteria($criteria); - $this->assertCount(1, $orderBy = $qb->getDQLPart('orderBy')); - $this->assertEquals('u.field DESC', (string) $orderBy[0]); + self::assertCount(1, $orderBy = $qb->getDQLPart('orderBy')); + self::assertEquals('u.field DESC', (string) $orderBy[0]); } /** @@ -544,7 +546,7 @@ public function testAddCriteriaOrder() */ public function testAddCriteriaOrderOnJoinAlias() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') ->join('u.article','a'); @@ -554,13 +556,13 @@ public function testAddCriteriaOrderOnJoinAlias() $qb->addCriteria($criteria); - $this->assertCount(1, $orderBy = $qb->getDQLPart('orderBy')); - $this->assertEquals('a.field DESC', (string) $orderBy[0]); + self::assertCount(1, $orderBy = $qb->getDQLPart('orderBy')); + self::assertEquals('a.field DESC', (string) $orderBy[0]); } public function testAddCriteriaLimit() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u'); @@ -570,13 +572,13 @@ public function testAddCriteriaLimit() $qb->addCriteria($criteria); - $this->assertEquals(2, $qb->getFirstResult()); - $this->assertEquals(10, $qb->getMaxResults()); + self::assertEquals(2, $qb->getFirstResult()); + self::assertEquals(10, $qb->getMaxResults()); } public function testAddCriteriaUndefinedLimit() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') ->setFirstResult(2) @@ -586,23 +588,23 @@ public function testAddCriteriaUndefinedLimit() $qb->addCriteria($criteria); - $this->assertEquals(2, $qb->getFirstResult()); - $this->assertEquals(10, $qb->getMaxResults()); + self::assertEquals(2, $qb->getFirstResult()); + self::assertEquals(10, $qb->getMaxResults()); } public function testGetQuery() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u'); $q = $qb->getQuery(); - $this->assertEquals(Query::class, get_class($q)); + self::assertEquals(Query::class, get_class($q)); } public function testSetParameter() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->where('u.id = :id') @@ -610,12 +612,12 @@ public function testSetParameter() $parameter = new Parameter('id', 1, ParameterTypeInferer::inferType(1)); - $this->assertEquals($parameter, $qb->getParameter('id')); + self::assertEquals($parameter, $qb->getParameter('id')); } public function testSetParameters() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') ->where($qb->expr()->orX('u.username = :username', 'u.username = :username2')); @@ -626,13 +628,13 @@ public function testSetParameters() $qb->setParameters($parameters); - $this->assertEquals($parameters, $qb->getQuery()->getParameters()); + self::assertEquals($parameters, $qb->getQuery()->getParameters()); } public function testGetParameters() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') ->where('u.id = :id'); @@ -642,12 +644,12 @@ public function testGetParameters() $qb->setParameters($parameters); - $this->assertEquals($parameters, $qb->getParameters()); + self::assertEquals($parameters, $qb->getParameters()); } public function testGetParameter() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->where('u.id = :id'); @@ -657,42 +659,42 @@ public function testGetParameter() $qb->setParameters($parameters); - $this->assertEquals($parameters->first(), $qb->getParameter('id')); + self::assertEquals($parameters->first(), $qb->getParameter('id')); } public function testMultipleWhere() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->where('u.id = :uid', 'u.id = :uid2'); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid AND u.id = :uid2'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid AND u.id = :uid2'); } public function testMultipleAndWhere() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->andWhere('u.id = :uid', 'u.id = :uid2'); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid AND u.id = :uid2'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid AND u.id = :uid2'); } public function testMultipleOrWhere() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') ->orWhere('u.id = :uid', $qb->expr()->eq('u.id', ':uid2')); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid OR u.id = :uid2'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid OR u.id = :uid2'); } public function testComplexWhere() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $orExpr = $qb->expr()->orX(); $orExpr->add($qb->expr()->eq('u.id', ':uid3')); $orExpr->add($qb->expr()->in('u.id', [1])); @@ -701,70 +703,70 @@ public function testComplexWhere() ->from(CmsUser::class, 'u') ->where($orExpr); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid3 OR u.id IN(1)'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid3 OR u.id IN(1)'); } public function testWhereInWithStringLiterals() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') ->where($qb->expr()->in('u.name', ['one', 'two', 'three'])); - $this->assertValidQueryBuilder($qb, "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IN('one', 'two', 'three')"); + self::assertValidQueryBuilder($qb, "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IN('one', 'two', 'three')"); $qb->where($qb->expr()->in('u.name', ["O'Reilly", "O'Neil", 'Smith'])); - $this->assertValidQueryBuilder($qb, "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IN('O''Reilly', 'O''Neil', 'Smith')"); + self::assertValidQueryBuilder($qb, "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IN('O''Reilly', 'O''Neil', 'Smith')"); } public function testWhereInWithObjectLiterals() { - $qb = $this->_em->createQueryBuilder(); - $expr = $this->_em->getExpressionBuilder(); + $qb = $this->em->createQueryBuilder(); + $expr = $this->em->getExpressionBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') ->where($expr->in('u.name', [$expr->literal('one'), $expr->literal('two'), $expr->literal('three')])); - $this->assertValidQueryBuilder($qb, "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IN('one', 'two', 'three')"); + self::assertValidQueryBuilder($qb, "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IN('one', 'two', 'three')"); $qb->where($expr->in('u.name', [$expr->literal("O'Reilly"), $expr->literal("O'Neil"), $expr->literal('Smith')])); - $this->assertValidQueryBuilder($qb, "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IN('O''Reilly', 'O''Neil', 'Smith')"); + self::assertValidQueryBuilder($qb, "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IN('O''Reilly', 'O''Neil', 'Smith')"); } public function testNegation() { - $expr = $this->_em->getExpressionBuilder(); + $expr = $this->em->getExpressionBuilder(); $orExpr = $expr->orX(); $orExpr->add($expr->eq('u.id', ':uid3')); $orExpr->add($expr->not($expr->in('u.id', [1]))); - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') ->where($orExpr); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid3 OR NOT(u.id IN(1))'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid3 OR NOT(u.id IN(1))'); } public function testSomeAllAny() { - $qb = $this->_em->createQueryBuilder(); - $expr = $this->_em->getExpressionBuilder(); + $qb = $this->em->createQueryBuilder(); + $expr = $this->em->getExpressionBuilder(); $qb->select('u') ->from(CmsUser::class, 'u') ->where($expr->gt('u.id', $expr->all('select a.id from Doctrine\Tests\Models\CMS\CmsArticle a'))); - $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id > ALL(select a.id from Doctrine\Tests\Models\CMS\CmsArticle a)'); + self::assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id > ALL(select a.id from Doctrine\Tests\Models\CMS\CmsArticle a)'); } public function testMultipleIsolatedQueryConstruction() { - $qb = $this->_em->createQueryBuilder(); - $expr = $this->_em->getExpressionBuilder(); + $qb = $this->em->createQueryBuilder(); + $expr = $this->em->getExpressionBuilder(); $qb->select('u')->from(CmsUser::class, 'u'); $qb->where($expr->eq('u.name', ':name')); @@ -772,8 +774,8 @@ public function testMultipleIsolatedQueryConstruction() $q1 = $qb->getQuery(); - $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = :name', $q1->getDQL()); - $this->assertEquals(1, count($q1->getParameters())); + self::assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = :name', $q1->getDQL()); + self::assertEquals(1, count($q1->getParameters())); // add another condition and construct a second query $qb->andWhere($expr->eq('u.id', ':id')); @@ -781,84 +783,84 @@ public function testMultipleIsolatedQueryConstruction() $q2 = $qb->getQuery(); - $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = :name AND u.id = :id', $q2->getDQL()); - $this->assertTrue($q1 !== $q2); // two different, independent queries - $this->assertEquals(2, count($q2->getParameters())); - $this->assertEquals(1, count($q1->getParameters())); // $q1 unaffected + self::assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = :name AND u.id = :id', $q2->getDQL()); + self::assertTrue($q1 !== $q2); // two different, independent queries + self::assertEquals(2, count($q2->getParameters())); + self::assertEquals(1, count($q1->getParameters())); // $q1 unaffected } public function testGetEntityManager() { - $qb = $this->_em->createQueryBuilder(); - $this->assertEquals($this->_em, $qb->getEntityManager()); + $qb = $this->em->createQueryBuilder(); + self::assertEquals($this->em, $qb->getEntityManager()); } public function testInitialStateIsClean() { - $qb = $this->_em->createQueryBuilder(); - $this->assertEquals(QueryBuilder::STATE_CLEAN, $qb->getState()); + $qb = $this->em->createQueryBuilder(); + self::assertEquals(QueryBuilder::STATE_CLEAN, $qb->getState()); } public function testAlteringQueryChangesStateToDirty() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u'); - $this->assertEquals(QueryBuilder::STATE_DIRTY, $qb->getState()); + self::assertEquals(QueryBuilder::STATE_DIRTY, $qb->getState()); } public function testSelectWithFuncExpression() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $expr = $qb->expr(); $qb->select($expr->count('e.id')); - $this->assertValidQueryBuilder($qb, 'SELECT COUNT(e.id)'); + self::assertValidQueryBuilder($qb, 'SELECT COUNT(e.id)'); } public function testResetDQLPart() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->where('u.username = ?1')->orderBy('u.username'); - $this->assertEquals('u.username = ?1', (string)$qb->getDQLPart('where')); - $this->assertEquals(1, count($qb->getDQLPart('orderBy'))); + self::assertEquals('u.username = ?1', (string)$qb->getDQLPart('where')); + self::assertEquals(1, count($qb->getDQLPart('orderBy'))); $qb->resetDQLPart('where')->resetDQLPart('orderBy'); - $this->assertNull($qb->getDQLPart('where')); - $this->assertEquals(0, count($qb->getDQLPart('orderBy'))); + self::assertNull($qb->getDQLPart('where')); + self::assertEquals(0, count($qb->getDQLPart('orderBy'))); } public function testResetDQLParts() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->where('u.username = ?1')->orderBy('u.username'); $qb->resetDQLParts(['where', 'orderBy']); - $this->assertEquals(1, count($qb->getDQLPart('select'))); - $this->assertNull($qb->getDQLPart('where')); - $this->assertEquals(0, count($qb->getDQLPart('orderBy'))); + self::assertEquals(1, count($qb->getDQLPart('select'))); + self::assertNull($qb->getDQLPart('where')); + self::assertEquals(0, count($qb->getDQLPart('orderBy'))); } public function testResetAllDQLParts() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->where('u.username = ?1')->orderBy('u.username'); $qb->resetDQLParts(); - $this->assertEquals(0, count($qb->getDQLPart('select'))); - $this->assertNull($qb->getDQLPart('where')); - $this->assertEquals(0, count($qb->getDQLPart('orderBy'))); + self::assertEquals(0, count($qb->getDQLPart('select'))); + self::assertNull($qb->getDQLPart('where')); + self::assertEquals(0, count($qb->getDQLPart('orderBy'))); } /** @@ -866,19 +868,19 @@ public function testResetAllDQLParts() */ public function testDeepClone() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->andWhere('u.username = ?1') ->andWhere('u.status = ?2'); $expr = $qb->getDQLPart('where'); - $this->assertEquals(2, $expr->count(), "Modifying the second query should affect the first one."); + self::assertEquals(2, $expr->count(), "Modifying the second query should affect the first one."); $qb2 = clone $qb; $qb2->andWhere('u.name = ?3'); - $this->assertEquals(2, $expr->count(), "Modifying the second query should affect the first one."); + self::assertEquals(2, $expr->count(), "Modifying the second query should affect the first one."); } /** @@ -886,7 +888,7 @@ public function testDeepClone() */ public function testAddCriteriaWhereWithJoinAlias() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('alias1')->from(CmsUser::class, 'alias1'); $qb->join('alias1.articles','alias2'); @@ -896,9 +898,9 @@ public function testAddCriteriaWhereWithJoinAlias() $qb->addCriteria($criteria); - $this->assertEquals('alias1.field = :field AND alias2.field > :alias2_field', (string) $qb->getDQLPart('where')); - $this->assertSame('value1', $qb->getParameter('field')->getValue()); - $this->assertSame('value2', $qb->getParameter('alias2_field')->getValue()); + self::assertEquals('alias1.field = :field AND alias2.field > :alias2_field', (string) $qb->getDQLPart('where')); + self::assertSame('value1', $qb->getParameter('field')->getValue()); + self::assertSame('value2', $qb->getParameter('alias2_field')->getValue()); } /** @@ -906,7 +908,7 @@ public function testAddCriteriaWhereWithJoinAlias() */ public function testAddCriteriaWhereWithDefaultAndJoinAlias() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('alias1')->from(CmsUser::class, 'alias1'); $qb->join('alias1.articles','alias2'); @@ -916,9 +918,9 @@ public function testAddCriteriaWhereWithDefaultAndJoinAlias() $qb->addCriteria($criteria); - $this->assertEquals('alias1.field = :alias1_field AND alias2.field > :alias2_field', (string) $qb->getDQLPart('where')); - $this->assertSame('value1', $qb->getParameter('alias1_field')->getValue()); - $this->assertSame('value2', $qb->getParameter('alias2_field')->getValue()); + self::assertEquals('alias1.field = :alias1_field AND alias2.field > :alias2_field', (string) $qb->getDQLPart('where')); + self::assertSame('value1', $qb->getParameter('alias1_field')->getValue()); + self::assertSame('value2', $qb->getParameter('alias2_field')->getValue()); } /** @@ -926,7 +928,7 @@ public function testAddCriteriaWhereWithDefaultAndJoinAlias() */ public function testAddCriteriaWhereOnJoinAliasWithDuplicateFields() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('alias1')->from(CmsUser::class, 'alias1'); $qb->join('alias1.articles','alias2'); @@ -937,10 +939,10 @@ public function testAddCriteriaWhereOnJoinAliasWithDuplicateFields() $qb->addCriteria($criteria); - $this->assertEquals('(alias1.field = :alias1_field AND alias2.field > :alias2_field) AND alias2.field < :alias2_field_2', (string) $qb->getDQLPart('where')); - $this->assertSame('value1', $qb->getParameter('alias1_field')->getValue()); - $this->assertSame('value2', $qb->getParameter('alias2_field')->getValue()); - $this->assertSame('value3', $qb->getParameter('alias2_field_2')->getValue()); + self::assertEquals('(alias1.field = :alias1_field AND alias2.field > :alias2_field) AND alias2.field < :alias2_field_2', (string) $qb->getDQLPart('where')); + self::assertSame('value1', $qb->getParameter('alias1_field')->getValue()); + self::assertSame('value2', $qb->getParameter('alias2_field')->getValue()); + self::assertSame('value3', $qb->getParameter('alias2_field_2')->getValue()); } @@ -949,64 +951,64 @@ public function testAddCriteriaWhereOnJoinAliasWithDuplicateFields() */ public function testParametersAreCloned() { - $originalQb = new QueryBuilder($this->_em); + $originalQb = new QueryBuilder($this->em); $originalQb->setParameter('parameter1', 'value1'); $copy = clone $originalQb; $copy->setParameter('parameter2', 'value2'); - $this->assertCount(1, $originalQb->getParameters()); - $this->assertSame('value1', $copy->getParameter('parameter1')->getValue()); - $this->assertSame('value2', $copy->getParameter('parameter2')->getValue()); + self::assertCount(1, $originalQb->getParameters()); + self::assertSame('value1', $copy->getParameter('parameter1')->getValue()); + self::assertSame('value2', $copy->getParameter('parameter2')->getValue()); } public function testGetRootAlias() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u'); - $this->assertEquals('u', $qb->getRootAlias()); + self::assertEquals('u', $qb->getRootAlias()); } public function testGetRootAliases() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u'); - $this->assertEquals(['u'], $qb->getRootAliases()); + self::assertEquals(['u'], $qb->getRootAliases()); } public function testGetRootEntities() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u'); - $this->assertEquals([CmsUser::class], $qb->getRootEntities()); + self::assertEquals([CmsUser::class], $qb->getRootEntities()); } public function testGetSeveralRootAliases() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->from(CmsUser::class, 'u2'); - $this->assertEquals(['u', 'u2'], $qb->getRootAliases()); - $this->assertEquals('u', $qb->getRootAlias()); + self::assertEquals(['u', 'u2'], $qb->getRootAliases()); + self::assertEquals('u', $qb->getRootAlias()); } public function testBCAddJoinWithoutRootAlias() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->add('join', ['INNER JOIN u.groups g'], true); - $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.groups g', $qb->getDQL()); + self::assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.groups g', $qb->getDQL()); } /** @@ -1014,13 +1016,13 @@ public function testBCAddJoinWithoutRootAlias() */ public function testEmptyStringLiteral() { - $expr = $this->_em->getExpressionBuilder(); - $qb = $this->_em->createQueryBuilder() + $expr = $this->em->getExpressionBuilder(); + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->where($expr->eq('u.username', $expr->literal(""))); - $this->assertEquals("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = ''", $qb->getDQL()); + self::assertEquals("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = ''", $qb->getDQL()); } /** @@ -1028,13 +1030,13 @@ public function testEmptyStringLiteral() */ public function testEmptyNumericLiteral() { - $expr = $this->_em->getExpressionBuilder(); - $qb = $this->_em->createQueryBuilder() + $expr = $this->em->getExpressionBuilder(); + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->where($expr->eq('u.username', $expr->literal(0))); - $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 0', $qb->getDQL()); + self::assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 0', $qb->getDQL()); } /** @@ -1042,11 +1044,11 @@ public function testEmptyNumericLiteral() */ public function testAddFromString() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->add('select', 'u') ->add('from', CmsUser::class . ' u'); - $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $qb->getDQL()); + self::assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $qb->getDQL()); } /** @@ -1054,12 +1056,12 @@ public function testAddFromString() */ public function testAddDistinct() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->distinct() ->from(CmsUser::class, 'u'); - $this->assertEquals('SELECT DISTINCT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $qb->getDQL()); + self::assertEquals('SELECT DISTINCT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $qb->getDQL()); } /** @@ -1070,7 +1072,7 @@ public function testWhereAppend() $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage("Using \$append = true does not have an effect with 'where' or 'having' parts. See QueryBuilder#andWhere() for an example for correct usage."); - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->add('where', 'u.foo = ?1') ->add('where', 'u.bar = ?2', true) ; @@ -1078,23 +1080,23 @@ public function testWhereAppend() public function testSecondLevelCacheQueryBuilderOptions() { - $defaultQueryBuilder = $this->_em->createQueryBuilder() + $defaultQueryBuilder = $this->em->createQueryBuilder() ->select('s') ->from(State::class, 's'); - $this->assertFalse($defaultQueryBuilder->isCacheable()); - $this->assertEquals(0, $defaultQueryBuilder->getLifetime()); - $this->assertNull($defaultQueryBuilder->getCacheRegion()); - $this->assertNull($defaultQueryBuilder->getCacheMode()); + self::assertFalse($defaultQueryBuilder->isCacheable()); + self::assertEquals(0, $defaultQueryBuilder->getLifetime()); + self::assertNull($defaultQueryBuilder->getCacheRegion()); + self::assertNull($defaultQueryBuilder->getCacheMode()); $defaultQuery = $defaultQueryBuilder->getQuery(); - $this->assertFalse($defaultQuery->isCacheable()); - $this->assertEquals(0, $defaultQuery->getLifetime()); - $this->assertNull($defaultQuery->getCacheRegion()); - $this->assertNull($defaultQuery->getCacheMode()); + self::assertFalse($defaultQuery->isCacheable()); + self::assertEquals(0, $defaultQuery->getLifetime()); + self::assertNull($defaultQuery->getCacheRegion()); + self::assertNull($defaultQuery->getCacheMode()); - $builder = $this->_em->createQueryBuilder() + $builder = $this->em->createQueryBuilder() ->select('s') ->setLifetime(123) ->setCacheable(true) @@ -1102,17 +1104,17 @@ public function testSecondLevelCacheQueryBuilderOptions() ->setCacheMode(Cache::MODE_REFRESH) ->from(State::class, 's'); - $this->assertTrue($builder->isCacheable()); - $this->assertEquals(123, $builder->getLifetime()); - $this->assertEquals('foo_reg', $builder->getCacheRegion()); - $this->assertEquals(Cache::MODE_REFRESH, $builder->getCacheMode()); + self::assertTrue($builder->isCacheable()); + self::assertEquals(123, $builder->getLifetime()); + self::assertEquals('foo_reg', $builder->getCacheRegion()); + self::assertEquals(Cache::MODE_REFRESH, $builder->getCacheMode()); $query = $builder->getQuery(); - $this->assertTrue($query->isCacheable()); - $this->assertEquals(123, $query->getLifetime()); - $this->assertEquals('foo_reg', $query->getCacheRegion()); - $this->assertEquals(Cache::MODE_REFRESH, $query->getCacheMode()); + self::assertTrue($query->isCacheable()); + self::assertEquals(123, $query->getLifetime()); + self::assertEquals('foo_reg', $query->getCacheRegion()); + self::assertEquals(Cache::MODE_REFRESH, $query->getCacheMode()); } /** @@ -1120,7 +1122,7 @@ public function testSecondLevelCacheQueryBuilderOptions() */ public function testRebuildsFromParts() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->join('u.article', 'a'); @@ -1128,34 +1130,34 @@ public function testRebuildsFromParts() $dqlParts = $qb->getDQLParts(); $dql = $qb->getDQL(); - $qb2 = $this->_em->createQueryBuilder(); + $qb2 = $this->em->createQueryBuilder(); foreach (array_filter($dqlParts) as $name => $part) { $qb2->add($name, $part); } $dql2 = $qb2->getDQL(); - $this->assertEquals($dql, $dql2); + self::assertEquals($dql, $dql2); } public function testGetAllAliasesWithNoJoins() { - $qb = $this->_em->createQueryBuilder(); + $qb = $this->em->createQueryBuilder(); $qb->select('u')->from(CmsUser::class, 'u'); $aliases = $qb->getAllAliases(); - $this->assertEquals(['u'], $aliases); + self::assertEquals(['u'], $aliases); } public function testGetAllAliasesWithJoins() { - $qb = $this->_em->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select('u') ->from(CmsUser::class, 'u') ->join('u.groups', 'g'); $aliases = $qb->getAllAliases(); - $this->assertEquals(['u', 'g'], $aliases); + self::assertEquals(['u', 'g'], $aliases); } } diff --git a/tests/Doctrine/Tests/ORM/Repository/DefaultRepositoryFactoryTest.php b/tests/Doctrine/Tests/ORM/Repository/DefaultRepositoryFactoryTest.php index 85a63404618..3fcf4f19657 100644 --- a/tests/Doctrine/Tests/ORM/Repository/DefaultRepositoryFactoryTest.php +++ b/tests/Doctrine/Tests/ORM/Repository/DefaultRepositoryFactoryTest.php @@ -1,21 +1,26 @@ configuration = $this->createMock(Configuration::class); - $this->entityManager = $this->createEntityManager(); - $this->repositoryFactory = new DefaultRepositoryFactory(); + $this->metadataBuildingContext = new ClassMetadataBuildingContext( + $this->createMock(ClassMetadataFactory::class), + $this->createMock(ReflectionService::class) + ); + $this->configuration = $this->createMock(Configuration::class); + $this->entityManager = $this->createEntityManager(); + $this->repositoryFactory = new DefaultRepositoryFactory(); $this->configuration ->expects($this->any()) @@ -54,7 +68,7 @@ public function testCreatesRepositoryFromDefaultRepositoryClass() ->method('getClassMetadata') ->will($this->returnCallback([$this, 'buildClassMetadata'])); - $this->assertInstanceOf( + self::assertInstanceOf( DDC869PaymentRepository::class, $this->repositoryFactory->getRepository($this->entityManager, __CLASS__) ); @@ -67,7 +81,7 @@ public function testCreatedRepositoriesAreCached() ->method('getClassMetadata') ->will($this->returnCallback([$this, 'buildClassMetadata'])); - $this->assertSame( + self::assertSame( $this->repositoryFactory->getRepository($this->entityManager, __CLASS__), $this->repositoryFactory->getRepository($this->entityManager, __CLASS__) ); @@ -76,14 +90,16 @@ public function testCreatedRepositoriesAreCached() public function testCreatesRepositoryFromCustomClassMetadata() { $customMetadata = $this->buildClassMetadata(__DIR__); - $customMetadata->customRepositoryClassName = DDC753DefaultRepository::class; + + $customMetadata->setCustomRepositoryClassName(DDC753DefaultRepository::class); $this->entityManager ->expects($this->any()) ->method('getClassMetadata') - ->will($this->returnValue($customMetadata)); + ->will($this->returnValue($customMetadata)) + ; - $this->assertInstanceOf( + self::assertInstanceOf( DDC753DefaultRepository::class, $this->repositoryFactory->getRepository($this->entityManager, __CLASS__) ); @@ -105,10 +121,10 @@ public function testCachesDistinctRepositoriesPerDistinctEntityManager() $repo1 = $this->repositoryFactory->getRepository($em1, __CLASS__); $repo2 = $this->repositoryFactory->getRepository($em2, __CLASS__); - $this->assertSame($repo1, $this->repositoryFactory->getRepository($em1, __CLASS__)); - $this->assertSame($repo2, $this->repositoryFactory->getRepository($em2, __CLASS__)); + self::assertSame($repo1, $this->repositoryFactory->getRepository($em1, __CLASS__)); + self::assertSame($repo2, $this->repositoryFactory->getRepository($em2, __CLASS__)); - $this->assertNotSame($repo1, $repo2); + self::assertNotSame($repo1, $repo2); } /** @@ -116,16 +132,13 @@ public function testCachesDistinctRepositoriesPerDistinctEntityManager() * * @param string $className * - * @return \PHPUnit_Framework_MockObject_MockObject|\Doctrine\ORM\Mapping\ClassMetadata + * @return ClassMetadata */ public function buildClassMetadata($className) { - /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadata|\PHPUnit_Framework_MockObject_MockObject */ - $metadata = $this->createMock(ClassMetadata::class); - - $metadata->expects($this->any())->method('getName')->will($this->returnValue($className)); + $metadata = new ClassMetadata($className, $this->metadataBuildingContext); - $metadata->customRepositoryClassName = null; + $metadata->setCustomRepositoryClassName(null); return $metadata; } diff --git a/tests/Doctrine/Tests/ORM/Id/SequenceGeneratorTest.php b/tests/Doctrine/Tests/ORM/Sequencing/SequenceGeneratorTest.php similarity index 81% rename from tests/Doctrine/Tests/ORM/Id/SequenceGeneratorTest.php rename to tests/Doctrine/Tests/ORM/Sequencing/SequenceGeneratorTest.php index 5e4247715b0..67b8595b2e9 100644 --- a/tests/Doctrine/Tests/ORM/Id/SequenceGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Sequencing/SequenceGeneratorTest.php @@ -1,9 +1,11 @@ entityManager = $this->_getTestEntityManager(); + $this->entityManager = $this->getTestEntityManager(); $this->sequenceGenerator = new SequenceGenerator('seq', 10); $this->connection = $this->entityManager->getConnection(); - - self::assertInstanceOf(ConnectionMock::class, $this->connection); } public function testGeneration() : void @@ -44,7 +44,7 @@ public function testGeneration() : void )); for ($i = 0; $i < 42; ++$i) { - if ($i % 10 == 0) { + if ($i % 10 === 0) { $this->connection->setQueryResult(new StatementArrayMock([[(int)($i / 10) * 10]])); } diff --git a/tests/Doctrine/Tests/ORM/Tools/AttachEntityListenersListenerTest.php b/tests/Doctrine/Tests/ORM/Tools/AttachEntityListenersListenerTest.php index db4da0b5d88..0b11cf80508 100644 --- a/tests/Doctrine/Tests/ORM/Tools/AttachEntityListenersListenerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/AttachEntityListenersListenerTest.php @@ -1,16 +1,19 @@ listener = new AttachEntityListenersListener(); $driver = $this->createAnnotationDriver(); - $this->em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); $evm = $this->em->getEventManager(); $this->factory = new ClassMetadataFactory; @@ -48,10 +51,10 @@ public function testAttachEntityListeners() $metadata = $this->factory->getMetadataFor(AttachEntityListenersListenerTestFooEntity::class); - $this->assertArrayHasKey('postLoad', $metadata->entityListeners); - $this->assertCount(1, $metadata->entityListeners['postLoad']); - $this->assertEquals('postLoadHandler', $metadata->entityListeners['postLoad'][0]['method']); - $this->assertEquals(AttachEntityListenersListenerTestListener::class, $metadata->entityListeners['postLoad'][0]['class']); + self::assertArrayHasKey('postLoad', $metadata->entityListeners); + self::assertCount(1, $metadata->entityListeners['postLoad']); + self::assertEquals('postLoadHandler', $metadata->entityListeners['postLoad'][0]['method']); + self::assertEquals(AttachEntityListenersListenerTestListener::class, $metadata->entityListeners['postLoad'][0]['class']); } public function testAttachToExistingEntityListeners() @@ -71,23 +74,23 @@ public function testAttachToExistingEntityListeners() $metadata = $this->factory->getMetadataFor(AttachEntityListenersListenerTestBarEntity::class); - $this->assertArrayHasKey('postPersist', $metadata->entityListeners); - $this->assertArrayHasKey('prePersist', $metadata->entityListeners); + self::assertArrayHasKey('postPersist', $metadata->entityListeners); + self::assertArrayHasKey('prePersist', $metadata->entityListeners); - $this->assertCount(2, $metadata->entityListeners['prePersist']); - $this->assertCount(2, $metadata->entityListeners['postPersist']); + self::assertCount(2, $metadata->entityListeners['prePersist']); + self::assertCount(2, $metadata->entityListeners['postPersist']); - $this->assertEquals('prePersist', $metadata->entityListeners['prePersist'][0]['method']); - $this->assertEquals(AttachEntityListenersListenerTestListener::class, $metadata->entityListeners['prePersist'][0]['class']); + self::assertEquals('prePersist', $metadata->entityListeners['prePersist'][0]['method']); + self::assertEquals(AttachEntityListenersListenerTestListener::class, $metadata->entityListeners['prePersist'][0]['class']); - $this->assertEquals('prePersist', $metadata->entityListeners['prePersist'][1]['method']); - $this->assertEquals(AttachEntityListenersListenerTestListener2::class, $metadata->entityListeners['prePersist'][1]['class']); + self::assertEquals('prePersist', $metadata->entityListeners['prePersist'][1]['method']); + self::assertEquals(AttachEntityListenersListenerTestListener2::class, $metadata->entityListeners['prePersist'][1]['class']); - $this->assertEquals('postPersist', $metadata->entityListeners['postPersist'][0]['method']); - $this->assertEquals(AttachEntityListenersListenerTestListener::class, $metadata->entityListeners['postPersist'][0]['class']); + self::assertEquals('postPersist', $metadata->entityListeners['postPersist'][0]['method']); + self::assertEquals(AttachEntityListenersListenerTestListener::class, $metadata->entityListeners['postPersist'][0]['class']); - $this->assertEquals('postPersistHandler', $metadata->entityListeners['postPersist'][1]['method']); - $this->assertEquals(AttachEntityListenersListenerTestListener2::class, $metadata->entityListeners['postPersist'][1]['class']); + self::assertEquals('postPersistHandler', $metadata->entityListeners['postPersist'][1]['method']); + self::assertEquals(AttachEntityListenersListenerTestListener2::class, $metadata->entityListeners['postPersist'][1]['class']); } /** @@ -113,28 +116,28 @@ public function testDuplicateEntityListenerException() } /** - * @Entity + * @ORM\Entity */ class AttachEntityListenersListenerTestFooEntity { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; } /** - * @Entity - * @EntityListeners({"AttachEntityListenersListenerTestListener"}) + * @ORM\Entity + * @ORM\EntityListeners({"AttachEntityListenersListenerTestListener"}) */ class AttachEntityListenersListenerTestBarEntity { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheCollectionRegionCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheCollectionRegionCommandTest.php index 5ac2f97527d..cc14e6b7d08 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheCollectionRegionCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheCollectionRegionCommandTest.php @@ -1,5 +1,7 @@ application->setHelperSet(new HelperSet( [ - 'em' => new EntityManagerHelper($this->_em) + 'em' => new EntityManagerHelper($this->em) ] )); @@ -53,7 +55,7 @@ public function testClearAllRegion() ], ['decorated' => false] ); - $this->assertEquals('Clearing all second-level cache collection regions' . PHP_EOL, $tester->getDisplay()); + self::assertEquals('Clearing all second-level cache collection regions' . PHP_EOL, $tester->getDisplay()); } public function testClearByOwnerEntityClassName() @@ -68,7 +70,7 @@ public function testClearByOwnerEntityClassName() ], ['decorated' => false] ); - $this->assertEquals('Clearing second-level cache for collection "Doctrine\Tests\Models\Cache\State#cities"' . PHP_EOL, $tester->getDisplay()); + self::assertEquals('Clearing second-level cache for collection "Doctrine\Tests\Models\Cache\State#cities"' . PHP_EOL, $tester->getDisplay()); } public function testClearCacheEntryName() @@ -84,7 +86,7 @@ public function testClearCacheEntryName() ], ['decorated' => false] ); - $this->assertEquals('Clearing second-level cache entry for collection "Doctrine\Tests\Models\Cache\State#cities" owner entity identified by "1"' . PHP_EOL, $tester->getDisplay()); + self::assertEquals('Clearing second-level cache entry for collection "Doctrine\Tests\Models\Cache\State#cities" owner entity identified by "1"' . PHP_EOL, $tester->getDisplay()); } public function testFlushRegionName() @@ -100,6 +102,6 @@ public function testFlushRegionName() ], ['decorated' => false] ); - $this->assertEquals('Flushing cache provider configured for "Doctrine\Tests\Models\Cache\State#cities"' . PHP_EOL, $tester->getDisplay()); + self::assertEquals('Flushing cache provider configured for "Doctrine\Tests\Models\Cache\State#cities"' . PHP_EOL, $tester->getDisplay()); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheEntityRegionCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheEntityRegionCommandTest.php index 3546a3116df..ad9fdd8885c 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheEntityRegionCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheEntityRegionCommandTest.php @@ -1,5 +1,7 @@ application->setHelperSet(new HelperSet( [ - 'em' => new EntityManagerHelper($this->_em) + 'em' => new EntityManagerHelper($this->em) ] )); @@ -53,7 +55,7 @@ public function testClearAllRegion() ], ['decorated' => false] ); - $this->assertEquals('Clearing all second-level cache entity regions' . PHP_EOL, $tester->getDisplay()); + self::assertEquals('Clearing all second-level cache entity regions' . PHP_EOL, $tester->getDisplay()); } public function testClearByEntityClassName() @@ -67,7 +69,7 @@ public function testClearByEntityClassName() ], ['decorated' => false] ); - $this->assertEquals('Clearing second-level cache for entity "Doctrine\Tests\Models\Cache\Country"' . PHP_EOL, $tester->getDisplay()); + self::assertEquals('Clearing second-level cache for entity "Doctrine\Tests\Models\Cache\Country"' . PHP_EOL, $tester->getDisplay()); } public function testClearCacheEntryName() @@ -82,7 +84,7 @@ public function testClearCacheEntryName() ], ['decorated' => false] ); - $this->assertEquals('Clearing second-level cache entry for entity "Doctrine\Tests\Models\Cache\Country" identified by "1"' . PHP_EOL, $tester->getDisplay()); + self::assertEquals('Clearing second-level cache entry for entity "Doctrine\Tests\Models\Cache\Country" identified by "1"' . PHP_EOL, $tester->getDisplay()); } public function testFlushRegionName() @@ -97,6 +99,6 @@ public function testFlushRegionName() ], ['decorated' => false] ); - $this->assertEquals('Flushing cache provider configured for entity named "Doctrine\Tests\Models\Cache\Country"' . PHP_EOL, $tester->getDisplay()); + self::assertEquals('Flushing cache provider configured for entity named "Doctrine\Tests\Models\Cache\Country"' . PHP_EOL, $tester->getDisplay()); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheQueryRegionCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheQueryRegionCommandTest.php index 0d296bf553f..b0c3db7aab6 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheQueryRegionCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheQueryRegionCommandTest.php @@ -1,5 +1,7 @@ application->setHelperSet(new HelperSet( [ - 'em' => new EntityManagerHelper($this->_em) + 'em' => new EntityManagerHelper($this->em) ] )); @@ -52,7 +54,7 @@ public function testClearAllRegion() ], ['decorated' => false] ); - $this->assertEquals('Clearing all second-level cache query regions' . PHP_EOL, $tester->getDisplay()); + self::assertEquals('Clearing all second-level cache query regions' . PHP_EOL, $tester->getDisplay()); } public function testClearDefaultRegionName() @@ -66,7 +68,7 @@ public function testClearDefaultRegionName() ], ['decorated' => false] ); - $this->assertEquals('Clearing second-level cache query region named "query_cache_region"' . PHP_EOL, $tester->getDisplay()); + self::assertEquals('Clearing second-level cache query region named "query_cache_region"' . PHP_EOL, $tester->getDisplay()); } public function testClearByRegionName() @@ -80,7 +82,7 @@ public function testClearByRegionName() ], ['decorated' => false] ); - $this->assertEquals('Clearing second-level cache query region named "my_region"' . PHP_EOL, $tester->getDisplay()); + self::assertEquals('Clearing second-level cache query region named "my_region"' . PHP_EOL, $tester->getDisplay()); } public function testFlushRegionName() @@ -95,6 +97,6 @@ public function testFlushRegionName() ], ['decorated' => false] ); - $this->assertEquals('Flushing cache provider configured for second-level cache query region named "my_region"' . PHP_EOL, $tester->getDisplay()); + self::assertEquals('Flushing cache provider configured for second-level cache query region named "my_region"' . PHP_EOL, $tester->getDisplay()); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommandTest.php deleted file mode 100644 index 3e6a0e90486..00000000000 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommandTest.php +++ /dev/null @@ -1,25 +0,0 @@ -createMock(EntityGenerator::class); - $command = new ConvertDoctrine1SchemaCommand(); - $command->setEntityGenerator($entityGenerator); - - $output = $this->createMock(OutputInterface::class); - $output->expects($this->once()) - ->method('writeln') - ->with($this->equalTo('No Metadata Classes to process.')); - - $command->convertDoctrine1Schema([], sys_get_temp_dir(), 'annotation', 4, null, $output); - } -} diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/GenerateRepositoriesCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/GenerateRepositoriesCommandTest.php index 45bdfa3862f..46b5ae11baa 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/GenerateRepositoriesCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/GenerateRepositoriesCommandTest.php @@ -1,5 +1,7 @@ path); - $metadataDriver = $this->_em->getConfiguration()->getMetadataDriverImpl(); + $metadataDriver = $this->em->getConfiguration()->getMetadataDriverImpl(); $metadataDriver->addPaths( [ @@ -47,7 +49,7 @@ protected function setUp() $this->application->setHelperSet(new HelperSet( [ - 'em' => new EntityManagerHelper($this->_em) + 'em' => new EntityManagerHelper($this->em) ] )); @@ -88,20 +90,20 @@ public function testGenerateRepositories() $cname = 'Doctrine\Tests\Models\DDC3231\DDC3231User1Repository'; $fname = str_replace('\\', DIRECTORY_SEPARATOR, $cname) . '.php'; - $this->assertFileExists($this->path . DIRECTORY_SEPARATOR . $fname); - $this->assertFileExists($this->path . DIRECTORY_SEPARATOR . 'DDC3231User1NoNamespaceRepository.php'); + self::assertFileExists($this->path . DIRECTORY_SEPARATOR . $fname); + self::assertFileExists($this->path . DIRECTORY_SEPARATOR . 'DDC3231User1NoNamespaceRepository.php'); require $this->path . DIRECTORY_SEPARATOR . $fname; require $this->path . DIRECTORY_SEPARATOR . 'DDC3231User1NoNamespaceRepository.php'; - $this->assertTrue(class_exists($cname)); - $this->assertTrue(class_exists('DDC3231User1NoNamespaceRepository')); + self::assertTrue(class_exists($cname)); + self::assertTrue(class_exists('DDC3231User1NoNamespaceRepository')); $repo1 = new \ReflectionClass($cname); $repo2 = new \ReflectionClass('DDC3231User1NoNamespaceRepository'); - $this->assertSame(EntityRepository::class, $repo1->getParentClass()->getName()); - $this->assertSame(EntityRepository::class, $repo2->getParentClass()->getName()); + self::assertSame(EntityRepository::class, $repo1->getParentClass()->getName()); + self::assertSame(EntityRepository::class, $repo2->getParentClass()->getName()); } public function testGenerateRepositoriesCustomDefaultRepository() @@ -111,20 +113,20 @@ public function testGenerateRepositoriesCustomDefaultRepository() $cname = 'Doctrine\Tests\Models\DDC3231\DDC3231User2Repository'; $fname = str_replace('\\', DIRECTORY_SEPARATOR, $cname) . '.php'; - $this->assertFileExists($this->path . DIRECTORY_SEPARATOR . $fname); - $this->assertFileExists($this->path . DIRECTORY_SEPARATOR . 'DDC3231User2NoNamespaceRepository.php'); + self::assertFileExists($this->path . DIRECTORY_SEPARATOR . $fname); + self::assertFileExists($this->path . DIRECTORY_SEPARATOR . 'DDC3231User2NoNamespaceRepository.php'); require $this->path . DIRECTORY_SEPARATOR . $fname; require $this->path . DIRECTORY_SEPARATOR . 'DDC3231User2NoNamespaceRepository.php'; - $this->assertTrue(class_exists($cname)); - $this->assertTrue(class_exists('DDC3231User2NoNamespaceRepository')); + self::assertTrue(class_exists($cname)); + self::assertTrue(class_exists('DDC3231User2NoNamespaceRepository')); $repo1 = new \ReflectionClass($cname); $repo2 = new \ReflectionClass('DDC3231User2NoNamespaceRepository'); - $this->assertSame(DDC3231EntityRepository::class, $repo1->getParentClass()->getName()); - $this->assertSame(DDC3231EntityRepository::class, $repo2->getParentClass()->getName()); + self::assertSame(DDC3231EntityRepository::class, $repo1->getParentClass()->getName()); + self::assertSame(DDC3231EntityRepository::class, $repo2->getParentClass()->getName()); } /** @@ -134,7 +136,7 @@ public function testGenerateRepositoriesCustomDefaultRepository() private function generateRepositories($filter, $defaultRepository = null) { if ($defaultRepository) { - $this->_em->getConfiguration()->setDefaultRepositoryClassName($defaultRepository); + $this->em->getConfiguration()->setDefaultRepositoryClassName($defaultRepository); } $command = $this->application->find('orm:generate-repositories'); diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/InfoCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/InfoCommandTest.php index a27fb90d79a..2ebe1a18aa2 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/InfoCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/InfoCommandTest.php @@ -1,5 +1,7 @@ application->setHelperSet( - new HelperSet(['em' => new EntityManagerHelper($this->_em)]) + new HelperSet(['em' => new EntityManagerHelper($this->em)]) ); $this->application->add($command); @@ -49,7 +51,7 @@ public function testListAllClasses() { $this->tester->execute(['command' => $this->command->getName()]); - $this->assertContains(AttractionInfo::class, $this->tester->getDisplay()); - $this->assertContains(City::class, $this->tester->getDisplay()); + self::assertContains(AttractionInfo::class, $this->tester->getDisplay()); + self::assertContains(City::class, $this->tester->getDisplay()); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/MappingDescribeCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/MappingDescribeCommandTest.php index 437f521e3d7..13f14b3ac47 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/MappingDescribeCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/MappingDescribeCommandTest.php @@ -1,5 +1,7 @@ application->setHelperSet(new HelperSet( [ - 'em' => new EntityManagerHelper($this->_em) + 'em' => new EntityManagerHelper($this->em) ] )); @@ -55,14 +57,14 @@ public function testShowSpecificFuzzySingle() { $this->tester->execute( [ - 'command' => $this->command->getName(), - 'entityName' => 'AttractionInfo', + 'command' => $this->command->getName(), + 'entityName' => 'AttractionInfo', ] ); $display = $this->tester->getDisplay(); - $this->assertContains(AttractionInfo::class, $display); - $this->assertContains('Root entity name', $display); + self::assertContains(AttractionInfo::class, $display); + self::assertContains('Root entity name', $display); } /** diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/RunDqlCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/RunDqlCommandTest.php index e2e68bd7e28..2cfa0fcda62 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/RunDqlCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/RunDqlCommandTest.php @@ -1,5 +1,7 @@ application->setHelperSet(new HelperSet( [ - 'em' => new EntityManagerHelper($this->_em) + 'em' => new EntityManagerHelper($this->em) ] )); @@ -54,15 +56,15 @@ protected function setUp() public function testCommandName() { - $this->assertSame($this->command, $this->application->get('orm:run-dql')); + self::assertSame($this->command, $this->application->get('orm:run-dql')); } public function testWillRunQuery() { - $this->_em->persist(new DateTimeModel()); - $this->_em->flush(); + $this->em->persist(new DateTimeModel()); + $this->em->flush(); - $this->assertSame( + self::assertSame( 0, $this->tester->execute( [ @@ -72,15 +74,15 @@ public function testWillRunQuery() ) ); - $this->assertContains(DateTimeModel::class, $this->tester->getDisplay()); + self::assertContains(DateTimeModel::class, $this->tester->getDisplay()); } public function testWillShowQuery() { - $this->_em->persist(new DateTimeModel()); - $this->_em->flush(); + $this->em->persist(new DateTimeModel()); + $this->em->flush(); - $this->assertSame( + self::assertSame( 0, $this->tester->execute( [ @@ -91,6 +93,6 @@ public function testWillShowQuery() ) ); - $this->assertStringMatchesFormat('%Astring%sSELECT %a', $this->tester->getDisplay()); + self::assertStringMatchesFormat('%Astring%sSELECT %a', $this->tester->getDisplay()); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/ConsoleRunnerTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/ConsoleRunnerTest.php index a53ba514dd9..1e939ec4c75 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/ConsoleRunnerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/ConsoleRunnerTest.php @@ -1,10 +1,12 @@ getHelperSet()); - self::assertEquals(Version::VERSION, $app->getVersion()); + self::assertEquals(Versions::getVersion('doctrine/orm'), $app->getVersion()); self::assertTrue($app->has('dbal:import')); self::assertTrue($app->has('dbal:reserved-words')); @@ -32,9 +34,7 @@ public function testCreateApplicationShouldReturnAnApplicationWithTheCorrectComm self::assertTrue($app->has('orm:clear-cache:metadata')); self::assertTrue($app->has('orm:clear-cache:query')); self::assertTrue($app->has('orm:clear-cache:result')); - self::assertTrue($app->has('orm:convert-d1-schema')); self::assertTrue($app->has('orm:convert-mapping')); - self::assertTrue($app->has('orm:convert:d1-schema')); self::assertTrue($app->has('orm:convert:mapping')); self::assertTrue($app->has('orm:ensure-production-settings')); self::assertTrue($app->has('orm:generate-entities')); diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/MetadataFilterTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/MetadataFilterTest.php index 24f3b54a3a8..23b2d0ae646 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/MetadataFilterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/MetadataFilterTest.php @@ -1,7 +1,10 @@ createAnnotationDriver(); - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); $em->getConfiguration()->setMetadataDriverImpl($driver); @@ -40,9 +43,9 @@ public function testFilterWithEmptyArray() : void $metadatas = $originalMetadatas; $metadatas = MetadataFilter::filter($metadatas, []); - $this->assertContains($metadataAaa, $metadatas); - $this->assertContains($metadataBbb, $metadatas); - $this->assertCount(count($originalMetadatas), $metadatas); + self::assertContains($metadataAaa, $metadatas); + self::assertContains($metadataBbb, $metadatas); + self::assertCount(count($originalMetadatas), $metadatas); } public function testFilterWithString() : void @@ -56,26 +59,26 @@ public function testFilterWithString() : void $metadatas = $originalMetadatas; $metadatas = MetadataFilter::filter($metadatas, 'MetadataFilterTestEntityAaa'); - $this->assertContains($metadataAaa, $metadatas); - $this->assertNotContains($metadataBbb, $metadatas); - $this->assertNotContains($metadataCcc, $metadatas); - $this->assertCount(1, $metadatas); + self::assertContains($metadataAaa, $metadatas); + self::assertNotContains($metadataBbb, $metadatas); + self::assertNotContains($metadataCcc, $metadatas); + self::assertCount(1, $metadatas); $metadatas = $originalMetadatas; $metadatas = MetadataFilter::filter($metadatas, 'MetadataFilterTestEntityBbb'); - $this->assertNotContains($metadataAaa, $metadatas); - $this->assertContains($metadataBbb, $metadatas); - $this->assertNotContains($metadataCcc, $metadatas); - $this->assertCount(1, $metadatas); + self::assertNotContains($metadataAaa, $metadatas); + self::assertContains($metadataBbb, $metadatas); + self::assertNotContains($metadataCcc, $metadatas); + self::assertCount(1, $metadatas); $metadatas = $originalMetadatas; $metadatas = MetadataFilter::filter($metadatas, 'MetadataFilterTestEntityCcc'); - $this->assertNotContains($metadataAaa, $metadatas); - $this->assertNotContains($metadataBbb, $metadatas); - $this->assertContains($metadataCcc, $metadatas); - $this->assertCount(1, $metadatas); + self::assertNotContains($metadataAaa, $metadatas); + self::assertNotContains($metadataBbb, $metadatas); + self::assertContains($metadataCcc, $metadatas); + self::assertCount(1, $metadatas); } public function testFilterWithString2() : void @@ -89,10 +92,10 @@ public function testFilterWithString2() : void $metadatas = $originalMetadatas; $metadatas = MetadataFilter::filter($metadatas, 'MetadataFilterTestEntityFoo'); - $this->assertContains($metadataFoo, $metadatas); - $this->assertContains($metadataFooBar, $metadatas); - $this->assertNotContains($metadataBar, $metadatas); - $this->assertCount(2, $metadatas); + self::assertContains($metadataFoo, $metadatas); + self::assertContains($metadataFooBar, $metadatas); + self::assertNotContains($metadataBar, $metadatas); + self::assertCount(2, $metadatas); } public function testFilterWithArray() : void @@ -109,10 +112,10 @@ public function testFilterWithArray() : void 'MetadataFilterTestEntityCcc', ]); - $this->assertContains($metadataAaa, $metadatas); - $this->assertNotContains($metadataBbb, $metadatas); - $this->assertContains($metadataCcc, $metadatas); - $this->assertCount(2, $metadatas); + self::assertContains($metadataAaa, $metadatas); + self::assertNotContains($metadataBbb, $metadatas); + self::assertContains($metadataCcc, $metadatas); + self::assertCount(2, $metadatas); } public function testFilterWithRegex() : void @@ -126,59 +129,59 @@ public function testFilterWithRegex() : void $metadatas = $originalMetadatas; $metadatas = MetadataFilter::filter($metadatas, 'Foo$'); - $this->assertContains($metadataFoo, $metadatas); - $this->assertNotContains($metadataFooBar, $metadatas); - $this->assertNotContains($metadataBar, $metadatas); - $this->assertCount(1, $metadatas); + self::assertContains($metadataFoo, $metadatas); + self::assertNotContains($metadataFooBar, $metadatas); + self::assertNotContains($metadataBar, $metadatas); + self::assertCount(1, $metadatas); $metadatas = $originalMetadatas; $metadatas = MetadataFilter::filter($metadatas, 'Bar$'); - $this->assertNotContains($metadataFoo, $metadatas); - $this->assertContains($metadataFooBar, $metadatas); - $this->assertContains($metadataBar, $metadatas); - $this->assertCount(2, $metadatas); + self::assertNotContains($metadataFoo, $metadatas); + self::assertContains($metadataFooBar, $metadatas); + self::assertContains($metadataBar, $metadatas); + self::assertCount(2, $metadatas); } } -/** @Entity */ +/** @ORM\Entity */ class MetadataFilterTestEntityAaa { - /** @Id @Column */ + /** @ORM\Id @ORM\Column */ protected $id; } -/** @Entity */ +/** @ORM\Entity */ class MetadataFilterTestEntityBbb { - /** @Id @Column */ + /** @ORM\Id @ORM\Column */ protected $id; } -/** @Entity */ +/** @ORM\Entity */ class MetadataFilterTestEntityCcc { - /** @Id @Column */ + /** @ORM\Id @ORM\Column */ protected $id; } -/** @Entity */ +/** @ORM\Entity */ class MetadataFilterTestEntityFoo { - /** @Id @Column */ + /** @ORM\Id @ORM\Column */ protected $id; } -/** @Entity */ +/** @ORM\Entity */ class MetadataFilterTestEntityBar { - /** @Id @Column */ + /** @ORM\Id @ORM\Column */ protected $id; } -/** @Entity */ +/** @ORM\Entity */ class MetadataFilterTestEntityFooBar { - /** @Id @Column */ + /** @ORM\Id @ORM\Column */ protected $id; } diff --git a/tests/Doctrine/Tests/ORM/Tools/ConvertDoctrine1SchemaTest.php b/tests/Doctrine/Tests/ORM/Tools/ConvertDoctrine1SchemaTest.php deleted file mode 100644 index ca6192faa29..00000000000 --- a/tests/Doctrine/Tests/ORM/Tools/ConvertDoctrine1SchemaTest.php +++ /dev/null @@ -1,88 +0,0 @@ - - * @author Roman Borschel setProxyDir(__DIR__ . '/../../Proxies'); - $config->setProxyNamespace('Doctrine\Tests\Proxies'); - $eventManager = new EventManager(); - $conn = new ConnectionMock([], $driverMock, $config, $eventManager); - $config->setMetadataDriverImpl($metadataDriver); - - return EntityManagerMock::create($conn, $config, $eventManager); - } - - public function testTest() - { - if ( ! class_exists('Symfony\Component\Yaml\Yaml', true)) { - $this->markTestSkipped('Please install Symfony YAML Component into the include path of your PHP installation.'); - } - - $cme = new ClassMetadataExporter(); - $converter = new ConvertDoctrine1Schema(__DIR__ . '/doctrine1schema'); - - $exporter = $cme->getExporter('yml', __DIR__ . '/convert'); - $exporter->setOverwriteExistingFiles(true); - $exporter->setMetadata($converter->getMetadata()); - $exporter->export(); - - $this->assertTrue(file_exists(__DIR__ . '/convert/User.dcm.yml')); - $this->assertTrue(file_exists(__DIR__ . '/convert/Profile.dcm.yml')); - - $metadataDriver = new YamlDriver(__DIR__ . '/convert'); - $em = $this->_createEntityManager($metadataDriver); - $cmf = new DisconnectedClassMetadataFactory(); - $cmf->setEntityManager($em); - $metadata = $cmf->getAllMetadata(); - $profileClass = $cmf->getMetadataFor('Profile'); - $userClass = $cmf->getMetadataFor('User'); - - $this->assertEquals(2, count($metadata)); - $this->assertEquals('Profile', $profileClass->name); - $this->assertEquals('User', $userClass->name); - $this->assertEquals(4, count($profileClass->fieldMappings)); - $this->assertEquals(5, count($userClass->fieldMappings)); - $this->assertEquals('text', $userClass->fieldMappings['clob']['type']); - $this->assertEquals('test_alias', $userClass->fieldMappings['theAlias']['columnName']); - $this->assertEquals('theAlias', $userClass->fieldMappings['theAlias']['fieldName']); - - $this->assertEquals('Profile', $profileClass->associationMappings['User']['sourceEntity']); - $this->assertEquals('User', $profileClass->associationMappings['User']['targetEntity']); - - $this->assertEquals('username', $userClass->table['uniqueConstraints']['username']['columns'][0]); - } - - public function tearDown() - { - @unlink(__DIR__ . '/convert/User.dcm.yml'); - @unlink(__DIR__ . '/convert/Profile.dcm.yml'); - @rmdir(__DIR__ . '/convert'); - } -} diff --git a/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php b/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php index f2d74d0437f..e8bba8cb5cf 100644 --- a/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php @@ -1,230 +1,369 @@ _namespace = uniqid("doctrine_"); - $this->_tmpDir = \sys_get_temp_dir(); - \mkdir($this->_tmpDir . \DIRECTORY_SEPARATOR . $this->_namespace); - $this->_generator = new EntityGenerator(); - $this->_generator->setAnnotationPrefix(""); - $this->_generator->setGenerateAnnotations(true); - $this->_generator->setGenerateStubMethods(true); - $this->_generator->setRegenerateEntityIfExists(false); - $this->_generator->setUpdateEntityIfExists(true); - $this->_generator->setFieldVisibility(EntityGenerator::FIELD_VISIBLE_PROTECTED); + $this->staticMetadataBuildingContext = new Mapping\ClassMetadataBuildingContext( + $this->createMock(ClassMetadataFactory::class), + new StaticReflectionService() + ); + + $this->runtimeMetadataBuildingContext = new Mapping\ClassMetadataBuildingContext( + $this->createMock(ClassMetadataFactory::class), + new RuntimeReflectionService() + ); + + $this->namespace = uniqid("doctrine_", false); + $this->tmpDir = sys_get_temp_dir(); + + mkdir($this->tmpDir . \DIRECTORY_SEPARATOR . $this->namespace); + + $this->generator = new EntityGenerator(); + + $this->generator->setGenerateAnnotations(true); + $this->generator->setGenerateStubMethods(true); + $this->generator->setRegenerateEntityIfExists(false); + $this->generator->setUpdateEntityIfExists(true); + $this->generator->setFieldVisibility(EntityGenerator::FIELD_VISIBLE_PROTECTED); } public function tearDown() { - $ri = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->_tmpDir . '/' . $this->_namespace)); + $ri = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->tmpDir . '/' . $this->namespace)); + foreach ($ri AS $file) { /* @var $file \SplFileInfo */ if ($file->isFile()) { - \unlink($file->getPathname()); + unlink($file->getPathname()); } } - rmdir($this->_tmpDir . '/' . $this->_namespace); + + rmdir($this->tmpDir . '/' . $this->namespace); } /** - * @param ClassMetadataInfo[] $embeddedClasses + * @param ClassMetadata[] $embeddedClasses * - * @return ClassMetadataInfo + * @return ClassMetadata */ public function generateBookEntityFixture(array $embeddedClasses = []) { - $metadata = new ClassMetadataInfo($this->_namespace . '\EntityGeneratorBook'); - $metadata->namespace = $this->_namespace; - $metadata->customRepositoryClassName = $this->_namespace . '\EntityGeneratorBookRepository'; - - $metadata->table['name'] = 'book'; - $metadata->table['uniqueConstraints']['name_uniq'] = ['columns' => ['name']]; - $metadata->table['indexes']['status_idx'] = ['columns' => ['status']]; - $metadata->mapField(['fieldName' => 'name', 'type' => 'string']); - $metadata->mapField(['fieldName' => 'status', 'type' => 'string', 'options' => ['default' => 'published']]); - $metadata->mapField(['fieldName' => 'id', 'type' => 'integer', 'id' => true]); - $metadata->mapOneToOne( - ['fieldName' => 'author', 'targetEntity' => EntityGeneratorAuthor::class, 'mappedBy' => 'book'] + $metadata = new ClassMetadata($this->namespace . '\EntityGeneratorBook', $this->staticMetadataBuildingContext); + + $metadata->setCustomRepositoryClassName($this->namespace . '\EntityGeneratorBookRepository'); + + $tableMetadata = new Mapping\TableMetadata(); + + $tableMetadata->setName('book'); + $tableMetadata->addUniqueConstraint( + [ + 'name' => 'name_uniq', + 'columns' => ['name'], + 'options' => [], + 'flags' => [], + ] ); - $joinColumns = [ - ['name' => 'author_id', 'referencedColumnName' => 'id'] - ]; - $metadata->mapManyToMany( + + $tableMetadata->addIndex( [ - 'fieldName' => 'comments', - 'targetEntity' => EntityGeneratorComment::class, - 'fetch' => ClassMetadataInfo::FETCH_EXTRA_LAZY, - 'joinTable' => [ - 'name' => 'book_comment', - 'joinColumns' => [['name' => 'book_id', 'referencedColumnName' => 'id']], - 'inverseJoinColumns' => [['name' => 'comment_id', 'referencedColumnName' => 'id']], - ], + 'name' => 'status_idx', + 'columns' => ['status'], + 'unique' => false, + 'options' => [], + 'flags' => [], ] ); + + $metadata->setTable($tableMetadata); + + // Property: "name" + $fieldMetadata = new Mapping\FieldMetadata('name'); + + $fieldMetadata->setType(Type::getType('string')); + $fieldMetadata->setNullable(false); + $fieldMetadata->setUnique(false); + + $metadata->addProperty($fieldMetadata); + + // Property: "status" + $fieldMetadata = new Mapping\FieldMetadata('status'); + + $fieldMetadata->setType(Type::getType('string')); + $fieldMetadata->setNullable(false); + $fieldMetadata->setUnique(false); + $fieldMetadata->setOptions([ + 'default' => 'published', + ]); + + $metadata->addProperty($fieldMetadata); + + // Property: "id" + $fieldMetadata = new Mapping\FieldMetadata('id'); + + $fieldMetadata->setType(Type::getType('integer')); + $fieldMetadata->setPrimaryKey(true); + $fieldMetadata->setNullable(false); + $fieldMetadata->setUnique(false); + $fieldMetadata->setValueGenerator(new Mapping\ValueGeneratorMetadata(Mapping\GeneratorType::AUTO)); + + $metadata->addProperty($fieldMetadata); + + // Property: "author" + $joinColumns = []; + + $joinColumn = new Mapping\JoinColumnMetadata(); + $joinColumn->setColumnName('author_id'); + $joinColumn->setReferencedColumnName('id'); + + $joinColumns[] = $joinColumn; + + $association = new Mapping\OneToOneAssociationMetadata('author'); + + $association->setJoinColumns($joinColumns); + $association->setTargetEntity(EntityGeneratorAuthor::class); + $association->setMappedBy('book'); + + $metadata->addProperty($association); + + // Property: "comments" + $joinTable = new Mapping\JoinTableMetadata(); + $joinTable->setName('book_comment'); + + $joinColumn = new Mapping\JoinColumnMetadata(); + $joinColumn->setColumnName("book_id"); + $joinColumn->setReferencedColumnName("id"); + + $joinTable->addJoinColumn($joinColumn); + + $joinColumn = new Mapping\JoinColumnMetadata(); + $joinColumn->setColumnName("comment_id"); + $joinColumn->setReferencedColumnName("id"); + + $joinTable->addInverseJoinColumn($joinColumn); + + $association = new Mapping\ManyToManyAssociationMetadata('comments'); + + $association->setJoinTable($joinTable); + $association->setTargetEntity(EntityGeneratorComment::class); + $association->setFetchMode(Mapping\FetchMode::EXTRA_LAZY); + + $metadata->addProperty($association); + $metadata->addLifecycleCallback('loading', 'postLoad'); $metadata->addLifecycleCallback('willBeRemoved', 'preRemove'); - $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); foreach ($embeddedClasses as $fieldName => $embeddedClass) { - $this->mapNestedEmbedded($fieldName, $metadata, $embeddedClass); - $this->mapEmbedded($fieldName, $metadata, $embeddedClass); + $metadata->mapEmbedded( + [ + 'fieldName' => $fieldName, + 'class' => $embeddedClass->getClassName(), + 'columnPrefix' => null, + ] + ); } - $this->_generator->writeEntityClass($metadata, $this->_tmpDir); + $this->generator->writeEntityClass($metadata, $this->tmpDir); return $metadata; } private function generateEntityTypeFixture(array $field) { - $metadata = new ClassMetadataInfo($this->_namespace . '\EntityType'); - $metadata->namespace = $this->_namespace; + $metadata = new ClassMetadata($this->namespace . '\EntityType', $this->staticMetadataBuildingContext); + + $tableMetadata = new Mapping\TableMetadata(); + $tableMetadata->setName('entity_type'); + + $metadata->setTable($tableMetadata); + + $fieldMetadata = new Mapping\FieldMetadata('id'); + $fieldMetadata->setType(Type::getType('integer')); + $fieldMetadata->setPrimaryKey(true); + $fieldMetadata->setNullable(false); + $fieldMetadata->setUnique(false); + $fieldMetadata->setValueGenerator(new Mapping\ValueGeneratorMetadata(Mapping\GeneratorType::AUTO)); - $metadata->table['name'] = 'entity_type'; - $metadata->mapField(['fieldName' => 'id', 'type' => 'integer', 'id' => true]); - $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); + $metadata->addProperty($fieldMetadata); - $name = $field['fieldName']; - $type = $field['dbType']; - $metadata->mapField(['fieldName' => $name, 'type' => $type]); + $fieldMetadata = new Mapping\FieldMetadata($field['fieldName']); + $fieldMetadata->setType(Type::getType($field['dbType'])); + $fieldMetadata->setNullable(false); + $fieldMetadata->setUnique(false); - $this->_generator->writeEntityClass($metadata, $this->_tmpDir); + $metadata->addProperty($fieldMetadata); + + $this->generator->writeEntityClass($metadata, $this->tmpDir); return $metadata; } /** - * @return ClassMetadataInfo + * @return ClassMetadata */ private function generateIsbnEmbeddableFixture(array $embeddedClasses = [], $columnPrefix = null) { - $metadata = new ClassMetadataInfo($this->_namespace . '\EntityGeneratorIsbn'); - $metadata->namespace = $this->_namespace; + $metadata = new ClassMetadata($this->namespace . '\EntityGeneratorIsbn', $this->staticMetadataBuildingContext); + $metadata->isEmbeddedClass = true; - $metadata->mapField(['fieldName' => 'prefix', 'type' => 'integer']); - $metadata->mapField(['fieldName' => 'groupNumber', 'type' => 'integer']); - $metadata->mapField(['fieldName' => 'publisherNumber', 'type' => 'integer']); - $metadata->mapField(['fieldName' => 'titleNumber', 'type' => 'integer']); - $metadata->mapField(['fieldName' => 'checkDigit', 'type' => 'integer']); + + $fieldMetadata = new Mapping\FieldMetadata('prefix'); + $fieldMetadata->setType(Type::getType('integer')); + $fieldMetadata->setNullable(false); + $fieldMetadata->setUnique(false); + + $metadata->addProperty($fieldMetadata); + + $fieldMetadata = new Mapping\FieldMetadata('groupNumber'); + $fieldMetadata->setType(Type::getType('integer')); + $fieldMetadata->setNullable(false); + $fieldMetadata->setUnique(false); + + $metadata->addProperty($fieldMetadata); + + $fieldMetadata = new Mapping\FieldMetadata('publisherNumber'); + $fieldMetadata->setType(Type::getType('integer')); + $fieldMetadata->setNullable(false); + $fieldMetadata->setUnique(false); + + $metadata->addProperty($fieldMetadata); + + $fieldMetadata = new Mapping\FieldMetadata('titleNumber'); + $fieldMetadata->setType(Type::getType('integer')); + $fieldMetadata->setNullable(false); + $fieldMetadata->setUnique(false); + + $metadata->addProperty($fieldMetadata); + + $fieldMetadata = new Mapping\FieldMetadata('checkDigit'); + $fieldMetadata->setType(Type::getType('integer')); + $fieldMetadata->setNullable(false); + $fieldMetadata->setUnique(false); + + $metadata->addProperty($fieldMetadata); foreach ($embeddedClasses as $fieldName => $embeddedClass) { - $this->mapEmbedded($fieldName, $metadata, $embeddedClass, $columnPrefix); + $metadata->mapEmbedded( + [ + 'fieldName' => $fieldName, + 'class' => $embeddedClass->getClassName(), + 'columnPrefix' => $columnPrefix, + ] + ); } - $this->_generator->writeEntityClass($metadata, $this->_tmpDir); + $this->generator->writeEntityClass($metadata, $this->tmpDir); return $metadata; } /** - * @return ClassMetadataInfo + * @return ClassMetadata */ private function generateTestEmbeddableFixture() { - $metadata = new ClassMetadataInfo($this->_namespace . '\EntityGeneratorTestEmbeddable'); - $metadata->namespace = $this->_namespace; + $metadata = new ClassMetadata($this->namespace . '\EntityGeneratorTestEmbeddable', $this->staticMetadataBuildingContext); + $metadata->isEmbeddedClass = true; - $metadata->mapField(['fieldName' => 'field1', 'type' => 'integer']); - $metadata->mapField(['fieldName' => 'field2', 'type' => 'integer', 'nullable' => true]); - $metadata->mapField(['fieldName' => 'field3', 'type' => 'datetime']); - $metadata->mapField(['fieldName' => 'field4', 'type' => 'datetime', 'nullable' => true]); - $this->_generator->writeEntityClass($metadata, $this->_tmpDir); + $fieldMetadata = new Mapping\FieldMetadata('field1'); + $fieldMetadata->setType(Type::getType('integer')); + $fieldMetadata->setNullable(false); + $fieldMetadata->setUnique(false); - return $metadata; - } + $metadata->addProperty($fieldMetadata); - /** - * @param string $fieldName - * @param ClassMetadataInfo $classMetadata - * @param ClassMetadataInfo $embeddableMetadata - * @param string|null $columnPrefix - */ - private function mapEmbedded( - $fieldName, - ClassMetadataInfo $classMetadata, - ClassMetadataInfo $embeddableMetadata, - $columnPrefix = false - ) { - $classMetadata->mapEmbedded( - ['fieldName' => $fieldName, 'class' => $embeddableMetadata->name, 'columnPrefix' => $columnPrefix] - ); - } + $fieldMetadata = new Mapping\FieldMetadata('field2'); + $fieldMetadata->setType(Type::getType('integer')); + $fieldMetadata->setNullable(true); + $fieldMetadata->setUnique(false); - /** - * @param string $fieldName - * @param ClassMetadataInfo $classMetadata - * @param ClassMetadataInfo $embeddableMetadata - */ - private function mapNestedEmbedded( - $fieldName, - ClassMetadataInfo $classMetadata, - ClassMetadataInfo $embeddableMetadata - ) { - foreach ($embeddableMetadata->embeddedClasses as $property => $embeddableClass) { - $classMetadata->mapEmbedded( - [ - 'fieldName' => $fieldName . '.' . $property, - 'class' => $embeddableClass['class'], - 'columnPrefix' => $embeddableClass['columnPrefix'], - 'declaredField' => $embeddableClass['declaredField'] - ? $fieldName . '.' . $embeddableClass['declaredField'] - : $fieldName, - 'originalField' => $embeddableClass['originalField'] ?: $property, - ] - ); - } + $metadata->addProperty($fieldMetadata); + + $fieldMetadata = new Mapping\FieldMetadata('field3'); + $fieldMetadata->setType(Type::getType('datetime')); + $fieldMetadata->setNullable(false); + $fieldMetadata->setUnique(false); + + $metadata->addProperty($fieldMetadata); + + $fieldMetadata = new Mapping\FieldMetadata('field4'); + $fieldMetadata->setType(Type::getType('datetime')); + $fieldMetadata->setNullable(true); + $fieldMetadata->setUnique(false); + + $metadata->addProperty($fieldMetadata); + + $this->generator->writeEntityClass($metadata, $this->tmpDir); + + return $metadata; } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata */ - private function loadEntityClass(ClassMetadataInfo $metadata) + private function loadEntityClass(ClassMetadata $metadata) { - $className = basename(str_replace('\\', '/', $metadata->name)); - $path = $this->_tmpDir . '/' . $this->_namespace . '/' . $className . '.php'; + $className = basename(str_replace('\\', '/', $metadata->getClassName())); + $path = $this->tmpDir . '/' . $this->namespace . '/' . $className . '.php'; - $this->assertFileExists($path); + self::assertFileExists($path); require_once $path; } /** - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata * * @return mixed An instance of the given metadata's class. */ - public function newInstance($metadata) + public function newInstance(ClassMetadata $metadata) { $this->loadEntityClass($metadata); - return new $metadata->name; + $className = $metadata->getClassName(); + + return new $className; } /** + * @group embedded * @group GH-6314 */ public function testEmbeddedEntityWithNamedColumnPrefix() @@ -237,11 +376,12 @@ public function testEmbeddedEntityWithNamedColumnPrefix() self::assertTrue($refClass->hasProperty('testEmbedded')); $docComment = $refClass->getProperty('testEmbedded')->getDocComment(); - $needle = sprintf('@Embedded(class="%s", columnPrefix="%s")', $testMetadata->name, $columnPrefix); + $needle = sprintf('@Embedded(class="%s", columnPrefix="%s")', $testMetadata->getClassName(), $columnPrefix); self::assertContains($needle, $docComment); } /** + * @group embedded * @group GH-6314 */ public function testEmbeddedEntityWithoutColumnPrefix() @@ -253,144 +393,137 @@ public function testEmbeddedEntityWithoutColumnPrefix() self::assertTrue($refClass->hasProperty('testEmbedded')); $docComment = $refClass->getProperty('testEmbedded')->getDocComment(); - $needle = sprintf('@Embedded(class="%s", columnPrefix=false)', $testMetadata->name); + $needle = sprintf('@Embedded(class="%s", columnPrefix=false)', $testMetadata->getClassName()); self::assertContains($needle, $docComment); } + /** + * @group embedded + */ public function testGeneratedEntityClass() { $testMetadata = $this->generateTestEmbeddableFixture(); $isbnMetadata = $this->generateIsbnEmbeddableFixture(['test' => $testMetadata]); - $metadata = $this->generateBookEntityFixture(['isbn' => $isbnMetadata]); + $metadata = $this->generateBookEntityFixture(['isbn' => $isbnMetadata]); + $book = $this->newInstance($metadata); - $book = $this->newInstance($metadata); - $this->assertTrue(class_exists($metadata->name), "Class does not exist."); - $this->assertTrue(method_exists($metadata->namespace . '\EntityGeneratorBook', '__construct'), "EntityGeneratorBook::__construct() missing."); - $this->assertTrue(method_exists($metadata->namespace . '\EntityGeneratorBook', 'getId'), "EntityGeneratorBook::getId() missing."); - $this->assertTrue(method_exists($metadata->namespace . '\EntityGeneratorBook', 'setName'), "EntityGeneratorBook::setName() missing."); - $this->assertTrue(method_exists($metadata->namespace . '\EntityGeneratorBook', 'getName'), "EntityGeneratorBook::getName() missing."); - $this->assertTrue(method_exists($metadata->namespace . '\EntityGeneratorBook', 'setStatus'), "EntityGeneratorBook::setStatus() missing."); - $this->assertTrue(method_exists($metadata->namespace . '\EntityGeneratorBook', 'getStatus'), "EntityGeneratorBook::getStatus() missing."); - $this->assertTrue(method_exists($metadata->namespace . '\EntityGeneratorBook', 'setAuthor'), "EntityGeneratorBook::setAuthor() missing."); - $this->assertTrue(method_exists($metadata->namespace . '\EntityGeneratorBook', 'getAuthor'), "EntityGeneratorBook::getAuthor() missing."); - $this->assertTrue(method_exists($metadata->namespace . '\EntityGeneratorBook', 'getComments'), "EntityGeneratorBook::getComments() missing."); - $this->assertTrue(method_exists($metadata->namespace . '\EntityGeneratorBook', 'addComment'), "EntityGeneratorBook::addComment() missing."); - $this->assertTrue(method_exists($metadata->namespace . '\EntityGeneratorBook', 'removeComment'), "EntityGeneratorBook::removeComment() missing."); - $this->assertTrue(method_exists($metadata->namespace . '\EntityGeneratorBook', 'setIsbn'), "EntityGeneratorBook::setIsbn() missing."); - $this->assertTrue(method_exists($metadata->namespace . '\EntityGeneratorBook', 'getIsbn'), "EntityGeneratorBook::getIsbn() missing."); - - $reflClass = new \ReflectionClass($metadata->name); - - $this->assertCount(6, $reflClass->getProperties()); - $this->assertCount(15, $reflClass->getMethods()); - - $this->assertEquals('published', $book->getStatus()); + $bookClassName = $metadata->getClassName(); + + self::assertTrue(class_exists($bookClassName), "Class does not exist."); + self::assertTrue(method_exists($bookClassName, '__construct'), "EntityGeneratorBook::__construct() missing."); + self::assertTrue(method_exists($bookClassName, 'getId'), "EntityGeneratorBook::getId() missing."); + self::assertTrue(method_exists($bookClassName, 'setName'), "EntityGeneratorBook::setName() missing."); + self::assertTrue(method_exists($bookClassName, 'getName'), "EntityGeneratorBook::getName() missing."); + self::assertTrue(method_exists($bookClassName, 'setStatus'), "EntityGeneratorBook::setStatus() missing."); + self::assertTrue(method_exists($bookClassName, 'getStatus'), "EntityGeneratorBook::getStatus() missing."); + self::assertTrue(method_exists($bookClassName, 'setAuthor'), "EntityGeneratorBook::setAuthor() missing."); + self::assertTrue(method_exists($bookClassName, 'getAuthor'), "EntityGeneratorBook::getAuthor() missing."); + self::assertTrue(method_exists($bookClassName, 'getComments'), "EntityGeneratorBook::getComments() missing."); + self::assertTrue(method_exists($bookClassName, 'addComment'), "EntityGeneratorBook::addComment() missing."); + self::assertTrue(method_exists($bookClassName, 'removeComment'), "EntityGeneratorBook::removeComment() missing."); + self::assertTrue(method_exists($bookClassName, 'setIsbn'), "EntityGeneratorBook::setIsbn() missing."); + self::assertTrue(method_exists($bookClassName, 'getIsbn'), "EntityGeneratorBook::getIsbn() missing."); + + $reflClass = new \ReflectionClass($metadata->getClassName()); + + self::assertCount(6, $reflClass->getProperties()); + self::assertCount(15, $reflClass->getMethods()); + + self::assertEquals('published', $book->getStatus()); $book->setName('Jonathan H. Wage'); - $this->assertEquals('Jonathan H. Wage', $book->getName()); + self::assertEquals('Jonathan H. Wage', $book->getName()); - $reflMethod = new \ReflectionMethod($metadata->name, 'addComment'); + $reflMethod = new \ReflectionMethod($metadata->getClassName(), 'addComment'); $addCommentParameters = $reflMethod->getParameters(); - $this->assertEquals('comment', $addCommentParameters[0]->getName()); + self::assertEquals('comment', $addCommentParameters[0]->getName()); - $reflMethod = new \ReflectionMethod($metadata->name, 'removeComment'); + $reflMethod = new \ReflectionMethod($metadata->getClassName(), 'removeComment'); $removeCommentParameters = $reflMethod->getParameters(); - $this->assertEquals('comment', $removeCommentParameters[0]->getName()); + self::assertEquals('comment', $removeCommentParameters[0]->getName()); $author = new EntityGeneratorAuthor(); $book->setAuthor($author); - $this->assertEquals($author, $book->getAuthor()); + self::assertEquals($author, $book->getAuthor()); $comment = new EntityGeneratorComment(); - $this->assertInstanceOf($metadata->name, $book->addComment($comment)); - $this->assertInstanceOf(ArrayCollection::class, $book->getComments()); - $this->assertEquals(new ArrayCollection([$comment]), $book->getComments()); - $this->assertInternalType('boolean', $book->removeComment($comment)); - $this->assertEquals(new ArrayCollection([]), $book->getComments()); + self::assertInstanceOf($metadata->getClassName(), $book->addComment($comment)); + self::assertInstanceOf(ArrayCollection::class, $book->getComments()); + self::assertEquals(new ArrayCollection([$comment]), $book->getComments()); + self::assertInternalType('boolean', $book->removeComment($comment)); + self::assertEquals(new ArrayCollection([]), $book->getComments()); $this->newInstance($isbnMetadata); - $isbn = new $isbnMetadata->name(); + + $isbnClassName = $isbnMetadata->getClassName(); + + $isbn = new $isbnClassName(); $book->setIsbn($isbn); - $this->assertSame($isbn, $book->getIsbn()); + self::assertSame($isbn, $book->getIsbn()); - $reflMethod = new \ReflectionMethod($metadata->name, 'setIsbn'); + $reflMethod = new \ReflectionMethod($metadata->getClassName(), 'setIsbn'); $reflParameters = $reflMethod->getParameters(); - $this->assertEquals($isbnMetadata->name, $reflParameters[0]->getClass()->name); + self::assertEquals($isbnMetadata->getClassName(), $reflParameters[0]->getClass()->name); } + /** + * @group embedded + */ public function testEntityUpdatingWorks() { $metadata = $this->generateBookEntityFixture(['isbn' => $this->generateIsbnEmbeddableFixture()]); - $metadata->mapField(['fieldName' => 'test', 'type' => 'string']); + $fieldMetadata = new Mapping\FieldMetadata('test'); + + $fieldMetadata->setType(Type::getType('string')); + + $metadata->addProperty($fieldMetadata); $testEmbeddableMetadata = $this->generateTestEmbeddableFixture(); - $this->mapEmbedded('testEmbedded', $metadata, $testEmbeddableMetadata); - $this->_generator->writeEntityClass($metadata, $this->_tmpDir); + $metadata->mapEmbedded( + [ + 'fieldName' => 'testEmbedded', + 'class' => $testEmbeddableMetadata->getClassName(), + 'columnPrefix' => null, + ] + ); + + $this->generator->writeEntityClass($metadata, $this->tmpDir); - $this->assertFileExists($this->_tmpDir . "/" . $this->_namespace . "/EntityGeneratorBook.php~"); + self::assertFileExists($this->tmpDir . "/" . $this->namespace . "/EntityGeneratorBook.php~"); $book = $this->newInstance($metadata); - $reflClass = new \ReflectionClass($metadata->name); - - $this->assertTrue($reflClass->hasProperty('name'), "Regenerating keeps property 'name'."); - $this->assertTrue($reflClass->hasProperty('status'), "Regenerating keeps property 'status'."); - $this->assertTrue($reflClass->hasProperty('id'), "Regenerating keeps property 'id'."); - $this->assertTrue($reflClass->hasProperty('isbn'), "Regenerating keeps property 'isbn'."); - - $this->assertTrue($reflClass->hasProperty('test'), "Check for property test failed."); - $this->assertTrue($reflClass->getProperty('test')->isProtected(), "Check for protected property test failed."); - $this->assertTrue($reflClass->hasProperty('testEmbedded'), "Check for property testEmbedded failed."); - $this->assertTrue($reflClass->getProperty('testEmbedded')->isProtected(), "Check for protected property testEmbedded failed."); - $this->assertTrue($reflClass->hasMethod('getTest'), "Check for method 'getTest' failed."); - $this->assertTrue($reflClass->getMethod('getTest')->isPublic(), "Check for public visibility of method 'getTest' failed."); - $this->assertTrue($reflClass->hasMethod('setTest'), "Check for method 'setTest' failed."); - $this->assertTrue($reflClass->getMethod('setTest')->isPublic(), "Check for public visibility of method 'setTest' failed."); - $this->assertTrue($reflClass->hasMethod('getTestEmbedded'), "Check for method 'getTestEmbedded' failed."); - $this->assertTrue( + $reflClass = new \ReflectionClass($metadata->getClassName()); + + self::assertTrue($reflClass->hasProperty('name'), "Regenerating keeps property 'name'."); + self::assertTrue($reflClass->hasProperty('status'), "Regenerating keeps property 'status'."); + self::assertTrue($reflClass->hasProperty('id'), "Regenerating keeps property 'id'."); + self::assertTrue($reflClass->hasProperty('isbn'), "Regenerating keeps property 'isbn'."); + + self::assertTrue($reflClass->hasProperty('test'), "Check for property test failed."); + self::assertTrue($reflClass->getProperty('test')->isProtected(), "Check for protected property test failed."); + self::assertTrue($reflClass->hasProperty('testEmbedded'), "Check for property testEmbedded failed."); + self::assertTrue($reflClass->getProperty('testEmbedded')->isProtected(), "Check for protected property testEmbedded failed."); + self::assertTrue($reflClass->hasMethod('getTest'), "Check for method 'getTest' failed."); + self::assertTrue($reflClass->getMethod('getTest')->isPublic(), "Check for public visibility of method 'getTest' failed."); + self::assertTrue($reflClass->hasMethod('setTest'), "Check for method 'setTest' failed."); + self::assertTrue($reflClass->getMethod('setTest')->isPublic(), "Check for public visibility of method 'setTest' failed."); + self::assertTrue($reflClass->hasMethod('getTestEmbedded'), "Check for method 'getTestEmbedded' failed."); + self::assertTrue( $reflClass->getMethod('getTestEmbedded')->isPublic(), "Check for public visibility of method 'getTestEmbedded' failed." ); - $this->assertTrue($reflClass->hasMethod('setTestEmbedded'), "Check for method 'setTestEmbedded' failed."); - $this->assertTrue( + self::assertTrue($reflClass->hasMethod('setTestEmbedded'), "Check for method 'setTestEmbedded' failed."); + self::assertTrue( $reflClass->getMethod('setTestEmbedded')->isPublic(), "Check for public visibility of method 'setTestEmbedded' failed." ); } /** - * @group DDC-3152 - */ - public function testDoesNotRegenerateExistingMethodsWithDifferentCase() - { - $metadata = $this->generateBookEntityFixture(['isbn' => $this->generateIsbnEmbeddableFixture()]); - - // Workaround to change existing fields case (just to simulate the use case) - $metadata->fieldMappings['status']['fieldName'] = 'STATUS'; - $metadata->embeddedClasses['ISBN'] = $metadata->embeddedClasses['isbn']; - unset($metadata->embeddedClasses['isbn']); - - // Should not throw a PHP fatal error - $this->_generator->writeEntityClass($metadata, $this->_tmpDir); - - $this->assertFileExists($this->_tmpDir . "/" . $this->_namespace . "/EntityGeneratorBook.php~"); - - $this->newInstance($metadata); - $reflClass = new \ReflectionClass($metadata->name); - - $this->assertTrue($reflClass->hasProperty('status')); - $this->assertTrue($reflClass->hasProperty('STATUS')); - $this->assertTrue($reflClass->hasProperty('isbn')); - $this->assertTrue($reflClass->hasProperty('ISBN')); - $this->assertTrue($reflClass->hasMethod('getStatus')); - $this->assertTrue($reflClass->hasMethod('setStatus')); - $this->assertTrue($reflClass->hasMethod('getIsbn')); - $this->assertTrue($reflClass->hasMethod('setIsbn')); - } - - /** + * @group embedded * @group DDC-2121 */ public function testMethodDocBlockShouldStartWithBackSlash() @@ -399,34 +532,38 @@ public function testMethodDocBlockShouldStartWithBackSlash() $metadata = $this->generateBookEntityFixture(['isbn' => $embeddedMetadata]); $book = $this->newInstance($metadata); - $this->assertPhpDocVarType('\Doctrine\Common\Collections\Collection', new \ReflectionProperty($book, 'comments')); - $this->assertPhpDocReturnType('\Doctrine\Common\Collections\Collection', new \ReflectionMethod($book, 'getComments')); - $this->assertPhpDocParamType('\Doctrine\Tests\ORM\Tools\EntityGeneratorComment', new \ReflectionMethod($book, 'addComment')); - $this->assertPhpDocReturnType('EntityGeneratorBook', new \ReflectionMethod($book, 'addComment')); - $this->assertPhpDocParamType('\Doctrine\Tests\ORM\Tools\EntityGeneratorComment', new \ReflectionMethod($book, 'removeComment')); - $this->assertPhpDocReturnType('boolean', new \ReflectionMethod($book, 'removeComment')); - - $this->assertPhpDocVarType('\Doctrine\Tests\ORM\Tools\EntityGeneratorAuthor', new \ReflectionProperty($book, 'author')); - $this->assertPhpDocReturnType('\Doctrine\Tests\ORM\Tools\EntityGeneratorAuthor|null', new \ReflectionMethod($book, 'getAuthor')); - $this->assertPhpDocParamType('\Doctrine\Tests\ORM\Tools\EntityGeneratorAuthor|null', new \ReflectionMethod($book, 'setAuthor')); - - $expectedClassName = '\\' . $embeddedMetadata->name; - $this->assertPhpDocVarType($expectedClassName, new \ReflectionProperty($book, 'isbn')); - $this->assertPhpDocReturnType($expectedClassName, new \ReflectionMethod($book, 'getIsbn')); - $this->assertPhpDocParamType($expectedClassName, new \ReflectionMethod($book, 'setIsbn')); + self::assertPhpDocVarType('\Doctrine\Common\Collections\Collection', new \ReflectionProperty($book, 'comments')); + self::assertPhpDocReturnType('\Doctrine\Common\Collections\Collection', new \ReflectionMethod($book, 'getComments')); + self::assertPhpDocParamType('\Doctrine\Tests\ORM\Tools\EntityGeneratorComment', new \ReflectionMethod($book, 'addComment')); + self::assertPhpDocReturnType('EntityGeneratorBook', new \ReflectionMethod($book, 'addComment')); + self::assertPhpDocParamType('\Doctrine\Tests\ORM\Tools\EntityGeneratorComment', new \ReflectionMethod($book, 'removeComment')); + self::assertPhpDocReturnType('boolean', new \ReflectionMethod($book, 'removeComment')); + + self::assertPhpDocVarType('\Doctrine\Tests\ORM\Tools\EntityGeneratorAuthor', new \ReflectionProperty($book, 'author')); + self::assertPhpDocReturnType('\Doctrine\Tests\ORM\Tools\EntityGeneratorAuthor|null', new \ReflectionMethod($book, 'getAuthor')); + self::assertPhpDocParamType('\Doctrine\Tests\ORM\Tools\EntityGeneratorAuthor|null', new \ReflectionMethod($book, 'setAuthor')); + + $expectedClassName = '\\' . $embeddedMetadata->getClassName(); + + self::assertPhpDocVarType($expectedClassName, new \ReflectionProperty($book, 'isbn')); + self::assertPhpDocReturnType($expectedClassName, new \ReflectionMethod($book, 'getIsbn')); + self::assertPhpDocParamType($expectedClassName, new \ReflectionMethod($book, 'setIsbn')); } + /** + * @group embedded + */ public function testEntityExtendsStdClass() { - $this->_generator->setClassToExtend('stdClass'); + $this->generator->setClassToExtend('stdClass'); $metadata = $this->generateBookEntityFixture(); $book = $this->newInstance($metadata); - $this->assertInstanceOf('stdClass', $book); + self::assertInstanceOf('stdClass', $book); $metadata = $this->generateIsbnEmbeddableFixture(); $isbn = $this->newInstance($metadata); - $this->assertInstanceOf('stdClass', $isbn); + self::assertInstanceOf('stdClass', $isbn); } public function testLifecycleCallbacks() @@ -434,53 +571,50 @@ public function testLifecycleCallbacks() $metadata = $this->generateBookEntityFixture(); $book = $this->newInstance($metadata); - $reflClass = new \ReflectionClass($metadata->name); + $reflClass = new \ReflectionClass($metadata->getClassName()); - $this->assertTrue($reflClass->hasMethod('loading'), "Check for postLoad lifecycle callback."); - $this->assertTrue($reflClass->hasMethod('willBeRemoved'), "Check for preRemove lifecycle callback."); + self::assertTrue($reflClass->hasMethod('loading'), "Check for postLoad lifecycle callback."); + self::assertTrue($reflClass->hasMethod('willBeRemoved'), "Check for preRemove lifecycle callback."); } + /** + * @group embedded + */ public function testLoadMetadata() { $embeddedMetadata = $this->generateIsbnEmbeddableFixture(); - $metadata = $this->generateBookEntityFixture(['isbn' => $embeddedMetadata]); + $metadata = $this->generateBookEntityFixture(['isbn' => $embeddedMetadata]); + $book = $this->newInstance($metadata); - $book = $this->newInstance($metadata); - - $reflectionService = new RuntimeReflectionService(); - - $cm = new ClassMetadataInfo($metadata->name); - $cm->initializeReflection($reflectionService); + $cm = new ClassMetadata($metadata->getClassName(), $this->runtimeMetadataBuildingContext); $driver = $this->createAnnotationDriver(); - $driver->loadMetadataForClass($cm->name, $cm); + $driver->loadMetadataForClass($cm->getClassName(), $cm, $this->runtimeMetadataBuildingContext); - $this->assertEquals($cm->columnNames, $metadata->columnNames); - $this->assertEquals($cm->getTableName(), $metadata->getTableName()); - $this->assertEquals($cm->lifecycleCallbacks, $metadata->lifecycleCallbacks); - $this->assertEquals($cm->identifier, $metadata->identifier); - $this->assertEquals($cm->idGenerator, $metadata->idGenerator); - $this->assertEquals($cm->customRepositoryClassName, $metadata->customRepositoryClassName); - $this->assertEquals($cm->embeddedClasses, $metadata->embeddedClasses); - $this->assertEquals($cm->isEmbeddedClass, $metadata->isEmbeddedClass); + self::assertEquals($cm->getTableName(), $metadata->getTableName()); + self::assertEquals($cm->lifecycleCallbacks, $metadata->lifecycleCallbacks); + self::assertEquals($cm->identifier, $metadata->identifier); + self::assertEquals($cm->getCustomRepositoryClassName(), $metadata->getCustomRepositoryClassName()); + self::assertEquals($cm->embeddedClasses, $metadata->embeddedClasses); + self::assertEquals($cm->isEmbeddedClass, $metadata->isEmbeddedClass); - $this->assertEquals(ClassMetadataInfo::FETCH_EXTRA_LAZY, $cm->associationMappings['comments']['fetch']); + self::assertEquals(Mapping\FetchMode::EXTRA_LAZY, $cm->getProperty('comments')->getFetchMode()); $isbn = $this->newInstance($embeddedMetadata); - $cm = new ClassMetadataInfo($embeddedMetadata->name); - $cm->initializeReflection($reflectionService); + $cm = new ClassMetadata($embeddedMetadata->getClassName(), $this->runtimeMetadataBuildingContext); - $driver->loadMetadataForClass($cm->name, $cm); + $driver->loadMetadataForClass($cm->getClassName(), $cm); - $this->assertEquals($cm->columnNames, $embeddedMetadata->columnNames); - $this->assertEquals($cm->embeddedClasses, $embeddedMetadata->embeddedClasses); - $this->assertEquals($cm->isEmbeddedClass, $embeddedMetadata->isEmbeddedClass); + self::assertEquals($cm->embeddedClasses, $embeddedMetadata->embeddedClasses); + self::assertEquals($cm->isEmbeddedClass, $embeddedMetadata->isEmbeddedClass); } + /** + * @group embedded + */ public function testLoadPrefixedMetadata() { - $this->_generator->setAnnotationPrefix('ORM\\'); $embeddedMetadata = $this->generateIsbnEmbeddableFixture(); $metadata = $this->generateBookEntityFixture(['isbn' => $embeddedMetadata]); @@ -489,30 +623,23 @@ public function testLoadPrefixedMetadata() $book = $this->newInstance($metadata); - $reflectionService = new RuntimeReflectionService(); - - $cm = new ClassMetadataInfo($metadata->name); - $cm->initializeReflection($reflectionService); + $cm = new ClassMetadata($metadata->getClassName(), $this->runtimeMetadataBuildingContext); - $driver->loadMetadataForClass($cm->name, $cm); + $driver->loadMetadataForClass($cm->getClassName(), $cm, $this->runtimeMetadataBuildingContext); - $this->assertEquals($cm->columnNames, $metadata->columnNames); - $this->assertEquals($cm->getTableName(), $metadata->getTableName()); - $this->assertEquals($cm->lifecycleCallbacks, $metadata->lifecycleCallbacks); - $this->assertEquals($cm->identifier, $metadata->identifier); - $this->assertEquals($cm->idGenerator, $metadata->idGenerator); - $this->assertEquals($cm->customRepositoryClassName, $metadata->customRepositoryClassName); + self::assertEquals($cm->getTableName(), $metadata->getTableName()); + self::assertEquals($cm->lifecycleCallbacks, $metadata->lifecycleCallbacks); + self::assertEquals($cm->identifier, $metadata->identifier); + self::assertEquals($cm->getCustomRepositoryClassName(), $metadata->getCustomRepositoryClassName()); $isbn = $this->newInstance($embeddedMetadata); - $cm = new ClassMetadataInfo($embeddedMetadata->name); - $cm->initializeReflection($reflectionService); + $cm = new ClassMetadata($embeddedMetadata->getClassName(), $this->runtimeMetadataBuildingContext); - $driver->loadMetadataForClass($cm->name, $cm); + $driver->loadMetadataForClass($cm->getClassName(), $cm); - $this->assertEquals($cm->columnNames, $embeddedMetadata->columnNames); - $this->assertEquals($cm->embeddedClasses, $embeddedMetadata->embeddedClasses); - $this->assertEquals($cm->isEmbeddedClass, $embeddedMetadata->isEmbeddedClass); + self::assertEquals($cm->embeddedClasses, $embeddedMetadata->embeddedClasses); + self::assertEquals($cm->isEmbeddedClass, $embeddedMetadata->isEmbeddedClass); } /** @@ -520,21 +647,20 @@ public function testLoadPrefixedMetadata() */ public function testMappedSuperclassAnnotationGeneration() { - $metadata = new ClassMetadataInfo($this->_namespace . '\EntityGeneratorBook'); - $metadata->namespace = $this->_namespace; + $metadata = new ClassMetadata($this->namespace . '\EntityGeneratorBook', $this->staticMetadataBuildingContext); + $metadata->isMappedSuperclass = true; - $this->_generator->setAnnotationPrefix('ORM\\'); - $this->_generator->writeEntityClass($metadata, $this->_tmpDir); + $this->generator->writeEntityClass($metadata, $this->tmpDir); + $this->newInstance($metadata); // force instantiation (causes autoloading to kick in) $driver = new AnnotationDriver(new AnnotationReader(), []); - $cm = new ClassMetadataInfo($metadata->name); + $cm = new ClassMetadata($metadata->getClassName(), $this->runtimeMetadataBuildingContext); - $cm->initializeReflection(new RuntimeReflectionService); - $driver->loadMetadataForClass($cm->name, $cm); + $driver->loadMetadataForClass($cm->getClassName(), $cm, $this->runtimeMetadataBuildingContext); - $this->assertTrue($cm->isMappedSuperclass); + self::assertTrue($cm->isMappedSuperclass); } /** @@ -542,15 +668,15 @@ public function testMappedSuperclassAnnotationGeneration() */ public function testParseTokensInEntityFile($php, $classes) { - $r = new \ReflectionObject($this->_generator); + $r = new \ReflectionObject($this->generator); $m = $r->getMethod('parseTokensInEntityFile'); $m->setAccessible(true); $p = $r->getProperty('staticReflection'); $p->setAccessible(true); - $ret = $m->invoke($this->_generator, $php); - $this->assertEquals($classes, array_keys($p->getValue($this->_generator))); + $ret = $m->invoke($this->generator, $php); + self::assertEquals($classes, array_keys($p->getValue($this->generator))); } /** @@ -558,33 +684,38 @@ public function testParseTokensInEntityFile($php, $classes) */ public function testGenerateEntityWithSequenceGenerator() { - $metadata = new ClassMetadataInfo($this->_namespace . '\DDC1784Entity'); - $metadata->namespace = $this->_namespace; - $metadata->mapField(['fieldName' => 'id', 'type' => 'integer', 'id' => true]); - $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE); - $metadata->setSequenceGeneratorDefinition( + $metadata = new ClassMetadata($this->namespace . '\DDC1784Entity', $this->staticMetadataBuildingContext); + $metadata->setTable(new Mapping\TableMetadata('ddc1784_entity')); + + $fieldMetadata = new Mapping\FieldMetadata('id'); + $fieldMetadata->setType(Type::getType('integer')); + $fieldMetadata->setPrimaryKey(true); + $fieldMetadata->setValueGenerator(new Mapping\ValueGeneratorMetadata( + Mapping\GeneratorType::SEQUENCE, [ - 'sequenceName' => 'DDC1784_ID_SEQ', - 'allocationSize' => 1, - 'initialValue' => 2 + 'sequenceName' => 'DDC1784_ID_SEQ', + 'allocationSize' => 1, ] - ); - $this->_generator->writeEntityClass($metadata, $this->_tmpDir); + )); - $filename = $this->_tmpDir . DIRECTORY_SEPARATOR - . $this->_namespace . DIRECTORY_SEPARATOR . 'DDC1784Entity.php'; + $metadata->addProperty($fieldMetadata); - $this->assertFileExists($filename); - require_once $filename; + $this->generator->writeEntityClass($metadata, $this->tmpDir); + + $filename = $this->tmpDir . DIRECTORY_SEPARATOR + . $this->namespace . DIRECTORY_SEPARATOR . 'DDC1784Entity.php'; + self::assertFileExists($filename); - $reflection = new \ReflectionProperty($metadata->name, 'id'); + require_once $filename; + + $reflection = new \ReflectionProperty($metadata->getClassName(), 'id'); $docComment = $reflection->getDocComment(); - $this->assertContains('@Id', $docComment); - $this->assertContains('@Column(name="id", type="integer")', $docComment); - $this->assertContains('@GeneratedValue(strategy="SEQUENCE")', $docComment); - $this->assertContains('@SequenceGenerator(sequenceName="DDC1784_ID_SEQ", allocationSize=1, initialValue=2)', $docComment); + self::assertContains('@ORM\Id', $docComment); + self::assertContains('@ORM\Column(name="id", type="integer")', $docComment); + self::assertContains('@ORM\GeneratedValue(strategy="SEQUENCE")', $docComment); + self::assertContains('@ORM\SequenceGenerator(sequenceName="DDC1784_ID_SEQ", allocationSize=1)', $docComment); } /** @@ -592,44 +723,68 @@ public function testGenerateEntityWithSequenceGenerator() */ public function testGenerateEntityWithMultipleInverseJoinColumns() { - $metadata = new ClassMetadataInfo($this->_namespace . '\DDC2079Entity'); - $metadata->namespace = $this->_namespace; - $metadata->mapField(['fieldName' => 'id', 'type' => 'integer', 'id' => true]); - $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE); - $metadata->mapManyToMany( - [ - 'fieldName' => 'centroCustos', - 'targetEntity' => 'DDC2079CentroCusto', - 'joinTable' => [ - 'name' => 'unidade_centro_custo', - 'joinColumns' => [ - ['name' => 'idorcamento', 'referencedColumnName' => 'idorcamento'], - ['name' => 'idunidade', 'referencedColumnName' => 'idunidade'] - ], - 'inverseJoinColumns' => [ - ['name' => 'idcentrocusto', 'referencedColumnName' => 'idcentrocusto'], - ['name' => 'idpais', 'referencedColumnName' => 'idpais'], - ], - ], - ] - ); - $this->_generator->writeEntityClass($metadata, $this->_tmpDir); + $metadata = new ClassMetadata($this->namespace . '\DDC2079Entity', $this->staticMetadataBuildingContext); + $metadata->setTable(new Mapping\TableMetadata('ddc2079_entity')); + + $fieldMetadata = new Mapping\FieldMetadata('id'); + $fieldMetadata->setType(Type::getType('integer')); + $fieldMetadata->setPrimaryKey(true); + $fieldMetadata->setValueGenerator(new Mapping\ValueGeneratorMetadata(Mapping\GeneratorType::SEQUENCE)); + + $metadata->addProperty($fieldMetadata); + + $joinTable = new Mapping\JoinTableMetadata(); + $joinTable->setName('unidade_centro_custo'); + + $joinColumn = new Mapping\JoinColumnMetadata(); + $joinColumn->setColumnName("idorcamento"); + $joinColumn->setReferencedColumnName("idorcamento"); + + $joinTable->addJoinColumn($joinColumn); + + $joinColumn = new Mapping\JoinColumnMetadata(); + $joinColumn->setColumnName("idunidade"); + $joinColumn->setReferencedColumnName("idunidade"); + + $joinTable->addJoinColumn($joinColumn); + + $joinColumn = new Mapping\JoinColumnMetadata(); + $joinColumn->setColumnName("idcentrocusto"); + $joinColumn->setReferencedColumnName("idcentrocusto"); + + $joinTable->addInverseJoinColumn($joinColumn); - $filename = $this->_tmpDir . DIRECTORY_SEPARATOR - . $this->_namespace . DIRECTORY_SEPARATOR . 'DDC2079Entity.php'; + $joinColumn = new Mapping\JoinColumnMetadata(); + $joinColumn->setColumnName("idpais"); + $joinColumn->setReferencedColumnName("idpais"); + + $joinTable->addInverseJoinColumn($joinColumn); + + $association = new Mapping\ManyToManyAssociationMetadata('centroCustos'); + + $association->setJoinTable($joinTable); + $association->setTargetEntity($this->namespace . '\\DDC2079CentroCusto'); + + $metadata->addProperty($association); + + $this->generator->writeEntityClass($metadata, $this->tmpDir); + + $filename = $this->tmpDir . DIRECTORY_SEPARATOR + . $this->namespace . DIRECTORY_SEPARATOR . 'DDC2079Entity.php'; + + self::assertFileExists($filename); - $this->assertFileExists($filename); require_once $filename; - $property = new \ReflectionProperty($metadata->name, 'centroCustos'); + $property = new \ReflectionProperty($metadata->getClassName(), 'centroCustos'); $docComment = $property->getDocComment(); //joinColumns - $this->assertContains('@JoinColumn(name="idorcamento", referencedColumnName="idorcamento"),', $docComment); - $this->assertContains('@JoinColumn(name="idunidade", referencedColumnName="idunidade")', $docComment); + self::assertContains('@ORM\JoinColumn(name="idorcamento", referencedColumnName="idorcamento"),', $docComment); + self::assertContains('@ORM\JoinColumn(name="idunidade", referencedColumnName="idunidade")', $docComment); //inverseJoinColumns - $this->assertContains('@JoinColumn(name="idcentrocusto", referencedColumnName="idcentrocusto"),', $docComment); - $this->assertContains('@JoinColumn(name="idpais", referencedColumnName="idpais")', $docComment); + self::assertContains('@ORM\JoinColumn(name="idcentrocusto", referencedColumnName="idcentrocusto"),', $docComment); + self::assertContains('@ORM\JoinColumn(name="idpais", referencedColumnName="idpais")', $docComment); } @@ -638,10 +793,10 @@ public function testGenerateEntityWithMultipleInverseJoinColumns() */ public function testGetInheritanceTypeString() { - $reflection = new \ReflectionClass('\Doctrine\ORM\Mapping\ClassMetadataInfo'); - $method = new \ReflectionMethod($this->_generator, 'getInheritanceTypeString'); + $reflection = new \ReflectionClass('\Doctrine\ORM\Mapping\ClassMetadata'); + $method = new \ReflectionMethod($this->generator, 'getInheritanceTypeString'); $constants = $reflection->getConstants(); - $pattern = '/^INHERITANCE_TYPE_/'; + $pattern = '/^InheritanceType::/'; $method->setAccessible(true); @@ -651,15 +806,15 @@ public function testGetInheritanceTypeString() } $expected = preg_replace($pattern, '', $name); - $actual = $method->invoke($this->_generator, $value); + $actual = $method->invoke($this->generator, $value); - $this->assertEquals($expected, $actual); + self::assertEquals($expected, $actual); } $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Invalid provided InheritanceType: INVALID'); - $method->invoke($this->_generator, 'INVALID'); + $method->invoke($this->generator, 'INVALID'); } /** @@ -668,9 +823,9 @@ public function testGetInheritanceTypeString() public function testGetChangeTrackingPolicyString() { $reflection = new \ReflectionClass('\Doctrine\ORM\Mapping\ClassMetadata'); - $method = new \ReflectionMethod($this->_generator, 'getChangeTrackingPolicyString'); + $method = new \ReflectionMethod($this->generator, 'getChangeTrackingPolicyString'); $constants = $reflection->getConstants(); - $pattern = '/^CHANGETRACKING_/'; + $pattern = '/^ChangeTrackingPolicy::/'; $method->setAccessible(true); @@ -680,15 +835,15 @@ public function testGetChangeTrackingPolicyString() } $expected = preg_replace($pattern, '', $name); - $actual = $method->invoke($this->_generator, $value); + $actual = $method->invoke($this->generator, $value); - $this->assertEquals($expected, $actual); + self::assertEquals($expected, $actual); } $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Invalid provided ChangeTrackingPolicy: INVALID'); - $method->invoke($this->_generator, 'INVALID'); + $method->invoke($this->generator, 'INVALID'); } /** @@ -696,10 +851,10 @@ public function testGetChangeTrackingPolicyString() */ public function testGetIdGeneratorTypeString() { - $reflection = new \ReflectionClass('\Doctrine\ORM\Mapping\ClassMetadataInfo'); - $method = new \ReflectionMethod($this->_generator, 'getIdGeneratorTypeString'); + $reflection = new \ReflectionClass('\Doctrine\ORM\Mapping\ClassMetadata'); + $method = new \ReflectionMethod($this->generator, 'getIdGeneratorTypeString'); $constants = $reflection->getConstants(); - $pattern = '/^GENERATOR_TYPE_/'; + $pattern = '/^GeneratorType::/'; $method->setAccessible(true); @@ -709,15 +864,15 @@ public function testGetIdGeneratorTypeString() } $expected = preg_replace($pattern, '', $name); - $actual = $method->invoke($this->_generator, $value); + $actual = $method->invoke($this->generator, $value); - $this->assertEquals($expected, $actual); + self::assertEquals($expected, $actual); } $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Invalid provided IdGeneratorType: INVALID'); - $method->invoke($this->_generator, 'INVALID'); + $method->invoke($this->generator, 'INVALID'); } /** @@ -728,13 +883,15 @@ public function testGetIdGeneratorTypeString() public function testEntityTypeAlias(array $field) { $metadata = $this->generateEntityTypeFixture($field); - $path = $this->_tmpDir . '/'. $this->_namespace . '/EntityType.php'; + $path = $this->tmpDir . '/'. $this->namespace . '/EntityType.php'; - $this->assertFileExists($path); + self::assertFileExists($path); require_once $path; - $entity = new $metadata->name; - $reflClass = new \ReflectionClass($metadata->name); + $entityClassName = $metadata->getClassName(); + + $entity = new $entityClassName; + $reflClass = new \ReflectionClass($entityClassName); $type = $field['phpType']; $name = $field['fieldName']; @@ -742,12 +899,12 @@ public function testEntityTypeAlias(array $field) $getter = "get" . ucfirst($name); $setter = "set" . ucfirst($name); - $this->assertPhpDocVarType($type, $reflClass->getProperty($name)); - $this->assertPhpDocParamType($type, $reflClass->getMethod($setter)); - $this->assertPhpDocReturnType($type, $reflClass->getMethod($getter)); + self::assertPhpDocVarType($type, $reflClass->getProperty($name)); + self::assertPhpDocParamType($type, $reflClass->getMethod($setter)); + self::assertPhpDocReturnType($type, $reflClass->getMethod($getter)); - $this->assertSame($entity, $entity->{$setter}($value)); - $this->assertEquals($value, $entity->{$getter}()); + self::assertSame($entity, $entity->{$setter}($value)); + self::assertEquals($value, $entity->{$getter}()); } /** @@ -756,24 +913,26 @@ public function testEntityTypeAlias(array $field) public function testTraitPropertiesAndMethodsAreNotDuplicated() { $cmf = new ClassMetadataFactory(); - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); $cmf->setEntityManager($em); $user = new DDC2372User(); $metadata = $cmf->getMetadataFor(get_class($user)); - $metadata->name = $this->_namespace . "\DDC2372User"; - $metadata->namespace = $this->_namespace; - $this->_generator->writeEntityClass($metadata, $this->_tmpDir); + // @todo guilhermeblanco Fix this test as changing Entity class should never be allowed. + $metadata->setClassName($this->namespace . "\DDC2372User"); + + $this->generator->writeEntityClass($metadata, $this->tmpDir); - $this->assertFileExists($this->_tmpDir . "/" . $this->_namespace . "/DDC2372User.php"); - require $this->_tmpDir . "/" . $this->_namespace . "/DDC2372User.php"; + self::assertFileExists($this->tmpDir . "/" . $this->namespace . "/DDC2372User.php"); - $reflClass = new \ReflectionClass($metadata->name); + require $this->tmpDir . "/" . $this->namespace . "/DDC2372User.php"; - $this->assertSame($reflClass->hasProperty('address'), false); - $this->assertSame($reflClass->hasMethod('setAddress'), false); - $this->assertSame($reflClass->hasMethod('getAddress'), false); + $reflClass = new \ReflectionClass($metadata->getClassName()); + + self::assertSame($reflClass->hasProperty('address'), false); + self::assertSame($reflClass->hasMethod('setAddress'), false); + self::assertSame($reflClass->hasMethod('getAddress'), false); } /** @@ -782,24 +941,25 @@ public function testTraitPropertiesAndMethodsAreNotDuplicated() public function testTraitPropertiesAndMethodsAreNotDuplicatedInChildClasses() { $cmf = new ClassMetadataFactory(); - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); $cmf->setEntityManager($em); $user = new DDC2372Admin(); $metadata = $cmf->getMetadataFor(get_class($user)); - $metadata->name = $this->_namespace . "\DDC2372Admin"; - $metadata->namespace = $this->_namespace; - $this->_generator->writeEntityClass($metadata, $this->_tmpDir); + // @todo guilhermeblanco Fix this test as changing Entity class should never be allowed. + $metadata->setClassName($this->namespace . "\DDC2372Admin"); + + $this->generator->writeEntityClass($metadata, $this->tmpDir); - $this->assertFileExists($this->_tmpDir . "/" . $this->_namespace . "/DDC2372Admin.php"); - require $this->_tmpDir . "/" . $this->_namespace . "/DDC2372Admin.php"; + self::assertFileExists($this->tmpDir . "/" . $this->namespace . "/DDC2372Admin.php"); + require $this->tmpDir . "/" . $this->namespace . "/DDC2372Admin.php"; - $reflClass = new \ReflectionClass($metadata->name); + $reflClass = new \ReflectionClass($metadata->getClassName()); - $this->assertSame($reflClass->hasProperty('address'), false); - $this->assertSame($reflClass->hasMethod('setAddress'), false); - $this->assertSame($reflClass->hasMethod('getAddress'), false); + self::assertSame($reflClass->hasProperty('address'), false); + self::assertSame($reflClass->hasMethod('setAddress'), false); + self::assertSame($reflClass->hasMethod('getAddress'), false); } /** @@ -808,13 +968,14 @@ public function testTraitPropertiesAndMethodsAreNotDuplicatedInChildClasses() public function testMethodsAndPropertiesAreNotDuplicatedInChildClasses() { $cmf = new ClassMetadataFactory(); - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); $cmf->setEntityManager($em); - $ns = $this->_namespace; - $nsdir = $this->_tmpDir . '/' . $ns; + $ns = $this->namespace; + $nsdir = $this->tmpDir . '/' . $ns; + // Dump DDC1590User into temp file $content = str_replace( 'namespace Doctrine\Tests\Models\DDC1590', 'namespace ' . $ns, @@ -823,11 +984,12 @@ public function testMethodsAndPropertiesAreNotDuplicatedInChildClasses() $fname = $nsdir . "/DDC1590User.php"; file_put_contents($fname, $content); - require $fname; + // Require DDC1590User + require $fname; $metadata = $cmf->getMetadataFor($ns . '\DDC1590User'); - $this->_generator->writeEntityClass($metadata, $this->_tmpDir); + $this->generator->writeEntityClass($metadata, $this->tmpDir); // class DDC1590User extends DDC1590Entity { ... } $source = file_get_contents($fname); @@ -848,34 +1010,34 @@ public function testMethodsAndPropertiesAreNotDuplicatedInChildClasses() // class _DDC1590User extends DDC1590Entity { ... } $rc2 = new \ReflectionClass($ns.'\_DDC1590User'); - $this->assertTrue($rc2->hasProperty('name')); - $this->assertTrue($rc2->hasProperty('id')); - $this->assertTrue($rc2->hasProperty('created_at')); - - $this->assertTrue($rc2->hasMethod('getName')); - $this->assertTrue($rc2->hasMethod('setName')); - $this->assertTrue($rc2->hasMethod('getId')); - $this->assertFalse($rc2->hasMethod('setId')); - $this->assertTrue($rc2->hasMethod('getCreatedAt')); - $this->assertTrue($rc2->hasMethod('setCreatedAt')); + self::assertTrue($rc2->hasProperty('name')); + self::assertTrue($rc2->hasProperty('id')); + self::assertTrue($rc2->hasProperty('created_at')); + self::assertTrue($rc2->hasMethod('getName')); + self::assertTrue($rc2->hasMethod('setName')); + self::assertTrue($rc2->hasMethod('getId')); + self::assertFalse($rc2->hasMethod('setId')); + self::assertTrue($rc2->hasMethod('getCreatedAt')); + self::assertTrue($rc2->hasMethod('setCreatedAt')); // class __DDC1590User { ... } $rc3 = new \ReflectionClass($ns.'\__DDC1590User'); - $this->assertTrue($rc3->hasProperty('name')); - $this->assertFalse($rc3->hasProperty('id')); - $this->assertFalse($rc3->hasProperty('created_at')); + self::assertTrue($rc3->hasProperty('name')); + self::assertFalse($rc3->hasProperty('id')); + self::assertFalse($rc3->hasProperty('created_at')); - $this->assertTrue($rc3->hasMethod('getName')); - $this->assertTrue($rc3->hasMethod('setName')); - $this->assertFalse($rc3->hasMethod('getId')); - $this->assertFalse($rc3->hasMethod('setId')); - $this->assertFalse($rc3->hasMethod('getCreatedAt')); - $this->assertFalse($rc3->hasMethod('setCreatedAt')); + self::assertTrue($rc3->hasMethod('getName')); + self::assertTrue($rc3->hasMethod('setName')); + self::assertFalse($rc3->hasMethod('getId')); + self::assertFalse($rc3->hasMethod('setId')); + self::assertFalse($rc3->hasMethod('getCreatedAt')); + self::assertFalse($rc3->hasMethod('setCreatedAt')); } /** + * @group embedded * @group DDC-3304 */ public function testGeneratedMutableEmbeddablesClass() @@ -884,108 +1046,117 @@ public function testGeneratedMutableEmbeddablesClass() $metadata = $this->generateIsbnEmbeddableFixture(['test' => $embeddedMetadata]); $isbn = $this->newInstance($metadata); - - $this->assertTrue(class_exists($metadata->name), "Class does not exist."); - $this->assertFalse(method_exists($metadata->name, '__construct'), "EntityGeneratorIsbn::__construct present."); - $this->assertTrue(method_exists($metadata->name, 'getPrefix'), "EntityGeneratorIsbn::getPrefix() missing."); - $this->assertTrue(method_exists($metadata->name, 'setPrefix'), "EntityGeneratorIsbn::setPrefix() missing."); - $this->assertTrue(method_exists($metadata->name, 'getGroupNumber'), "EntityGeneratorIsbn::getGroupNumber() missing."); - $this->assertTrue(method_exists($metadata->name, 'setGroupNumber'), "EntityGeneratorIsbn::setGroupNumber() missing."); - $this->assertTrue(method_exists($metadata->name, 'getPublisherNumber'), "EntityGeneratorIsbn::getPublisherNumber() missing."); - $this->assertTrue(method_exists($metadata->name, 'setPublisherNumber'), "EntityGeneratorIsbn::setPublisherNumber() missing."); - $this->assertTrue(method_exists($metadata->name, 'getTitleNumber'), "EntityGeneratorIsbn::getTitleNumber() missing."); - $this->assertTrue(method_exists($metadata->name, 'setTitleNumber'), "EntityGeneratorIsbn::setTitleNumber() missing."); - $this->assertTrue(method_exists($metadata->name, 'getCheckDigit'), "EntityGeneratorIsbn::getCheckDigit() missing."); - $this->assertTrue(method_exists($metadata->name, 'setCheckDigit'), "EntityGeneratorIsbn::setCheckDigit() missing."); - $this->assertTrue(method_exists($metadata->name, 'getTest'), "EntityGeneratorIsbn::getTest() missing."); - $this->assertTrue(method_exists($metadata->name, 'setTest'), "EntityGeneratorIsbn::setTest() missing."); + $isbnClassName = $metadata->getClassName(); + + self::assertTrue(class_exists($isbnClassName), "Class does not exist."); + self::assertFalse(method_exists($isbnClassName, '__construct'), "EntityGeneratorIsbn::__construct present."); + self::assertTrue(method_exists($isbnClassName, 'getPrefix'), "EntityGeneratorIsbn::getPrefix() missing."); + self::assertTrue(method_exists($isbnClassName, 'setPrefix'), "EntityGeneratorIsbn::setPrefix() missing."); + self::assertTrue(method_exists($isbnClassName, 'getGroupNumber'), "EntityGeneratorIsbn::getGroupNumber() missing."); + self::assertTrue(method_exists($isbnClassName, 'setGroupNumber'), "EntityGeneratorIsbn::setGroupNumber() missing."); + self::assertTrue(method_exists($isbnClassName, 'getPublisherNumber'), "EntityGeneratorIsbn::getPublisherNumber() missing."); + self::assertTrue(method_exists($isbnClassName, 'setPublisherNumber'), "EntityGeneratorIsbn::setPublisherNumber() missing."); + self::assertTrue(method_exists($isbnClassName, 'getTitleNumber'), "EntityGeneratorIsbn::getTitleNumber() missing."); + self::assertTrue(method_exists($isbnClassName, 'setTitleNumber'), "EntityGeneratorIsbn::setTitleNumber() missing."); + self::assertTrue(method_exists($isbnClassName, 'getCheckDigit'), "EntityGeneratorIsbn::getCheckDigit() missing."); + self::assertTrue(method_exists($isbnClassName, 'setCheckDigit'), "EntityGeneratorIsbn::setCheckDigit() missing."); + self::assertTrue(method_exists($isbnClassName, 'getTest'), "EntityGeneratorIsbn::getTest() missing."); + self::assertTrue(method_exists($isbnClassName, 'setTest'), "EntityGeneratorIsbn::setTest() missing."); $isbn->setPrefix(978); - $this->assertSame(978, $isbn->getPrefix()); + self::assertSame(978, $isbn->getPrefix()); $this->newInstance($embeddedMetadata); - $test = new $embeddedMetadata->name(); + + $testEmbeddedCLassName = $embeddedMetadata->getClassName(); + + $test = new $testEmbeddedCLassName(); $isbn->setTest($test); - $this->assertSame($test, $isbn->getTest()); + self::assertSame($test, $isbn->getTest()); - $reflMethod = new \ReflectionMethod($metadata->name, 'setTest'); + $reflMethod = new \ReflectionMethod($isbnClassName, 'setTest'); $reflParameters = $reflMethod->getParameters(); - $this->assertEquals($embeddedMetadata->name, $reflParameters[0]->getClass()->name); + self::assertEquals($embeddedMetadata->getClassName(), $reflParameters[0]->getClass()->name); } /** + * @group embedded * @group DDC-3304 */ public function testGeneratedImmutableEmbeddablesClass() { - $this->_generator->setEmbeddablesImmutable(true); + $this->generator->setEmbeddablesImmutable(true); $embeddedMetadata = $this->generateTestEmbeddableFixture(); $metadata = $this->generateIsbnEmbeddableFixture(['test' => $embeddedMetadata]); $this->loadEntityClass($embeddedMetadata); $this->loadEntityClass($metadata); - $this->assertTrue(class_exists($metadata->name), "Class does not exist."); - $this->assertTrue(method_exists($metadata->name, '__construct'), "EntityGeneratorIsbn::__construct missing."); - $this->assertTrue(method_exists($metadata->name, 'getPrefix'), "EntityGeneratorIsbn::getPrefix() missing."); - $this->assertFalse(method_exists($metadata->name, 'setPrefix'), "EntityGeneratorIsbn::setPrefix() present."); - $this->assertTrue(method_exists($metadata->name, 'getGroupNumber'), "EntityGeneratorIsbn::getGroupNumber() missing."); - $this->assertFalse(method_exists($metadata->name, 'setGroupNumber'), "EntityGeneratorIsbn::setGroupNumber() present."); - $this->assertTrue(method_exists($metadata->name, 'getPublisherNumber'), "EntityGeneratorIsbn::getPublisherNumber() missing."); - $this->assertFalse(method_exists($metadata->name, 'setPublisherNumber'), "EntityGeneratorIsbn::setPublisherNumber() present."); - $this->assertTrue(method_exists($metadata->name, 'getTitleNumber'), "EntityGeneratorIsbn::getTitleNumber() missing."); - $this->assertFalse(method_exists($metadata->name, 'setTitleNumber'), "EntityGeneratorIsbn::setTitleNumber() present."); - $this->assertTrue(method_exists($metadata->name, 'getCheckDigit'), "EntityGeneratorIsbn::getCheckDigit() missing."); - $this->assertFalse(method_exists($metadata->name, 'setCheckDigit'), "EntityGeneratorIsbn::setCheckDigit() present."); - $this->assertTrue(method_exists($metadata->name, 'getTest'), "EntityGeneratorIsbn::getTest() missing."); - $this->assertFalse(method_exists($metadata->name, 'setTest'), "EntityGeneratorIsbn::setTest() present."); - - $test = new $embeddedMetadata->name(1, new \DateTime()); - $isbn = new $metadata->name($test, 978, 3, 12, 732320, 83); + $isbnClassName = $metadata->getClassName(); + + self::assertTrue(class_exists($isbnClassName), "Class does not exist."); + self::assertTrue(method_exists($isbnClassName, '__construct'), "EntityGeneratorIsbn::__construct missing."); + self::assertTrue(method_exists($isbnClassName, 'getPrefix'), "EntityGeneratorIsbn::getPrefix() missing."); + self::assertFalse(method_exists($isbnClassName, 'setPrefix'), "EntityGeneratorIsbn::setPrefix() present."); + self::assertTrue(method_exists($isbnClassName, 'getGroupNumber'), "EntityGeneratorIsbn::getGroupNumber() missing."); + self::assertFalse(method_exists($isbnClassName, 'setGroupNumber'), "EntityGeneratorIsbn::setGroupNumber() present."); + self::assertTrue(method_exists($isbnClassName, 'getPublisherNumber'), "EntityGeneratorIsbn::getPublisherNumber() missing."); + self::assertFalse(method_exists($isbnClassName, 'setPublisherNumber'), "EntityGeneratorIsbn::setPublisherNumber() present."); + self::assertTrue(method_exists($isbnClassName, 'getTitleNumber'), "EntityGeneratorIsbn::getTitleNumber() missing."); + self::assertFalse(method_exists($isbnClassName, 'setTitleNumber'), "EntityGeneratorIsbn::setTitleNumber() present."); + self::assertTrue(method_exists($isbnClassName, 'getCheckDigit'), "EntityGeneratorIsbn::getCheckDigit() missing."); + self::assertFalse(method_exists($isbnClassName, 'setCheckDigit'), "EntityGeneratorIsbn::setCheckDigit() present."); + self::assertTrue(method_exists($isbnClassName, 'getTest'), "EntityGeneratorIsbn::getTest() missing."); + self::assertFalse(method_exists($isbnClassName, 'setTest'), "EntityGeneratorIsbn::setTest() present."); + + $embeddedClassName = $embeddedMetadata->getClassName(); + + $test = new $embeddedClassName(1, new \DateTime()); + $isbn = new $isbnClassName($test, 978, 3, 12, 732320, 83); $reflMethod = new \ReflectionMethod($isbn, '__construct'); $reflParameters = $reflMethod->getParameters(); - $this->assertCount(6, $reflParameters); + self::assertCount(6, $reflParameters); - $this->assertSame($embeddedMetadata->name, $reflParameters[0]->getClass()->name); - $this->assertSame('test', $reflParameters[0]->getName()); - $this->assertFalse($reflParameters[0]->isOptional()); + self::assertSame($embeddedMetadata->getClassName(), $reflParameters[0]->getClass()->name); + self::assertSame('test', $reflParameters[0]->getName()); + self::assertFalse($reflParameters[0]->isOptional()); - $this->assertSame('prefix', $reflParameters[1]->getName()); - $this->assertFalse($reflParameters[1]->isOptional()); + self::assertSame('prefix', $reflParameters[1]->getName()); + self::assertFalse($reflParameters[1]->isOptional()); - $this->assertSame('groupNumber', $reflParameters[2]->getName()); - $this->assertFalse($reflParameters[2]->isOptional()); + self::assertSame('groupNumber', $reflParameters[2]->getName()); + self::assertFalse($reflParameters[2]->isOptional()); - $this->assertSame('publisherNumber', $reflParameters[3]->getName()); - $this->assertFalse($reflParameters[3]->isOptional()); + self::assertSame('publisherNumber', $reflParameters[3]->getName()); + self::assertFalse($reflParameters[3]->isOptional()); - $this->assertSame('titleNumber', $reflParameters[4]->getName()); - $this->assertFalse($reflParameters[4]->isOptional()); + self::assertSame('titleNumber', $reflParameters[4]->getName()); + self::assertFalse($reflParameters[4]->isOptional()); - $this->assertSame('checkDigit', $reflParameters[5]->getName()); - $this->assertFalse($reflParameters[5]->isOptional()); + self::assertSame('checkDigit', $reflParameters[5]->getName()); + self::assertFalse($reflParameters[5]->isOptional()); $reflMethod = new \ReflectionMethod($test, '__construct'); $reflParameters = $reflMethod->getParameters(); - $this->assertCount(4, $reflParameters); + self::assertCount(4, $reflParameters); - $this->assertSame('field1', $reflParameters[0]->getName()); - $this->assertFalse($reflParameters[0]->isOptional()); + self::assertSame('field1', $reflParameters[0]->getName()); + self::assertFalse($reflParameters[0]->isOptional()); - $this->assertSame('DateTime', $reflParameters[1]->getClass()->name); - $this->assertSame('field3', $reflParameters[1]->getName()); - $this->assertFalse($reflParameters[1]->isOptional()); + self::assertSame('DateTime', $reflParameters[1]->getClass()->name); + self::assertSame('field3', $reflParameters[1]->getName()); + self::assertFalse($reflParameters[1]->isOptional()); - $this->assertSame('field2', $reflParameters[2]->getName()); - $this->assertTrue($reflParameters[2]->isOptional()); + self::assertSame('field2', $reflParameters[2]->getName()); + self::assertTrue($reflParameters[2]->isOptional()); - $this->assertSame('DateTime', $reflParameters[3]->getClass()->name); - $this->assertSame('field4', $reflParameters[3]->getName()); - $this->assertTrue($reflParameters[3]->isOptional()); + self::assertSame('DateTime', $reflParameters[3]->getClass()->name); + self::assertSame('field4', $reflParameters[3]->getName()); + self::assertTrue($reflParameters[3]->isOptional()); } public function testRegenerateEntityClass() @@ -993,17 +1164,17 @@ public function testRegenerateEntityClass() $metadata = $this->generateBookEntityFixture(); $this->loadEntityClass($metadata); - $className = basename(str_replace('\\', '/', $metadata->name)); - $path = $this->_tmpDir . '/' . $this->_namespace . '/' . $className . '.php'; + $className = basename(str_replace('\\', '/', $metadata->getClassName())); + $path = $this->tmpDir . '/' . $this->namespace . '/' . $className . '.php'; $classTest = file_get_contents($path); - $this->_generator->setRegenerateEntityIfExists(true); - $this->_generator->setBackupExisting(false); + $this->generator->setRegenerateEntityIfExists(true); + $this->generator->setBackupExisting(false); - $this->_generator->writeEntityClass($metadata, $this->_tmpDir); + $this->generator->writeEntityClass($metadata, $this->tmpDir); $classNew = file_get_contents($path); - $this->assertSame($classTest,$classNew); + self::assertSame($classTest,$classNew); } /** @@ -1146,9 +1317,9 @@ private function assertPhpDocVarType($type, \ReflectionProperty $property) $docComment = $property->getDocComment(); $regex = '/@var\s+([\S]+)$/m'; - $this->assertRegExp($regex, $docComment); - $this->assertEquals(1, preg_match($regex, $docComment, $matches)); - $this->assertEquals($type, $matches[1]); + self::assertRegExp($regex, $docComment); + self::assertEquals(1, preg_match($regex, $docComment, $matches)); + self::assertEquals($type, $matches[1]); } /** @@ -1160,9 +1331,9 @@ private function assertPhpDocReturnType($type, \ReflectionMethod $method) $docComment = $method->getDocComment(); $regex = '/@return\s+([\S]+)(\s+.*)$/m'; - $this->assertRegExp($regex, $docComment); - $this->assertEquals(1, preg_match($regex, $docComment, $matches)); - $this->assertEquals($type, $matches[1]); + self::assertRegExp($regex, $docComment); + self::assertEquals(1, preg_match($regex, $docComment, $matches)); + self::assertEquals($type, $matches[1]); } /** @@ -1171,8 +1342,8 @@ private function assertPhpDocReturnType($type, \ReflectionMethod $method) */ private function assertPhpDocParamType($type, \ReflectionMethod $method) { - $this->assertEquals(1, preg_match('/@param\s+([^\s]+)/', $method->getDocComment(), $matches)); - $this->assertEquals($type, $matches[1]); + self::assertEquals(1, preg_match('/@param\s+([^\s]+)/', $method->getDocComment(), $matches)); + self::assertEquals($type, $matches[1]); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/EntityRepositoryGeneratorTest.php b/tests/Doctrine/Tests/ORM/Tools/EntityRepositoryGeneratorTest.php index feff13dc066..7782fb13bef 100644 --- a/tests/Doctrine/Tests/ORM/Tools/EntityRepositoryGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/EntityRepositoryGeneratorTest.php @@ -1,5 +1,7 @@ _namespace = uniqid('doctrine_'); - $this->_tmpDir = \sys_get_temp_dir() . DIRECTORY_SEPARATOR . $this->_namespace; - \mkdir($this->_tmpDir); - - $this->_generator = new EntityGenerator(); - $this->_generator->setAnnotationPrefix(""); - $this->_generator->setGenerateAnnotations(true); - $this->_generator->setGenerateStubMethods(true); - $this->_generator->setRegenerateEntityIfExists(false); - $this->_generator->setUpdateEntityIfExists(true); - $this->_generator->setFieldVisibility(EntityGenerator::FIELD_VISIBLE_PROTECTED); - - $this->_repositoryGenerator = new EntityRepositoryGenerator(); + $this->namespace = uniqid('doctrine_'); + $this->tmpDir = \sys_get_temp_dir() . DIRECTORY_SEPARATOR . $this->namespace; + \mkdir($this->tmpDir); + + $this->generator = new EntityGenerator(); + + $this->generator->setGenerateAnnotations(true); + $this->generator->setGenerateStubMethods(true); + $this->generator->setRegenerateEntityIfExists(false); + $this->generator->setUpdateEntityIfExists(true); + $this->generator->setFieldVisibility(EntityGenerator::FIELD_VISIBLE_PROTECTED); + + $this->repositoryGenerator = new EntityRepositoryGenerator(); } /** @@ -53,7 +55,7 @@ public function tearDown() { $dirs = []; - $ri = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->_tmpDir)); + $ri = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->tmpDir)); foreach ($ri AS $file) { /* @var $file \SplFileInfo */ if ($file->isFile()) { @@ -75,23 +77,23 @@ public function tearDown() */ public function testGeneratedEntityRepositoryClass() { - $em = $this->_getTestEntityManager(); - $ns = $this->_namespace; + $em = $this->getTestEntityManager(); + $ns = $this->namespace; $className = $ns . '\DDC3231User1Tmp'; $this->writeEntityClass(DDC3231User1::class, $className); $rpath = $this->writeRepositoryClass($className); - $this->assertFileExists($rpath); + self::assertFileExists($rpath); require $rpath; $repo = new \ReflectionClass($em->getRepository($className)); - $this->assertTrue($repo->inNamespace()); - $this->assertSame($className . 'Repository', $repo->getName()); - $this->assertSame(EntityRepository::class, $repo->getParentClass()->getName()); + self::assertTrue($repo->inNamespace()); + self::assertSame($className . 'Repository', $repo->getName()); + self::assertSame(EntityRepository::class, $repo->getParentClass()->getName()); require_once __DIR__ . '/../../Models/DDC3231/DDC3231User1NoNamespace.php'; @@ -100,15 +102,15 @@ public function testGeneratedEntityRepositoryClass() $rpath2 = $this->writeRepositoryClass($className2); - $this->assertFileExists($rpath2); + self::assertFileExists($rpath2); require $rpath2; $repo2 = new \ReflectionClass($em->getRepository($className2)); - $this->assertFalse($repo2->inNamespace()); - $this->assertSame($className2 . 'Repository', $repo2->getName()); - $this->assertSame(EntityRepository::class, $repo2->getParentClass()->getName()); + self::assertFalse($repo2->inNamespace()); + self::assertSame($className2 . 'Repository', $repo2->getName()); + self::assertSame(EntityRepository::class, $repo2->getParentClass()->getName()); } /** @@ -116,24 +118,24 @@ public function testGeneratedEntityRepositoryClass() */ public function testGeneratedEntityRepositoryClassCustomDefaultRepository() { - $em = $this->_getTestEntityManager(); - $ns = $this->_namespace; + $em = $this->getTestEntityManager(); + $ns = $this->namespace; $className = $ns . '\DDC3231User2Tmp'; $this->writeEntityClass(DDC3231User2::class, $className); $rpath = $this->writeRepositoryClass($className, DDC3231EntityRepository::class); - $this->assertNotNull($rpath); - $this->assertFileExists($rpath); + self::assertNotNull($rpath); + self::assertFileExists($rpath); require $rpath; $repo = new \ReflectionClass($em->getRepository($className)); - $this->assertTrue($repo->inNamespace()); - $this->assertSame($className . 'Repository', $repo->getName()); - $this->assertSame(DDC3231EntityRepository::class, $repo->getParentClass()->getName()); + self::assertTrue($repo->inNamespace()); + self::assertSame($className . 'Repository', $repo->getName()); + self::assertSame(DDC3231EntityRepository::class, $repo->getParentClass()->getName()); require_once __DIR__ . '/../../Models/DDC3231/DDC3231User2NoNamespace.php'; @@ -143,16 +145,16 @@ public function testGeneratedEntityRepositoryClassCustomDefaultRepository() $rpath2 = $this->writeRepositoryClass($className2, DDC3231EntityRepository::class); - $this->assertNotNull($rpath2); - $this->assertFileExists($rpath2); + self::assertNotNull($rpath2); + self::assertFileExists($rpath2); require $rpath2; $repo2 = new \ReflectionClass($em->getRepository($className2)); - $this->assertFalse($repo2->inNamespace()); - $this->assertSame($className2 . 'Repository', $repo2->getName()); - $this->assertSame(DDC3231EntityRepository::class, $repo2->getParentClass()->getName()); + self::assertFalse($repo2->inNamespace()); + self::assertSame($className2 . 'Repository', $repo2->getName()); + self::assertSame(DDC3231EntityRepository::class, $repo2->getParentClass()->getName()); } /** @@ -162,18 +164,19 @@ public function testGeneratedEntityRepositoryClassCustomDefaultRepository() private function writeEntityClass($className, $newClassName) { $cmf = new ClassMetadataFactory(); - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); $cmf->setEntityManager($em); - $metadata = $cmf->getMetadataFor($className); - $metadata->namespace = $this->_namespace; - $metadata->name = $newClassName; - $metadata->customRepositoryClassName = $newClassName . "Repository"; + $metadata = $cmf->getMetadataFor($className); + + // @todo guilhermeblanco Fix this test as changing Entity class should never be allowed. + $metadata->setClassName($newClassName); + $metadata->setCustomRepositoryClassName($newClassName . "Repository"); - $this->_generator->writeEntityClass($metadata, $this->_tmpDir); + $this->generator->writeEntityClass($metadata, $this->tmpDir); - require $this->_tmpDir . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $newClassName) . ".php"; + require $this->tmpDir . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $newClassName) . ".php"; } /** @@ -183,11 +186,11 @@ private function writeEntityClass($className, $newClassName) */ private function writeRepositoryClass($className, $defaultRepository = null) { - $this->_repositoryGenerator->setDefaultRepositoryName($defaultRepository); + $this->repositoryGenerator->setDefaultRepositoryName($defaultRepository); - $this->_repositoryGenerator->writeEntityRepositoryClass($className . 'Repository', $this->_tmpDir); + $this->repositoryGenerator->writeEntityRepositoryClass($className . 'Repository', $this->tmpDir); - return $this->_tmpDir . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $className) . 'Repository.php'; + return $this->tmpDir . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $className) . 'Repository.php'; } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php b/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php index e9523b5b1df..f4a7e7d072a 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php @@ -1,15 +1,20 @@ setProxyDir(__DIR__ . '/../../Proxies'); $config->setProxyNamespace('Doctrine\Tests\Proxies'); $eventManager = new EventManager(); $conn = new ConnectionMock([], $driverMock, $config, $eventManager); $config->setMetadataDriverImpl($metadataDriver); - return EntityManagerMock::create($conn, $config, $eventManager); + $driverMock = new DriverMock(); + $eventManager = new EventManager(); + $connection = new ConnectionMock([], $driverMock, $config, $eventManager); + + return EntityManagerMock::create($connection, $config, $eventManager); } - protected function _createMetadataDriver($type, $path) + protected function createMetadataDriver($type, $path) { $mappingDriver = [ - 'php' => PHPDriver::class, 'annotation' => AnnotationDriver::class, 'xml' => XmlDriver::class, - 'yaml' => YamlDriver::class, ]; - $this->assertArrayHasKey($type, $mappingDriver, "There is no metadata driver for the type '" . $type . "'."); + self::assertArrayHasKey($type, $mappingDriver, "There is no metadata driver for the type '" . $type . "'."); $class = $mappingDriver[$type]; $driver = ($type === 'annotation') @@ -67,7 +74,7 @@ protected function _createMetadataDriver($type, $path) return $driver; } - protected function _createClassMetadataFactory($em, $type) + protected function createClassMetadataFactory($em, $type) { $factory = ($type === 'annotation') ? new ClassMetadataFactory() @@ -80,38 +87,36 @@ protected function _createClassMetadataFactory($em, $type) public function testExportDirectoryAndFilesAreCreated() { - $this->_deleteDirectory(__DIR__ . '/export/'.$this->_getType()); + $this->deleteDirectory(__DIR__ . '/export/'.$this->getType()); - $type = $this->_getType(); - $metadataDriver = $this->_createMetadataDriver($type, __DIR__ . '/' . $type); - $em = $this->_createEntityManager($metadataDriver); - $cmf = $this->_createClassMetadataFactory($em, $type); + $type = $this->getType(); + $metadataDriver = $this->createMetadataDriver($type, __DIR__ . '/' . $type); + $em = $this->createEntityManager($metadataDriver); + $cmf = $this->createClassMetadataFactory($em, $type); $metadata = $cmf->getAllMetadata(); - $metadata[0]->name = ExportedUser::class; + // @todo guilhermeblanco Fix this test as changing Entity class should never be allowed. + $metadata[0]->setClassName(ExportedUser::class); - $this->assertEquals(ExportedUser::class, $metadata[0]->name); + self::assertEquals(ExportedUser::class, $metadata[0]->getClassName()); - $type = $this->_getType(); + $type = $this->getType(); $cme = new ClassMetadataExporter(); $exporter = $cme->getExporter($type, __DIR__ . '/export/' . $type); if ($type === 'annotation') { - $entityGenerator = new EntityGenerator(); - - $entityGenerator->setAnnotationPrefix(""); - $exporter->setEntityGenerator($entityGenerator); + $exporter->setEntityGenerator(new EntityGenerator()); } - $this->_extension = $exporter->getExtension(); + $this->extension = $exporter->getExtension(); $exporter->setMetadata($metadata); $exporter->export(); if ($type == 'annotation') { - $this->assertTrue(file_exists(__DIR__ . '/export/' . $type . '/'.str_replace('\\', '/', ExportedUser::class).$this->_extension)); + self::assertTrue(file_exists(__DIR__ . '/export/' . $type . '/'.str_replace('\\', '/', ExportedUser::class).$this->extension)); } else { - $this->assertTrue(file_exists(__DIR__ . '/export/' . $type . '/Doctrine.Tests.ORM.Tools.Export.ExportedUser'.$this->_extension)); + self::assertTrue(file_exists(__DIR__ . '/export/' . $type . '/Doctrine.Tests.ORM.Tools.Export.ExportedUser'.$this->extension)); } } @@ -120,126 +125,128 @@ public function testExportDirectoryAndFilesAreCreated() */ public function testExportedMetadataCanBeReadBackIn() { - $type = $this->_getType(); + $type = $this->getType(); - $metadataDriver = $this->_createMetadataDriver($type, __DIR__ . '/export/' . $type); - $em = $this->_createEntityManager($metadataDriver); - $cmf = $this->_createClassMetadataFactory($em, $type); + $metadataDriver = $this->createMetadataDriver($type, __DIR__ . '/export/' . $type); + $em = $this->createEntityManager($metadataDriver); + $cmf = $this->createClassMetadataFactory($em, $type); $metadata = $cmf->getAllMetadata(); - $this->assertEquals(1, count($metadata)); + self::assertEquals(1, count($metadata)); $class = current($metadata); - $this->assertEquals(ExportedUser::class, $class->name); + self::assertEquals(ExportedUser::class, $class->getClassName()); return $class; } /** * @depends testExportedMetadataCanBeReadBackIn - * @param ClassMetadataInfo $class + * @param ClassMetadata $class */ public function testTableIsExported($class) { - $this->assertEquals('cms_users', $class->table['name']); - $this->assertEquals( + self::assertEquals('cms_users', $class->table->getName()); + self::assertEquals( ['engine' => 'MyISAM', 'foo' => ['bar' => 'baz']], - $class->table['options']); + $class->table->getOptions() + ); return $class; } /** * @depends testTableIsExported - * @param ClassMetadataInfo $class + * @param ClassMetadata $class */ public function testTypeIsExported($class) { - $this->assertFalse($class->isMappedSuperclass); + self::assertFalse($class->isMappedSuperclass); return $class; } /** * @depends testTypeIsExported - * @param ClassMetadataInfo $class + * @param ClassMetadata $class */ public function testIdentifierIsExported($class) { - $this->assertEquals(ClassMetadataInfo::GENERATOR_TYPE_IDENTITY, $class->generatorType, "Generator Type wrong"); - $this->assertEquals(['id'], $class->identifier); - $this->assertTrue(isset($class->fieldMappings['id']['id']) && $class->fieldMappings['id']['id'] === true); + self::assertNotNull($class->getProperty('id')); + + $property = $class->getProperty('id'); + + self::assertTrue($property->isPrimaryKey()); + self::assertEquals(['id'], $class->identifier); + self::assertEquals(GeneratorType::IDENTITY, $class->getProperty('id')->getValueGenerator()->getType(), "Generator Type wrong"); return $class; } /** * @depends testIdentifierIsExported - * @param ClassMetadataInfo $class + * @param ClassMetadata $class */ public function testFieldsAreExported($class) { - $this->assertTrue(isset($class->fieldMappings['id']['id']) && $class->fieldMappings['id']['id'] === true); - $this->assertEquals('id', $class->fieldMappings['id']['fieldName']); - $this->assertEquals('integer', $class->fieldMappings['id']['type']); - $this->assertEquals('id', $class->fieldMappings['id']['columnName']); - - $this->assertEquals('name', $class->fieldMappings['name']['fieldName']); - $this->assertEquals('string', $class->fieldMappings['name']['type']); - $this->assertEquals(50, $class->fieldMappings['name']['length']); - $this->assertEquals('name', $class->fieldMappings['name']['columnName']); - - $this->assertEquals('email', $class->fieldMappings['email']['fieldName']); - $this->assertEquals('string', $class->fieldMappings['email']['type']); - $this->assertEquals('user_email', $class->fieldMappings['email']['columnName']); - $this->assertEquals('CHAR(32) NOT NULL', $class->fieldMappings['email']['columnDefinition']); - - $this->assertEquals(true, $class->fieldMappings['age']['options']['unsigned']); + self::assertNotNull($class->getProperty('id')); + self::assertNotNull($class->getProperty('name')); + self::assertNotNull($class->getProperty('email')); + self::assertNotNull($class->getProperty('age')); + + $idProperty = $class->getProperty('id'); + $nameProperty = $class->getProperty('name'); + $emailProperty = $class->getProperty('email'); + $ageProperty = $class->getProperty('age'); + + self::assertTrue($idProperty->isPrimaryKey()); + self::assertEquals('id', $idProperty->getName()); + self::assertEquals('integer', $idProperty->getTypeName()); + self::assertEquals('id', $idProperty->getColumnName()); + + self::assertEquals('name', $nameProperty->getName()); + self::assertEquals('string', $nameProperty->getTypeName()); + self::assertEquals('name', $nameProperty->getColumnName()); + self::assertEquals(50, $nameProperty->getLength()); + + self::assertEquals('email', $emailProperty->getName()); + self::assertEquals('string', $emailProperty->getTypeName()); + self::assertEquals('user_email', $emailProperty->getColumnName()); + self::assertEquals('CHAR(32) NOT NULL', $emailProperty->getColumnDefinition()); + + self::assertEquals('age', $ageProperty->getName()); + self::assertEquals('integer', $ageProperty->getTypeName()); + self::assertEquals('age', $ageProperty->getColumnName()); + self::assertArrayHasKey('unsigned', $ageProperty->getOptions()); + self::assertEquals(true, $ageProperty->getOptions()['unsigned']); return $class; } /** - * @depends testExportDirectoryAndFilesAreCreated + * @depends testFieldsAreExported + * @param ClassMetadata $class */ - public function testFieldsAreProperlySerialized() + public function testOneToOneAssociationsAreExported($class) { - $type = $this->_getType(); + $property = $class->getProperty('address'); - if ($type == 'xml') { - $xml = simplexml_load_file(__DIR__ . '/export/'.$type.'/Doctrine.Tests.ORM.Tools.Export.ExportedUser.dcm.xml'); + self::assertNotNull($property); - $xml->registerXPathNamespace("d", "http://doctrine-project.org/schemas/orm/doctrine-mapping"); - $nodes = $xml->xpath("/d:doctrine-mapping/d:entity/d:field[@name='name' and @type='string' and @nullable='true']"); - $this->assertEquals(1, count($nodes)); + $joinColumns = $property->getJoinColumns(); + $joinColumn = reset($joinColumns); - $nodes = $xml->xpath("/d:doctrine-mapping/d:entity/d:field[@name='name' and @type='string' and @unique='true']"); - $this->assertEquals(1, count($nodes)); - } else { - $this->markTestSkipped('Test not available for '.$type.' driver'); - } - } + self::assertEquals('Doctrine\Tests\ORM\Tools\Export\Address', $property->getTargetEntity()); + self::assertEquals('address_id', $joinColumn->getColumnName()); + self::assertEquals('id', $joinColumn->getReferencedColumnName()); + self::assertEquals('CASCADE', $joinColumn->getOnDelete()); - /** - * @depends testFieldsAreExported - * @param ClassMetadataInfo $class - */ - public function testOneToOneAssociationsAreExported($class) - { - $this->assertTrue(isset($class->associationMappings['address'])); - $this->assertEquals(Address::class, $class->associationMappings['address']['targetEntity']); - $this->assertEquals('address_id', $class->associationMappings['address']['joinColumns'][0]['name']); - $this->assertEquals('id', $class->associationMappings['address']['joinColumns'][0]['referencedColumnName']); - $this->assertEquals('CASCADE', $class->associationMappings['address']['joinColumns'][0]['onDelete']); - - $this->assertTrue($class->associationMappings['address']['isCascadeRemove']); - $this->assertTrue($class->associationMappings['address']['isCascadePersist']); - $this->assertFalse($class->associationMappings['address']['isCascadeRefresh']); - $this->assertFalse($class->associationMappings['address']['isCascadeMerge']); - $this->assertFalse($class->associationMappings['address']['isCascadeDetach']); - $this->assertTrue($class->associationMappings['address']['orphanRemoval']); - $this->assertEquals(ClassMetadataInfo::FETCH_EAGER, $class->associationMappings['address']['fetch']); + self::assertContains('remove', $property->getCascade()); + self::assertContains('persist', $property->getCascade()); + self::assertNotContains('refresh', $property->getCascade()); + self::assertTrue($property->isOrphanRemoval()); + self::assertEquals(FetchMode::EAGER, $property->getFetchMode()); return $class; } @@ -249,123 +256,139 @@ public function testOneToOneAssociationsAreExported($class) */ public function testManyToOneAssociationsAreExported($class) { - $this->assertTrue(isset($class->associationMappings['mainGroup'])); - $this->assertEquals(Group::class, $class->associationMappings['mainGroup']['targetEntity']); + $property = $class->getProperty('mainGroup'); + + self::assertNotNull($property); + self::assertEquals(Group::class, $property->getTargetEntity()); } /** * @depends testOneToOneAssociationsAreExported - * @param ClassMetadataInfo $class + * @param ClassMetadata $class */ public function testOneToManyAssociationsAreExported($class) { - $this->assertTrue(isset($class->associationMappings['phonenumbers'])); - $this->assertEquals(Phonenumber::class, $class->associationMappings['phonenumbers']['targetEntity']); - $this->assertEquals('user', $class->associationMappings['phonenumbers']['mappedBy']); - $this->assertEquals(['number' => 'ASC'], $class->associationMappings['phonenumbers']['orderBy']); - - $this->assertTrue($class->associationMappings['phonenumbers']['isCascadeRemove']); - $this->assertTrue($class->associationMappings['phonenumbers']['isCascadePersist']); - $this->assertFalse($class->associationMappings['phonenumbers']['isCascadeRefresh']); - $this->assertTrue($class->associationMappings['phonenumbers']['isCascadeMerge']); - $this->assertFalse($class->associationMappings['phonenumbers']['isCascadeDetach']); - $this->assertTrue($class->associationMappings['phonenumbers']['orphanRemoval']); - $this->assertEquals(ClassMetadataInfo::FETCH_LAZY, $class->associationMappings['phonenumbers']['fetch']); + /** @var OneToManyAssociationMetadata $property */ + $property = $class->getProperty('phonenumbers'); + + self::assertNotNull($property); + + self::assertInstanceOf(OneToManyAssociationMetadata::class, $property); + self::assertEquals(Phonenumber::class, $property->getTargetEntity()); + self::assertEquals('user', $property->getMappedBy()); + self::assertEquals(['number' => 'ASC'], $property->getOrderBy()); + + self::assertContains('remove', $property->getCascade()); + self::assertContains('persist', $property->getCascade()); + self::assertNotContains('refresh', $property->getCascade()); + self::assertTrue($property->isOrphanRemoval()); + self::assertEquals(FetchMode::LAZY, $property->getFetchMode()); return $class; } /** * @depends testOneToManyAssociationsAreExported - * @param ClassMetadataInfo $metadata + * @param ClassMetadata $metadata */ public function testManyToManyAssociationsAreExported($class) { - $this->assertTrue(isset($class->associationMappings['groups'])); - $this->assertEquals(Group::class, $class->associationMappings['groups']['targetEntity']); - $this->assertEquals('cms_users_groups', $class->associationMappings['groups']['joinTable']['name']); + $property = $class->getProperty('groups'); + + self::assertNotNull($property); - $this->assertEquals('user_id', $class->associationMappings['groups']['joinTable']['joinColumns'][0]['name']); - $this->assertEquals('id', $class->associationMappings['groups']['joinTable']['joinColumns'][0]['referencedColumnName']); + $joinTable = $property->getJoinTable(); + $joinColumns = $joinTable->getJoinColumns(); + $joinColumn = reset($joinColumns); + $inverseJoinColumns = $joinTable->getInverseJoinColumns(); + $inverseJoinColumn = reset($inverseJoinColumns); - $this->assertEquals('group_id', $class->associationMappings['groups']['joinTable']['inverseJoinColumns'][0]['name']); - $this->assertEquals('id', $class->associationMappings['groups']['joinTable']['inverseJoinColumns'][0]['referencedColumnName']); - $this->assertEquals('INT NULL', $class->associationMappings['groups']['joinTable']['inverseJoinColumns'][0]['columnDefinition']); + self::assertInstanceOf(ManyToManyAssociationMetadata::class, $property); + self::assertEquals(Group::class, $property->getTargetEntity()); + self::assertEquals('cms_users_groups', $joinTable->getName()); - $this->assertTrue($class->associationMappings['groups']['isCascadeRemove']); - $this->assertTrue($class->associationMappings['groups']['isCascadePersist']); - $this->assertTrue($class->associationMappings['groups']['isCascadeRefresh']); - $this->assertTrue($class->associationMappings['groups']['isCascadeMerge']); - $this->assertTrue($class->associationMappings['groups']['isCascadeDetach']); - $this->assertEquals(ClassMetadataInfo::FETCH_EXTRA_LAZY, $class->associationMappings['groups']['fetch']); + self::assertEquals('user_id', $joinColumn->getColumnName()); + self::assertEquals('id', $joinColumn->getReferencedColumnName()); + + self::assertEquals('group_id', $inverseJoinColumn->getColumnName()); + self::assertEquals('id', $inverseJoinColumn->getReferencedColumnName()); + self::assertEquals('INT NULL', $inverseJoinColumn->getColumnDefinition()); + + self::assertContains('remove', $property->getCascade()); + self::assertContains('persist', $property->getCascade()); + self::assertContains('refresh', $property->getCascade()); + + self::assertEquals(FetchMode::EXTRA_LAZY, $property->getFetchMode()); return $class; } /** * @depends testManyToManyAssociationsAreExported - * @param ClassMetadataInfo $class + * @param ClassMetadata $class */ public function testLifecycleCallbacksAreExported($class) { - $this->assertTrue(isset($class->lifecycleCallbacks['prePersist'])); - $this->assertEquals(2, count($class->lifecycleCallbacks['prePersist'])); - $this->assertEquals('doStuffOnPrePersist', $class->lifecycleCallbacks['prePersist'][0]); - $this->assertEquals('doOtherStuffOnPrePersistToo', $class->lifecycleCallbacks['prePersist'][1]); + self::assertTrue(isset($class->lifecycleCallbacks['prePersist'])); + self::assertEquals(2, count($class->lifecycleCallbacks['prePersist'])); + self::assertEquals('doStuffOnPrePersist', $class->lifecycleCallbacks['prePersist'][0]); + self::assertEquals('doOtherStuffOnPrePersistToo', $class->lifecycleCallbacks['prePersist'][1]); - $this->assertTrue(isset($class->lifecycleCallbacks['postPersist'])); - $this->assertEquals(1, count($class->lifecycleCallbacks['postPersist'])); - $this->assertEquals('doStuffOnPostPersist', $class->lifecycleCallbacks['postPersist'][0]); + self::assertTrue(isset($class->lifecycleCallbacks['postPersist'])); + self::assertEquals(1, count($class->lifecycleCallbacks['postPersist'])); + self::assertEquals('doStuffOnPostPersist', $class->lifecycleCallbacks['postPersist'][0]); return $class; } /** * @depends testLifecycleCallbacksAreExported - * @param ClassMetadataInfo $class + * @param ClassMetadata $class */ public function testCascadeIsExported($class) { - $this->assertTrue($class->associationMappings['phonenumbers']['isCascadePersist']); - $this->assertTrue($class->associationMappings['phonenumbers']['isCascadeMerge']); - $this->assertTrue($class->associationMappings['phonenumbers']['isCascadeRemove']); - $this->assertFalse($class->associationMappings['phonenumbers']['isCascadeRefresh']); - $this->assertFalse($class->associationMappings['phonenumbers']['isCascadeDetach']); - $this->assertTrue($class->associationMappings['phonenumbers']['orphanRemoval']); + $property = $class->getProperty('phonenumbers'); + + self::assertNotNull($property); + + self::assertContains('persist', $property->getCascade()); + self::assertContains('remove', $property->getCascade()); + self::assertNotContains('refresh', $property->getCascade()); + + self::assertTrue($property->isOrphanRemoval()); return $class; } /** * @depends testCascadeIsExported - * @param ClassMetadataInfo $class + * @param ClassMetadata $class */ public function testInversedByIsExported($class) { - $this->assertEquals('user', $class->associationMappings['address']['inversedBy']); + $property = $class->getProperty('address'); + + self::assertNotNull($property); + + self::assertEquals('user', $property->getInversedBy()); } /** * @depends testExportDirectoryAndFilesAreCreated */ public function testCascadeAllCollapsed() { - $type = $this->_getType(); + $type = $this->getType(); - if ($type == 'xml') { + if ($type === 'xml') { $xml = simplexml_load_file(__DIR__ . '/export/'.$type.'/Doctrine.Tests.ORM.Tools.Export.ExportedUser.dcm.xml'); $xml->registerXPathNamespace("d", "http://doctrine-project.org/schemas/orm/doctrine-mapping"); $nodes = $xml->xpath("/d:doctrine-mapping/d:entity/d:one-to-many[@field='interests']/d:cascade/d:*"); - $this->assertEquals(1, count($nodes)); - - $this->assertEquals('cascade-all', $nodes[0]->getName()); - } else if ($type == 'yaml') { - $yaml = new Parser(); - $value = $yaml->parse(file_get_contents(__DIR__ . '/export/'.$type.'/Doctrine.Tests.ORM.Tools.Export.ExportedUser.dcm.yml')); + self::assertCount(3, $nodes); - $this->assertTrue(isset($value[ExportedUser::class]['oneToMany']['interests']['cascade'])); - $this->assertEquals(1, count($value[ExportedUser::class]['oneToMany']['interests']['cascade'])); - $this->assertEquals('all', $value[ExportedUser::class]['oneToMany']['interests']['cascade'][0]); + self::assertEquals('cascade-persist', $nodes[0]->getName()); + self::assertEquals('cascade-remove', $nodes[1]->getName()); + self::assertEquals('cascade-refresh', $nodes[2]->getName()); } else { $this->markTestSkipped('Test not available for '.$type.' driver'); } @@ -373,10 +396,10 @@ public function testCascadeAllCollapsed() public function __destruct() { -# $this->_deleteDirectory(__DIR__ . '/export/'.$this->_getType()); +# $this->deleteDirectory(__DIR__ . '/export/'.$this->getType()); } - protected function _deleteDirectory($path) + protected function deleteDirectory($path) { if (is_file($path)) { return unlink($path); @@ -385,7 +408,7 @@ protected function _deleteDirectory($path) if (is_array($files)) { foreach ($files as $file){ - $this->_deleteDirectory($file); + $this->deleteDirectory($file); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/AnnotationClassMetadataExporterTest.php b/tests/Doctrine/Tests/ORM/Tools/Export/AnnotationClassMetadataExporterTest.php index a432ec45187..c920ba80652 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/AnnotationClassMetadataExporterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/AnnotationClassMetadataExporterTest.php @@ -1,5 +1,7 @@ - * @author Roman Borschel registerXPathNamespace("d", "http://doctrine-project.org/schemas/orm/doctrine-mapping"); + + $nodes = $xml->xpath("/d:doctrine-mapping/d:entity/d:field[@name='name' and @type='string' and @nullable='true']"); + self::assertEquals(1, count($nodes)); + + $nodes = $xml->xpath("/d:doctrine-mapping/d:entity/d:field[@name='name' and @type='string' and @unique='true']"); + self::assertEquals(1, count($nodes)); + } + /** * @group DDC-3428 */ - public function testSequenceGenerator() { + public function testSequenceGenerator() + { + $metadataBuildingContext = new Mapping\ClassMetadataBuildingContext( + $this->createMock(Mapping\ClassMetadataFactory::class), + $this->createMock(ReflectionService::class) + ); + $exporter = new XmlExporter(); - $metadata = new ClassMetadata('entityTest'); - $metadata->mapField( - [ - "fieldName" => 'id', - "type" => 'integer', - "columnName" => 'id', - "id" => true, - ] - ); + $metadata = new ClassMetadata('entityTest', $metadataBuildingContext); + $metadata->setTable(new Mapping\TableMetadata('entityTest')); - $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE); - $metadata->setSequenceGeneratorDefinition( + $fieldMetadata = new Mapping\FieldMetadata('id'); + $fieldMetadata->setType(Type::getType('integer')); + $fieldMetadata->setPrimaryKey(true); + $fieldMetadata->setValueGenerator(new Mapping\ValueGeneratorMetadata( + Mapping\GeneratorType::SEQUENCE, [ - 'sequenceName' => 'seq_entity_test_id', - 'allocationSize' => 5, - 'initialValue' => 1 + 'sequenceName' => 'seq_entity_test_id', + 'allocationSize' => 5, ] - ); + )); + + $metadata->addProperty($fieldMetadata); $expectedFileContent = <<<'XML' @@ -54,16 +78,16 @@ public function testSequenceGenerator() { xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd" > - + - + XML; - $this->assertXmlStringEqualsXmlString($expectedFileContent, $exporter->exportClassMetadata($metadata)); + self::assertXmlStringEqualsXmlString($expectedFileContent, $exporter->exportClassMetadata($metadata)); } /** @@ -71,26 +95,34 @@ public function testSequenceGenerator() { * @group 1216 * @group DDC-3439 */ - public function testFieldOptionsExport() { + public function testFieldOptionsExport() + { + $metadataBuildingContext = new Mapping\ClassMetadataBuildingContext( + $this->createMock(Mapping\ClassMetadataFactory::class), + $this->createMock(ReflectionService::class) + ); + $exporter = new XmlExporter(); - $metadata = new ClassMetadata('entityTest'); - $metadata->mapField( + $metadata = new ClassMetadata('entityTest', $metadataBuildingContext); + $metadata->setTable(new Mapping\TableMetadata('entityTest')); + + $fieldMetadata = new Mapping\FieldMetadata('myField'); + $fieldMetadata->setType(Type::getType('string')); + $fieldMetadata->setColumnName('my_field'); + $fieldMetadata->setOptions( [ - "fieldName" => 'myField', - "type" => 'string', - "columnName" => 'my_field', - "options" => [ - "default" => "default_string", - "comment" => "The comment for the field", - ], + 'default' => 'default_string', + 'comment' => 'The comment for the field', ] ); + $metadata->addProperty($fieldMetadata); + $expectedFileContent = <<<'XML' - + @@ -101,6 +133,6 @@ public function testFieldOptionsExport() { XML; - $this->assertXmlStringEqualsXmlString($expectedFileContent, $exporter->exportClassMetadata($metadata)); + self::assertXmlStringEqualsXmlString($expectedFileContent, $exporter->exportClassMetadata($metadata)); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/YamlClassMetadataExporterTest.php b/tests/Doctrine/Tests/ORM/Tools/Export/YamlClassMetadataExporterTest.php deleted file mode 100644 index a47c396d2ce..00000000000 --- a/tests/Doctrine/Tests/ORM/Tools/Export/YamlClassMetadataExporterTest.php +++ /dev/null @@ -1,25 +0,0 @@ - - * @author Roman Borschel markTestSkipped('Please install Symfony YAML Component into the include path of your PHP installation.'); - } - - return 'yaml'; - } -} diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/annotation/Doctrine.Tests.ORM.Tools.Export.User.php b/tests/Doctrine/Tests/ORM/Tools/Export/annotation/Doctrine.Tests.ORM.Tools.Export.User.php index 34470805953..6ca851bd642 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/annotation/Doctrine.Tests.ORM.Tools.Export.User.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/annotation/Doctrine.Tests.ORM.Tools.Export.User.php @@ -1,75 +1,79 @@ setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); -$metadata->setPrimaryTable( - [ - 'name' => 'cms_users', - 'options' => ['engine' => 'MyISAM', 'foo' => ['bar' => 'baz']], - ] -); -$metadata->setChangeTrackingPolicy(ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT); +$tableMetadata = new Mapping\TableMetadata(); +$tableMetadata->setName('cms_users'); +$tableMetadata->addOption('engine', 'MyISAM'); +$tableMetadata->addOption('foo', ['bar' => 'baz']); + +$metadata->setTable($tableMetadata); +$metadata->setInheritanceType(Mapping\InheritanceType::NONE); +$metadata->setChangeTrackingPolicy(Mapping\ChangeTrackingPolicy::DEFERRED_IMPLICIT); + $metadata->addLifecycleCallback('doStuffOnPrePersist', 'prePersist'); $metadata->addLifecycleCallback('doOtherStuffOnPrePersistToo', 'prePersist'); $metadata->addLifecycleCallback('doStuffOnPostPersist', 'postPersist'); -$metadata->mapField( - [ - 'id' => true, - 'fieldName' => 'id', - 'type' => 'integer', - 'columnName' => 'id', - ] -); -$metadata->mapField( - [ - 'fieldName' => 'name', - 'type' => 'string', - 'length' => 50, - 'unique' => true, - 'nullable' => true, - 'columnName' => 'name', - ] -); -$metadata->mapField( - [ - 'fieldName' => 'email', - 'type' => 'string', - 'columnName' => 'user_email', - 'columnDefinition' => 'CHAR(32) NOT NULL', - ] -); -$metadata->mapField( - [ - 'fieldName' => 'age', - 'type' => 'integer', - 'options' => ["unsigned"=>true], - ] -); -$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); -$metadata->mapManyToOne( - [ - 'fieldName' => 'mainGroup', - 'targetEntity' => Export\Group::class, - ] -); -$metadata->mapOneToOne( - [ - 'fieldName' => 'address', - 'targetEntity' => Export\Address::class, - 'inversedBy' => 'user', - 'cascade' => - [ - 0 => 'persist', - ], - 'mappedBy' => NULL, - 'joinColumns' => - [ - 0 => - [ - 'name' => 'address_id', - 'referencedColumnName' => 'id', - 'onDelete' => 'CASCADE', - ], - ], - 'orphanRemoval' => true, - 'fetch' => ClassMetadataInfo::FETCH_EAGER, - ] -); -$metadata->mapOneToOne( - [ - 'fieldName' => 'cart', - 'targetEntity' => Export\Cart::class, - 'mappedBy' => 'user', - 'cascade' => - [ - 0 => 'persist', - ], - 'inversedBy' => NULL, - 'orphanRemoval' => false, - 'fetch' => ClassMetadataInfo::FETCH_EAGER, - ] -); -$metadata->mapOneToMany( - [ - 'fieldName' => 'phonenumbers', - 'targetEntity' => Export\Phonenumber::class, - 'cascade' => - [ - 1 => 'persist', - 2 => 'merge', - ], - 'mappedBy' => 'user', - 'orphanRemoval' => true, - 'fetch' => ClassMetadataInfo::FETCH_LAZY, - 'orderBy' => - [ - 'number' => 'ASC', - ], - ] -); -$metadata->mapManyToMany( - [ - 'fieldName' => 'groups', - 'targetEntity' => Export\Group::class, - 'fetch' => ClassMetadataInfo::FETCH_EXTRA_LAZY, - 'cascade' => - [ - 0 => 'remove', - 1 => 'persist', - 2 => 'refresh', - 3 => 'merge', - 4 => 'detach', - ], - 'mappedBy' => NULL, - 'joinTable' => - [ - 'name' => 'cms_users_groups', - 'joinColumns' => - [ - 0 => - [ - 'name' => 'user_id', - 'referencedColumnName' => 'id', - 'unique' => false, - 'nullable' => false, - ], - ], - 'inverseJoinColumns' => - [ - 0 => - [ - 'name' => 'group_id', - 'referencedColumnName' => 'id', - 'columnDefinition' => 'INT NULL', - ], - ], - ], - 'orderBy' => NULL, - ] -); + +// Property: "id" +$fieldMetadata = new Mapping\FieldMetadata('id'); + +$fieldMetadata->setType(Type::getType('integer')); +$fieldMetadata->setPrimaryKey(true); +$fieldMetadata->setValueGenerator(new Mapping\ValueGeneratorMetadata(Mapping\GeneratorType::AUTO)); + +$metadata->addProperty($fieldMetadata); + +// Property: "name" +$fieldMetadata = new Mapping\FieldMetadata('name'); + +$fieldMetadata->setType(Type::getType('string')); +$fieldMetadata->setLength(50); +$fieldMetadata->setColumnName('name'); +$fieldMetadata->setNullable(true); +$fieldMetadata->setUnique(true); + +$metadata->addProperty($fieldMetadata); + +// Property: "email" +$fieldMetadata = new Mapping\FieldMetadata('email'); + +$fieldMetadata->setType(Type::getType('string')); +$fieldMetadata->setColumnName('user_email'); +$fieldMetadata->setColumnDefinition('CHAR(32) NOT NULL'); + +$metadata->addProperty($fieldMetadata); + +// Property: "age" +$fieldMetadata = new Mapping\FieldMetadata('age'); + +$fieldMetadata->setType(Type::getType('integer')); +$fieldMetadata->setOptions(['unsigned' => true]); + +$metadata->addProperty($fieldMetadata); + +// Property: "mainGroup" +$association = new Mapping\ManyToOneAssociationMetadata('mainGroup'); + +$association->setTargetEntity(Export\Group::class); + +$metadata->addProperty($association); + +// Property: "address" +$joinColumns = []; + +$joinColumn = new Mapping\JoinColumnMetadata(); + +$joinColumn->setColumnName("address_id"); +$joinColumn->setReferencedColumnName("id"); +$joinColumn->setOnDelete("CASCADE"); + +$joinColumns[] = $joinColumn; + +$association = new Mapping\OneToOneAssociationMetadata('address'); + +$association->setJoinColumns($joinColumns); +$association->setTargetEntity(Export\Address::class); +$association->setInversedBy('user'); +$association->setCascade(['persist']); +$association->setFetchMode(Mapping\FetchMode::EAGER); +$association->setOrphanRemoval(true); + +$metadata->addProperty($association); + +// Property: "cart" +$association = new Mapping\OneToOneAssociationMetadata('cart'); + +$association->setTargetEntity(Export\Cart::class); +$association->setMappedBy('user'); +$association->setCascade(['persist']); +$association->setFetchMode(Mapping\FetchMode::EAGER); +$association->setOrphanRemoval(false); + +$metadata->addProperty($association); + +// Property: "phonenumbers" +$association = new Mapping\OneToManyAssociationMetadata('phonenumbers'); + +$association->setTargetEntity(Export\Phonenumber::class); +$association->setMappedBy('user'); +$association->setCascade(['persist']); +$association->setFetchMode(Mapping\FetchMode::LAZY); +$association->setOrphanRemoval(true); +$association->setOrderBy(['number' => 'ASC']); + +$metadata->addProperty($association); + +// Property: "groups" +$joinTable = new Mapping\JoinTableMetadata(); +$joinTable->setName('cms_users_groups'); + +$joinColumn = new Mapping\JoinColumnMetadata(); +$joinColumn->setColumnName("user_id"); +$joinColumn->setReferencedColumnName("id"); + +$joinTable->addJoinColumn($joinColumn); + +$inverseJoinColumns = []; + +$joinColumn = new Mapping\JoinColumnMetadata(); +$joinColumn->setColumnName("group_id"); +$joinColumn->setReferencedColumnName("id"); +$joinColumn->setColumnDefinition("INT NULL"); + +$joinTable->addInverseJoinColumn($joinColumn); + +$association = new Mapping\ManyToManyAssociationMetadata('groups'); + +$association->setJoinTable($joinTable); +$association->setTargetEntity(Export\Group::class); +$association->setCascade(['remove', 'persist', 'refresh']); +$association->setFetchMode(Mapping\FetchMode::EXTRA_LAZY); + +$metadata->addProperty($association); diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/xml/Doctrine.Tests.ORM.Tools.Export.User.dcm.xml b/tests/Doctrine/Tests/ORM/Tools/Export/xml/Doctrine.Tests.ORM.Tools.Export.User.dcm.xml index 8d0c5d217e3..6d9c0a76306 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/xml/Doctrine.Tests.ORM.Tools.Export.User.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Tools/Export/xml/Doctrine.Tests.ORM.Tools.Export.User.dcm.xml @@ -32,7 +32,7 @@ - + @@ -46,7 +46,6 @@ - @@ -57,8 +56,6 @@ - - diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/yaml/Doctrine.Tests.ORM.Tools.Export.User.dcm.yml b/tests/Doctrine/Tests/ORM/Tools/Export/yaml/Doctrine.Tests.ORM.Tools.Export.User.dcm.yml deleted file mode 100644 index d52e94601da..00000000000 --- a/tests/Doctrine/Tests/ORM/Tools/Export/yaml/Doctrine.Tests.ORM.Tools.Export.User.dcm.yml +++ /dev/null @@ -1,77 +0,0 @@ -Doctrine\Tests\ORM\Tools\Export\User: - type: entity - table: cms_users - options: - engine: MyISAM - foo: { bar: baz } - id: - id: - type: integer - generator: - strategy: AUTO - fields: - name: - type: string - length: 50 - nullable: true - unique: true - email: - type: string - column: user_email - columnDefinition: CHAR(32) NOT NULL - age: - type: integer - options: - unsigned: true - oneToOne: - address: - targetEntity: Doctrine\Tests\ORM\Tools\Export\Address - joinColumn: - name: address_id - referencedColumnName: id - onDelete: CASCADE - cascade: [ persist ] - inversedBy: user - orphanRemoval: true - fetch: EAGER - cart: - targetEntity: Doctrine\Tests\ORM\Tools\Export\Cart - mappedBy: user - cascade: [ remove ] - manyToOne: - mainGroup: - targetEntity: Doctrine\Tests\ORM\Tools\Export\Group - oneToMany: - phonenumbers: - targetEntity: Doctrine\Tests\ORM\Tools\Export\Phonenumber - mappedBy: user - orderBy: - number: ASC - cascade: [ persist, merge ] - orphanRemoval: true - fetch: LAZY - interests: - targetEntity: Doctrine\Tests\ORM\Tools\Export\Interests - mappedBy: user - cascade: [ persist, merge, remove, refresh, detach ] - orphanRemoval: true - manyToMany: - groups: - targetEntity: Doctrine\Tests\ORM\Tools\Export\Group - fetch: EXTRA_LAZY - joinTable: - name: cms_users_groups - joinColumns: - user_id: - referencedColumnName: id - nullable: false - unique: false - inverseJoinColumns: - group_id: - referencedColumnName: id - columnDefinition: INT NULL - cascade: - - all - lifecycleCallbacks: - prePersist: [ doStuffOnPrePersist, doOtherStuffOnPrePersistToo ] - postPersist: [ doStuffOnPostPersist ] diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/CountOutputWalkerTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/CountOutputWalkerTest.php index df7f73f7881..f84d1de5c3e 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/CountOutputWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/CountOutputWalkerTest.php @@ -1,5 +1,7 @@ entityManager->createQuery( - 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p JOIN p.category c JOIN p.author a'); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountOutputWalker::class); - $query->setFirstResult(null)->setMaxResults(null); - - $this->assertEquals( - "SELECT COUNT(*) AS dctrn_count FROM (SELECT DISTINCT id_0 FROM (SELECT b0_.id AS id_0, c1_.id AS id_1, a2_.id AS id_2, a2_.name AS name_3, b0_.author_id AS author_id_4, b0_.category_id AS category_id_5 FROM BlogPost b0_ INNER JOIN Category c1_ ON b0_.category_id = c1_.id INNER JOIN Author a2_ ON b0_.author_id = a2_.id) dctrn_result) dctrn_table", $query->getSQL() - ); - } - - public function testCountQuery_MixedResultsWithName() - { - $query = $this->entityManager->createQuery( - 'SELECT a, sum(a.name) as foo FROM Doctrine\Tests\ORM\Tools\Pagination\Author a'); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountOutputWalker::class); - $query->setFirstResult(null)->setMaxResults(null); - - $this->assertEquals( - "SELECT COUNT(*) AS dctrn_count FROM (SELECT DISTINCT id_0 FROM (SELECT a0_.id AS id_0, a0_.name AS name_1, sum(a0_.name) AS sclr_2 FROM Author a0_) dctrn_result) dctrn_table", $query->getSQL() - ); - } + $query = $this->entityManager->createQuery($dql); - public function testCountQuery_GroupBy(): void - { - $query = $this->entityManager->createQuery( - 'SELECT p.name FROM Doctrine\Tests\ORM\Tools\Pagination\Person p GROUP BY p.name'); $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountOutputWalker::class); $query->setFirstResult(null)->setMaxResults(null); - $this->assertSame( - "SELECT COUNT(*) AS dctrn_count FROM (SELECT p0_.name AS name_0 FROM Person p0_ GROUP BY p0_.name) dctrn_table", $query->getSQL() - ); + self::assertEquals($sql, $query->getSQL()); } - public function testCountQuery_Having(): void + public function provideDataForCountQuery() { - $query = $this->entityManager->createQuery( - 'SELECT g, u, count(u.id) AS userCount FROM Doctrine\Tests\ORM\Tools\Pagination\Group g LEFT JOIN g.users u GROUP BY g.id HAVING userCount > 0'); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountOutputWalker::class); - $query->setFirstResult(null)->setMaxResults(null); - - $this->assertSame( - "SELECT COUNT(*) AS dctrn_count FROM (SELECT count(u0_.id) AS sclr_0, g1_.id AS id_1, u0_.id AS id_2 FROM groups g1_ LEFT JOIN user_group u2_ ON g1_.id = u2_.group_id LEFT JOIN User u0_ ON u0_.id = u2_.user_id GROUP BY g1_.id HAVING sclr_0 > 0) dctrn_table", $query->getSQL() - ); + return [ + // Multiple results and joins + [ + 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p JOIN p.category c JOIN p.author a', + 'SELECT COUNT(*) AS dctrn_count FROM (SELECT DISTINCT c0 FROM (SELECT t0."id" AS c0, t1."id" AS c1, t2."id" AS c2, t2."name" AS c3, t0."author_id" AS c4, t0."category_id" AS c5 FROM "BlogPost" t0 INNER JOIN "Category" t1 ON t0."category_id" = t1."id" INNER JOIN "Author" t2 ON t0."author_id" = t2."id") dctrn_result) dctrn_table' + ], + // Mixed results with name + [ + 'SELECT a, sum(a.name) as foo FROM Doctrine\Tests\ORM\Tools\Pagination\Author a', + 'SELECT COUNT(*) AS dctrn_count FROM (SELECT DISTINCT c0 FROM (SELECT t0."id" AS c0, t0."name" AS c1, sum(t0."name") AS c2 FROM "Author" t0) dctrn_result) dctrn_table' + ], + // Grouping support + [ + 'SELECT p.name FROM Doctrine\Tests\ORM\Tools\Pagination\Person p GROUP BY p.name', + 'SELECT COUNT(*) AS dctrn_count FROM (SELECT t0."name" AS c0 FROM "Person" t0 GROUP BY t0."name") dctrn_table' + ], + // Having support + [ + 'SELECT g, u, count(u.id) AS userCount FROM Doctrine\Tests\ORM\Tools\Pagination\Group g LEFT JOIN g.users u GROUP BY g.id HAVING userCount > 0', + 'SELECT COUNT(*) AS dctrn_count FROM (SELECT count(t0."id") AS c0, t1."id" AS c1, t0."id" AS c2 FROM "groups" t1 LEFT JOIN "user_group" t2 ON t1."id" = t2."group_id" LEFT JOIN "User" t0 ON t0."id" = t2."user_id" GROUP BY t1."id" HAVING c0 > 0) dctrn_table' + ], + ]; } public function testCountQueryOrderBySqlServer() @@ -61,14 +54,9 @@ public function testCountQueryOrderBySqlServer() $this->markTestSkipped('SQLServer only test.'); } - $query = $this->entityManager->createQuery( - 'SELECT p FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p ORDER BY p.id'); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountOutputWalker::class); - $query->setFirstResult(null)->setMaxResults(null); - - $this->assertEquals( - "SELECT COUNT(*) AS dctrn_count FROM (SELECT DISTINCT id_0 FROM (SELECT b0_.id AS id_0, b0_.author_id AS author_id_1, b0_.category_id AS category_id_2 FROM BlogPost b0_) dctrn_result) dctrn_table", - $query->getSQL() + $this->testCountQuery( + 'SELECT p FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p ORDER BY p.id', + 'SELECT COUNT(*) AS dctrn_count FROM (SELECT DISTINCT c0 FROM (SELECT t0.[id] AS c0, t0.[author_id] AS c1, t0.[category_id] AS c2 FROM [BlogPost] t0) dctrn_result) dctrn_table' ); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/CountWalkerTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/CountWalkerTest.php index 2aa398d6fbe..ff99b4dd23a 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/CountWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/CountWalkerTest.php @@ -1,5 +1,7 @@ entityManager->createQuery( - 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p JOIN p.category c JOIN p.author a'); - $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CountWalker::class]); - $query->setHint(CountWalker::HINT_DISTINCT, true); - $query->setFirstResult(null)->setMaxResults(null); + $query = $this->entityManager->createQuery($dql); - $this->assertEquals( - "SELECT count(DISTINCT b0_.id) AS sclr_0 FROM BlogPost b0_ INNER JOIN Category c1_ ON b0_.category_id = c1_.id INNER JOIN Author a2_ ON b0_.author_id = a2_.id", $query->getSQL() - ); - } - - public function testCountQuery_MixedResultsWithName() - { - $query = $this->entityManager->createQuery( - 'SELECT a, sum(a.name) as foo FROM Doctrine\Tests\ORM\Tools\Pagination\Author a'); $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CountWalker::class]); $query->setHint(CountWalker::HINT_DISTINCT, true); - $query->setFirstResult(null)->setMaxResults(null); - $this->assertEquals( - "SELECT count(DISTINCT a0_.id) AS sclr_0 FROM Author a0_", $query->getSQL() - ); - } - - public function testCountQuery_KeepsGroupBy() - { - $query = $this->entityManager->createQuery( - 'SELECT b FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost b GROUP BY b.id'); - $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CountWalker::class]); - $query->setHint(CountWalker::HINT_DISTINCT, true); $query->setFirstResult(null)->setMaxResults(null); - $this->assertEquals( - "SELECT count(DISTINCT b0_.id) AS sclr_0 FROM BlogPost b0_ GROUP BY b0_.id", $query->getSQL() - ); + self::assertEquals($sql, $query->getSQL()); } - public function testCountQuery_RemovesOrderBy() + public function provideDataForCountQuery() { - $query = $this->entityManager->createQuery( - 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p JOIN p.category c JOIN p.author a ORDER BY a.name'); - $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CountWalker::class]); - $query->setHint(CountWalker::HINT_DISTINCT, true); - $query->setFirstResult(null)->setMaxResults(null); - - $this->assertEquals( - "SELECT count(DISTINCT b0_.id) AS sclr_0 FROM BlogPost b0_ INNER JOIN Category c1_ ON b0_.category_id = c1_.id INNER JOIN Author a2_ ON b0_.author_id = a2_.id", $query->getSQL() - ); - } - - public function testCountQuery_RemovesLimits() - { - $query = $this->entityManager->createQuery( - 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p JOIN p.category c JOIN p.author a'); - $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CountWalker::class]); - $query->setHint(CountWalker::HINT_DISTINCT, true); - $query->setFirstResult(null)->setMaxResults(null); - - $this->assertEquals( - "SELECT count(DISTINCT b0_.id) AS sclr_0 FROM BlogPost b0_ INNER JOIN Category c1_ ON b0_.category_id = c1_.id INNER JOIN Author a2_ ON b0_.author_id = a2_.id", $query->getSQL() - ); + return [ + // Multiple results and joins + [ + 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p JOIN p.category c JOIN p.author a', + 'SELECT count(DISTINCT t0."id") AS c0 FROM "BlogPost" t0 INNER JOIN "Category" t1 ON t0."category_id" = t1."id" INNER JOIN "Author" t2 ON t0."author_id" = t2."id"' + ], + // Mixed results with name + [ + 'SELECT a, sum(a.name) as foo FROM Doctrine\Tests\ORM\Tools\Pagination\Author a', + 'SELECT count(DISTINCT t0."id") AS c0 FROM "Author" t0' + ], + // Keeps group by + [ + 'SELECT b FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost b GROUP BY b.id', + 'SELECT count(DISTINCT t0."id") AS c0 FROM "BlogPost" t0 GROUP BY t0."id"' + ], + // Removes order by + [ + 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p JOIN p.category c JOIN p.author a ORDER BY a.name', + 'SELECT count(DISTINCT t0."id") AS c0 FROM "BlogPost" t0 INNER JOIN "Category" t1 ON t0."category_id" = t1."id" INNER JOIN "Author" t2 ON t0."author_id" = t2."id"' + ], + // Arbitrary join + [ + 'SELECT p FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p LEFT JOIN Doctrine\Tests\ORM\Tools\Pagination\Category c WITH p.category = c', + 'SELECT count(DISTINCT t0."id") AS c0 FROM "BlogPost" t0 LEFT JOIN "Category" t1 ON (t0."category_id" = t1."id")' + ], + ]; } + /** + * @expectedException \RuntimeException + * @expectedExceptionMessage Cannot count query that uses a HAVING clause. Use the output walkers for pagination + */ public function testCountQuery_HavingException() { $query = $this->entityManager->createQuery( - "SELECT g, COUNT(u.id) AS userCount FROM Doctrine\Tests\Models\CMS\CmsGroup g LEFT JOIN g.users u GROUP BY g.id HAVING userCount > 0" + 'SELECT g, COUNT(u.id) AS userCount FROM Doctrine\Tests\Models\CMS\CmsGroup g LEFT JOIN g.users u GROUP BY g.id HAVING userCount > 0' ); - $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CountWalker::class]); - $query->setFirstResult(null)->setMaxResults(null); - - $this->expectException(\RuntimeException::class); - $this->expectExceptionMessage('Cannot count query that uses a HAVING clause. Use the output walkers for pagination'); - - $query->getSQL(); - } - /** - * Arbitrary Join - */ - public function testCountQueryWithArbitraryJoin() - { - $query = $this->entityManager->createQuery( - 'SELECT p FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p LEFT JOIN Doctrine\Tests\ORM\Tools\Pagination\Category c WITH p.category = c'); $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CountWalker::class]); - $query->setHint(CountWalker::HINT_DISTINCT, true); $query->setFirstResult(null)->setMaxResults(null); - $this->assertEquals( - "SELECT count(DISTINCT b0_.id) AS sclr_0 FROM BlogPost b0_ LEFT JOIN Category c1_ ON (b0_.category_id = c1_.id)", $query->getSQL() - ); + $query->getSQL(); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryOutputWalkerTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryOutputWalkerTest.php index 39ee1360dc9..77f65e299b5 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryOutputWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryOutputWalkerTest.php @@ -1,5 +1,7 @@ setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - "SELECT DISTINCT id_0 FROM (SELECT m0_.id AS id_0, m0_.title AS title_1, c1_.id AS id_2, a2_.id AS id_3, a2_.name AS name_4, m0_.author_id AS author_id_5, m0_.category_id AS category_id_6 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON m0_.category_id = c1_.id INNER JOIN Author a2_ ON m0_.author_id = a2_.id) dctrn_result", $limitQuery->getSQL() + 'SELECT DISTINCT c0 FROM (SELECT t0."id" AS c0, t0."title" AS c1, t1."id" AS c2, t2."id" AS c3, t2."name" AS c4, t0."author_id" AS c5, t0."category_id" AS c6 FROM "MyBlogPost" t0 INNER JOIN "Category" t1 ON t0."category_id" = t1."id" INNER JOIN "Author" t2 ON t0."author_id" = t2."id") dctrn_result', + $limitQuery->getSQL() ); } @@ -34,7 +37,8 @@ public function testLimitSubqueryWithSortPg() : void $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - "SELECT DISTINCT id_0, MIN(sclr_5) AS dctrn_minrownum FROM (SELECT m0_.id AS id_0, m0_.title AS title_1, c1_.id AS id_2, a2_.id AS id_3, a2_.name AS name_4, ROW_NUMBER() OVER(ORDER BY m0_.title ASC) AS sclr_5, m0_.author_id AS author_id_6, m0_.category_id AS category_id_7 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON m0_.category_id = c1_.id INNER JOIN Author a2_ ON m0_.author_id = a2_.id) dctrn_result GROUP BY id_0 ORDER BY dctrn_minrownum ASC", $limitQuery->getSQL() + 'SELECT DISTINCT c0, MIN(c5) AS dctrn_minrownum FROM (SELECT t0."id" AS c0, t0."title" AS c1, t1."id" AS c2, t2."id" AS c3, t2."name" AS c4, ROW_NUMBER() OVER(ORDER BY t0."title" ASC) AS c5, t0."author_id" AS c6, t0."category_id" AS c7 FROM "MyBlogPost" t0 INNER JOIN "Category" t1 ON t0."category_id" = t1."id" INNER JOIN "Author" t2 ON t0."author_id" = t2."id") dctrn_result GROUP BY c0 ORDER BY dctrn_minrownum ASC', + $limitQuery->getSQL() ); $this->entityManager->getConnection()->setDatabasePlatform($odp); @@ -52,7 +56,7 @@ public function testLimitSubqueryWithScalarSortPg() : void $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - "SELECT DISTINCT id_1, MIN(sclr_3) AS dctrn_minrownum FROM (SELECT COUNT(g0_.id) AS sclr_0, u1_.id AS id_1, g0_.id AS id_2, ROW_NUMBER() OVER(ORDER BY COUNT(g0_.id) ASC) AS sclr_3 FROM User u1_ INNER JOIN user_group u2_ ON u1_.id = u2_.user_id INNER JOIN groups g0_ ON g0_.id = u2_.group_id) dctrn_result GROUP BY id_1 ORDER BY dctrn_minrownum ASC", + 'SELECT DISTINCT c1, MIN(c3) AS dctrn_minrownum FROM (SELECT COUNT(t0."id") AS c0, t1."id" AS c1, t0."id" AS c2, ROW_NUMBER() OVER(ORDER BY COUNT(t0."id") ASC) AS c3 FROM "User" t1 INNER JOIN "user_group" t2 ON t1."id" = t2."user_id" INNER JOIN "groups" t0 ON t0."id" = t2."group_id") dctrn_result GROUP BY c1 ORDER BY dctrn_minrownum ASC', $limitQuery->getSQL() ); @@ -71,7 +75,7 @@ public function testLimitSubqueryWithMixedSortPg() : void $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - "SELECT DISTINCT id_1, MIN(sclr_3) AS dctrn_minrownum FROM (SELECT COUNT(g0_.id) AS sclr_0, u1_.id AS id_1, g0_.id AS id_2, ROW_NUMBER() OVER(ORDER BY COUNT(g0_.id) ASC, u1_.id DESC) AS sclr_3 FROM User u1_ INNER JOIN user_group u2_ ON u1_.id = u2_.user_id INNER JOIN groups g0_ ON g0_.id = u2_.group_id) dctrn_result GROUP BY id_1 ORDER BY dctrn_minrownum ASC", + 'SELECT DISTINCT c1, MIN(c3) AS dctrn_minrownum FROM (SELECT COUNT(t0."id") AS c0, t1."id" AS c1, t0."id" AS c2, ROW_NUMBER() OVER(ORDER BY COUNT(t0."id") ASC, t1."id" DESC) AS c3 FROM "User" t1 INNER JOIN "user_group" t2 ON t1."id" = t2."user_id" INNER JOIN "groups" t0 ON t0."id" = t2."group_id") dctrn_result GROUP BY c1 ORDER BY dctrn_minrownum ASC', $limitQuery->getSQL() ); @@ -90,7 +94,7 @@ public function testLimitSubqueryWithHiddenScalarSortPg() : void $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - "SELECT DISTINCT id_1, MIN(sclr_3) AS dctrn_minrownum FROM (SELECT COUNT(g0_.id) AS sclr_0, u1_.id AS id_1, g0_.id AS id_2, ROW_NUMBER() OVER(ORDER BY COUNT(g0_.id) ASC, u1_.id DESC) AS sclr_3 FROM User u1_ INNER JOIN user_group u2_ ON u1_.id = u2_.user_id INNER JOIN groups g0_ ON g0_.id = u2_.group_id) dctrn_result GROUP BY id_1 ORDER BY dctrn_minrownum ASC", + 'SELECT DISTINCT c1, MIN(c3) AS dctrn_minrownum FROM (SELECT COUNT(t0."id") AS c0, t1."id" AS c1, t0."id" AS c2, ROW_NUMBER() OVER(ORDER BY COUNT(t0."id") ASC, t1."id" DESC) AS c3 FROM "User" t1 INNER JOIN "user_group" t2 ON t1."id" = t2."user_id" INNER JOIN "groups" t0 ON t0."id" = t2."group_id") dctrn_result GROUP BY c1 ORDER BY dctrn_minrownum ASC', $limitQuery->getSQL() ); @@ -119,7 +123,8 @@ public function testLimitSubqueryWithSortOracle() : void $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - "SELECT DISTINCT ID_0, MIN(SCLR_5) AS dctrn_minrownum FROM (SELECT m0_.id AS ID_0, m0_.title AS TITLE_1, c1_.id AS ID_2, a2_.id AS ID_3, a2_.name AS NAME_4, ROW_NUMBER() OVER(ORDER BY m0_.title ASC) AS SCLR_5, m0_.author_id AS AUTHOR_ID_6, m0_.category_id AS CATEGORY_ID_7 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON m0_.category_id = c1_.id INNER JOIN Author a2_ ON m0_.author_id = a2_.id) dctrn_result GROUP BY ID_0 ORDER BY dctrn_minrownum ASC", $limitQuery->getSQL() + 'SELECT DISTINCT C0, MIN(C5) AS dctrn_minrownum FROM (SELECT t0."id" AS C0, t0."title" AS C1, t1."id" AS C2, t2."id" AS C3, t2."name" AS C4, ROW_NUMBER() OVER(ORDER BY t0."title" ASC) AS C5, t0."author_id" AS C6, t0."category_id" AS C7 FROM "MyBlogPost" t0 INNER JOIN "Category" t1 ON t0."category_id" = t1."id" INNER JOIN "Author" t2 ON t0."author_id" = t2."id") dctrn_result GROUP BY C0 ORDER BY dctrn_minrownum ASC', + $limitQuery->getSQL() ); $this->entityManager->getConnection()->setDatabasePlatform($odp); @@ -138,7 +143,7 @@ public function testLimitSubqueryWithScalarSortOracle() : void $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - "SELECT DISTINCT ID_1, MIN(SCLR_3) AS dctrn_minrownum FROM (SELECT COUNT(g0_.id) AS SCLR_0, u1_.id AS ID_1, g0_.id AS ID_2, ROW_NUMBER() OVER(ORDER BY COUNT(g0_.id) ASC) AS SCLR_3 FROM User u1_ INNER JOIN user_group u2_ ON u1_.id = u2_.user_id INNER JOIN groups g0_ ON g0_.id = u2_.group_id) dctrn_result GROUP BY ID_1 ORDER BY dctrn_minrownum ASC", + 'SELECT DISTINCT C1, MIN(C3) AS dctrn_minrownum FROM (SELECT COUNT(t0."id") AS C0, t1."id" AS C1, t0."id" AS C2, ROW_NUMBER() OVER(ORDER BY COUNT(t0."id") ASC) AS C3 FROM "User" t1 INNER JOIN "user_group" t2 ON t1."id" = t2."user_id" INNER JOIN "groups" t0 ON t0."id" = t2."group_id") dctrn_result GROUP BY C1 ORDER BY dctrn_minrownum ASC', $limitQuery->getSQL() ); @@ -158,7 +163,7 @@ public function testLimitSubqueryWithMixedSortOracle() : void $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - "SELECT DISTINCT ID_1, MIN(SCLR_3) AS dctrn_minrownum FROM (SELECT COUNT(g0_.id) AS SCLR_0, u1_.id AS ID_1, g0_.id AS ID_2, ROW_NUMBER() OVER(ORDER BY COUNT(g0_.id) ASC, u1_.id DESC) AS SCLR_3 FROM User u1_ INNER JOIN user_group u2_ ON u1_.id = u2_.user_id INNER JOIN groups g0_ ON g0_.id = u2_.group_id) dctrn_result GROUP BY ID_1 ORDER BY dctrn_minrownum ASC", + 'SELECT DISTINCT C1, MIN(C3) AS dctrn_minrownum FROM (SELECT COUNT(t0."id") AS C0, t1."id" AS C1, t0."id" AS C2, ROW_NUMBER() OVER(ORDER BY COUNT(t0."id") ASC, t1."id" DESC) AS C3 FROM "User" t1 INNER JOIN "user_group" t2 ON t1."id" = t2."user_id" INNER JOIN "groups" t0 ON t0."id" = t2."group_id") dctrn_result GROUP BY C1 ORDER BY dctrn_minrownum ASC', $limitQuery->getSQL() ); @@ -177,7 +182,8 @@ public function testLimitSubqueryOracle() : void $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - "SELECT DISTINCT ID_0 FROM (SELECT m0_.id AS ID_0, m0_.title AS TITLE_1, c1_.id AS ID_2, a2_.id AS ID_3, a2_.name AS NAME_4, m0_.author_id AS AUTHOR_ID_5, m0_.category_id AS CATEGORY_ID_6 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON m0_.category_id = c1_.id INNER JOIN Author a2_ ON m0_.author_id = a2_.id) dctrn_result", $limitQuery->getSQL() + 'SELECT DISTINCT C0 FROM (SELECT t0."id" AS C0, t0."title" AS C1, t1."id" AS C2, t2."id" AS C3, t2."name" AS C4, t0."author_id" AS C5, t0."category_id" AS C6 FROM "MyBlogPost" t0 INNER JOIN "Category" t1 ON t0."category_id" = t1."id" INNER JOIN "Author" t2 ON t0."author_id" = t2."id") dctrn_result', + $limitQuery->getSQL() ); $this->entityManager->getConnection()->setDatabasePlatform($odp); @@ -191,7 +197,8 @@ public function testCountQueryMixedResultsWithName() : void $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - "SELECT DISTINCT id_0 FROM (SELECT a0_.id AS id_0, a0_.name AS name_1, sum(a0_.name) AS sclr_2 FROM Author a0_) dctrn_result", $limitQuery->getSQL() + 'SELECT DISTINCT c0 FROM (SELECT t0."id" AS c0, t0."name" AS c1, sum(t0."name") AS c2 FROM "Author" t0) dctrn_result', + $limitQuery->getSQL() ); } @@ -207,8 +214,8 @@ public function testCountQueryWithArithmeticOrderByCondition() : void $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertSame( - 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0, (1 - 1000) * 1 FROM (SELECT a0_.id AS id_0, a0_.name AS name_1 FROM Author a0_) dctrn_result_inner ORDER BY (1 - 1000) * 1 DESC) dctrn_result', + self::assertSame( + 'SELECT DISTINCT c0 FROM (SELECT DISTINCT c0, (1 - 1000) * 1 FROM (SELECT t0.`id` AS c0, t0.`name` AS c1 FROM `Author` t0) dctrn_result_inner ORDER BY (1 - 1000) * 1 DESC) dctrn_result', $query->getSQL() ); } @@ -222,8 +229,8 @@ public function testCountQueryWithComplexScalarOrderByItem() : void $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertSame( - 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0, image_height_2 * image_width_3 FROM (SELECT a0_.id AS id_0, a0_.image AS image_1, a0_.image_height AS image_height_2, a0_.image_width AS image_width_3, a0_.image_alt_desc AS image_alt_desc_4, a0_.user_id AS user_id_5 FROM Avatar a0_) dctrn_result_inner ORDER BY image_height_2 * image_width_3 DESC) dctrn_result', + self::assertSame( + 'SELECT DISTINCT c0 FROM (SELECT DISTINCT c0, c2 * c3 FROM (SELECT t0.`id` AS c0, t0.`image` AS c1, t0.`image_height` AS c2, t0.`image_width` AS c3, t0.`image_alt_desc` AS c4, t0.`user_id` AS c5 FROM `Avatar` t0) dctrn_result_inner ORDER BY c2 * c3 DESC) dctrn_result', $query->getSQL() ); } @@ -237,8 +244,8 @@ public function testCountQueryWithComplexScalarOrderByItemJoined() : void $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertSame( - 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0, image_height_1 * image_width_2 FROM (SELECT u0_.id AS id_0, a1_.image_height AS image_height_1, a1_.image_width AS image_width_2, a1_.user_id AS user_id_3 FROM User u0_ INNER JOIN Avatar a1_ ON u0_.id = a1_.user_id) dctrn_result_inner ORDER BY image_height_1 * image_width_2 DESC) dctrn_result', + self::assertSame( + 'SELECT DISTINCT c0 FROM (SELECT DISTINCT c0, c1 * c2 FROM (SELECT t0.`id` AS c0, t1.`image_height` AS c1, t1.`image_width` AS c2, t1.`user_id` AS c3 FROM `User` t0 INNER JOIN `Avatar` t1 ON t0.`id` = t1.`user_id`) dctrn_result_inner ORDER BY c1 * c2 DESC) dctrn_result', $query->getSQL() ); } @@ -252,8 +259,8 @@ public function testCountQueryWithComplexScalarOrderByItemJoinedWithPartial() : $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertSame( - 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0, image_height_3 * image_width_4 FROM (SELECT u0_.id AS id_0, a1_.id AS id_1, a1_.image_alt_desc AS image_alt_desc_2, a1_.image_height AS image_height_3, a1_.image_width AS image_width_4, a1_.user_id AS user_id_5 FROM User u0_ INNER JOIN Avatar a1_ ON u0_.id = a1_.user_id) dctrn_result_inner ORDER BY image_height_3 * image_width_4 DESC) dctrn_result', + self::assertSame( + 'SELECT DISTINCT c0 FROM (SELECT DISTINCT c0, c3 * c4 FROM (SELECT t0.`id` AS c0, t1.`id` AS c1, t1.`image_alt_desc` AS c2, t1.`image_height` AS c3, t1.`image_width` AS c4, t1.`user_id` AS c5 FROM `User` t0 INNER JOIN `Avatar` t1 ON t0.`id` = t1.`user_id`) dctrn_result_inner ORDER BY c3 * c4 DESC) dctrn_result', $query->getSQL() ); } @@ -267,8 +274,8 @@ public function testCountQueryWithComplexScalarOrderByItemOracle() : void $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertSame( - 'SELECT DISTINCT ID_0, MIN(SCLR_5) AS dctrn_minrownum FROM (SELECT a0_.id AS ID_0, a0_.image AS IMAGE_1, a0_.image_height AS IMAGE_HEIGHT_2, a0_.image_width AS IMAGE_WIDTH_3, a0_.image_alt_desc AS IMAGE_ALT_DESC_4, ROW_NUMBER() OVER(ORDER BY a0_.image_height * a0_.image_width DESC) AS SCLR_5, a0_.user_id AS USER_ID_6 FROM Avatar a0_) dctrn_result GROUP BY ID_0 ORDER BY dctrn_minrownum ASC', + self::assertSame( + 'SELECT DISTINCT C0, MIN(C5) AS dctrn_minrownum FROM (SELECT t0."id" AS C0, t0."image" AS C1, t0."image_height" AS C2, t0."image_width" AS C3, t0."image_alt_desc" AS C4, ROW_NUMBER() OVER(ORDER BY t0."image_height" * t0."image_width" DESC) AS C5, t0."user_id" AS C6 FROM "Avatar" t0) dctrn_result GROUP BY C0 ORDER BY dctrn_minrownum ASC', $query->getSQL() ); } @@ -285,12 +292,12 @@ public function testLimitSubqueryWithHiddenSelectionInOrderBy() : void $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0, name_2 FROM (SELECT a0_.id AS id_0, a0_.name AS name_1, a0_.name AS name_2 FROM Author a0_) dctrn_result_inner ORDER BY name_2 DESC) dctrn_result', + 'SELECT DISTINCT c0 FROM (SELECT DISTINCT c0, c2 FROM (SELECT t0."id" AS c0, t0."name" AS c1, t0."name" AS c2 FROM "Author" t0) dctrn_result_inner ORDER BY c2 DESC) dctrn_result', $query->getSQL() ); } - public function testLimitSubqueryWithColumnWithSortDirectionInName() : void + public function testLimitSubqueryWithColumnWithSortDirectionInNameMySql() : void { $query = $this->entityManager->createQuery( 'SELECT a FROM Doctrine\Tests\ORM\Tools\Pagination\Avatar a ORDER BY a.image_alt_desc DESC' @@ -299,8 +306,8 @@ public function testLimitSubqueryWithColumnWithSortDirectionInName() : void $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertSame( - 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0, image_alt_desc_4 FROM (SELECT a0_.id AS id_0, a0_.image AS image_1, a0_.image_height AS image_height_2, a0_.image_width AS image_width_3, a0_.image_alt_desc AS image_alt_desc_4, a0_.user_id AS user_id_5 FROM Avatar a0_) dctrn_result_inner ORDER BY image_alt_desc_4 DESC) dctrn_result', + self::assertSame( + 'SELECT DISTINCT c0 FROM (SELECT DISTINCT c0, c4 FROM (SELECT t0.`id` AS c0, t0.`image` AS c1, t0.`image_height` AS c2, t0.`image_width` AS c3, t0.`image_alt_desc` AS c4, t0.`user_id` AS c5 FROM `Avatar` t0) dctrn_result_inner ORDER BY c4 DESC) dctrn_result', $query->getSQL() ); } @@ -314,7 +321,7 @@ public function testLimitSubqueryWithOrderByInnerJoined() : void $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0, name_1 FROM (SELECT b0_.id AS id_0, a1_.name AS name_1, b0_.author_id AS author_id_2, b0_.category_id AS category_id_3 FROM BlogPost b0_ INNER JOIN Author a1_ ON b0_.author_id = a1_.id) dctrn_result_inner ORDER BY name_1 ASC) dctrn_result', + 'SELECT DISTINCT c0 FROM (SELECT DISTINCT c0, c1 FROM (SELECT t0."id" AS c0, t1."name" AS c1, t0."author_id" AS c2, t0."category_id" AS c3 FROM "BlogPost" t0 INNER JOIN "Author" t1 ON t0."author_id" = t1."id") dctrn_result_inner ORDER BY c1 ASC) dctrn_result', $query->getSQL() ); } @@ -330,7 +337,7 @@ public function testLimitSubqueryWithOrderByAndSubSelectInWhereClauseMySql() : v $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0 FROM (SELECT b0_.id AS id_0, b0_.author_id AS author_id_1, b0_.category_id AS category_id_2 FROM BlogPost b0_ WHERE ((SELECT COUNT(b1_.id) AS sclr_3 FROM BlogPost b1_) = 1)) dctrn_result_inner ORDER BY id_0 DESC) dctrn_result', + 'SELECT DISTINCT c0 FROM (SELECT DISTINCT c0 FROM (SELECT t0.`id` AS c0, t0.`author_id` AS c1, t0.`category_id` AS c2 FROM `BlogPost` t0 WHERE ((SELECT COUNT(t1.`id`) AS c3 FROM `BlogPost` t1) = 1)) dctrn_result_inner ORDER BY c0 DESC) dctrn_result', $query->getSQL() ); } @@ -346,7 +353,7 @@ public function testLimitSubqueryWithOrderByAndSubSelectInWhereClausePgSql() : v $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - 'SELECT DISTINCT id_0, MIN(sclr_1) AS dctrn_minrownum FROM (SELECT b0_.id AS id_0, ROW_NUMBER() OVER(ORDER BY b0_.id DESC) AS sclr_1, b0_.author_id AS author_id_2, b0_.category_id AS category_id_3 FROM BlogPost b0_ WHERE ((SELECT COUNT(b1_.id) AS sclr_4 FROM BlogPost b1_) = 1)) dctrn_result GROUP BY id_0 ORDER BY dctrn_minrownum ASC', + 'SELECT DISTINCT c0, MIN(c1) AS dctrn_minrownum FROM (SELECT t0."id" AS c0, ROW_NUMBER() OVER(ORDER BY t0."id" DESC) AS c1, t0."author_id" AS c2, t0."category_id" AS c3 FROM "BlogPost" t0 WHERE ((SELECT COUNT(t1."id") AS c4 FROM "BlogPost" t1) = 1)) dctrn_result GROUP BY c0 ORDER BY dctrn_minrownum ASC', $query->getSQL() ); } @@ -354,7 +361,7 @@ public function testLimitSubqueryWithOrderByAndSubSelectInWhereClausePgSql() : v /** * This tests ordering by property that has the 'declared' field. */ - public function testLimitSubqueryOrderByFieldFromMappedSuperclass() : void + public function testLimitSubqueryOrderByFieldFromMappedSuperclassMySql() : void { $this->entityManager->getConnection()->setDatabasePlatform(new MySqlPlatform()); @@ -365,7 +372,7 @@ public function testLimitSubqueryOrderByFieldFromMappedSuperclass() : void $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0 FROM (SELECT b0_.id AS id_0, b0_.name AS name_1 FROM Banner b0_) dctrn_result_inner ORDER BY id_0 DESC) dctrn_result', + 'SELECT DISTINCT c0 FROM (SELECT DISTINCT c0 FROM (SELECT t0.`id` AS c0, t0.`name` AS c1 FROM `Banner` t0) dctrn_result_inner ORDER BY c0 DESC) dctrn_result', $query->getSQL() ); } @@ -373,7 +380,7 @@ public function testLimitSubqueryOrderByFieldFromMappedSuperclass() : void /** * Tests order by on a subselect expression (mysql). */ - public function testLimitSubqueryOrderBySubSelectOrderByExpression() : void + public function testLimitSubqueryOrderBySubSelectOrderByExpressionMySql() : void { $this->entityManager->getConnection()->setDatabasePlatform(new MySqlPlatform()); @@ -390,7 +397,7 @@ public function testLimitSubqueryOrderBySubSelectOrderByExpression() : void $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0, sclr_2 FROM (SELECT a0_.id AS id_0, a0_.name AS name_1, (SELECT MIN(m1_.title) AS sclr_3 FROM MyBlogPost m1_ WHERE m1_.author_id = a0_.id) AS sclr_2 FROM Author a0_) dctrn_result_inner ORDER BY sclr_2 DESC) dctrn_result', + 'SELECT DISTINCT c0 FROM (SELECT DISTINCT c0, c2 FROM (SELECT t0.`id` AS c0, t0.`name` AS c1, (SELECT MIN(t1.`title`) AS c3 FROM `MyBlogPost` t1 WHERE t1.`author_id` = t0.`id`) AS c2 FROM `Author` t0) dctrn_result_inner ORDER BY c2 DESC) dctrn_result', $query->getSQL() ); } @@ -398,7 +405,7 @@ public function testLimitSubqueryOrderBySubSelectOrderByExpression() : void /** * Tests order by on a subselect expression invoking RowNumberOverFunction (postgres). */ - public function testLimitSubqueryOrderBySubSelectOrderByExpressionPg() : void + public function testLimitSubqueryOrderBySubSelectOrderByExpressionPgSql() : void { $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform()); @@ -415,7 +422,7 @@ public function testLimitSubqueryOrderBySubSelectOrderByExpressionPg() : void $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - 'SELECT DISTINCT id_0, MIN(sclr_4) AS dctrn_minrownum FROM (SELECT a0_.id AS id_0, a0_.name AS name_1, (SELECT MIN(m1_.title) AS sclr_3 FROM MyBlogPost m1_ WHERE m1_.author_id = a0_.id) AS sclr_2, ROW_NUMBER() OVER(ORDER BY (SELECT MIN(m1_.title) AS sclr_5 FROM MyBlogPost m1_ WHERE m1_.author_id = a0_.id) DESC) AS sclr_4 FROM Author a0_) dctrn_result GROUP BY id_0 ORDER BY dctrn_minrownum ASC', + 'SELECT DISTINCT c0, MIN(c4) AS dctrn_minrownum FROM (SELECT t0."id" AS c0, t0."name" AS c1, (SELECT MIN(t1."title") AS c3 FROM "MyBlogPost" t1 WHERE t1."author_id" = t0."id") AS c2, ROW_NUMBER() OVER(ORDER BY (SELECT MIN(t1."title") AS c5 FROM "MyBlogPost" t1 WHERE t1."author_id" = t0."id") DESC) AS c4 FROM "Author" t0) dctrn_result GROUP BY c0 ORDER BY dctrn_minrownum ASC', $query->getSQL() ); } @@ -440,7 +447,7 @@ public function testLimitSubqueryOrderBySubSelectOrderByExpressionOracle() : voi $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); self::assertSame( - 'SELECT DISTINCT ID_0, MIN(SCLR_4) AS dctrn_minrownum FROM (SELECT a0_.id AS ID_0, a0_.name AS NAME_1, (SELECT MIN(m1_.title) AS SCLR_3 FROM MyBlogPost m1_ WHERE m1_.author_id = a0_.id) AS SCLR_2, ROW_NUMBER() OVER(ORDER BY (SELECT MIN(m1_.title) AS SCLR_5 FROM MyBlogPost m1_ WHERE m1_.author_id = a0_.id) DESC) AS SCLR_4 FROM Author a0_) dctrn_result GROUP BY ID_0 ORDER BY dctrn_minrownum ASC', + 'SELECT DISTINCT C0, MIN(C4) AS dctrn_minrownum FROM (SELECT t0."id" AS C0, t0."name" AS C1, (SELECT MIN(t1."title") AS C3 FROM "MyBlogPost" t1 WHERE t1."author_id" = t0."id") AS C2, ROW_NUMBER() OVER(ORDER BY (SELECT MIN(t1."title") AS C5 FROM "MyBlogPost" t1 WHERE t1."author_id" = t0."id") DESC) AS C4 FROM "Author" t0) dctrn_result GROUP BY C0 ORDER BY dctrn_minrownum ASC', $query->getSQL() ); } diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryWalkerTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryWalkerTest.php index 8ddc158b928..efa5d33f700 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryWalkerTest.php @@ -1,5 +1,7 @@ setHint(Query::HINT_CUSTOM_TREE_WALKERS, [LimitSubqueryWalker::class]); - $this->assertEquals( - "SELECT DISTINCT m0_.id AS id_0 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON m0_.category_id = c1_.id INNER JOIN Author a2_ ON m0_.author_id = a2_.id", + self::assertEquals( + 'SELECT DISTINCT t0."id" AS c0 FROM "MyBlogPost" t0 INNER JOIN "Category" t1 ON t0."category_id" = t1."id" INNER JOIN "Author" t2 ON t0."author_id" = t2."id"', $limitQuery->getSQL() ); } @@ -32,8 +34,8 @@ public function testLimitSubqueryWithSort() $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [LimitSubqueryWalker::class]); - $this->assertEquals( - "SELECT DISTINCT m0_.id AS id_0, m0_.title AS title_1 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON m0_.category_id = c1_.id INNER JOIN Author a2_ ON m0_.author_id = a2_.id ORDER BY m0_.title ASC", + self::assertEquals( + 'SELECT DISTINCT t0."id" AS c0, t0."title" AS c1 FROM "MyBlogPost" t0 INNER JOIN "Category" t1 ON t0."category_id" = t1."id" INNER JOIN "Author" t2 ON t0."author_id" = t2."id" ORDER BY t0."title" ASC', $limitQuery->getSQL() ); } @@ -46,8 +48,8 @@ public function testCountQuery_MixedResultsWithName() $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [LimitSubqueryWalker::class]); - $this->assertEquals( - "SELECT DISTINCT a0_.id AS id_0, sum(a0_.name) AS sclr_1 FROM Author a0_", + self::assertEquals( + 'SELECT DISTINCT t0."id" AS c0, sum(t0."name") AS c1 FROM "Author" t0', $limitQuery->getSQL() ); } @@ -63,8 +65,8 @@ public function testLimitSubqueryWithSortOnAssociation() $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [LimitSubqueryWalker::class]); - $this->assertEquals( - "SELECT DISTINCT m0_.id AS id_0, m0_.author_id AS sclr_1 FROM MyBlogPost m0_ ORDER BY m0_.author_id ASC", + self::assertEquals( + 'SELECT DISTINCT t0."id" AS c0, t0."author_id" AS c1 FROM "MyBlogPost" t0 ORDER BY t0."author_id" ASC', $limitQuery->getSQL() ); } @@ -80,8 +82,8 @@ public function testLimitSubqueryWithArbitraryJoin() $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [LimitSubqueryWalker::class]); - $this->assertEquals( - "SELECT DISTINCT m0_.id AS id_0 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON (m0_.category_id = c1_.id)", + self::assertEquals( + 'SELECT DISTINCT t0."id" AS c0 FROM "MyBlogPost" t0 INNER JOIN "Category" t1 ON (t0."category_id" = t1."id")', $limitQuery->getSQL() ); } @@ -94,8 +96,8 @@ public function testLimitSubqueryWithSortWithArbitraryJoin() $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [LimitSubqueryWalker::class]); - $this->assertEquals( - "SELECT DISTINCT m0_.id AS id_0, m0_.title AS title_1 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON (m0_.category_id = c1_.id) ORDER BY m0_.title ASC", + self::assertEquals( + 'SELECT DISTINCT t0."id" AS c0, t0."title" AS c1 FROM "MyBlogPost" t0 INNER JOIN "Category" t1 ON (t0."category_id" = t1."id") ORDER BY t0."title" ASC', $limitQuery->getSQL() ); } diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginationTestCase.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginationTestCase.php index fe8ee0f8252..1e9a5343ba5 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginationTestCase.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginationTestCase.php @@ -1,7 +1,10 @@ entityManager = $this->_getTestEntityManager(); + $this->entityManager = $this->getTestEntityManager(); } -} + public function tearDown() + { + $this->entityManager = null; + } +} /** -* @Entity +* @ORM\Entity */ class MyBlogPost { - - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; /** - * @ManyToOne(targetEntity="Author") + * @ORM\ManyToOne(targetEntity="Author") */ public $author; /** - * @ManyToOne(targetEntity="Category") + * @ORM\ManyToOne(targetEntity="Category") */ public $category; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $title; } /** - * @Entity + * @ORM\Entity */ class MyAuthor { - - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - } /** -* @Entity +* @ORM\Entity */ class MyCategory { - - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - } - /** - * @Entity + * @ORM\Entity */ class BlogPost { - - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; /** - * @ManyToOne(targetEntity="Author") + * @ORM\ManyToOne(targetEntity="Author") */ public $author; /** - * @ManyToOne(targetEntity="Category") + * @ORM\ManyToOne(targetEntity="Category") */ public $category; } /** - * @Entity + * @ORM\Entity */ class Author { - - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $name; - } /** - * @Entity + * @ORM\Entity */ class Person { - - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $name; - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $biography; - } /** - * @Entity + * @ORM\Entity */ class Category { - - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - } - -/** @Entity @Table(name="groups") */ +/** @ORM\Entity @ORM\Table(name="groups") */ class Group { - - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; - /** @ManyToMany(targetEntity="User", mappedBy="groups") */ + /** @ORM\ManyToMany(targetEntity="User", mappedBy="groups") */ public $users; } -/** @Entity */ +/** @ORM\Entity */ class User { - - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; /** - * @ManyToMany(targetEntity="Group", inversedBy="users") - * @JoinTable( + * @ORM\ManyToMany(targetEntity="Group", inversedBy="users") + * @ORM\JoinTable( * name="user_group", - * joinColumns = {@JoinColumn(name="user_id", referencedColumnName="id")}, - * inverseJoinColumns = {@JoinColumn(name="group_id", referencedColumnName="id")} + * joinColumns = {@ORM\JoinColumn(name="user_id", referencedColumnName="id")}, + * inverseJoinColumns = {@ORM\JoinColumn(name="group_id", referencedColumnName="id")} * ) */ public $groups; /** - * @OneToOne(targetEntity="Avatar", mappedBy="user") + * @ORM\OneToOne(targetEntity="Avatar", mappedBy="user") */ public $avatar; } -/** @Entity */ +/** @ORM\Entity */ class Avatar { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ public $id; /** - * @OneToOne(targetEntity="User", inversedBy="avatar") - * @JoinColumn(name="user_id", referencedColumnName="id") + * @ORM\OneToOne(targetEntity="User", inversedBy="avatar") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id") */ public $user; - /** @Column(type="string", length=255) */ + /** @ORM\Column(type="string", length=255) */ public $image; - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ public $image_height; - /** @Column(type="integer") */ + /** @ORM\Column(type="integer") */ public $image_width; - /** @Column(type="string", length=255) */ + /** @ORM\Column(type="string", length=255) */ public $image_alt_desc; } -/** @MappedSuperclass */ +/** @ORM\MappedSuperclass */ abstract class Identified { - /** @Id @Column(type="integer") @GeneratedValue */ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */ private $id; public function getId() @@ -182,9 +173,9 @@ public function getId() } } -/** @Entity */ +/** @ORM\Entity */ class Banner extends Identified { - /** @Column(type="string") */ + /** @ORM\Column(type="string") */ public $name; } diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/WhereInWalkerTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/WhereInWalkerTest.php index 0c7cd48c2d3..e1e974c8cfd 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/WhereInWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/WhereInWalkerTest.php @@ -1,5 +1,7 @@ setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); - $this->assertEquals( - "SELECT u0_.id AS id_0, g1_.id AS id_1 FROM User u0_ INNER JOIN user_group u2_ ON u0_.id = u2_.user_id INNER JOIN groups g1_ ON g1_.id = u2_.group_id WHERE u0_.id IN (?)", $whereInQuery->getSQL() + self::assertEquals( + 'SELECT t0."id" AS c0, t1."id" AS c1 FROM "User" t0 INNER JOIN "user_group" t2 ON t0."id" = t2."user_id" INNER JOIN "groups" t1 ON t1."id" = t2."group_id" WHERE t0."id" IN (?)', + $whereInQuery->getSQL() ); } @@ -33,8 +36,9 @@ public function testCountQuery_MixedResultsWithName() $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); - $this->assertEquals( - "SELECT a0_.id AS id_0, a0_.name AS name_1, sum(a0_.name) AS sclr_2 FROM Author a0_ WHERE a0_.id IN (?)", $whereInQuery->getSQL() + self::assertEquals( + 'SELECT t0."id" AS c0, t0."name" AS c1, sum(t0."name") AS c2 FROM "Author" t0 WHERE t0."id" IN (?)', + $whereInQuery->getSQL() ); } @@ -47,8 +51,9 @@ public function testWhereInQuery_SingleWhere() $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); - $this->assertEquals( - "SELECT u0_.id AS id_0, g1_.id AS id_1 FROM User u0_ INNER JOIN user_group u2_ ON u0_.id = u2_.user_id INNER JOIN groups g1_ ON g1_.id = u2_.group_id WHERE 1 = 1 AND u0_.id IN (?)", $whereInQuery->getSQL() + self::assertEquals( + 'SELECT t0."id" AS c0, t1."id" AS c1 FROM "User" t0 INNER JOIN "user_group" t2 ON t0."id" = t2."user_id" INNER JOIN "groups" t1 ON t1."id" = t2."group_id" WHERE 1 = 1 AND t0."id" IN (?)', + $whereInQuery->getSQL() ); } @@ -61,8 +66,9 @@ public function testWhereInQuery_MultipleWhereWithAnd() $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); - $this->assertEquals( - "SELECT u0_.id AS id_0, g1_.id AS id_1 FROM User u0_ INNER JOIN user_group u2_ ON u0_.id = u2_.user_id INNER JOIN groups g1_ ON g1_.id = u2_.group_id WHERE 1 = 1 AND 2 = 2 AND u0_.id IN (?)", $whereInQuery->getSQL() + self::assertEquals( + 'SELECT t0."id" AS c0, t1."id" AS c1 FROM "User" t0 INNER JOIN "user_group" t2 ON t0."id" = t2."user_id" INNER JOIN "groups" t1 ON t1."id" = t2."group_id" WHERE 1 = 1 AND 2 = 2 AND t0."id" IN (?)', + $whereInQuery->getSQL() ); } @@ -75,8 +81,9 @@ public function testWhereInQuery_MultipleWhereWithOr() $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); - $this->assertEquals( - "SELECT u0_.id AS id_0, g1_.id AS id_1 FROM User u0_ INNER JOIN user_group u2_ ON u0_.id = u2_.user_id INNER JOIN groups g1_ ON g1_.id = u2_.group_id WHERE (1 = 1 OR 2 = 2) AND u0_.id IN (?)", $whereInQuery->getSQL() + self::assertEquals( + 'SELECT t0."id" AS c0, t1."id" AS c1 FROM "User" t0 INNER JOIN "user_group" t2 ON t0."id" = t2."user_id" INNER JOIN "groups" t1 ON t1."id" = t2."group_id" WHERE (1 = 1 OR 2 = 2) AND t0."id" IN (?)', + $whereInQuery->getSQL() ); } @@ -89,8 +96,9 @@ public function testWhereInQuery_MultipleWhereWithMixed_1() $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); - $this->assertEquals( - "SELECT u0_.id AS id_0, g1_.id AS id_1 FROM User u0_ INNER JOIN user_group u2_ ON u0_.id = u2_.user_id INNER JOIN groups g1_ ON g1_.id = u2_.group_id WHERE (1 = 1 OR 2 = 2) AND 3 = 3 AND u0_.id IN (?)", $whereInQuery->getSQL() + self::assertEquals( + 'SELECT t0."id" AS c0, t1."id" AS c1 FROM "User" t0 INNER JOIN "user_group" t2 ON t0."id" = t2."user_id" INNER JOIN "groups" t1 ON t1."id" = t2."group_id" WHERE (1 = 1 OR 2 = 2) AND 3 = 3 AND t0."id" IN (?)', + $whereInQuery->getSQL() ); } @@ -103,8 +111,9 @@ public function testWhereInQuery_MultipleWhereWithMixed_2() $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); - $this->assertEquals( - "SELECT u0_.id AS id_0, g1_.id AS id_1 FROM User u0_ INNER JOIN user_group u2_ ON u0_.id = u2_.user_id INNER JOIN groups g1_ ON g1_.id = u2_.group_id WHERE (1 = 1 AND 2 = 2 OR 3 = 3) AND u0_.id IN (?)", $whereInQuery->getSQL() + self::assertEquals( + 'SELECT t0."id" AS c0, t1."id" AS c1 FROM "User" t0 INNER JOIN "user_group" t2 ON t0."id" = t2."user_id" INNER JOIN "groups" t1 ON t1."id" = t2."group_id" WHERE (1 = 1 AND 2 = 2 OR 3 = 3) AND t0."id" IN (?)', + $whereInQuery->getSQL() ); } @@ -117,8 +126,9 @@ public function testWhereInQuery_WhereNot() $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); - $this->assertEquals( - "SELECT u0_.id AS id_0, g1_.id AS id_1 FROM User u0_ INNER JOIN user_group u2_ ON u0_.id = u2_.user_id INNER JOIN groups g1_ ON g1_.id = u2_.group_id WHERE (NOT 1 = 2) AND u0_.id IN (?)", $whereInQuery->getSQL() + self::assertEquals( + 'SELECT t0."id" AS c0, t1."id" AS c1 FROM "User" t0 INNER JOIN "user_group" t2 ON t0."id" = t2."user_id" INNER JOIN "groups" t1 ON t1."id" = t2."group_id" WHERE (NOT 1 = 2) AND t0."id" IN (?)', + $whereInQuery->getSQL() ); } @@ -133,8 +143,9 @@ public function testWhereInQueryWithArbitraryJoin_NoWhere() $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); - $this->assertEquals( - "SELECT b0_.id AS id_0, b0_.author_id AS author_id_1, b0_.category_id AS category_id_2 FROM BlogPost b0_ INNER JOIN Category c1_ ON (b0_.category_id = c1_.id) WHERE b0_.id IN (?)", $whereInQuery->getSQL() + self::assertEquals( + 'SELECT t0."id" AS c0, t0."author_id" AS c1, t0."category_id" AS c2 FROM "BlogPost" t0 INNER JOIN "Category" t1 ON (t0."category_id" = t1."id") WHERE t0."id" IN (?)', + $whereInQuery->getSQL() ); } @@ -146,8 +157,9 @@ public function testWhereInQueryWithArbitraryJoin_SingleWhere() $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); - $this->assertEquals( - "SELECT b0_.id AS id_0, b0_.author_id AS author_id_1, b0_.category_id AS category_id_2 FROM BlogPost b0_ INNER JOIN Category c1_ ON (b0_.category_id = c1_.id) WHERE 1 = 1 AND b0_.id IN (?)", $whereInQuery->getSQL() + self::assertEquals( + 'SELECT t0."id" AS c0, t0."author_id" AS c1, t0."category_id" AS c2 FROM "BlogPost" t0 INNER JOIN "Category" t1 ON (t0."category_id" = t1."id") WHERE 1 = 1 AND t0."id" IN (?)', + $whereInQuery->getSQL() ); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/ResolveTargetEntityListenerTest.php b/tests/Doctrine/Tests/ORM/Tools/ResolveTargetEntityListenerTest.php index 910df27f87c..b17207ccd1a 100644 --- a/tests/Doctrine/Tests/ORM/Tools/ResolveTargetEntityListenerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/ResolveTargetEntityListenerTest.php @@ -1,7 +1,10 @@ createAnnotationDriver(); - $this->em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); $this->em->getConfiguration()->setMetadataDriverImpl($annotationDriver); $this->factory = $this->em->getMetadataFactory(); $this->listener = new ResolveTargetEntityListener(); @@ -40,19 +43,21 @@ public function setUp() public function testResolveTargetEntityListenerCanResolveTargetEntity() { $evm = $this->em->getEventManager(); - $this->listener->addResolveTargetEntity(ResolveTargetInterface::class, ResolveTargetEntity::class, []); - $this->listener->addResolveTargetEntity(TargetInterface::class, TargetEntity::class, []); + + $this->listener->addResolveTargetEntity(ResolveTargetInterface::class, ResolveTargetEntity::class); + $this->listener->addResolveTargetEntity(TargetInterface::class, TargetEntity::class); + $evm->addEventSubscriber($this->listener); $cm = $this->factory->getMetadataFor(ResolveTargetEntity::class); - $meta = $cm->associationMappings; + $meta = iterator_to_array($cm->getDeclaredPropertiesIterator()); - $this->assertSame(TargetEntity::class, $meta['manyToMany']['targetEntity']); - $this->assertSame(ResolveTargetEntity::class, $meta['manyToOne']['targetEntity']); - $this->assertSame(ResolveTargetEntity::class, $meta['oneToMany']['targetEntity']); - $this->assertSame(TargetEntity::class, $meta['oneToOne']['targetEntity']); + self::assertSame(TargetEntity::class, $meta['manyToMany']->getTargetEntity()); + self::assertSame(ResolveTargetEntity::class, $meta['manyToOne']->getTargetEntity()); + self::assertSame(ResolveTargetEntity::class, $meta['oneToMany']->getTargetEntity()); + self::assertSame(TargetEntity::class, $meta['oneToOne']->getTargetEntity()); - $this->assertSame($cm, $this->factory->getMetadataFor(ResolveTargetInterface::class)); + self::assertSame($cm, $this->factory->getMetadataFor(ResolveTargetInterface::class)); } /** @@ -62,13 +67,13 @@ public function testResolveTargetEntityListenerCanResolveTargetEntity() */ public function testResolveTargetEntityListenerCanRetrieveTargetEntityByInterfaceName() { - $this->listener->addResolveTargetEntity(ResolveTargetInterface::class, ResolveTargetEntity::class, []); + $this->listener->addResolveTargetEntity(ResolveTargetInterface::class, ResolveTargetEntity::class); $this->em->getEventManager()->addEventSubscriber($this->listener); $cm = $this->factory->getMetadataFor(ResolveTargetInterface::class); - $this->assertSame($this->factory->getMetadataFor(ResolveTargetEntity::class), $cm); + self::assertSame($this->factory->getMetadataFor(ResolveTargetEntity::class), $cm); } /** @@ -77,15 +82,14 @@ public function testResolveTargetEntityListenerCanRetrieveTargetEntityByInterfac public function testAssertTableColumnsAreNotAddedInManyToMany() { $evm = $this->em->getEventManager(); - $this->listener->addResolveTargetEntity(ResolveTargetInterface::class, ResolveTargetEntity::class, []); - $this->listener->addResolveTargetEntity(TargetInterface::class, TargetEntity::class, []); + $this->listener->addResolveTargetEntity(ResolveTargetInterface::class, ResolveTargetEntity::class); + $this->listener->addResolveTargetEntity(TargetInterface::class, TargetEntity::class); $evm->addEventListener(Events::loadClassMetadata, $this->listener); $cm = $this->factory->getMetadataFor(ResolveTargetEntity::class); - $meta = $cm->associationMappings['manyToMany']; + $meta = $cm->getProperty('manyToMany'); - $this->assertSame(TargetEntity::class, $meta['targetEntity']); - $this->assertEquals(['resolvetargetentity_id', 'targetinterface_id'], $meta['joinTableColumns']); + self::assertSame(TargetEntity::class, $meta->getTargetEntity()); } /** @@ -97,12 +101,12 @@ public function testAssertTableColumnsAreNotAddedInManyToMany() public function testDoesResolveTargetEntitiesInDQLAlsoWithInterfaces() { $evm = $this->em->getEventManager(); - $this->listener->addResolveTargetEntity(ResolveTargetInterface::class, ResolveTargetEntity::class, []); + $this->listener->addResolveTargetEntity(ResolveTargetInterface::class, ResolveTargetEntity::class); $evm->addEventSubscriber($this->listener); - $this->assertStringMatchesFormat( - 'SELECT%AFROM ResolveTargetEntity%A', + self::assertStringMatchesFormat( + 'SELECT %A FROM "ResolveTargetEntity" %A', $this ->em ->createQuery('SELECT f FROM Doctrine\Tests\ORM\Tools\ResolveTargetInterface f') @@ -121,35 +125,35 @@ interface TargetInterface extends ResolveTargetInterface } /** - * @Entity + * @ORM\Entity */ class ResolveTargetEntity implements ResolveTargetInterface { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** - * @ManyToMany(targetEntity="Doctrine\Tests\ORM\Tools\TargetInterface") + * @ORM\ManyToMany(targetEntity="Doctrine\Tests\ORM\Tools\TargetInterface") */ private $manyToMany; /** - * @ManyToOne(targetEntity="Doctrine\Tests\ORM\Tools\ResolveTargetInterface", inversedBy="oneToMany") + * @ORM\ManyToOne(targetEntity="Doctrine\Tests\ORM\Tools\ResolveTargetInterface", inversedBy="oneToMany") */ private $manyToOne; /** - * @OneToMany(targetEntity="Doctrine\Tests\ORM\Tools\ResolveTargetInterface", mappedBy="manyToOne") + * @ORM\OneToMany(targetEntity="Doctrine\Tests\ORM\Tools\ResolveTargetInterface", mappedBy="manyToOne") */ private $oneToMany; /** - * @OneToOne(targetEntity="Doctrine\Tests\ORM\Tools\TargetInterface") - * @JoinColumn(name="target_entity_id", referencedColumnName="id") + * @ORM\OneToOne(targetEntity="Doctrine\Tests\ORM\Tools\TargetInterface") + * @ORM\JoinColumn(name="target_entity_id", referencedColumnName="id") */ private $oneToOne; @@ -160,14 +164,14 @@ public function getId() } /** - * @Entity + * @ORM\Entity */ class TargetEntity implements TargetInterface { /** - * @Id - * @Column(type="integer") - * @GeneratedValue(strategy="AUTO") + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") */ private $id; diff --git a/tests/Doctrine/Tests/ORM/Tools/SchemaToolTest.php b/tests/Doctrine/Tests/ORM/Tools/SchemaToolTest.php index 1164ae219a2..63267eed4e8 100644 --- a/tests/Doctrine/Tests/ORM/Tools/SchemaToolTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/SchemaToolTest.php @@ -1,8 +1,13 @@ _getTestEntityManager(); + $em = $this->getTestEntityManager(); $schemaTool = new SchemaTool($em); $classes = [ @@ -38,13 +43,13 @@ public function testAddUniqueIndexForUniqueFieldAnnotation() $schema = $schemaTool->getSchemaFromMetadata($classes); - $this->assertTrue($schema->hasTable('cms_users'), "Table cms_users should exist."); - $this->assertTrue($schema->getTable('cms_users')->columnsAreIndexed(['username']), "username column should be indexed."); + self::assertTrue($schema->hasTable('cms_users'), "Table cms_users should exist."); + self::assertTrue($schema->getTable('cms_users')->columnsAreIndexed(['username']), "username column should be indexed."); } public function testAnnotationOptionsAttribute() { - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); $schemaTool = new SchemaTool($em); $classes = [ @@ -55,8 +60,8 @@ public function testAnnotationOptionsAttribute() $expected = ['foo' => 'bar', 'baz' => ['key' => 'val']]; - $this->assertEquals($expected, $schema->getTable('TestEntityWithAnnotationOptionsAttribute')->getOptions(), "options annotation are passed to the tables options"); - $this->assertEquals($expected, $schema->getTable('TestEntityWithAnnotationOptionsAttribute')->getColumn('test')->getCustomSchemaOptions(), "options annotation are passed to the columns customSchemaOptions"); + self::assertEquals($expected, $schema->getTable('TestEntityWithAnnotationOptionsAttribute')->getOptions(), "options annotation are passed to the tables options"); + self::assertEquals($expected, $schema->getTable('TestEntityWithAnnotationOptionsAttribute')->getColumn('test')->getCustomSchemaOptions(), "options annotation are passed to the columns customSchemaOptions"); } /** @@ -66,21 +71,24 @@ public function testPassColumnDefinitionToJoinColumn() { $customColumnDef = "MEDIUMINT(6) UNSIGNED NOT NULL"; - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); $schemaTool = new SchemaTool($em); - $avatar = $em->getClassMetadata(ForumAvatar::class); - $avatar->fieldMappings['id']['columnDefinition'] = $customColumnDef; - $user = $em->getClassMetadata(ForumUser::class); + $avatar = $em->getClassMetadata(ForumAvatar::class); + $idProperty = $avatar->getProperty('id'); + + $idProperty->setColumnDefinition($customColumnDef); + $user = $em->getClassMetadata(ForumUser::class); $classes = [$avatar, $user]; + $schema = $schemaTool->getSchemaFromMetadata($classes); - $schema = $schemaTool->getSchemaFromMetadata($classes); + self::assertTrue($schema->hasTable('forum_users')); - $this->assertTrue($schema->hasTable('forum_users')); $table = $schema->getTable("forum_users"); - $this->assertTrue($table->hasColumn('avatar_id')); - $this->assertEquals($customColumnDef, $table->getColumn('avatar_id')->getColumnDefinition()); + + self::assertTrue($table->hasColumn('avatar_id')); + self::assertEquals($customColumnDef, $table->getColumn('avatar_id')->getColumnDefinition()); } /** @@ -90,7 +98,7 @@ public function testPostGenerateEvents() { $listener = new GenerateSchemaEventListener(); - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); $em->getEventManager()->addEventListener( [ToolEvents::postGenerateSchemaTable, ToolEvents::postGenerateSchema], $listener ); @@ -108,13 +116,13 @@ public function testPostGenerateEvents() $schema = $schemaTool->getSchemaFromMetadata($classes); - $this->assertEquals(count($classes), $listener->tableCalls); - $this->assertTrue($listener->schemaCalled); + self::assertEquals(count($classes), $listener->tableCalls); + self::assertTrue($listener->schemaCalled); } public function testNullDefaultNotAddedToCustomSchemaOptions() { - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); $schemaTool = new SchemaTool($em); $customSchemaOptions = $schemaTool->getSchemaFromMetadata([$em->getClassMetadata(NullDefaultColumn::class)]) @@ -122,7 +130,7 @@ public function testNullDefaultNotAddedToCustomSchemaOptions() ->getColumn('nullDefault') ->getCustomSchemaOptions(); - $this->assertSame([], $customSchemaOptions); + self::assertSame([], $customSchemaOptions); } /** @@ -130,7 +138,7 @@ public function testNullDefaultNotAddedToCustomSchemaOptions() */ public function testSchemaHasProperIndexesFromUniqueConstraintAnnotation() { - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); $schemaTool = new SchemaTool($em); $classes = [ $em->getClassMetadata(UniqueConstraintAnnotationModel::class), @@ -138,17 +146,18 @@ public function testSchemaHasProperIndexesFromUniqueConstraintAnnotation() $schema = $schemaTool->getSchemaFromMetadata($classes); - $this->assertTrue($schema->hasTable('unique_constraint_annotation_table')); + self::assertTrue($schema->hasTable('unique_constraint_annotation_table')); $table = $schema->getTable('unique_constraint_annotation_table'); - $this->assertEquals(2, count($table->getIndexes())); - $this->assertTrue($table->hasIndex('primary')); - $this->assertTrue($table->hasIndex('uniq_hash')); + self::assertEquals(1, count($table->getIndexes())); + self::assertEquals(1, count($table->getUniqueConstraints())); + self::assertTrue($table->hasIndex('primary')); + self::assertTrue($table->hasUniqueConstraint('uniq_hash')); } public function testRemoveUniqueIndexOverruledByPrimaryKey() { - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); $schemaTool = new SchemaTool($em); $classes = [ $em->getClassMetadata(FirstEntity::class), @@ -157,46 +166,52 @@ public function testRemoveUniqueIndexOverruledByPrimaryKey() $schema = $schemaTool->getSchemaFromMetadata($classes); - $this->assertTrue($schema->hasTable('first_entity'), "Table first_entity should exist."); + self::assertTrue($schema->hasTable('first_entity'), "Table first_entity should exist."); $indexes = $schema->getTable('first_entity')->getIndexes(); - $this->assertCount(1, $indexes, "there should be only one index"); - $this->assertTrue(current($indexes)->isPrimary(), "index should be primary"); + self::assertCount(1, $indexes, "there should be only one index"); + self::assertTrue(current($indexes)->isPrimary(), "index should be primary"); } public function testSetDiscriminatorColumnWithoutLength() : void { - $em = $this->_getTestEntityManager(); + $em = $this->getTestEntityManager(); $schemaTool = new SchemaTool($em); $metadata = $em->getClassMetadata(FirstEntity::class); - $metadata->setInheritanceType(ClassMetadata::INHERITANCE_TYPE_SINGLE_TABLE); - $metadata->setDiscriminatorColumn(['name' => 'discriminator', 'type' => 'string']); + $metadata->setInheritanceType(InheritanceType::SINGLE_TABLE); + + $discriminatorColumn = new DiscriminatorColumnMetadata(); + + $discriminatorColumn->setColumnName('discriminator'); + $discriminatorColumn->setType(Type::getType('string')); + + $metadata->setDiscriminatorColumn($discriminatorColumn); $schema = $schemaTool->getSchemaFromMetadata([$metadata]); - $this->assertTrue($schema->hasTable('first_entity')); + self::assertTrue($schema->hasTable('first_entity')); $table = $schema->getTable('first_entity'); - $this->assertTrue($table->hasColumn('discriminator')); + self::assertTrue($table->hasColumn('discriminator')); $column = $table->getColumn('discriminator'); - $this->assertEquals(255, $column->getLength()); + self::assertEquals(255, $column->getLength()); } } /** - * @Entity - * @Table(options={"foo": "bar", "baz": {"key": "val"}}) + * @ORM\Entity + * @ORM\Table(options={"foo": "bar", "baz": {"key": "val"}}) */ class TestEntityWithAnnotationOptionsAttribute { - /** @Id @Column */ + /** @ORM\Id @ORM\Column */ private $id; /** - * @Column(type="string", options={"foo": "bar", "baz": {"key": "val"}}) + * @ORM\Column(type="string", options={"foo": "bar", "baz": {"key": "val"}}) */ private $test; } @@ -218,60 +233,63 @@ public function postGenerateSchema(GenerateSchemaEventArgs $eventArgs) } /** - * @Entity - * @Table(name="unique_constraint_annotation_table", uniqueConstraints={ - * @UniqueConstraint(name="uniq_hash", columns={"hash"}) - * }) + * @ORM\Entity + * @ORM\Table( + * name="unique_constraint_annotation_table", + * uniqueConstraints={ + * @ORM\UniqueConstraint(name="uniq_hash", columns={"hash"}) + * } + * ) */ class UniqueConstraintAnnotationModel { - /** @Id @Column */ + /** @ORM\Id @ORM\Column */ private $id; /** - * @Column(name="hash", type="string", length=8, nullable=false, unique=true) + * @ORM\Column(name="hash", type="string", length=8, nullable=false, unique=true) */ private $hash; } /** - * @Entity - * @Table(name="first_entity") + * @ORM\Entity + * @ORM\Table(name="first_entity") */ class FirstEntity { /** - * @Id - * @Column(name="id") + * @ORM\Id + * @ORM\Column(name="id") */ public $id; /** - * @OneToOne(targetEntity="SecondEntity") - * @JoinColumn(name="id", referencedColumnName="fist_entity_id") + * @ORM\OneToOne(targetEntity="SecondEntity") + * @ORM\JoinColumn(name="id", referencedColumnName="fist_entity_id") */ public $secondEntity; /** - * @Column(name="name") + * @ORM\Column(name="name") */ public $name; } /** - * @Entity - * @Table(name="second_entity") + * @ORM\Entity + * @ORM\Table(name="second_entity") */ class SecondEntity { /** - * @Id - * @Column(name="fist_entity_id") + * @ORM\Id + * @ORM\Column(name="fist_entity_id") */ public $fist_entity_id; /** - * @Column(name="name") + * @ORM\Column(name="name") */ public $name; } diff --git a/tests/Doctrine/Tests/ORM/Tools/SchemaValidatorTest.php b/tests/Doctrine/Tests/ORM/Tools/SchemaValidatorTest.php index 682ee896d1a..3a6c57c2376 100644 --- a/tests/Doctrine/Tests/ORM/Tools/SchemaValidatorTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/SchemaValidatorTest.php @@ -1,15 +1,18 @@ em = $this->_getTestEntityManager(); + $this->em = $this->getTestEntityManager(); $this->validator = new SchemaValidator($this->em); } @@ -58,10 +61,13 @@ public function testInvalidManyToManyJoinColumnSchema() $ce = $this->validator->validateClass($class1); - $this->assertEquals( + $message1 = "The inverse join columns of the many-to-many table '%s' have to contain to ALL identifier columns of the target entity '%s', however '%s' are missing."; + $message2 = "The join columns of the many-to-many table '%s' have to contain to ALL identifier columns of the source entity '%s', however '%s' are missing."; + + self::assertEquals( [ - "The inverse join columns of the many-to-many table 'Entity1Entity2' have to contain to ALL identifier columns of the target entity 'Doctrine\Tests\ORM\Tools\InvalidEntity2', however 'key4' are missing.", - "The join columns of the many-to-many table 'Entity1Entity2' have to contain to ALL identifier columns of the source entity 'Doctrine\Tests\ORM\Tools\InvalidEntity1', however 'key2' are missing." + sprintf($message1, 'Entity1Entity2', InvalidEntity2::class, 'key4'), + sprintf($message2, 'Entity1Entity2', InvalidEntity1::class, 'key2'), ], $ce ); @@ -77,10 +83,13 @@ public function testInvalidToOneJoinColumnSchema() $ce = $this->validator->validateClass($class2); - $this->assertEquals( + $message1 = "The referenced column name '%s' has to be a primary key column on the target entity class '%s'."; + $message2 = "The join columns of the association '%s' have to match to ALL identifier columns of the target entity '%s', however '%s' are missing."; + + self::assertEquals( [ - "The referenced column name 'id' has to be a primary key column on the target entity class 'Doctrine\Tests\ORM\Tools\InvalidEntity1'.", - "The join columns of the association 'assoc' have to match to ALL identifier columns of the target entity 'Doctrine\Tests\ORM\Tools\InvalidEntity1', however 'key1, key2' are missing." + sprintf($message1, 'id', InvalidEntity1::class), + sprintf($message2, 'assoc', InvalidEntity1::class, "key1', 'key2"), ], $ce ); @@ -96,7 +105,7 @@ public function testValidOneToOneAsIdentifierSchema() $ce = $this->validator->validateClass($class1); - $this->assertEquals([], $ce); + self::assertEquals([], $ce); } /** @@ -107,11 +116,16 @@ public function testInvalidTripleAssociationAsKeyMapping() $classThree = $this->em->getClassMetadata(DDC1649Three::class); $ce = $this->validator->validateClass($classThree); - $this->assertEquals( + $message1 = "Cannot map association %s#%s as identifier, because the target entity '%s' also maps an association as identifier."; + $message2 = "The referenced column name '%s' has to be a primary key column on the target entity class '%s'."; + + self::assertEquals( [ - "Cannot map association 'Doctrine\Tests\ORM\Tools\DDC1649Three#two as identifier, because the target entity 'Doctrine\Tests\ORM\Tools\DDC1649Two' also maps an association as identifier.", - "The referenced column name 'id' has to be a primary key column on the target entity class 'Doctrine\Tests\ORM\Tools\DDC1649Two'." - ], $ce); + sprintf($message1, DDC1649Three::class, 'two', DDC1649Two::class), + sprintf($message2, 'id', DDC1649Two::class), + ], + $ce + ); } /** @@ -122,11 +136,12 @@ public function testInvalidBiDirectionalRelationMappingMissingInversedByAttribut $class = $this->em->getClassMetadata(DDC3274One::class); $ce = $this->validator->validateClass($class); - $this->assertEquals( + $message = "The property %s#%s is on the inverse side of a bi-directional relationship, but the " + . "specified mappedBy association on the target-entity %s#%s does not contain the required 'inversedBy=\"%s\"' attribute."; + + self::assertEquals( [ - "The field Doctrine\Tests\ORM\Tools\DDC3274One#two is on the inverse side of a bi-directional " . - "relationship, but the specified mappedBy association on the target-entity " . - "Doctrine\Tests\ORM\Tools\DDC3274Two#one does not contain the required 'inversedBy=\"two\"' attribute." + sprintf($message, DDC3274One::class, 'two', DDC3274Two::class, 'one', 'two') ], $ce ); @@ -140,10 +155,11 @@ public function testInvalidOrderByInvalidField() $class = $this->em->getClassMetadata(DDC3322One::class); $ce = $this->validator->validateClass($class); - $this->assertEquals( + $message = "The association %s#%s is ordered by a property '%s' that is non-existing field on the target entity '%s'."; + + self::assertEquals( [ - "The association Doctrine\Tests\ORM\Tools\DDC3322One#invalidAssoc is ordered by a foreign field " . - "invalidField that is not a field on the target entity Doctrine\Tests\ORM\Tools\DDC3322ValidEntity1." + sprintf($message, DDC3322One::class, 'invalidAssoc', 'invalidField', DDC3322ValidEntity1::class) ], $ce ); @@ -157,10 +173,11 @@ public function testInvalidOrderByCollectionValuedAssociation() $class = $this->em->getClassMetadata(DDC3322Two::class); $ce = $this->validator->validateClass($class); - $this->assertEquals( + $message = "The association %s#%s is ordered by a property '%s' on '%s' that is a collection-valued association."; + + self::assertEquals( [ - "The association Doctrine\Tests\ORM\Tools\DDC3322Two#invalidAssoc is ordered by a field oneToMany " . - "on Doctrine\Tests\ORM\Tools\DDC3322ValidEntity1 that is a collection-valued association." + sprintf($message, DDC3322Two::class, 'invalidAssoc', 'oneToMany', DDC3322ValidEntity1::class) ], $ce ); @@ -174,10 +191,11 @@ public function testInvalidOrderByAssociationInverseSide() $class = $this->em->getClassMetadata(DDC3322Three::class); $ce = $this->validator->validateClass($class); - $this->assertEquals( + $message = "The association %s#%s is ordered by a property '%s' on '%s' that is the inverse side of an association."; + + self::assertEquals( [ - "The association Doctrine\Tests\ORM\Tools\DDC3322Three#invalidAssoc is ordered by a field oneToOneInverse " . - "on Doctrine\Tests\ORM\Tools\DDC3322ValidEntity1 that is the inverse side of an association." + sprintf($message, DDC3322Three::class, 'invalidAssoc', 'oneToOneInverse', DDC3322ValidEntity1::class) ], $ce ); @@ -185,317 +203,317 @@ public function testInvalidOrderByAssociationInverseSide() } /** - * @Entity + * @ORM\Entity */ class InvalidEntity1 { /** - * @Id @Column + * @ORM\Id @ORM\Column */ protected $key1; /** - * @Id @Column + * @ORM\Id @ORM\Column */ protected $key2; /** - * @ManyToMany (targetEntity="InvalidEntity2") - * @JoinTable (name="Entity1Entity2", - * joinColumns={@JoinColumn(name="key1", referencedColumnName="key1")}, - * inverseJoinColumns={@JoinColumn(name="key3", referencedColumnName="key3")} + * @ORM\ManyToMany (targetEntity="InvalidEntity2") + * @ORM\JoinTable (name="Entity1Entity2", + * joinColumns={@ORM\JoinColumn(name="key1", referencedColumnName="key1")}, + * inverseJoinColumns={@ORM\JoinColumn(name="key3", referencedColumnName="key3")} * ) */ protected $entity2; } /** - * @Entity + * @ORM\Entity */ class InvalidEntity2 { /** - * @Id @Column + * @ORM\Id @ORM\Column */ protected $key3; /** - * @Id @Column + * @ORM\Id @ORM\Column */ protected $key4; /** - * @ManyToOne(targetEntity="InvalidEntity1") + * @ORM\ManyToOne(targetEntity="InvalidEntity1") */ protected $assoc; } /** - * @Entity(repositoryClass="Entity\Repository\Agent") - * @Table(name="agent") + * @ORM\Entity(repositoryClass="Entity\Repository\Agent") + * @ORM\Table(name="agent") */ class DDC1587ValidEntity1 { /** * @var int * - * @Id @GeneratedValue - * @Column(name="pk", type="integer") + * @ORM\Id @ORM\GeneratedValue + * @ORM\Column(name="pk", type="integer") */ private $pk; /** * @var string * - * @Column(name="name", type="string", length=32) + * @ORM\Column(name="name", type="string", length=32) */ private $name; /** * @var Identifier * - * @OneToOne(targetEntity="DDC1587ValidEntity2", cascade={"all"}, mappedBy="agent") - * @JoinColumn(name="pk", referencedColumnName="pk_agent") + * @ORM\OneToOne(targetEntity="DDC1587ValidEntity2", cascade={"all"}, mappedBy="agent") + * @ORM\JoinColumn(name="pk", referencedColumnName="pk_agent") */ private $identifier; } /** - * @Entity - * @Table + * @ORM\Entity + * @ORM\Table */ class DDC1587ValidEntity2 { /** * @var DDC1587ValidEntity1 * - * @Id - * @OneToOne(targetEntity="DDC1587ValidEntity1", inversedBy="identifier") - * @JoinColumn(name="pk_agent", referencedColumnName="pk", nullable=false) + * @ORM\Id + * @ORM\OneToOne(targetEntity="DDC1587ValidEntity1", inversedBy="identifier") + * @ORM\JoinColumn(name="pk_agent", referencedColumnName="pk", nullable=false) */ private $agent; /** * @var string * - * @Column(name="num", type="string", length=16, nullable=true) + * @ORM\Column(name="num", type="string", length=16, nullable=true) */ private $num; } /** - * @Entity + * @ORM\Entity */ class DDC1649One { /** - * @Id @Column @GeneratedValue + * @ORM\Id @ORM\Column @ORM\GeneratedValue */ public $id; } /** - * @Entity + * @ORM\Entity */ class DDC1649Two { - /** @Id @ManyToOne(targetEntity="DDC1649One")@JoinColumn(name="id", referencedColumnName="id") */ + /** @ORM\Id @ORM\ManyToOne(targetEntity="DDC1649One")@ORM\JoinColumn(name="id", referencedColumnName="id") */ public $one; } /** - * @Entity + * @ORM\Entity */ class DDC1649Three { - /** @Id @ManyToOne(targetEntity="DDC1649Two") @JoinColumn(name="id", + /** @ORM\Id @ORM\ManyToOne(targetEntity="DDC1649Two") @ORM\JoinColumn(name="id", * referencedColumnName="id") */ private $two; } /** - * @Entity + * @ORM\Entity */ class DDC3274One { /** - * @Id @Column @GeneratedValue + * @ORM\Id @ORM\Column @ORM\GeneratedValue */ private $id; /** - * @OneToMany(targetEntity="DDC3274Two", mappedBy="one") + * @ORM\OneToMany(targetEntity="DDC3274Two", mappedBy="one") */ private $two; } /** - * @Entity + * @ORM\Entity */ class DDC3274Two { /** - * @Id - * @ManyToOne(targetEntity="DDC3274One") + * @ORM\Id + * @ORM\ManyToOne(targetEntity="DDC3274One") */ private $one; } /** - * @Entity + * @ORM\Entity */ class DDC3322ValidEntity1 { /** - * @Id @Column @GeneratedValue + * @ORM\Id @ORM\Column @ORM\GeneratedValue */ private $id; /** - * @ManyToOne(targetEntity="DDC3322One", inversedBy="validAssoc") + * @ORM\ManyToOne(targetEntity="DDC3322One", inversedBy="validAssoc") */ private $oneValid; /** - * @ManyToOne(targetEntity="DDC3322One", inversedBy="invalidAssoc") + * @ORM\ManyToOne(targetEntity="DDC3322One", inversedBy="invalidAssoc") */ private $oneInvalid; /** - * @ManyToOne(targetEntity="DDC3322Two", inversedBy="validAssoc") + * @ORM\ManyToOne(targetEntity="DDC3322Two", inversedBy="validAssoc") */ private $twoValid; /** - * @ManyToOne(targetEntity="DDC3322Two", inversedBy="invalidAssoc") + * @ORM\ManyToOne(targetEntity="DDC3322Two", inversedBy="invalidAssoc") */ private $twoInvalid; /** - * @ManyToOne(targetEntity="DDC3322Three", inversedBy="validAssoc") + * @ORM\ManyToOne(targetEntity="DDC3322Three", inversedBy="validAssoc") */ private $threeValid; /** - * @ManyToOne(targetEntity="DDC3322Three", inversedBy="invalidAssoc") + * @ORM\ManyToOne(targetEntity="DDC3322Three", inversedBy="invalidAssoc") */ private $threeInvalid; /** - * @OneToMany(targetEntity="DDC3322ValidEntity2", mappedBy="manyToOne") + * @ORM\OneToMany(targetEntity="DDC3322ValidEntity2", mappedBy="manyToOne") */ private $oneToMany; /** - * @ManyToOne(targetEntity="DDC3322ValidEntity2", inversedBy="oneToMany") + * @ORM\ManyToOne(targetEntity="DDC3322ValidEntity2", inversedBy="oneToMany") */ private $manyToOne; /** - * @OneToOne(targetEntity="DDC3322ValidEntity2", mappedBy="oneToOneOwning") + * @ORM\OneToOne(targetEntity="DDC3322ValidEntity2", mappedBy="oneToOneOwning") */ private $oneToOneInverse; /** - * @OneToOne(targetEntity="DDC3322ValidEntity2", inversedBy="oneToOneInverse") + * @ORM\OneToOne(targetEntity="DDC3322ValidEntity2", inversedBy="oneToOneInverse") */ private $oneToOneOwning; } /** - * @Entity + * @ORM\Entity */ class DDC3322ValidEntity2 { /** - * @Id @Column @GeneratedValue + * @ORM\Id @ORM\Column @ORM\GeneratedValue */ private $id; /** - * @ManyToOne(targetEntity="DDC3322ValidEntity1", inversedBy="oneToMany") + * @ORM\ManyToOne(targetEntity="DDC3322ValidEntity1", inversedBy="oneToMany") */ private $manyToOne; /** - * @OneToMany(targetEntity="DDC3322ValidEntity1", mappedBy="manyToOne") + * @ORM\OneToMany(targetEntity="DDC3322ValidEntity1", mappedBy="manyToOne") */ private $oneToMany; /** - * @OneToOne(targetEntity="DDC3322ValidEntity1", inversedBy="oneToOneInverse") + * @ORM\OneToOne(targetEntity="DDC3322ValidEntity1", inversedBy="oneToOneInverse") */ private $oneToOneOwning; /** - * @OneToOne(targetEntity="DDC3322ValidEntity1", mappedBy="oneToOneOwning") + * @ORM\OneToOne(targetEntity="DDC3322ValidEntity1", mappedBy="oneToOneOwning") */ private $oneToOneInverse; } /** - * @Entity + * @ORM\Entity */ class DDC3322One { /** - * @Id @Column @GeneratedValue + * @ORM\Id @ORM\Column @ORM\GeneratedValue */ private $id; /** - * @OneToMany(targetEntity="DDC3322ValidEntity1", mappedBy="oneValid") - * @OrderBy({"id" = "ASC"}) + * @ORM\OneToMany(targetEntity="DDC3322ValidEntity1", mappedBy="oneValid") + * @ORM\OrderBy({"id" = "ASC"}) */ private $validAssoc; /** - * @OneToMany(targetEntity="DDC3322ValidEntity1", mappedBy="oneInvalid") - * @OrderBy({"invalidField" = "ASC"}) + * @ORM\OneToMany(targetEntity="DDC3322ValidEntity1", mappedBy="oneInvalid") + * @ORM\OrderBy({"invalidField" = "ASC"}) */ private $invalidAssoc; } /** - * @Entity + * @ORM\Entity */ class DDC3322Two { /** - * @Id @Column @GeneratedValue + * @ORM\Id @ORM\Column @ORM\GeneratedValue */ private $id; /** - * @OneToMany(targetEntity="DDC3322ValidEntity1", mappedBy="twoValid") - * @OrderBy({"manyToOne" = "ASC"}) + * @ORM\OneToMany(targetEntity="DDC3322ValidEntity1", mappedBy="twoValid") + * @ORM\OrderBy({"manyToOne" = "ASC"}) */ private $validAssoc; /** - * @OneToMany(targetEntity="DDC3322ValidEntity1", mappedBy="twoInvalid") - * @OrderBy({"oneToMany" = "ASC"}) + * @ORM\OneToMany(targetEntity="DDC3322ValidEntity1", mappedBy="twoInvalid") + * @ORM\OrderBy({"oneToMany" = "ASC"}) */ private $invalidAssoc; } /** - * @Entity + * @ORM\Entity */ class DDC3322Three { /** - * @Id @Column @GeneratedValue + * @ORM\Id @ORM\Column @ORM\GeneratedValue */ private $id; /** - * @OneToMany(targetEntity="DDC3322ValidEntity1", mappedBy="threeValid") - * @OrderBy({"oneToOneOwning" = "ASC"}) + * @ORM\OneToMany(targetEntity="DDC3322ValidEntity1", mappedBy="threeValid") + * @ORM\OrderBy({"oneToOneOwning" = "ASC"}) */ private $validAssoc; /** - * @OneToMany(targetEntity="DDC3322ValidEntity1", mappedBy="threeInvalid") - * @OrderBy({"oneToOneInverse" = "ASC"}) + * @ORM\OneToMany(targetEntity="DDC3322ValidEntity1", mappedBy="threeInvalid") + * @ORM\OrderBy({"oneToOneInverse" = "ASC"}) */ private $invalidAssoc; } diff --git a/tests/Doctrine/Tests/ORM/Tools/SetupTest.php b/tests/Doctrine/Tests/ORM/Tools/SetupTest.php index c44cb6bcf56..25e32059a1a 100644 --- a/tests/Doctrine/Tests/ORM/Tools/SetupTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/SetupTest.php @@ -1,5 +1,7 @@ markTestSkipped("Test only runs in a dev-installation from Github"); - } - $this->originalAutoloaderCount = count(spl_autoload_functions()); $this->originalIncludePath = get_include_path(); } @@ -34,11 +30,10 @@ public function tearDown() } set_include_path($this->originalIncludePath); - $loaders = spl_autoload_functions(); - $numberOfLoaders = count($loaders); - for ($i = 0; $i < $numberOfLoaders; $i++) { - if ($i > $this->originalAutoloaderCount+1) { - spl_autoload_unregister($loaders[$i]); + + foreach (spl_autoload_functions() as $i => $loader) { + if ($i > $this->originalAutoloaderCount + 1) { + spl_autoload_unregister($loader); } } } @@ -47,33 +42,25 @@ public function testDirectoryAutoload() { Setup::registerAutoloadDirectory(__DIR__ . "/../../../../../vendor/doctrine/common/lib"); - $this->assertEquals($this->originalAutoloaderCount + 2, count(spl_autoload_functions())); + self::assertEquals($this->originalAutoloaderCount + 2, count(spl_autoload_functions())); } public function testAnnotationConfiguration() { $config = Setup::createAnnotationMetadataConfiguration([], true); - $this->assertInstanceOf(Configuration::class, $config); - $this->assertEquals(sys_get_temp_dir(), $config->getProxyDir()); - $this->assertEquals('DoctrineProxies', $config->getProxyNamespace()); - $this->assertInstanceOf(AnnotationDriver::class, $config->getMetadataDriverImpl()); + self::assertInstanceOf(Configuration::class, $config); + self::assertEquals(sys_get_temp_dir(), $config->getProxyDir()); + self::assertEquals('DoctrineProxies', $config->getProxyNamespace()); + self::assertInstanceOf(AnnotationDriver::class, $config->getMetadataDriverImpl()); } public function testXMLConfiguration() { $config = Setup::createXMLMetadataConfiguration([], true); - $this->assertInstanceOf(Configuration::class, $config); - $this->assertInstanceOf(XmlDriver::class, $config->getMetadataDriverImpl()); - } - - public function testYAMLConfiguration() - { - $config = Setup::createYAMLMetadataConfiguration([], true); - - $this->assertInstanceOf(Configuration::class, $config); - $this->assertInstanceOf(YamlDriver::class, $config->getMetadataDriverImpl()); + self::assertInstanceOf(Configuration::class, $config); + self::assertInstanceOf(XmlDriver::class, $config->getMetadataDriverImpl()); } /** @@ -82,7 +69,7 @@ public function testYAMLConfiguration() public function testConfigureProxyDir() { $config = Setup::createAnnotationMetadataConfiguration([], true, "/foo"); - $this->assertEquals('/foo', $config->getProxyDir()); + self::assertEquals('/foo', $config->getProxyDir()); } /** @@ -93,9 +80,9 @@ public function testConfigureCache() $cache = new ArrayCache(); $config = Setup::createAnnotationMetadataConfiguration([], true, null, $cache); - $this->assertSame($cache, $config->getResultCacheImpl()); - $this->assertSame($cache, $config->getMetadataCacheImpl()); - $this->assertSame($cache, $config->getQueryCacheImpl()); + self::assertSame($cache, $config->getResultCacheImpl()); + self::assertSame($cache, $config->getMetadataCacheImpl()); + self::assertSame($cache, $config->getQueryCacheImpl()); } /** @@ -106,8 +93,8 @@ public function testConfigureCacheCustomInstance() $cache = $this->createMock(Cache::class); $config = Setup::createConfiguration([], true, $cache); - $this->assertSame($cache, $config->getResultCacheImpl()); - $this->assertSame($cache, $config->getMetadataCacheImpl()); - $this->assertSame($cache, $config->getQueryCacheImpl()); + self::assertSame($cache, $config->getResultCacheImpl()); + self::assertSame($cache, $config->getMetadataCacheImpl()); + self::assertSame($cache, $config->getQueryCacheImpl()); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/doctrine1schema/schema.yml b/tests/Doctrine/Tests/ORM/Tools/doctrine1schema/schema.yml deleted file mode 100644 index efa24c79169..00000000000 --- a/tests/Doctrine/Tests/ORM/Tools/doctrine1schema/schema.yml +++ /dev/null @@ -1,28 +0,0 @@ -User: - tableName: users - columns: - username: - type: string(255) - length: 100 - notnull: true - unique: true - password: - type: string(255) - clob: clob - test_alias as theAlias: - type: string(255) - indexes: - username: - fields: [username] - type: unique - -Profile: - columns: - first_name: string(255) - last_name: string(255) - user_id: integer - relations: - User: - onDelete: CASCADE - foreignType: one - type: one \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/UnitOfWorkTest.php b/tests/Doctrine/Tests/ORM/UnitOfWorkTest.php index ff025df4f4b..7021cff5cce 100644 --- a/tests/Doctrine/Tests/ORM/UnitOfWorkTest.php +++ b/tests/Doctrine/Tests/ORM/UnitOfWorkTest.php @@ -1,5 +1,7 @@ _connectionMock = new ConnectionMock([], new DriverMock()); - $this->eventManager = $this->getMockBuilder(EventManager::class)->getMock(); - $this->_emMock = EntityManagerMock::create($this->_connectionMock, null, $this->eventManager); - // SUT - $this->_unitOfWork = new UnitOfWorkMock($this->_emMock); - $this->_emMock->setUnitOfWork($this->_unitOfWork); + + $this->metadataBuildingContext = new ClassMetadataBuildingContext( + $this->createMock(ClassMetadataFactory::class), + new RuntimeReflectionService() + ); + $this->eventManager = $this->getMockBuilder(EventManager::class)->getMock(); + $this->connectionMock = new ConnectionMock([], new DriverMock(), null, $this->eventManager); + $this->emMock = EntityManagerMock::create($this->connectionMock, null, $this->eventManager); + $this->unitOfWork = new UnitOfWorkMock($this->emMock); + + $this->emMock->setUnitOfWork($this->unitOfWork); } public function testRegisterRemovedOnNewEntityIsIgnored() { $user = new ForumUser(); $user->username = 'romanb'; - $this->assertFalse($this->_unitOfWork->isScheduledForDelete($user)); - $this->_unitOfWork->scheduleForDelete($user); - $this->assertFalse($this->_unitOfWork->isScheduledForDelete($user)); + self::assertFalse($this->unitOfWork->isScheduledForDelete($user)); + $this->unitOfWork->scheduleForDelete($user); + self::assertFalse($this->unitOfWork->isScheduledForDelete($user)); } @@ -82,36 +99,36 @@ public function testRegisterRemovedOnNewEntityIsIgnored() public function testSavingSingleEntityWithIdentityColumnForcesInsert() { // Setup fake persister and id generator for identity generation - $userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(ForumUser::class)); - $this->_unitOfWork->setEntityPersister(ForumUser::class, $userPersister); - $userPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY); + $userPersister = new EntityPersisterMock($this->emMock, $this->emMock->getClassMetadata(ForumUser::class)); + $this->unitOfWork->setEntityPersister(ForumUser::class, $userPersister); + $userPersister->setMockIdGeneratorType(GeneratorType::IDENTITY); // Test $user = new ForumUser(); $user->username = 'romanb'; - $this->_unitOfWork->persist($user); + $this->unitOfWork->persist($user); // Check - $this->assertEquals(0, count($userPersister->getInserts())); - $this->assertEquals(0, count($userPersister->getUpdates())); - $this->assertEquals(0, count($userPersister->getDeletes())); - $this->assertFalse($this->_unitOfWork->isInIdentityMap($user)); + self::assertEquals(0, count($userPersister->getInserts())); + self::assertEquals(0, count($userPersister->getUpdates())); + self::assertEquals(0, count($userPersister->getDeletes())); + self::assertFalse($this->unitOfWork->isInIdentityMap($user)); // should no longer be scheduled for insert - $this->assertTrue($this->_unitOfWork->isScheduledForInsert($user)); + self::assertTrue($this->unitOfWork->isScheduledForInsert($user)); // Now lets check whether a subsequent commit() does anything $userPersister->reset(); // Test - $this->_unitOfWork->commit(); + $this->unitOfWork->commit(); // Check. - $this->assertEquals(1, count($userPersister->getInserts())); - $this->assertEquals(0, count($userPersister->getUpdates())); - $this->assertEquals(0, count($userPersister->getDeletes())); + self::assertEquals(1, count($userPersister->getInserts())); + self::assertEquals(0, count($userPersister->getUpdates())); + self::assertEquals(0, count($userPersister->getDeletes())); // should have an id - $this->assertTrue(is_numeric($user->id)); + self::assertTrue(is_numeric($user->id)); } /** @@ -122,111 +139,117 @@ public function testCascadedIdentityColumnInsert() { // Setup fake persister and id generator for identity generation //ForumUser - $userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(ForumUser::class)); - $this->_unitOfWork->setEntityPersister(ForumUser::class, $userPersister); - $userPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY); + $userPersister = new EntityPersisterMock($this->emMock, $this->emMock->getClassMetadata(ForumUser::class)); + $this->unitOfWork->setEntityPersister(ForumUser::class, $userPersister); + $userPersister->setMockIdGeneratorType(GeneratorType::IDENTITY); // ForumAvatar - $avatarPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(ForumAvatar::class)); - $this->_unitOfWork->setEntityPersister(ForumAvatar::class, $avatarPersister); - $avatarPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY); + $avatarPersister = new EntityPersisterMock($this->emMock, $this->emMock->getClassMetadata(ForumAvatar::class)); + $this->unitOfWork->setEntityPersister(ForumAvatar::class, $avatarPersister); + $avatarPersister->setMockIdGeneratorType(GeneratorType::IDENTITY); // Test $user = new ForumUser(); $user->username = 'romanb'; $avatar = new ForumAvatar(); $user->avatar = $avatar; - $this->_unitOfWork->persist($user); // save cascaded to avatar + $this->unitOfWork->persist($user); // save cascaded to avatar - $this->_unitOfWork->commit(); + $this->unitOfWork->commit(); - $this->assertTrue(is_numeric($user->id)); - $this->assertTrue(is_numeric($avatar->id)); + self::assertTrue(is_numeric($user->id)); + self::assertTrue(is_numeric($avatar->id)); - $this->assertEquals(1, count($userPersister->getInserts())); - $this->assertEquals(0, count($userPersister->getUpdates())); - $this->assertEquals(0, count($userPersister->getDeletes())); + self::assertEquals(1, count($userPersister->getInserts())); + self::assertEquals(0, count($userPersister->getUpdates())); + self::assertEquals(0, count($userPersister->getDeletes())); - $this->assertEquals(1, count($avatarPersister->getInserts())); - $this->assertEquals(0, count($avatarPersister->getUpdates())); - $this->assertEquals(0, count($avatarPersister->getDeletes())); + self::assertEquals(1, count($avatarPersister->getInserts())); + self::assertEquals(0, count($avatarPersister->getUpdates())); + self::assertEquals(0, count($avatarPersister->getDeletes())); } public function testChangeTrackingNotify() { - $persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(NotifyChangedEntity::class)); - $this->_unitOfWork->setEntityPersister(NotifyChangedEntity::class, $persister); - $itemPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(NotifyChangedRelatedItem::class)); - $this->_unitOfWork->setEntityPersister(NotifyChangedRelatedItem::class, $itemPersister); + $persister = new EntityPersisterMock($this->emMock, $this->emMock->getClassMetadata(NotifyChangedEntity::class)); + $this->unitOfWork->setEntityPersister(NotifyChangedEntity::class, $persister); + $itemPersister = new EntityPersisterMock($this->emMock, $this->emMock->getClassMetadata(NotifyChangedRelatedItem::class)); + $this->unitOfWork->setEntityPersister(NotifyChangedRelatedItem::class, $itemPersister); $entity = new NotifyChangedEntity; $entity->setData('thedata'); - $this->_unitOfWork->persist($entity); + $this->unitOfWork->persist($entity); - $this->_unitOfWork->commit(); - $this->assertEquals(1, count($persister->getInserts())); + $this->unitOfWork->commit(); + self::assertEquals(1, count($persister->getInserts())); $persister->reset(); - $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity)); + self::assertTrue($this->unitOfWork->isInIdentityMap($entity)); $entity->setData('newdata'); $entity->setTransient('newtransientvalue'); - $this->assertTrue($this->_unitOfWork->isScheduledForDirtyCheck($entity)); + self::assertTrue($this->unitOfWork->isScheduledForDirtyCheck($entity)); - $this->assertEquals(['data' => ['thedata', 'newdata']], $this->_unitOfWork->getEntityChangeSet($entity)); + self::assertEquals( + [ + 'data' => ['thedata', 'newdata'], + 'transient' => [null, 'newtransientvalue'], + ], + $this->unitOfWork->getEntityChangeSet($entity) + ); $item = new NotifyChangedRelatedItem(); $entity->getItems()->add($item); $item->setOwner($entity); - $this->_unitOfWork->persist($item); + $this->unitOfWork->persist($item); - $this->_unitOfWork->commit(); - $this->assertEquals(1, count($itemPersister->getInserts())); + $this->unitOfWork->commit(); + self::assertEquals(1, count($itemPersister->getInserts())); $persister->reset(); $itemPersister->reset(); $entity->getItems()->removeElement($item); $item->setOwner(null); - $this->assertTrue($entity->getItems()->isDirty()); - $this->_unitOfWork->commit(); + self::assertTrue($entity->getItems()->isDirty()); + $this->unitOfWork->commit(); $updates = $itemPersister->getUpdates(); - $this->assertEquals(1, count($updates)); - $this->assertTrue($updates[0] === $item); + self::assertEquals(1, count($updates)); + self::assertTrue($updates[0] === $item); } public function testGetEntityStateOnVersionedEntityWithAssignedIdentifier() { - $persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(VersionedAssignedIdentifierEntity::class)); - $this->_unitOfWork->setEntityPersister(VersionedAssignedIdentifierEntity::class, $persister); + $persister = new EntityPersisterMock($this->emMock, $this->emMock->getClassMetadata(VersionedAssignedIdentifierEntity::class)); + $this->unitOfWork->setEntityPersister(VersionedAssignedIdentifierEntity::class, $persister); $e = new VersionedAssignedIdentifierEntity(); $e->id = 42; - $this->assertEquals(UnitOfWork::STATE_NEW, $this->_unitOfWork->getEntityState($e)); - $this->assertFalse($persister->isExistsCalled()); + self::assertEquals(UnitOfWork::STATE_NEW, $this->unitOfWork->getEntityState($e)); + self::assertFalse($persister->isExistsCalled()); } public function testGetEntityStateWithAssignedIdentity() { - $persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(CmsPhonenumber::class)); - $this->_unitOfWork->setEntityPersister(CmsPhonenumber::class, $persister); + $persister = new EntityPersisterMock($this->emMock, $this->emMock->getClassMetadata(CmsPhonenumber::class)); + $this->unitOfWork->setEntityPersister(CmsPhonenumber::class, $persister); $ph = new CmsPhonenumber(); $ph->phonenumber = '12345'; - $this->assertEquals(UnitOfWork::STATE_NEW, $this->_unitOfWork->getEntityState($ph)); - $this->assertTrue($persister->isExistsCalled()); + self::assertEquals(UnitOfWork::STATE_NEW, $this->unitOfWork->getEntityState($ph)); + self::assertTrue($persister->isExistsCalled()); $persister->reset(); // if the entity is already managed the exists() check should be skipped - $this->_unitOfWork->registerManaged($ph, ['phonenumber' => '12345'], []); - $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_unitOfWork->getEntityState($ph)); - $this->assertFalse($persister->isExistsCalled()); + $this->unitOfWork->registerManaged($ph, ['phonenumber' => '12345'], []); + self::assertEquals(UnitOfWork::STATE_MANAGED, $this->unitOfWork->getEntityState($ph)); + self::assertFalse($persister->isExistsCalled()); $ph2 = new CmsPhonenumber(); $ph2->phonenumber = '12345'; - $this->assertEquals(UnitOfWork::STATE_DETACHED, $this->_unitOfWork->getEntityState($ph2)); - $this->assertFalse($persister->isExistsCalled()); + self::assertEquals(UnitOfWork::STATE_DETACHED, $this->unitOfWork->getEntityState($ph2)); + self::assertFalse($persister->isExistsCalled()); } /** @@ -235,25 +258,25 @@ public function testGetEntityStateWithAssignedIdentity() public function testNoUndefinedIndexNoticeOnScheduleForUpdateWithoutChanges() { // Setup fake persister and id generator - $userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(ForumUser::class)); - $userPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY); - $this->_unitOfWork->setEntityPersister(ForumUser::class, $userPersister); + $userPersister = new EntityPersisterMock($this->emMock, $this->emMock->getClassMetadata(ForumUser::class)); + $userPersister->setMockIdGeneratorType(GeneratorType::IDENTITY); + $this->unitOfWork->setEntityPersister(ForumUser::class, $userPersister); // Create a test user $user = new ForumUser(); $user->name = 'Jasper'; - $this->_unitOfWork->persist($user); - $this->_unitOfWork->commit(); + $this->unitOfWork->persist($user); + $this->unitOfWork->commit(); // Schedule user for update without changes - $this->_unitOfWork->scheduleForUpdate($user); + $this->unitOfWork->scheduleForUpdate($user); - self::assertNotEmpty($this->_unitOfWork->getScheduledEntityUpdates()); + self::assertNotEmpty($this->unitOfWork->getScheduledEntityUpdates()); // This commit should not raise an E_NOTICE - $this->_unitOfWork->commit(); + $this->unitOfWork->commit(); - self::assertEmpty($this->_unitOfWork->getScheduledEntityUpdates()); + self::assertEmpty($this->unitOfWork->getScheduledEntityUpdates()); } /** @@ -262,7 +285,7 @@ public function testNoUndefinedIndexNoticeOnScheduleForUpdateWithoutChanges() public function testLockWithoutEntityThrowsException() { $this->expectException(\InvalidArgumentException::class); - $this->_unitOfWork->lock(null, null, null); + $this->unitOfWork->lock(null, null, null); } /** @@ -274,11 +297,11 @@ public function testLockWithoutEntityThrowsException() */ public function testRejectsPersistenceOfObjectsWithInvalidAssociationValue($invalidValue) { - $this->_unitOfWork->setEntityPersister( + $this->unitOfWork->setEntityPersister( ForumUser::class, new EntityPersisterMock( - $this->_emMock, - $this->_emMock->getClassMetadata(ForumUser::class) + $this->emMock, + $this->emMock->getClassMetadata(ForumUser::class) ) ); @@ -288,7 +311,7 @@ public function testRejectsPersistenceOfObjectsWithInvalidAssociationValue($inva $this->expectException(\Doctrine\ORM\ORMInvalidArgumentException::class); - $this->_unitOfWork->persist($user); + $this->unitOfWork->persist($user); } /** @@ -300,23 +323,23 @@ public function testRejectsPersistenceOfObjectsWithInvalidAssociationValue($inva */ public function testRejectsChangeSetComputationForObjectsWithInvalidAssociationValue($invalidValue) { - $metadata = $this->_emMock->getClassMetadata(ForumUser::class); + $metadata = $this->emMock->getClassMetadata(ForumUser::class); - $this->_unitOfWork->setEntityPersister( + $this->unitOfWork->setEntityPersister( ForumUser::class, - new EntityPersisterMock($this->_emMock, $metadata) + new EntityPersisterMock($this->emMock, $metadata) ); $user = new ForumUser(); - $this->_unitOfWork->persist($user); + $this->unitOfWork->persist($user); $user->username = 'John'; $user->avatar = $invalidValue; $this->expectException(\Doctrine\ORM\ORMInvalidArgumentException::class); - $this->_unitOfWork->computeChangeSet($metadata, $user); + $this->unitOfWork->computeChangeSet($metadata, $user); } /** @@ -328,14 +351,14 @@ public function testRemovedAndRePersistedEntitiesAreInTheIdentityMapAndAreNotGar $entity = new ForumUser(); $entity->id = 123; - $this->_unitOfWork->registerManaged($entity, ['id' => 123], []); - $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity)); + $this->unitOfWork->registerManaged($entity, ['id' => 123], []); + self::assertTrue($this->unitOfWork->isInIdentityMap($entity)); - $this->_unitOfWork->remove($entity); - $this->assertFalse($this->_unitOfWork->isInIdentityMap($entity)); + $this->unitOfWork->remove($entity); + self::assertFalse($this->unitOfWork->isInIdentityMap($entity)); - $this->_unitOfWork->persist($entity); - $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity)); + $this->unitOfWork->persist($entity); + self::assertTrue($this->unitOfWork->isInIdentityMap($entity)); } /** @@ -347,17 +370,19 @@ public function testPersistedEntityAndClearManager() $entity1 = new City(123, 'London'); $entity2 = new Country(456, 'United Kingdom'); - $this->_unitOfWork->persist($entity1); - $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity1)); + $this->unitOfWork->persist($entity1); + self::assertTrue($this->unitOfWork->isInIdentityMap($entity1)); + + $this->unitOfWork->persist($entity2); + self::assertTrue($this->unitOfWork->isInIdentityMap($entity2)); - $this->_unitOfWork->persist($entity2); - $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity2)); + $this->unitOfWork->clear(); - $this->_unitOfWork->clear(Country::class); - $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity1)); - $this->assertFalse($this->_unitOfWork->isInIdentityMap($entity2)); - $this->assertTrue($this->_unitOfWork->isScheduledForInsert($entity1)); - $this->assertFalse($this->_unitOfWork->isScheduledForInsert($entity2)); + self::assertFalse($this->unitOfWork->isInIdentityMap($entity1)); + self::assertFalse($this->unitOfWork->isInIdentityMap($entity2)); + + self::assertFalse($this->unitOfWork->isScheduledForInsert($entity1)); + self::assertFalse($this->unitOfWork->isScheduledForInsert($entity2)); } /** @@ -387,10 +412,10 @@ public function invalidAssociationValuesDataProvider() */ public function testAddToIdentityMapValidIdentifiers($entity, $idHash) { - $this->_unitOfWork->persist($entity); - $this->_unitOfWork->addToIdentityMap($entity); + $this->unitOfWork->persist($entity); + $this->unitOfWork->addToIdentityMap($entity); - self::assertSame($entity, $this->_unitOfWork->getByIdHash($idHash, get_class($entity))); + self::assertSame($entity, $this->unitOfWork->getByIdHash($idHash, get_class($entity))); } public function entitiesWithValidIdentifiersProvider() @@ -435,7 +460,7 @@ public function testRegisteringAManagedInstanceRequiresANonEmptyIdentifier() { $this->expectException(ORMInvalidArgumentException::class); - $this->_unitOfWork->registerManaged(new EntityWithBooleanIdentifier(), [], []); + $this->unitOfWork->registerManaged(new EntityWithBooleanIdentifier(), [], []); } /** @@ -450,7 +475,7 @@ public function testAddToIdentityMapInvalidIdentifiers($entity, array $identifie { $this->expectException(ORMInvalidArgumentException::class); - $this->_unitOfWork->registerManaged($entity, $identifier, []); + $this->unitOfWork->registerManaged($entity, $identifier, []); } @@ -473,136 +498,53 @@ public function entitiesWithInvalidIdentifiersProvider() } /** - * @group 5689 - * @group 1465 + * @group DDC-3120 */ - public function testObjectHashesOfMergedEntitiesAreNotUsedInOriginalEntityDataMap() + public function testCanInstantiateInternalPhpClassSubclass() { - $user = new CmsUser(); - $user->name = 'ocramius'; - $mergedUser = $this->_unitOfWork->merge($user); - - self::assertSame([], $this->_unitOfWork->getOriginalEntityData($user), 'No original data was stored'); - self::assertSame([], $this->_unitOfWork->getOriginalEntityData($mergedUser), 'No original data was stored'); - - - $user = null; - $mergedUser = null; - - // force garbage collection of $user (frees the used object hashes, which may be recycled) - gc_collect_cycles(); + $classMetadata = new ClassMetadata(MyArrayObjectEntity::class, $this->metadataBuildingContext); - $newUser = new CmsUser(); - $newUser->name = 'ocramius'; - - $this->_unitOfWork->persist($newUser); - - self::assertSame([], $this->_unitOfWork->getOriginalEntityData($newUser), 'No original data was stored'); - } - - /** - * @group DDC-1955 - * @group 5570 - * @group 6174 - */ - public function testMergeWithNewEntityWillPersistItAndTriggerPrePersistListenersWithMergedEntityData() - { - $entity = new EntityWithRandomlyGeneratedField(); - - $generatedFieldValue = $entity->generatedField; - - $this - ->eventManager - ->expects(self::any()) - ->method('hasListeners') - ->willReturnCallback(function ($eventName) { - return $eventName === Events::prePersist; - }); - $this - ->eventManager - ->expects(self::once()) - ->method('dispatchEvent') - ->with( - self::anything(), - self::callback(function (LifecycleEventArgs $args) use ($entity, $generatedFieldValue) { - /* @var $object EntityWithRandomlyGeneratedField */ - $object = $args->getObject(); - - self::assertInstanceOf(EntityWithRandomlyGeneratedField::class, $object); - self::assertNotSame($entity, $object); - self::assertSame($generatedFieldValue, $object->generatedField); - - return true; - }) - ); - - /* @var $object EntityWithRandomlyGeneratedField */ - $object = $this->_unitOfWork->merge($entity); - - self::assertNotSame($object, $entity); - self::assertInstanceOf(EntityWithRandomlyGeneratedField::class, $object); - self::assertSame($object->generatedField, $entity->generatedField); + self::assertInstanceOf(MyArrayObjectEntity::class, $this->unitOfWork->newInstance($classMetadata)); } /** - * @group DDC-1955 - * @group 5570 - * @group 6174 + * @group DDC-3120 */ - public function testMergeWithExistingEntityWillNotPersistItNorTriggerPrePersistListeners() + public function testCanInstantiateInternalPhpClassSubclassFromUnserializedMetadata() { - $persistedEntity = new EntityWithRandomlyGeneratedField(); - $mergedEntity = new EntityWithRandomlyGeneratedField(); - - $mergedEntity->id = $persistedEntity->id; - $mergedEntity->generatedField = mt_rand( - $persistedEntity->generatedField + 1, - $persistedEntity->generatedField + 1000 - ); - - $this - ->eventManager - ->expects(self::any()) - ->method('hasListeners') - ->willReturnCallback(function ($eventName) { - return $eventName === Events::prePersist; - }); - $this->eventManager->expects(self::never())->method('dispatchEvent'); - - $this->_unitOfWork->registerManaged( - $persistedEntity, - ['id' => $persistedEntity->id], - ['generatedField' => $persistedEntity->generatedField] + /* @var $classMetadata ClassMetadata */ + $classMetadata = unserialize( + serialize( + new ClassMetadata(MyArrayObjectEntity::class, $this->metadataBuildingContext) + ) ); - /* @var $merged EntityWithRandomlyGeneratedField */ - $merged = $this->_unitOfWork->merge($mergedEntity); + $classMetadata->wakeupReflection(new RuntimeReflectionService()); - self::assertSame($merged, $persistedEntity); - self::assertSame($persistedEntity->generatedField, $mergedEntity->generatedField); + self::assertInstanceOf(MyArrayObjectEntity::class, $this->unitOfWork->newInstance($classMetadata)); } } /** - * @Entity + * @ORM\Entity */ class NotifyChangedEntity implements NotifyPropertyChanged { - private $_listeners = []; + private $listeners = []; /** - * @Id - * @Column(type="integer") - * @GeneratedValue + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue */ private $id; /** - * @Column(type="string") + * @ORM\Column(type="string") */ private $data; private $transient; // not persisted - /** @OneToMany(targetEntity="NotifyChangedRelatedItem", mappedBy="owner") */ + /** @ORM\OneToMany(targetEntity="NotifyChangedRelatedItem", mappedBy="owner") */ private $items; public function __construct() { @@ -619,7 +561,7 @@ public function getItems() { public function setTransient($value) { if ($value != $this->transient) { - $this->_onPropertyChanged('transient', $this->transient, $value); + $this->onPropertyChanged('transient', $this->transient, $value); $this->transient = $value; } } @@ -630,36 +572,36 @@ public function getData() { public function setData($data) { if ($data != $this->data) { - $this->_onPropertyChanged('data', $this->data, $data); + $this->onPropertyChanged('data', $this->data, $data); $this->data = $data; } } public function addPropertyChangedListener(PropertyChangedListener $listener) { - $this->_listeners[] = $listener; + $this->listeners[] = $listener; } - protected function _onPropertyChanged($propName, $oldValue, $newValue) { - if ($this->_listeners) { - foreach ($this->_listeners as $listener) { + protected function onPropertyChanged($propName, $oldValue, $newValue) { + if ($this->listeners) { + foreach ($this->listeners as $listener) { $listener->propertyChanged($this, $propName, $oldValue, $newValue); } } } } -/** @Entity */ +/** @ORM\Entity */ class NotifyChangedRelatedItem { /** - * @Id - * @Column(type="integer") - * @GeneratedValue + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue */ private $id; - /** @ManyToOne(targetEntity="NotifyChangedEntity", inversedBy="items") */ + /** @ORM\ManyToOne(targetEntity="NotifyChangedEntity", inversedBy="items") */ private $owner; public function getId() { @@ -675,67 +617,67 @@ public function setOwner($owner) { } } -/** @Entity */ +/** @ORM\Entity */ class VersionedAssignedIdentifierEntity { /** - * @Id @Column(type="integer") + * @ORM\Id @ORM\Column(type="integer") */ public $id; /** - * @Version @Column(type="integer") + * @ORM\Version @ORM\Column(type="integer") */ public $version; } -/** @Entity */ +/** @ORM\Entity */ class EntityWithStringIdentifier { /** - * @Id @Column(type="string") + * @ORM\Id @ORM\Column(type="string") * * @var string|null */ public $id; } -/** @Entity */ +/** @ORM\Entity */ class EntityWithBooleanIdentifier { /** - * @Id @Column(type="boolean") + * @ORM\Id @ORM\Column(type="boolean") * * @var bool|null */ public $id; } -/** @Entity */ +/** @ORM\Entity */ class EntityWithCompositeStringIdentifier { /** - * @Id @Column(type="string") + * @ORM\Id @ORM\Column(type="string") * * @var string|null */ public $id1; /** - * @Id @Column(type="string") + * @ORM\Id @ORM\Column(type="string") * * @var string|null */ public $id2; } -/** @Entity */ +/** @ORM\Entity */ class EntityWithRandomlyGeneratedField { - /** @Id @Column(type="string") */ + /** @ORM\Id @ORM\Column(type="string") */ public $id; /** - * @Column(type="integer") + * @ORM\Column(type="integer") */ public $generatedField; @@ -745,3 +687,7 @@ public function __construct() $this->generatedField = mt_rand(0, 100000); } } + +class MyArrayObjectEntity extends \ArrayObject +{ +} diff --git a/tests/Doctrine/Tests/ORM/Utility/IdentifierFlattenerTest.php b/tests/Doctrine/Tests/ORM/Utility/IdentifierFlattenerTest.php index 86b6503d376..31582c22c7b 100644 --- a/tests/Doctrine/Tests/ORM/Utility/IdentifierFlattenerTest.php +++ b/tests/Doctrine/Tests/ORM/Utility/IdentifierFlattenerTest.php @@ -1,5 +1,7 @@ identifierFlattener = new IdentifierFlattener( - $this->_em->getUnitOfWork(), - $this->_em->getMetadataFactory() + $this->em->getUnitOfWork(), + $this->em->getMetadataFactory() ); try { - $this->_schemaTool->createSchema( + $this->schemaTool->createSchema( [ - $this->_em->getClassMetadata(FirstRelatedEntity::class), - $this->_em->getClassMetadata(SecondRelatedEntity::class), - $this->_em->getClassMetadata(Flight::class), - $this->_em->getClassMetadata(City::class) + $this->em->getClassMetadata(FirstRelatedEntity::class), + $this->em->getClassMetadata(SecondRelatedEntity::class), + $this->em->getClassMetadata(Flight::class), + $this->em->getClassMetadata(City::class) ] ); } catch (ORMException $e) { @@ -55,28 +57,29 @@ public function testFlattenIdentifierWithOneToOneId() $secondRelatedEntity = new SecondRelatedEntity(); $secondRelatedEntity->name = 'Bob'; - $this->_em->persist($secondRelatedEntity); - $this->_em->flush(); + $this->em->persist($secondRelatedEntity); + $this->em->flush(); $firstRelatedEntity = new FirstRelatedEntity(); $firstRelatedEntity->name = 'Fred'; $firstRelatedEntity->secondEntity = $secondRelatedEntity; - $this->_em->persist($firstRelatedEntity); - $this->_em->flush(); + $this->em->persist($firstRelatedEntity); + $this->em->flush(); - $firstEntity = $this->_em->getRepository(FirstRelatedEntity::class) + $firstEntity = $this->em->getRepository(FirstRelatedEntity::class) ->findOneBy(['name' => 'Fred']); - $class = $this->_em->getClassMetadata(FirstRelatedEntity::class); + $class = $this->em->getClassMetadata(FirstRelatedEntity::class); + $persister = $this->em->getUnitOfWork()->getEntityPersister(FirstRelatedEntity::class); - $id = $class->getIdentifierValues($firstEntity); + $id = $persister->getIdentifier($firstEntity); - $this->assertCount(1, $id, 'We should have 1 identifier'); + self::assertCount(1, $id, 'We should have 1 identifier'); - $this->assertArrayHasKey('secondEntity', $id, 'It should be called secondEntity'); + self::assertArrayHasKey('secondEntity', $id, 'It should be called secondEntity'); - $this->assertInstanceOf( + self::assertInstanceOf( '\Doctrine\Tests\Models\VersionedOneToOne\SecondRelatedEntity', $id['secondEntity'], 'The entity should be an instance of SecondRelatedEntity' @@ -84,11 +87,11 @@ public function testFlattenIdentifierWithOneToOneId() $flatIds = $this->identifierFlattener->flattenIdentifier($class, $id); - $this->assertCount(1, $flatIds, 'We should have 1 flattened id'); + self::assertCount(1, $flatIds, 'We should have 1 flattened id'); - $this->assertArrayHasKey('secondEntity', $flatIds, 'It should be called secondEntity'); + self::assertArrayHasKey('secondEntity', $flatIds, 'It should be called secondEntity'); - $this->assertEquals($id['secondEntity']->id, $flatIds['secondEntity']); + self::assertEquals($id['secondEntity']->id, $flatIds['secondEntity']); } /** @@ -99,34 +102,35 @@ public function testFlattenIdentifierWithMutlipleIds() $leeds = new City('Leeds'); $london = new City('London'); - $this->_em->persist($leeds); - $this->_em->persist($london); - $this->_em->flush(); + $this->em->persist($leeds); + $this->em->persist($london); + $this->em->flush(); $flight = new Flight($leeds, $london); - $this->_em->persist($flight); - $this->_em->flush(); + $this->em->persist($flight); + $this->em->flush(); - $class = $this->_em->getClassMetadata(Flight::class); - $id = $class->getIdentifierValues($flight); + $class = $this->em->getClassMetadata(Flight::class); + $persister = $this->em->getUnitOfWork()->getEntityPersister(Flight::class); + $id = $persister->getIdentifier($flight); - $this->assertCount(2, $id); + self::assertCount(2, $id); - $this->assertArrayHasKey('leavingFrom', $id); - $this->assertArrayHasKey('goingTo', $id); + self::assertArrayHasKey('leavingFrom', $id); + self::assertArrayHasKey('goingTo', $id); - $this->assertEquals($leeds, $id['leavingFrom']); - $this->assertEquals($london, $id['goingTo']); + self::assertEquals($leeds, $id['leavingFrom']); + self::assertEquals($london, $id['goingTo']); $flatIds = $this->identifierFlattener->flattenIdentifier($class, $id); - $this->assertCount(2, $flatIds); + self::assertCount(2, $flatIds); - $this->assertArrayHasKey('leavingFrom', $flatIds); - $this->assertArrayHasKey('goingTo', $flatIds); + self::assertArrayHasKey('leavingFrom', $flatIds); + self::assertArrayHasKey('goingTo', $flatIds); - $this->assertEquals($id['leavingFrom']->getId(), $flatIds['leavingFrom']); - $this->assertEquals($id['goingTo']->getId(), $flatIds['goingTo']); + self::assertEquals($id['leavingFrom']->getId(), $flatIds['leavingFrom']); + self::assertEquals($id['goingTo']->getId(), $flatIds['goingTo']); } } diff --git a/tests/Doctrine/Tests/OrmFunctionalTestCase.php b/tests/Doctrine/Tests/OrmFunctionalTestCase.php index e9299b1c685..1891d1ea39a 100644 --- a/tests/Doctrine/Tests/OrmFunctionalTestCase.php +++ b/tests/Doctrine/Tests/OrmFunctionalTestCase.php @@ -1,5 +1,7 @@ [ Models\CMS\CmsUser::class, Models\CMS\CmsPhonenumber::class, @@ -312,6 +315,15 @@ abstract class OrmFunctionalTestCase extends OrmTestCase Models\Issue5989\Issue5989Employee::class, Models\Issue5989\Issue5989Manager::class, ], + 'valueGenerators' => [ + Models\ValueGenerators\CompositeGeneratedIdentifier::class, + Models\ValueGenerators\NonIdentifierGenerators::class, + Models\ValueGenerators\InheritanceGeneratorsRoot::class, + Models\ValueGenerators\InheritanceGeneratorsChildA::class, + Models\ValueGenerators\InheritanceGeneratorsChildB::class, + Models\ValueGenerators\AssociationIdentifier::class, + Models\ValueGenerators\AssociationIdentifierTarget::class, + ], ]; /** @@ -321,7 +333,7 @@ abstract class OrmFunctionalTestCase extends OrmTestCase */ protected function useModelSet($setName) { - $this->_usedModelSets[$setName] = true; + $this->usedModelSets[$setName] = true; } /** @@ -331,7 +343,7 @@ protected function useModelSet($setName) */ protected function tearDown() { - $conn = static::$_sharedConn; + $conn = static::$sharedConn; // In case test is skipped, tearDown is called, but no setup may have run if ( ! $conn) { @@ -340,9 +352,9 @@ protected function tearDown() $platform = $conn->getDatabasePlatform(); - $this->_sqlLoggerStack->enabled = false; + $this->sqlLoggerStack->enabled = false; - if (isset($this->_usedModelSets['cms'])) { + if (isset($this->usedModelSets['cms'])) { $conn->executeUpdate('DELETE FROM cms_users_groups'); $conn->executeUpdate('DELETE FROM cms_groups'); $conn->executeUpdate('DELETE FROM cms_users_tags'); @@ -355,7 +367,7 @@ protected function tearDown() $conn->executeUpdate('DELETE FROM cms_emails'); } - if (isset($this->_usedModelSets['ecommerce'])) { + if (isset($this->usedModelSets['ecommerce'])) { $conn->executeUpdate('DELETE FROM ecommerce_carts_products'); $conn->executeUpdate('DELETE FROM ecommerce_products_categories'); $conn->executeUpdate('DELETE FROM ecommerce_products_related'); @@ -368,7 +380,7 @@ protected function tearDown() $conn->executeUpdate('DELETE FROM ecommerce_categories'); } - if (isset($this->_usedModelSets['company'])) { + if (isset($this->usedModelSets['company'])) { $conn->executeUpdate('DELETE FROM company_contract_employees'); $conn->executeUpdate('DELETE FROM company_contract_managers'); $conn->executeUpdate('DELETE FROM company_contracts'); @@ -384,14 +396,14 @@ protected function tearDown() $conn->executeUpdate('DELETE FROM company_organizations'); } - if (isset($this->_usedModelSets['generic'])) { + if (isset($this->usedModelSets['generic'])) { $conn->executeUpdate('DELETE FROM boolean_model'); $conn->executeUpdate('DELETE FROM date_time_model'); $conn->executeUpdate('DELETE FROM decimal_model'); $conn->executeUpdate('DELETE FROM serialize_model'); } - if (isset($this->_usedModelSets['routing'])) { + if (isset($this->usedModelSets['routing'])) { $conn->executeUpdate('DELETE FROM RoutingRouteLegs'); $conn->executeUpdate('DELETE FROM RoutingRouteBooking'); $conn->executeUpdate('DELETE FROM RoutingRoute'); @@ -399,20 +411,20 @@ protected function tearDown() $conn->executeUpdate('DELETE FROM RoutingLocation'); } - if(isset($this->_usedModelSets['navigation'])) { + if(isset($this->usedModelSets['navigation'])) { $conn->executeUpdate('DELETE FROM navigation_tour_pois'); $conn->executeUpdate('DELETE FROM navigation_photos'); $conn->executeUpdate('DELETE FROM navigation_pois'); $conn->executeUpdate('DELETE FROM navigation_tours'); $conn->executeUpdate('DELETE FROM navigation_countries'); } - if (isset($this->_usedModelSets['directorytree'])) { + if (isset($this->usedModelSets['directorytree'])) { $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier("file")); // MySQL doesn't know deferred deletions therefore only executing the second query gives errors. $conn->executeUpdate('DELETE FROM Directory WHERE parentDirectory_id IS NOT NULL'); $conn->executeUpdate('DELETE FROM Directory'); } - if (isset($this->_usedModelSets['ddc117'])) { + if (isset($this->usedModelSets['ddc117'])) { $conn->executeUpdate('DELETE FROM ddc117editor_ddc117translation'); $conn->executeUpdate('DELETE FROM DDC117Editor'); $conn->executeUpdate('DELETE FROM DDC117ApproveChanges'); @@ -422,13 +434,13 @@ protected function tearDown() $conn->executeUpdate('DELETE FROM DDC117Translation'); $conn->executeUpdate('DELETE FROM DDC117Article'); } - if (isset($this->_usedModelSets['stockexchange'])) { + if (isset($this->usedModelSets['stockexchange'])) { $conn->executeUpdate('DELETE FROM exchange_bonds_stocks'); $conn->executeUpdate('DELETE FROM exchange_bonds'); $conn->executeUpdate('DELETE FROM exchange_stocks'); $conn->executeUpdate('DELETE FROM exchange_markets'); } - if (isset($this->_usedModelSets['legacy'])) { + if (isset($this->usedModelSets['legacy'])) { $conn->executeUpdate('DELETE FROM legacy_users_cars'); $conn->executeUpdate('DELETE FROM legacy_users_reference'); $conn->executeUpdate('DELETE FROM legacy_articles'); @@ -436,33 +448,33 @@ protected function tearDown() $conn->executeUpdate('DELETE FROM legacy_users'); } - if (isset($this->_usedModelSets['customtype'])) { + if (isset($this->usedModelSets['customtype'])) { $conn->executeUpdate('DELETE FROM customtype_parent_friends'); $conn->executeUpdate('DELETE FROM customtype_parents'); $conn->executeUpdate('DELETE FROM customtype_children'); $conn->executeUpdate('DELETE FROM customtype_uppercases'); } - if (isset($this->_usedModelSets['compositekeyinheritance'])) { + if (isset($this->usedModelSets['compositekeyinheritance'])) { $conn->executeUpdate('DELETE FROM JoinedChildClass'); $conn->executeUpdate('DELETE FROM JoinedRootClass'); $conn->executeUpdate('DELETE FROM SingleRootClass'); } - if (isset($this->_usedModelSets['taxi'])) { + if (isset($this->usedModelSets['taxi'])) { $conn->executeUpdate('DELETE FROM taxi_paid_ride'); $conn->executeUpdate('DELETE FROM taxi_ride'); $conn->executeUpdate('DELETE FROM taxi_car'); $conn->executeUpdate('DELETE FROM taxi_driver'); } - if (isset($this->_usedModelSets['tweet'])) { + if (isset($this->usedModelSets['tweet'])) { $conn->executeUpdate('DELETE FROM tweet_tweet'); $conn->executeUpdate('DELETE FROM tweet_user_list'); $conn->executeUpdate('DELETE FROM tweet_user'); } - if (isset($this->_usedModelSets['cache'])) { + if (isset($this->usedModelSets['cache'])) { $conn->executeUpdate('DELETE FROM cache_attraction_location_info'); $conn->executeUpdate('DELETE FROM cache_attraction_contact_info'); $conn->executeUpdate('DELETE FROM cache_attraction_info'); @@ -483,12 +495,12 @@ protected function tearDown() $conn->executeUpdate('DELETE FROM cache_client'); } - if (isset($this->_usedModelSets['ddc3346'])) { + if (isset($this->usedModelSets['ddc3346'])) { $conn->executeUpdate('DELETE FROM ddc3346_articles'); $conn->executeUpdate('DELETE FROM ddc3346_users'); } - if (isset($this->_usedModelSets['quote'])) { + if (isset($this->usedModelSets['quote'])) { $conn->executeUpdate( sprintf( 'UPDATE %s SET %s = NULL', @@ -498,105 +510,114 @@ protected function tearDown() ); $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier('quote-users-groups')); - $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier('quote-group')); - $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier('quote-phone')); - $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier('quote-user')); - $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier('quote-address')); + $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier("quote-group")); + $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier("quote-phone")); + $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier("quote-user")); + $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier("quote-address")); $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier('quote-city')); } - if (isset($this->_usedModelSets['vct_onetoone'])) { + if (isset($this->usedModelSets['vct_onetoone'])) { $conn->executeUpdate('DELETE FROM vct_owning_onetoone'); $conn->executeUpdate('DELETE FROM vct_inversed_onetoone'); } - if (isset($this->_usedModelSets['vct_onetoone_compositeid'])) { + if (isset($this->usedModelSets['vct_onetoone_compositeid'])) { $conn->executeUpdate('DELETE FROM vct_owning_onetoone_compositeid'); $conn->executeUpdate('DELETE FROM vct_inversed_onetoone_compositeid'); } - if (isset($this->_usedModelSets['vct_onetoone_compositeid_foreignkey'])) { + if (isset($this->usedModelSets['vct_onetoone_compositeid_foreignkey'])) { $conn->executeUpdate('DELETE FROM vct_owning_onetoone_compositeid_foreignkey'); $conn->executeUpdate('DELETE FROM vct_inversed_onetoone_compositeid_foreignkey'); $conn->executeUpdate('DELETE FROM vct_auxiliary'); } - if (isset($this->_usedModelSets['vct_onetomany'])) { + if (isset($this->usedModelSets['vct_onetomany'])) { $conn->executeUpdate('DELETE FROM vct_owning_manytoone'); $conn->executeUpdate('DELETE FROM vct_inversed_onetomany'); } - if (isset($this->_usedModelSets['vct_onetomany_compositeid'])) { + if (isset($this->usedModelSets['vct_onetomany_compositeid'])) { $conn->executeUpdate('DELETE FROM vct_owning_manytoone_compositeid'); $conn->executeUpdate('DELETE FROM vct_inversed_onetomany_compositeid'); } - if (isset($this->_usedModelSets['vct_onetomany_compositeid_foreignkey'])) { + if (isset($this->usedModelSets['vct_onetomany_compositeid_foreignkey'])) { $conn->executeUpdate('DELETE FROM vct_owning_manytoone_compositeid_foreignkey'); $conn->executeUpdate('DELETE FROM vct_inversed_onetomany_compositeid_foreignkey'); $conn->executeUpdate('DELETE FROM vct_auxiliary'); } - if (isset($this->_usedModelSets['vct_onetomany_extralazy'])) { + if (isset($this->usedModelSets['vct_onetomany_extralazy'])) { $conn->executeUpdate('DELETE FROM vct_owning_manytoone_extralazy'); $conn->executeUpdate('DELETE FROM vct_inversed_onetomany_extralazy'); } - if (isset($this->_usedModelSets['vct_manytomany'])) { + if (isset($this->usedModelSets['vct_manytomany'])) { $conn->executeUpdate('DELETE FROM vct_xref_manytomany'); $conn->executeUpdate('DELETE FROM vct_owning_manytomany'); $conn->executeUpdate('DELETE FROM vct_inversed_manytomany'); } - if (isset($this->_usedModelSets['vct_manytomany_compositeid'])) { + if (isset($this->usedModelSets['vct_manytomany_compositeid'])) { $conn->executeUpdate('DELETE FROM vct_xref_manytomany_compositeid'); $conn->executeUpdate('DELETE FROM vct_owning_manytomany_compositeid'); $conn->executeUpdate('DELETE FROM vct_inversed_manytomany_compositeid'); } - if (isset($this->_usedModelSets['vct_manytomany_compositeid_foreignkey'])) { + if (isset($this->usedModelSets['vct_manytomany_compositeid_foreignkey'])) { $conn->executeUpdate('DELETE FROM vct_xref_manytomany_compositeid_foreignkey'); $conn->executeUpdate('DELETE FROM vct_owning_manytomany_compositeid_foreignkey'); $conn->executeUpdate('DELETE FROM vct_inversed_manytomany_compositeid_foreignkey'); $conn->executeUpdate('DELETE FROM vct_auxiliary'); } - if (isset($this->_usedModelSets['vct_manytomany_extralazy'])) { + if (isset($this->usedModelSets['vct_manytomany_extralazy'])) { $conn->executeUpdate('DELETE FROM vct_xref_manytomany_extralazy'); $conn->executeUpdate('DELETE FROM vct_owning_manytomany_extralazy'); $conn->executeUpdate('DELETE FROM vct_inversed_manytomany_extralazy'); } - if (isset($this->_usedModelSets['geonames'])) { + + if (isset($this->usedModelSets['geonames'])) { $conn->executeUpdate('DELETE FROM geonames_admin1_alternate_name'); $conn->executeUpdate('DELETE FROM geonames_admin1'); $conn->executeUpdate('DELETE FROM geonames_city'); $conn->executeUpdate('DELETE FROM geonames_country'); } - if (isset($this->_usedModelSets['custom_id_object_type'])) { + if (isset($this->usedModelSets['custom_id_object_type'])) { $conn->executeUpdate('DELETE FROM custom_id_type_child'); $conn->executeUpdate('DELETE FROM custom_id_type_parent'); } - if (isset($this->_usedModelSets['pagination'])) { + if (isset($this->usedModelSets['pagination'])) { $conn->executeUpdate('DELETE FROM pagination_logo'); $conn->executeUpdate('DELETE FROM pagination_department'); $conn->executeUpdate('DELETE FROM pagination_company'); $conn->executeUpdate('DELETE FROM pagination_user'); } - if (isset($this->_usedModelSets['versioned_many_to_one'])) { + if (isset($this->usedModelSets['versioned_many_to_one'])) { $conn->executeUpdate('DELETE FROM versioned_many_to_one_article'); $conn->executeUpdate('DELETE FROM versioned_many_to_one_category'); } - if (isset($this->_usedModelSets['issue5989'])) { + if (isset($this->usedModelSets['issue5989'])) { $conn->executeUpdate('DELETE FROM issue5989_persons'); $conn->executeUpdate('DELETE FROM issue5989_employees'); $conn->executeUpdate('DELETE FROM issue5989_managers'); } - $this->_em->clear(); + if (isset($this->usedModelSets['value_generators'])) { + $conn->executeUpdate('DELETE FROM vg_composite_generated_identifier'); + $conn->executeUpdate('DELETE FROM vg_non_identifier_generators'); + $conn->executeUpdate('DELETE FROM vg_inheritance_generators'); + $conn->executeUpdate('DELETE FROM vg_association_identifier'); + $conn->executeUpdate('DELETE FROM vg_association_identifier_target'); + } + + $this->em->clear(); } /** @@ -608,20 +629,21 @@ protected function tearDown() */ protected function setUpEntitySchema(array $classNames) { - if ($this->_em === null) { + if ($this->em === null) { throw new \RuntimeException("EntityManager not set, you have to call parent::setUp() before invoking this method."); } $classes = []; + foreach ($classNames as $className) { - if ( ! isset(static::$_entityTablesCreated[$className])) { - static::$_entityTablesCreated[$className] = true; - $classes[] = $this->_em->getClassMetadata($className); + if ( ! isset(static::$entityTablesCreated[$className])) { + static::$entityTablesCreated[$className] = true; + $classes[] = $this->em->getClassMetadata($className); } } if ($classes) { - $this->_schemaTool->createSchema($classes); + $this->schemaTool->createSchema($classes); } } @@ -635,73 +657,67 @@ protected function setUp() { $this->setUpDBALTypes(); - if ( ! isset(static::$_sharedConn)) { - static::$_sharedConn = TestUtil::getConnection(); + if (! isset(static::$sharedConn)) { + static::$sharedConn = TestUtil::getConnection(); } if (isset($GLOBALS['DOCTRINE_MARK_SQL_LOGS'])) { - if (in_array(static::$_sharedConn->getDatabasePlatform()->getName(), ["mysql", "postgresql"])) { - static::$_sharedConn->executeQuery('SELECT 1 /*' . get_class($this) . '*/'); - } else if (static::$_sharedConn->getDatabasePlatform()->getName() == "oracle") { - static::$_sharedConn->executeQuery('SELECT 1 /*' . get_class($this) . '*/ FROM dual'); + if (in_array(static::$sharedConn->getDatabasePlatform()->getName(), ["mysql", "postgresql"])) { + static::$sharedConn->executeQuery('SELECT 1 /*' . get_class($this) . '*/'); + } else if (static::$sharedConn->getDatabasePlatform()->getName() === "oracle") { + static::$sharedConn->executeQuery('SELECT 1 /*' . get_class($this) . '*/ FROM dual'); } } - if ( ! $this->_em) { - $this->_em = $this->_getEntityManager(); - $this->_schemaTool = new SchemaTool($this->_em); + if ( ! $this->em) { + $this->em = $this->getEntityManager(); + $this->schemaTool = new SchemaTool($this->em); } - $classes = []; - - foreach ($this->_usedModelSets as $setName => $bool) { - if ( ! isset(static::$_tablesCreated[$setName])) { - foreach (static::$_modelSets[$setName] as $className) { - $classes[] = $this->_em->getClassMetadata($className); - } + foreach ($this->usedModelSets as $setName => $bool) { + if (! isset(static::$tablesCreated[$setName])) { + $this->setUpEntitySchema(static::$modelSets[$setName]); - static::$_tablesCreated[$setName] = true; + static::$tablesCreated[$setName] = true; } } - if ($classes) { - $this->_schemaTool->createSchema($classes); - } - - $this->_sqlLoggerStack->enabled = true; + $this->sqlLoggerStack->enabled = true; } /** * Gets an EntityManager for testing purposes. * - * @return EntityManager + * @return EntityManagerInterface * * @throws \Doctrine\ORM\ORMException */ - protected function _getEntityManager(Connection $connection = null) { + protected function getEntityManager(Connection $connection = null) + { // NOTE: Functional tests use their own shared metadata cache, because // the actual database platform used during execution has effect on some // metadata mapping behaviors (like the choice of the ID generation). - if (is_null(self::$_metadataCacheImpl)) { + if (is_null(self::$metadataCacheImpl)) { if (isset($GLOBALS['DOCTRINE_CACHE_IMPL'])) { - self::$_metadataCacheImpl = new $GLOBALS['DOCTRINE_CACHE_IMPL']; + self::$metadataCacheImpl = new $GLOBALS['DOCTRINE_CACHE_IMPL']; } else { - self::$_metadataCacheImpl = new ArrayCache(); + self::$metadataCacheImpl = new ArrayCache(); } } - if (is_null(self::$_queryCacheImpl)) { - self::$_queryCacheImpl = new ArrayCache(); + if (is_null(self::$queryCacheImpl)) { + self::$queryCacheImpl = new ArrayCache(); } - $this->_sqlLoggerStack = new DebugStack(); - $this->_sqlLoggerStack->enabled = false; + $this->sqlLoggerStack = new DebugStack(); + $this->sqlLoggerStack->enabled = false; //FIXME: two different configs! $conn and the created entity manager have // different configs. - $config = new Configuration(); - $config->setMetadataCacheImpl(self::$_metadataCacheImpl); - $config->setQueryCacheImpl(self::$_queryCacheImpl); + $config = new \Doctrine\ORM\Configuration(); + + $config->setMetadataCacheImpl(self::$metadataCacheImpl); + $config->setQueryCacheImpl(self::$queryCacheImpl); $config->setProxyDir(__DIR__ . '/Proxies'); $config->setProxyNamespace('Doctrine\Tests\Proxies'); @@ -712,7 +728,6 @@ protected function _getEntityManager(Connection $connection = null) { $enableSecondLevelCache = getenv('ENABLE_SECOND_LEVEL_CACHE'); if ($this->isSecondLevelCacheEnabled || $enableSecondLevelCache) { - $cacheConfig = new CacheConfiguration(); $cache = $this->getSharedSecondLevelCacheDriverImpl(); $factory = new DefaultCacheFactory($cacheConfig->getRegionsConfiguration(), $cache); @@ -731,21 +746,20 @@ protected function _getEntityManager(Connection $connection = null) { $this->isSecondLevelCacheEnabled = true; } + $conn = $connection ?: static::$sharedConn; + $config->setMetadataDriverImpl( - $config->newDefaultAnnotationDriver( - [ - realpath(__DIR__ . '/Models/Cache'), - realpath(__DIR__ . '/Models/GeoNames') - ], - true - ) + $config->newDefaultAnnotationDriver([ + realpath(__DIR__ . '/Models/Cache'), + realpath(__DIR__ . '/Models/GeoNames') + ]) ); - $conn = $connection ?: static::$_sharedConn; - $conn->getConfiguration()->setSQLLogger($this->_sqlLoggerStack); + $conn->getConfiguration()->setSQLLogger($this->sqlLoggerStack); // get rid of more global state $evm = $conn->getEventManager(); + foreach ($evm->getListeners() AS $event => $listeners) { foreach ($listeners AS $listener) { $evm->removeEventListener([$event], $listener); @@ -783,17 +797,24 @@ protected function onNotSuccessfulTest(\Throwable $e) throw $e; } - if(isset($this->_sqlLoggerStack->queries) && count($this->_sqlLoggerStack->queries)) { + if (isset($this->sqlLoggerStack->queries) && count($this->sqlLoggerStack->queries)) { $queries = ""; - $last25queries = array_slice(array_reverse($this->_sqlLoggerStack->queries, true), 0, 25, true); + $last25queries = array_slice(array_reverse($this->sqlLoggerStack->queries, true), 0, 25, true); + foreach ($last25queries as $i => $query) { - $params = array_map(function($p) { if (is_object($p)) return get_class($p); else return var_export($p, true); }, $query['params'] ?: [] + $params = array_map( + function($p) { + if (is_object($p)) return get_class($p); else return var_export($p, true); + }, + $query['params'] ?: [] ); + $queries .= $i.". SQL: '".$query['sql']."' Params: ".implode(", ", $params).PHP_EOL; } $trace = $e->getTrace(); $traceMsg = ""; + foreach($trace AS $part) { if(isset($part['file'])) { if(strpos($part['file'], "PHPUnit/") !== false) { @@ -809,12 +830,17 @@ protected function onNotSuccessfulTest(\Throwable $e) throw new \Exception($message, (int)$e->getCode(), $e); } + throw $e; } - public function assertSQLEquals($expectedSql, $actualSql) + public static function assertSQLEquals($expectedSql, $actualSql) { - return $this->assertEquals(strtolower($expectedSql), strtolower($actualSql), "Lowercase comparison of SQL statements failed."); + self::assertEquals( + strtolower((string) $expectedSql), + strtolower((string) $actualSql), + "Lowercase comparison of SQL statements failed." + ); } /** @@ -824,7 +850,7 @@ public function assertSQLEquals($expectedSql, $actualSql) */ protected function getCurrentQueryCount() { - return count($this->_sqlLoggerStack->queries); + return count($this->sqlLoggerStack->queries); } /** diff --git a/tests/Doctrine/Tests/OrmPerformanceTestCase.php b/tests/Doctrine/Tests/OrmPerformanceTestCase.php index b58390ac909..f3acb27311e 100644 --- a/tests/Doctrine/Tests/OrmPerformanceTestCase.php +++ b/tests/Doctrine/Tests/OrmPerformanceTestCase.php @@ -1,5 +1,7 @@ = 0) { - $this->maxRunningTime = $maxRunningTime; - } else { + if (! (is_int($maxRunningTime) && $maxRunningTime >= 0)) { throw new \InvalidArgumentException; } + + $this->maxRunningTime = $maxRunningTime; } /** diff --git a/tests/Doctrine/Tests/OrmTestCase.php b/tests/Doctrine/Tests/OrmTestCase.php index 46e8ea143ee..2aa38ef1854 100644 --- a/tests/Doctrine/Tests/OrmTestCase.php +++ b/tests/Doctrine/Tests/OrmTestCase.php @@ -1,10 +1,11 @@ =')) { - $reader = new Annotations\CachedReader(new Annotations\AnnotationReader(), new ArrayCache()); - } else if (version_compare(Version::VERSION, '2.2.0-DEV', '>=')) { - // Register the ORM Annotations in the AnnotationRegistry - $reader = new Annotations\SimpleAnnotationReader(); - - $reader->addNamespace('Doctrine\ORM\Mapping'); - - $reader = new Annotations\CachedReader($reader, new ArrayCache()); - } else if (version_compare(Version::VERSION, '2.1.0-BETA3-DEV', '>=')) { - $reader = new Annotations\AnnotationReader(); - - $reader->setIgnoreNotImportedAnnotations(true); - $reader->setEnableParsePhpImports(false); - - if ($alias) { - $reader->setAnnotationNamespaceAlias('Doctrine\ORM\Mapping\\', $alias); - } else { - $reader->setDefaultAnnotationNamespace('Doctrine\ORM\Mapping\\'); - } - - $reader = new Annotations\CachedReader(new Annotations\IndexedReader($reader), new ArrayCache()); - } else { - $reader = new Annotations\AnnotationReader(); - - if ($alias) { - $reader->setAnnotationNamespaceAlias('Doctrine\ORM\Mapping\\', $alias); - } else { - $reader->setDefaultAnnotationNamespace('Doctrine\ORM\Mapping\\'); - } - } + $reader = new Annotations\CachedReader(new Annotations\AnnotationReader(), new ArrayCache()); - Annotations\AnnotationRegistry::registerFile(__DIR__ . "/../../../lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php"); + Annotations\AnnotationRegistry::registerFile(__DIR__ . "/../../../lib/Doctrine/ORM/Annotation/DoctrineAnnotations.php"); return new AnnotationDriver($reader, (array) $paths); } @@ -110,13 +80,17 @@ protected function createAnnotationDriver($paths = [], $alias = null) * for a particular test, * * @param \Doctrine\DBAL\Connection|array $conn - * @param mixed $conf * @param \Doctrine\Common\EventManager|null $eventManager * @param bool $withSharedMetadata * - * @return \Doctrine\ORM\EntityManager + * @return \Doctrine\ORM\EntityManagerInterface */ - protected function _getTestEntityManager($conn = null, $conf = null, $eventManager = null, $withSharedMetadata = true) + protected function getTestEntityManager( + $conn = null, + $conf = null, + $eventManager = null, + $withSharedMetadata = true + ) { $metadataCache = $withSharedMetadata ? self::getSharedMetadataCacheImpl() @@ -125,17 +99,17 @@ protected function _getTestEntityManager($conn = null, $conf = null, $eventManag $config = new Configuration(); $config->setMetadataCacheImpl($metadataCache); - $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver([], true)); + $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver([])); $config->setQueryCacheImpl(self::getSharedQueryCacheImpl()); $config->setProxyDir(__DIR__ . '/Proxies'); $config->setProxyNamespace('Doctrine\Tests\Proxies'); - $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver( - [ - realpath(__DIR__ . '/Models/Cache') - ], true)); + $config->setMetadataDriverImpl( + $config->newDefaultAnnotationDriver([ + realpath(__DIR__ . '/Models/Cache') + ]) + ); if ($this->isSecondLevelCacheEnabled) { - $cacheConfig = new CacheConfiguration(); $cache = $this->getSharedSecondLevelCacheDriverImpl(); $factory = new DefaultCacheFactory($cacheConfig->getRegionsConfiguration(), $cache); @@ -160,7 +134,7 @@ protected function _getTestEntityManager($conn = null, $conf = null, $eventManag $conn = DriverManager::getConnection($conn, $config, $eventManager); } - return Mocks\EntityManagerMock::create($conn, $config, $eventManager); + return Mocks\EntityManagerMock::create($conn, $config, $eventManager)->getWrappedEntityManager(); } protected function enableSecondLevelCache($log = true) @@ -174,11 +148,11 @@ protected function enableSecondLevelCache($log = true) */ private static function getSharedMetadataCacheImpl() { - if (self::$_metadataCacheImpl === null) { - self::$_metadataCacheImpl = new ArrayCache(); + if (self::$metadataCacheImpl === null) { + self::$metadataCacheImpl = new ArrayCache(); } - return self::$_metadataCacheImpl; + return self::$metadataCacheImpl; } /** @@ -186,11 +160,11 @@ private static function getSharedMetadataCacheImpl() */ private static function getSharedQueryCacheImpl() { - if (self::$_queryCacheImpl === null) { - self::$_queryCacheImpl = new ArrayCache(); + if (self::$queryCacheImpl === null) { + self::$queryCacheImpl = new ArrayCache(); } - return self::$_queryCacheImpl; + return self::$queryCacheImpl; } /** diff --git a/tests/Doctrine/Tests/TestInit.php b/tests/Doctrine/Tests/TestInit.php index 1474bab4eb8..0de74c864b5 100644 --- a/tests/Doctrine/Tests/TestInit.php +++ b/tests/Doctrine/Tests/TestInit.php @@ -2,6 +2,8 @@ /* * This file bootstraps the test environment. */ +declare(strict_types=1); + namespace Doctrine\Tests; error_reporting(E_ALL | E_STRICT); diff --git a/tests/Doctrine/Tests/TestUtil.php b/tests/Doctrine/Tests/TestUtil.php index 812961c92e9..e2a1f296a9d 100644 --- a/tests/Doctrine/Tests/TestUtil.php +++ b/tests/Doctrine/Tests/TestUtil.php @@ -1,5 +1,7 @@